repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
marcoslarsen/pentaho-kettle
plugins/xml/core/src/test/java/org/pentaho/di/trans/steps/xmlinputstream/XmlInputStreamInputContentParsingTest.java
1928
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.xmlinputstream; import org.junit.ClassRule; import org.junit.Test; import org.pentaho.di.junit.rules.RestorePDIEngineEnvironment; public class XmlInputStreamInputContentParsingTest extends BaseXmlInputStreamParsingTest { @ClassRule public static RestorePDIEngineEnvironment env = new RestorePDIEngineEnvironment(); @Test public void testDefaultOptions() throws Exception { init( "default.xml" ); process(); check( new Object[][] { { "START_DOCUMENT", 0L, null, 0L, "", null, null, null }, { "START_ELEMENT", 1L, 0L, 1L, "/xml", "", "xml", null }, { "START_ELEMENT", 2L, 1L, 2L, "/xml/tag", "/xml", "tag", null }, { "ATTRIBUTE", 2L, 1L, 2L, "/xml/tag", "/xml", "a", "1" }, { "CHARACTERS", 2L, 1L, 2L, "/xml/tag", "/xml", "tag", "zz" }, { "END_ELEMENT", 2L, 1L, 2L, "/xml/tag", "/xml", "tag", null }, { "END_ELEMENT", 1L, 0L, 1L, "/xml", "", "xml", null }, { "END_DOCUMENT", 0L, null, 0L, "", null, null, null } } ); } }
apache-2.0
TribeMedia/aura
aura-resources/src/main/resources/aura/resources/ckeditor/ckeditor-4.x/src/plugins/preview/lang/id.js
218
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'preview', 'id', { preview: 'Pratinjau' } );
apache-2.0
chigraph/chigraph
third_party/boost/include/boost/smart_ptr/make_local_shared_object.hpp
4787
#ifndef BOOST_SMART_PTR_MAKE_LOCAL_SHARED_OBJECT_HPP_INCLUDED #define BOOST_SMART_PTR_MAKE_LOCAL_SHARED_OBJECT_HPP_INCLUDED // make_local_shared_object.hpp // // Copyright 2017 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://www.boost.org/libs/smart_ptr/ for documentation. #include <boost/smart_ptr/local_shared_ptr.hpp> #include <boost/smart_ptr/make_shared.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/config.hpp> #include <utility> #include <cstddef> namespace boost { namespace detail { // lsp_if_not_array template<class T> struct lsp_if_not_array { typedef boost::local_shared_ptr<T> type; }; template<class T> struct lsp_if_not_array<T[]> { }; template<class T, std::size_t N> struct lsp_if_not_array<T[N]> { }; // lsp_ms_deleter template<class T, class A> class lsp_ms_deleter: public local_counted_impl_em { private: typedef typename sp_aligned_storage<sizeof(T), ::boost::alignment_of<T>::value>::type storage_type; storage_type storage_; A a_; bool initialized_; private: void destroy() BOOST_SP_NOEXCEPT { if( initialized_ ) { T * p = reinterpret_cast< T* >( storage_.data_ ); #if !defined( BOOST_NO_CXX11_ALLOCATOR ) std::allocator_traits<A>::destroy( a_, p ); #else p->~T(); #endif initialized_ = false; } } public: explicit lsp_ms_deleter( A const & a ) BOOST_SP_NOEXCEPT : a_( a ), initialized_( false ) { } // optimization: do not copy storage_ lsp_ms_deleter( lsp_ms_deleter const & r ) BOOST_SP_NOEXCEPT : a_( r.a_), initialized_( false ) { } ~lsp_ms_deleter() BOOST_SP_NOEXCEPT { destroy(); } void operator()( T * ) BOOST_SP_NOEXCEPT { destroy(); } static void operator_fn( T* ) BOOST_SP_NOEXCEPT // operator() can't be static { } void * address() BOOST_SP_NOEXCEPT { return storage_.data_; } void set_initialized() BOOST_SP_NOEXCEPT { initialized_ = true; } }; } // namespace detail template<class T, class A, class... Args> typename boost::detail::lsp_if_not_array<T>::type allocate_local_shared( A const & a, Args&&... args ) { #if !defined( BOOST_NO_CXX11_ALLOCATOR ) typedef typename std::allocator_traits<A>::template rebind_alloc<T> A2; #else typedef typename A::template rebind<T>::other A2; #endif A2 a2( a ); typedef boost::detail::lsp_ms_deleter<T, A2> D; boost::shared_ptr<T> pt( static_cast< T* >( 0 ), boost::detail::sp_inplace_tag<D>(), a2 ); D * pd = static_cast< D* >( pt._internal_get_untyped_deleter() ); void * pv = pd->address(); #if !defined( BOOST_NO_CXX11_ALLOCATOR ) std::allocator_traits<A2>::construct( a2, static_cast< T* >( pv ), std::forward<Args>( args )... ); #else ::new( pv ) T( std::forward<Args>( args )... ); #endif pd->set_initialized(); T * pt2 = static_cast< T* >( pv ); boost::detail::sp_enable_shared_from_this( &pt, pt2, pt2 ); pd->pn_ = pt._internal_count(); return boost::local_shared_ptr<T>( boost::detail::lsp_internal_constructor_tag(), pt2, pd ); } template<class T, class A> typename boost::detail::lsp_if_not_array<T>::type allocate_local_shared_noinit( A const & a ) { #if !defined( BOOST_NO_CXX11_ALLOCATOR ) typedef typename std::allocator_traits<A>::template rebind_alloc<T> A2; #else typedef typename A::template rebind<T>::other A2; #endif A2 a2( a ); typedef boost::detail::lsp_ms_deleter< T, std::allocator<T> > D; boost::shared_ptr<T> pt( static_cast< T* >( 0 ), boost::detail::sp_inplace_tag<D>(), a2 ); D * pd = static_cast< D* >( pt._internal_get_untyped_deleter() ); void * pv = pd->address(); ::new( pv ) T; pd->set_initialized(); T * pt2 = static_cast< T* >( pv ); boost::detail::sp_enable_shared_from_this( &pt, pt2, pt2 ); pd->pn_ = pt._internal_count(); return boost::local_shared_ptr<T>( boost::detail::lsp_internal_constructor_tag(), pt2, pd ); } template<class T, class... Args> typename boost::detail::lsp_if_not_array<T>::type make_local_shared( Args&&... args ) { typedef typename boost::remove_const<T>::type T2; return boost::allocate_local_shared<T2>( std::allocator<T2>(), std::forward<Args>(args)... ); } template<class T> typename boost::detail::lsp_if_not_array<T>::type make_local_shared_noinit() { typedef typename boost::remove_const<T>::type T2; return boost::allocate_shared_noinit<T2>( std::allocator<T2>() ); } } // namespace boost #endif // #ifndef BOOST_SMART_PTR_MAKE_SHARED_OBJECT_HPP_INCLUDED
apache-2.0
jawilson/home-assistant
homeassistant/components/raincloud/binary_sensor.py
2263
"""Support for Melnor RainCloud sprinkler water timer.""" import logging import voluptuous as vol from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity from homeassistant.const import CONF_MONITORED_CONDITIONS import homeassistant.helpers.config_validation as cv from . import BINARY_SENSORS, DATA_RAINCLOUD, ICON_MAP, RainCloudEntity _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_MONITORED_CONDITIONS, default=list(BINARY_SENSORS)): vol.All( cv.ensure_list, [vol.In(BINARY_SENSORS)] ) } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a sensor for a raincloud device.""" raincloud = hass.data[DATA_RAINCLOUD].data sensors = [] for sensor_type in config.get(CONF_MONITORED_CONDITIONS): if sensor_type == "status": sensors.append(RainCloudBinarySensor(raincloud.controller, sensor_type)) sensors.append( RainCloudBinarySensor(raincloud.controller.faucet, sensor_type) ) else: # create a sensor for each zone managed by faucet for zone in raincloud.controller.faucet.zones: sensors.append(RainCloudBinarySensor(zone, sensor_type)) add_entities(sensors, True) return True class RainCloudBinarySensor(RainCloudEntity, BinarySensorEntity): """A sensor implementation for raincloud device.""" @property def is_on(self): """Return true if the binary sensor is on.""" return self._state def update(self): """Get the latest data and updates the state.""" _LOGGER.debug("Updating RainCloud sensor: %s", self._name) self._state = getattr(self.data, self._sensor_type) if self._sensor_type == "status": self._state = self._state == "Online" @property def icon(self): """Return the icon of this device.""" if self._sensor_type == "is_watering": return "mdi:water" if self.is_on else "mdi:water-off" if self._sensor_type == "status": return "mdi:pipe" if self.is_on else "mdi:pipe-disconnected" return ICON_MAP.get(self._sensor_type)
apache-2.0
flgiordano/netcash
node_modules/launchpad/lib/browserstack.js
1830
// Launches browserstack instances var BrowserStack = require( "browserstack"); var events = require('events'); var debug = require('debug')('launchpad:browserstack'); module.exports = function(configuration, callback) { var client = BrowserStack.createClient(configuration); var Instance = function(worker) { this.id = worker.id; this.worker = worker; }; debug('Created client from configuration', configuration); Instance.prototype = Object.create(events.EventEmitter.prototype); Instance.prototype.stop = function (callback) { var self = this; client.terminateWorker(this.id, function(err, data) { if(err) { return callback(err); } debug('Stopped instance', this.id); self.emit('stop', data); return callback(null, data); }); }; Instance.prototype.status = function(callback) { debug('Getting instance status', this.id); client.getWorker(this.id, callback); }; client.getBrowsers(function(err, browsers) { if(err) { return callback(err); } debug('Listed all browsers'); var api = function(url, settings, callback) { settings.url = url; debug('Creating worker', settings); client.createWorker(settings, function(err, worker) { if(err) { return callback(err); } return callback(null, new Instance(worker)); }); }; api.browsers = browsers; api.client = client; browsers.forEach(function(info) { debug('Adding browser to API', info); var name = info.browser; if(!api[name]) { api[name] = function(url, settings, callback) { if(!callback) { callback = settings; settings = {}; } settings.browser = name; settings.version = settings.version || 'latest'; callback(null, new Instance(url, settings, callback)); }; } }); return callback(null, api); }); };
bsd-3-clause
tophsic/PHP_CodeSniffer
CodeSniffer/Standards/Generic/Tests/Commenting/DocCommentUnitTest.php
2287
<?php /** * Unit test class for DocCommentSniff. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ /** * Unit test class for DocCommentSniff. * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ class Generic_Tests_Commenting_DocCommentUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * * The key of the array should represent the line number and the value * should represent the number of errors that should occur on that line. * * @return array(int => int) */ public function getErrorList() { return array( 14 => 1, 16 => 1, 18 => 1, 23 => 1, 26 => 1, 30 => 1, 32 => 1, 38 => 2, 40 => 1, 41 => 1, 51 => 1, 54 => 1, 58 => 1, 60 => 2, 67 => 1, 69 => 2, 80 => 1, 81 => 2, 88 => 1, 91 => 1, 95 => 1, 156 => 1, 158 => 1, 170 => 3, 171 => 3, ); }//end getErrorList() /** * Returns the lines where warnings should occur. * * The key of the array should represent the line number and the value * should represent the number of warnings that should occur on that line. * * @return array(int => int) */ public function getWarningList() { return array(); }//end getWarningList() }//end class ?>
bsd-3-clause
ViktorHofer/corefx
src/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs
28155
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using System.Threading.Tasks; namespace System.Xml { public interface IXmlTextWriterInitializer { void SetOutput(Stream stream, Encoding encoding, bool ownsStream); } internal class XmlUTF8TextWriter : XmlBaseWriter, IXmlTextWriterInitializer { private XmlUTF8NodeWriter _writer; public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (encoding.WebName != Encoding.UTF8.WebName) { stream = new EncodingStreamWrapper(stream, encoding, true); } if (_writer == null) { _writer = new XmlUTF8NodeWriter(); } _writer.SetOutput(stream, ownsStream, encoding); SetOutput(_writer); } protected override XmlSigningNodeWriter CreateSigningNodeWriter() { return new XmlSigningNodeWriter(true); } } internal class XmlUTF8NodeWriter : XmlStreamNodeWriter { private byte[] _entityChars; private readonly bool[] _isEscapedAttributeChar; private readonly bool[] _isEscapedElementChar; private bool _inAttribute; private const int bufferLength = 512; private const int maxEntityLength = 32; private Encoding _encoding; private char[] _chars; private static readonly byte[] s_startDecl = { (byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l', (byte)' ', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"', (byte)' ', (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=', (byte)'"', }; private static readonly byte[] s_endDecl = { (byte)'"', (byte)'?', (byte)'>' }; private static readonly byte[] s_utf8Decl = { (byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l', (byte)' ', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"', (byte)' ', (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=', (byte)'"', (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8', (byte)'"', (byte)'?', (byte)'>' }; private static readonly byte[] s_digits = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F' }; private static readonly bool[] s_defaultIsEscapedAttributeChar = new bool[] { true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, false, // '"', '&' false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false // '<', '>' }; private static readonly bool[] s_defaultIsEscapedElementChar = new bool[] { true, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, // All but 0x09, 0x0A true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, // '&' false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false // '<', '>' }; public XmlUTF8NodeWriter() : this(s_defaultIsEscapedAttributeChar, s_defaultIsEscapedElementChar) { } public XmlUTF8NodeWriter(bool[] isEscapedAttributeChar, bool[] isEscapedElementChar) { _isEscapedAttributeChar = isEscapedAttributeChar; _isEscapedElementChar = isEscapedElementChar; _inAttribute = false; } public new void SetOutput(Stream stream, bool ownsStream, Encoding encoding) { Encoding utf8Encoding = null; if (encoding != null && encoding.CodePage == Encoding.UTF8.CodePage) { utf8Encoding = encoding; encoding = null; } base.SetOutput(stream, ownsStream, utf8Encoding); _encoding = encoding; _inAttribute = false; } private byte[] GetCharEntityBuffer() { if (_entityChars == null) { _entityChars = new byte[maxEntityLength]; } return _entityChars; } private char[] GetCharBuffer(int charCount) { if (charCount >= 256) return new char[charCount]; if (_chars == null || _chars.Length < charCount) _chars = new char[charCount]; return _chars; } public override void WriteDeclaration() { if (_encoding == null) { WriteUTF8Chars(s_utf8Decl, 0, s_utf8Decl.Length); } else { WriteUTF8Chars(s_startDecl, 0, s_startDecl.Length); if (_encoding.WebName == Encoding.BigEndianUnicode.WebName) WriteUTF8Chars("utf-16BE"); else WriteUTF8Chars(_encoding.WebName); WriteUTF8Chars(s_endDecl, 0, s_endDecl.Length); } } public override void WriteCData(string text) { byte[] buffer; int offset; buffer = GetBuffer(9, out offset); buffer[offset + 0] = (byte)'<'; buffer[offset + 1] = (byte)'!'; buffer[offset + 2] = (byte)'['; buffer[offset + 3] = (byte)'C'; buffer[offset + 4] = (byte)'D'; buffer[offset + 5] = (byte)'A'; buffer[offset + 6] = (byte)'T'; buffer[offset + 7] = (byte)'A'; buffer[offset + 8] = (byte)'['; Advance(9); WriteUTF8Chars(text); buffer = GetBuffer(3, out offset); buffer[offset + 0] = (byte)']'; buffer[offset + 1] = (byte)']'; buffer[offset + 2] = (byte)'>'; Advance(3); } private void WriteStartComment() { int offset; byte[] buffer = GetBuffer(4, out offset); buffer[offset + 0] = (byte)'<'; buffer[offset + 1] = (byte)'!'; buffer[offset + 2] = (byte)'-'; buffer[offset + 3] = (byte)'-'; Advance(4); } private void WriteEndComment() { int offset; byte[] buffer = GetBuffer(3, out offset); buffer[offset + 0] = (byte)'-'; buffer[offset + 1] = (byte)'-'; buffer[offset + 2] = (byte)'>'; Advance(3); } public override void WriteComment(string text) { WriteStartComment(); WriteUTF8Chars(text); WriteEndComment(); } public override void WriteStartElement(string prefix, string localName) { WriteByte('<'); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); } public override async Task WriteStartElementAsync(string prefix, string localName) { await WriteByteAsync('<').ConfigureAwait(false); if (prefix.Length != 0) { // This method calls into unsafe method which cannot run asyncly. WritePrefix(prefix); await WriteByteAsync(':').ConfigureAwait(false); } // This method calls into unsafe method which cannot run asyncly. WriteLocalName(localName); } public override void WriteStartElement(string prefix, XmlDictionaryString localName) { WriteStartElement(prefix, localName.Value); } public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteByte('<'); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); } public override void WriteEndStartElement(bool isEmpty) { if (!isEmpty) { WriteByte('>'); } else { WriteBytes('/', '>'); } } public override async Task WriteEndStartElementAsync(bool isEmpty) { if (!isEmpty) { await WriteByteAsync('>').ConfigureAwait(false); } else { await WriteBytesAsync('/', '>').ConfigureAwait(false); } } public override void WriteEndElement(string prefix, string localName) { WriteBytes('<', '/'); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); WriteByte('>'); } public override async Task WriteEndElementAsync(string prefix, string localName) { await WriteBytesAsync('<', '/').ConfigureAwait(false); if (prefix.Length != 0) { WritePrefix(prefix); await WriteByteAsync(':').ConfigureAwait(false); } WriteLocalName(localName); await WriteByteAsync('>').ConfigureAwait(false); } public override void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteBytes('<', '/'); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); WriteByte('>'); } private void WriteStartXmlnsAttribute() { int offset; byte[] buffer = GetBuffer(6, out offset); buffer[offset + 0] = (byte)' '; buffer[offset + 1] = (byte)'x'; buffer[offset + 2] = (byte)'m'; buffer[offset + 3] = (byte)'l'; buffer[offset + 4] = (byte)'n'; buffer[offset + 5] = (byte)'s'; Advance(6); _inAttribute = true; } public override void WriteXmlnsAttribute(string prefix, string ns) { WriteStartXmlnsAttribute(); if (prefix.Length != 0) { WriteByte(':'); WritePrefix(prefix); } WriteBytes('=', '"'); WriteEscapedText(ns); WriteEndAttribute(); } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { WriteXmlnsAttribute(prefix, ns.Value); } public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { WriteStartXmlnsAttribute(); if (prefixLength != 0) { WriteByte(':'); WritePrefix(prefixBuffer, prefixOffset, prefixLength); } WriteBytes('=', '"'); WriteEscapedText(nsBuffer, nsOffset, nsLength); WriteEndAttribute(); } public override void WriteStartAttribute(string prefix, string localName) { WriteByte(' '); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); WriteBytes('=', '"'); _inAttribute = true; } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName) { WriteStartAttribute(prefix, localName.Value); } public override void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteByte(' '); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); WriteBytes('=', '"'); _inAttribute = true; } public override void WriteEndAttribute() { WriteByte('"'); _inAttribute = false; } public override async Task WriteEndAttributeAsync() { await WriteByteAsync('"').ConfigureAwait(false); _inAttribute = false; } private void WritePrefix(string prefix) { if (prefix.Length == 1) { WriteUTF8Char(prefix[0]); } else { WriteUTF8Chars(prefix); } } private void WritePrefix(byte[] prefixBuffer, int prefixOffset, int prefixLength) { if (prefixLength == 1) { WriteUTF8Char((char)prefixBuffer[prefixOffset]); } else { WriteUTF8Chars(prefixBuffer, prefixOffset, prefixLength); } } private void WriteLocalName(string localName) { WriteUTF8Chars(localName); } private void WriteLocalName(byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteUTF8Chars(localNameBuffer, localNameOffset, localNameLength); } public override void WriteEscapedText(XmlDictionaryString s) { WriteEscapedText(s.Value); } public unsafe override void WriteEscapedText(string s) { int count = s.Length; if (count > 0) { fixed (char* chars = s) { UnsafeWriteEscapedText(chars, count); } } } public unsafe override void WriteEscapedText(char[] s, int offset, int count) { if (count > 0) { fixed (char* chars = &s[offset]) { UnsafeWriteEscapedText(chars, count); } } } private unsafe void UnsafeWriteEscapedText(char* chars, int count) { bool[] isEscapedChar = (_inAttribute ? _isEscapedAttributeChar : _isEscapedElementChar); int isEscapedCharLength = isEscapedChar.Length; int i = 0; for (int j = 0; j < count; j++) { char ch = chars[j]; if (ch < isEscapedCharLength && isEscapedChar[ch] || ch >= 0xFFFE) { UnsafeWriteUTF8Chars(chars + i, j - i); WriteCharEntity(ch); i = j + 1; } } UnsafeWriteUTF8Chars(chars + i, count - i); } public override void WriteEscapedText(byte[] chars, int offset, int count) { bool[] isEscapedChar = (_inAttribute ? _isEscapedAttributeChar : _isEscapedElementChar); int isEscapedCharLength = isEscapedChar.Length; int i = 0; for (int j = 0; j < count; j++) { byte ch = chars[offset + j]; if (ch < isEscapedCharLength && isEscapedChar[ch]) { WriteUTF8Chars(chars, offset + i, j - i); WriteCharEntity(ch); i = j + 1; } else if (ch == 239 && offset + j + 2 < count) { // 0xFFFE and 0xFFFF must be written as char entities // UTF8(239, 191, 190) = (char) 0xFFFE // UTF8(239, 191, 191) = (char) 0xFFFF byte ch2 = chars[offset + j + 1]; byte ch3 = chars[offset + j + 2]; if (ch2 == 191 && (ch3 == 190 || ch3 == 191)) { WriteUTF8Chars(chars, offset + i, j - i); WriteCharEntity(ch3 == 190 ? (char)0xFFFE : (char)0xFFFF); i = j + 3; } } } WriteUTF8Chars(chars, offset + i, count - i); } public void WriteText(int ch) { WriteUTF8Char(ch); } public override void WriteText(byte[] chars, int offset, int count) { WriteUTF8Chars(chars, offset, count); } public unsafe override void WriteText(char[] chars, int offset, int count) { if (count > 0) { fixed (char* pch = &chars[offset]) { UnsafeWriteUTF8Chars(pch, count); } } } public override void WriteText(string value) { WriteUTF8Chars(value); } public override void WriteText(XmlDictionaryString value) { WriteUTF8Chars(value.Value); } public void WriteLessThanCharEntity() { int offset; byte[] buffer = GetBuffer(4, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'l'; buffer[offset + 2] = (byte)'t'; buffer[offset + 3] = (byte)';'; Advance(4); } public void WriteGreaterThanCharEntity() { int offset; byte[] buffer = GetBuffer(4, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'g'; buffer[offset + 2] = (byte)'t'; buffer[offset + 3] = (byte)';'; Advance(4); } public void WriteAmpersandCharEntity() { int offset; byte[] buffer = GetBuffer(5, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'a'; buffer[offset + 2] = (byte)'m'; buffer[offset + 3] = (byte)'p'; buffer[offset + 4] = (byte)';'; Advance(5); } public void WriteApostropheCharEntity() { int offset; byte[] buffer = GetBuffer(6, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'a'; buffer[offset + 2] = (byte)'p'; buffer[offset + 3] = (byte)'o'; buffer[offset + 4] = (byte)'s'; buffer[offset + 5] = (byte)';'; Advance(6); } public void WriteQuoteCharEntity() { int offset; byte[] buffer = GetBuffer(6, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'q'; buffer[offset + 2] = (byte)'u'; buffer[offset + 3] = (byte)'o'; buffer[offset + 4] = (byte)'t'; buffer[offset + 5] = (byte)';'; Advance(6); } private void WriteHexCharEntity(int ch) { byte[] chars = GetCharEntityBuffer(); int offset = maxEntityLength; chars[--offset] = (byte)';'; offset -= ToBase16(chars, offset, (uint)ch); chars[--offset] = (byte)'x'; chars[--offset] = (byte)'#'; chars[--offset] = (byte)'&'; WriteUTF8Chars(chars, offset, maxEntityLength - offset); } public override void WriteCharEntity(int ch) { switch (ch) { case '<': WriteLessThanCharEntity(); break; case '>': WriteGreaterThanCharEntity(); break; case '&': WriteAmpersandCharEntity(); break; case '\'': WriteApostropheCharEntity(); break; case '"': WriteQuoteCharEntity(); break; default: WriteHexCharEntity(ch); break; } } private int ToBase16(byte[] chars, int offset, uint value) { int count = 0; do { count++; chars[--offset] = s_digits[(int)(value & 0x0F)]; value /= 16; } while (value != 0); return count; } public override void WriteBoolText(bool value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxBoolChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteDecimalText(decimal value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxDecimalChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteDoubleText(double value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxDoubleChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteFloatText(float value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxFloatChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteDateTimeText(DateTime value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxDateTimeChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteUniqueIdText(UniqueId value) { if (value.IsGuid) { int charCount = value.CharArrayLength; char[] chars = GetCharBuffer(charCount); value.ToCharArray(chars, 0); WriteText(chars, 0, charCount); } else { WriteEscapedText(value.ToString()); } } public override void WriteInt32Text(int value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxInt32Chars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteInt64Text(long value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxInt64Chars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteUInt64Text(ulong value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxUInt64Chars, out offset); Advance(XmlConverter.ToChars((double)value, buffer, offset)); } public override void WriteGuidText(Guid value) { WriteText(value.ToString()); } public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (trailByteCount > 0) { InternalWriteBase64Text(trailBytes, 0, trailByteCount); } InternalWriteBase64Text(buffer, offset, count); } public override async Task WriteBase64TextAsync(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (trailByteCount > 0) { await InternalWriteBase64TextAsync(trailBytes, 0, trailByteCount).ConfigureAwait(false); } await InternalWriteBase64TextAsync(buffer, offset, count).ConfigureAwait(false); } private void InternalWriteBase64Text(byte[] buffer, int offset, int count) { Base64Encoding encoding = XmlConverter.Base64Encoding; while (count >= 3) { int byteCount = Math.Min(bufferLength / 4 * 3, count - count % 3); int charCount = byteCount / 3 * 4; int charOffset; byte[] chars = GetBuffer(charCount, out charOffset); Advance(encoding.GetChars(buffer, offset, byteCount, chars, charOffset)); offset += byteCount; count -= byteCount; } if (count > 0) { int charOffset; byte[] chars = GetBuffer(4, out charOffset); Advance(encoding.GetChars(buffer, offset, count, chars, charOffset)); } } private async Task InternalWriteBase64TextAsync(byte[] buffer, int offset, int count) { Base64Encoding encoding = XmlConverter.Base64Encoding; while (count >= 3) { int byteCount = Math.Min(bufferLength / 4 * 3, count - count % 3); int charCount = byteCount / 3 * 4; int charOffset; BytesWithOffset bufferResult = await GetBufferAsync(charCount).ConfigureAwait(false); byte[] chars = bufferResult.Bytes; charOffset = bufferResult.Offset; Advance(encoding.GetChars(buffer, offset, byteCount, chars, charOffset)); offset += byteCount; count -= byteCount; } if (count > 0) { int charOffset; BytesWithOffset bufferResult = await GetBufferAsync(4).ConfigureAwait(false); byte[] chars = bufferResult.Bytes; charOffset = bufferResult.Offset; Advance(encoding.GetChars(buffer, offset, count, chars, charOffset)); } } public override void WriteTimeSpanText(TimeSpan value) { WriteText(XmlConvert.ToString(value)); } public override void WriteStartListText() { } public override void WriteListSeparator() { WriteByte(' '); } public override void WriteEndListText() { } public override void WriteQualifiedName(string prefix, XmlDictionaryString localName) { if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteText(localName); } } }
mit
dogecoin/dogecoin
src/primitives/transaction.cpp
5217
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "primitives/transaction.h" #include "hash.h" #include "tinyformat.h" #include "utilstrencodings.h" std::string COutPoint::ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n); } CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } std::string CTxIn::ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig)); else str += strprintf(", scriptSig=%s", HexStr(scriptSig).substr(0, 24)); if (nSequence != SEQUENCE_FINAL) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; scriptPubKey = scriptPubKeyIn; } std::string CTxOut::ToString() const { return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, HexStr(scriptPubKey).substr(0, 30)); } CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0) {} CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) {} uint256 CMutableTransaction::GetHash() const { return SerializeHash(*this, SER_GETHASH, SERIALIZE_TRANSACTION_NO_WITNESS); } uint256 CTransaction::ComputeHash() const { return SerializeHash(*this, SER_GETHASH, SERIALIZE_TRANSACTION_NO_WITNESS); } uint256 CTransaction::GetWitnessHash() const { if (!HasWitness()) { return GetHash(); } return SerializeHash(*this, SER_GETHASH, 0); } /* For backward compatibility, the hash is initialized to 0. TODO: remove the need for this default constructor entirely. */ CTransaction::CTransaction() : nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0), hash() {} CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), hash(ComputeHash()) {} CTransaction::CTransaction(CMutableTransaction &&tx) : nVersion(tx.nVersion), vin(std::move(tx.vin)), vout(std::move(tx.vout)), nLockTime(tx.nLockTime), hash(ComputeHash()) {} CAmount CTransaction::GetValueOut() const { CAmount nValueOut = 0; for (std::vector<CTxOut>::const_iterator it(vout.begin()); it != vout.end(); ++it) { nValueOut += it->nValue; if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut)) throw std::runtime_error(std::string(__func__) + ": value out of range"); } return nValueOut; } double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const { nTxSize = CalculateModifiedSize(nTxSize); if (nTxSize == 0) return 0.0; return dPriorityInputs / nTxSize; } unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const { // In order to avoid disincentivizing cleaning up the UTXO set we don't count // the constant overhead for each txin and up to 110 bytes of scriptSig (which // is enough to cover a compressed pubkey p2sh redemption) for priority. // Providing any more cleanup incentive than making additional inputs free would // risk encouraging people to create junk outputs to redeem later. if (nTxSize == 0) nTxSize = (GetTransactionWeight(*this) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR; for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it) { unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size()); if (nTxSize > offset) nTxSize -= offset; } return nTxSize; } unsigned int CTransaction::GetTotalSize() const { return ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION); } std::string CTransaction::ToString() const { std::string str; str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n", GetHash().ToString().substr(0,10), nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].scriptWitness.ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } int64_t GetTransactionWeight(const CTransaction& tx) { return ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR -1) + ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); }
mit
sashberd/cdnjs
ajax/libs/ionicons/4.0.0-6/collection/icon/svg/md-arrow-round-back.js
387
loadIonicon('<svg width="1em" height="1em" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M401.4 224h-214l83-79.4c11.9-12.5 11.9-32.7 0-45.2s-31.2-12.5-43.2 0L89 233.4c-6 5.8-9 13.7-9 22.4v.4c0 8.7 3 16.6 9 22.4l138.1 134c12 12.5 31.3 12.5 43.2 0 11.9-12.5 11.9-32.7 0-45.2l-83-79.4h214c16.9 0 30.6-14.3 30.6-32 .1-18-13.6-32-30.5-32z"/></svg>','md-arrow-round-back');
mit
xissburg/XDefrac
boost/math/tools/detail/polynomial_horner1_2.hpp
1003
// (C) Copyright John Maddock 2007. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // This file is machine generated, do not edit by hand // Polynomial evaluation using Horners rule #ifndef BOOST_MATH_TOOLS_POLY_EVAL_2_HPP #define BOOST_MATH_TOOLS_POLY_EVAL_2_HPP namespace boost{ namespace math{ namespace tools{ namespace detail{ template <class T, class V> inline V evaluate_polynomial_c_imp(const T*, const V&, const mpl::int_<0>*) { return static_cast<V>(0); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V&, const mpl::int_<1>*) { return static_cast<V>(a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<2>*) { return static_cast<V>(a[1] * x + a[0]); } }}}} // namespaces #endif // include guard
mit
ViktorHofer/corefx
src/System.Reflection.Metadata/tests/TestUtilities/DiffUtil.cs
10331
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace System.Reflection.Metadata.Tests { public class DiffUtil { private enum EditKind { /// <summary> /// No change. /// </summary> None = 0, /// <summary> /// Node value was updated. /// </summary> Update = 1, /// <summary> /// Node was inserted. /// </summary> Insert = 2, /// <summary> /// Node was deleted. /// </summary> Delete = 3, } private class LCS<T> : LongestCommonSubsequence<IList<T>> { public static readonly LCS<T> Default = new LCS<T>(EqualityComparer<T>.Default); private readonly IEqualityComparer<T> _comparer; public LCS(IEqualityComparer<T> comparer) { _comparer = comparer; } protected override bool ItemsEqual(IList<T> sequenceA, int indexA, IList<T> sequenceB, int indexB) { return _comparer.Equals(sequenceA[indexA], sequenceB[indexB]); } public IEnumerable<string> CalculateDiff(IList<T> sequenceA, IList<T> sequenceB, Func<T, string> toString) { foreach (var edit in base.GetEdits(sequenceA, sequenceA.Count, sequenceB, sequenceB.Count).Reverse()) { switch (edit.Kind) { case EditKind.Delete: yield return "--> " + toString(sequenceA[edit.IndexA]); break; case EditKind.Insert: yield return "++> " + toString(sequenceB[edit.IndexB]); break; case EditKind.Update: yield return " " + toString(sequenceB[edit.IndexB]); break; } } } } public static string DiffReport<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer, Func<T, string> toString, string separator) { var lcs = (comparer != null) ? new LCS<T>(comparer) : LCS<T>.Default; toString = toString ?? new Func<T, string>(obj => obj.ToString()); IList<T> expectedList = expected as IList<T> ?? new List<T>(expected); IList<T> actualList = actual as IList<T> ?? new List<T>(actual); return string.Join(separator, lcs.CalculateDiff(expectedList, actualList, toString)); } private static readonly char[] s_LineSplitChars = new[] { '\r', '\n' }; public static string[] Lines(string s) { return s.Split(s_LineSplitChars, StringSplitOptions.RemoveEmptyEntries); } public static string DiffReport(string expected, string actual) { var exlines = Lines(expected); var aclines = Lines(actual); return DiffReport(exlines, aclines, null, null, Environment.NewLine); } /// <summary> /// Calculates Longest Common Subsequence. /// </summary> private abstract class LongestCommonSubsequence<TSequence> { protected struct Edit { public readonly EditKind Kind; public readonly int IndexA; public readonly int IndexB; internal Edit(EditKind kind, int indexA, int indexB) { this.Kind = kind; this.IndexA = indexA; this.IndexB = indexB; } } private const int DeleteCost = 1; private const int InsertCost = 1; private const int UpdateCost = 2; protected abstract bool ItemsEqual(TSequence sequenceA, int indexA, TSequence sequenceB, int indexB); protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB) { int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB); int i = lengthA; int j = lengthB; while (i != 0 && j != 0) { if (d[i, j] == d[i - 1, j] + DeleteCost) { i--; } else if (d[i, j] == d[i, j - 1] + InsertCost) { j--; } else { i--; j--; yield return new KeyValuePair<int, int>(i, j); } } } protected IEnumerable<Edit> GetEdits(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB) { int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB); int i = lengthA; int j = lengthB; while (i != 0 && j != 0) { if (d[i, j] == d[i - 1, j] + DeleteCost) { i--; yield return new Edit(EditKind.Delete, i, -1); } else if (d[i, j] == d[i, j - 1] + InsertCost) { j--; yield return new Edit(EditKind.Insert, -1, j); } else { i--; j--; yield return new Edit(EditKind.Update, i, j); } } while (i > 0) { i--; yield return new Edit(EditKind.Delete, i, -1); } while (j > 0) { j--; yield return new Edit(EditKind.Insert, -1, j); } } /// <summary> /// Returns a distance [0..1] of the specified sequences. /// The smaller distance the more of their elements match. /// </summary> /// <summary> /// Returns a distance [0..1] of the specified sequences. /// The smaller distance the more of their elements match. /// </summary> protected double ComputeDistance(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB) { Debug.Assert(lengthA >= 0 && lengthB >= 0); if (lengthA == 0 || lengthB == 0) { return (lengthA == lengthB) ? 0.0 : 1.0; } int lcsLength = 0; foreach (var pair in GetMatchingPairs(sequenceA, lengthA, sequenceB, lengthB)) { lcsLength++; } int max = Math.Max(lengthA, lengthB); Debug.Assert(lcsLength <= max); return 1.0 - (double)lcsLength / (double)max; } /// <summary> /// Calculates costs of all paths in an edit graph starting from vertex (0,0) and ending in vertex (lengthA, lengthB). /// </summary> /// <remarks> /// The edit graph for A and B has a vertex at each point in the grid (i,j), i in [0, lengthA] and j in [0, lengthB]. /// /// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph. /// Horizontal edges connect each vertex to its right neighbor. /// Vertical edges connect each vertex to the neighbor below it. /// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if <see cref="ItemsEqual"/>(sequenceA[i-1],sequenceB[j-1]) is true. /// /// Editing starts with S = []. /// Move along horizontal edge (i-1,j)-(i,j) represents the fact that sequenceA[i-1] is not added to S. /// Move along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1] to S. /// Move along diagonal edge (i-1,j-1)-(i,j) represents an addition of sequenceB[j-1] to S via an acceptable /// change of sequenceA[i-1] to sequenceB[j-1]. /// /// In every vertex the cheapest outgoing edge is selected. /// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common subsequence. /// </remarks> private int[,] ComputeCostMatrix(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB) { var la = lengthA + 1; var lb = lengthB + 1; // TODO: Optimization possible: O(ND) time, O(N) space // EUGENE W. MYERS: An O(ND) Difference Algorithm and Its Variations var d = new int[la, lb]; d[0, 0] = 0; for (int i = 1; i <= lengthA; i++) { d[i, 0] = d[i - 1, 0] + DeleteCost; } for (int j = 1; j <= lengthB; j++) { d[0, j] = d[0, j - 1] + InsertCost; } for (int i = 1; i <= lengthA; i++) { for (int j = 1; j <= lengthB; j++) { int m1 = d[i - 1, j - 1] + (ItemsEqual(sequenceA, i - 1, sequenceB, j - 1) ? 0 : UpdateCost); int m2 = d[i - 1, j] + DeleteCost; int m3 = d[i, j - 1] + InsertCost; d[i, j] = Math.Min(Math.Min(m1, m2), m3); } } return d; } } } }
mit
Econa77/fastlane
scan/lib/scan.rb
392
require_relative 'scan/manager' require_relative 'scan/options' require_relative 'scan/runner' require_relative 'scan/detect_values' require_relative 'scan/test_command_generator' require_relative 'scan/xcpretty_reporter_options_generator.rb' require_relative 'scan/test_result_parser' require_relative 'scan/error_handler' require_relative 'scan/slack_poster' require_relative 'scan/module'
mit
owenzoocha/hbm
sites/all/libraries/predis/lib/tests/Predis/Command/StringGetMultipleTest.php
2457
<?php /* * This file is part of the Predis package. * * (c) Daniele Alessandri <suppakilla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Predis\Command; /** * @group commands * @group realm-string */ class StringGetMultipleTest extends PredisCommandTestCase { /** * {@inheritdoc} */ protected function getExpectedCommand() { return 'Predis\Command\StringGetMultiple'; } /** * {@inheritdoc} */ protected function getExpectedId() { return 'MGET'; } /** * @group disconnected */ public function testFilterArguments() { $arguments = array('key1', 'key2', 'key3'); $expected = array('key1', 'key2', 'key3'); $command = $this->getCommand(); $command->setArguments($arguments); $this->assertSame($expected, $command->getArguments()); } /** * @group disconnected */ public function testFilterArgumentsAsSingleArray() { $arguments = array(array('key1', 'key2', 'key3')); $expected = array('key1', 'key2', 'key3'); $command = $this->getCommand(); $command->setArguments($arguments); $this->assertSame($expected, $command->getArguments()); } /** * @group disconnected */ public function testParseResponse() { $raw = array('value1', 'value2', 'value3'); $expected = array('value1', 'value2', 'value3'); $command = $this->getCommand(); $this->assertSame($expected, $command->parseResponse($raw)); } /** * @group connected */ public function testReturnsArrayOfValues() { $redis = $this->getClient(); $redis->set('foo', 'bar'); $redis->set('hoge', 'piyo'); $this->assertSame(array('bar', 'piyo'), $redis->mget('foo', 'hoge')); } /** * @group connected */ public function testReturnsArrayWithNullValuesOnNonExistingKeys() { $redis = $this->getClient(); $this->assertSame(array(null, null), $redis->mget('foo', 'hoge')); } /** * @group connected */ public function testDoesNotThrowExceptionOnWrongType() { $redis = $this->getClient(); $redis->lpush('metavars', 'foo'); $this->assertSame(array(null), $redis->mget('metavars')); } }
gpl-2.0
timshen91/gcc
libstdc++-v3/python/libstdcxx/v6/xmethods.py
21345
# Xmethods for libstdc++. # Copyright (C) 2014-2015 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gdb import gdb.xmethod import re matcher_name_prefix = 'libstdc++::' def get_bool_type(): return gdb.lookup_type('bool') def get_std_size_type(): return gdb.lookup_type('std::size_t') class LibStdCxxXMethod(gdb.xmethod.XMethod): def __init__(self, name, worker_class): gdb.xmethod.XMethod.__init__(self, name) self.worker_class = worker_class # Xmethods for std::array class ArrayWorkerBase(gdb.xmethod.XMethodWorker): def __init__(self, val_type, size): self._val_type = val_type self._size = size def null_value(self): nullptr = gdb.parse_and_eval('(void *) 0') return nullptr.cast(self._val_type.pointer()).dereference() class ArraySizeWorker(ArrayWorkerBase): def __init__(self, val_type, size): ArrayWorkerBase.__init__(self, val_type, size) def get_arg_types(self): return None def get_result_type(self, obj): return get_std_size_type() def __call__(self, obj): return self._size class ArrayEmptyWorker(ArrayWorkerBase): def __init__(self, val_type, size): ArrayWorkerBase.__init__(self, val_type, size) def get_arg_types(self): return None def get_result_type(self, obj): return get_bool_type() def __call__(self, obj): return (int(self._size) == 0) class ArrayFrontWorker(ArrayWorkerBase): def __init__(self, val_type, size): ArrayWorkerBase.__init__(self, val_type, size) def get_arg_types(self): return None def get_result_type(self, obj): return self._val_type def __call__(self, obj): if int(self._size) > 0: return obj['_M_elems'][0] else: return self.null_value() class ArrayBackWorker(ArrayWorkerBase): def __init__(self, val_type, size): ArrayWorkerBase.__init__(self, val_type, size) def get_arg_types(self): return None def get_result_type(self, obj): return self._val_type def __call__(self, obj): if int(self._size) > 0: return obj['_M_elems'][self._size - 1] else: return self.null_value() class ArrayAtWorker(ArrayWorkerBase): def __init__(self, val_type, size): ArrayWorkerBase.__init__(self, val_type, size) def get_arg_types(self): return get_std_size_type() def get_result_type(self, obj, index): return self._val_type def __call__(self, obj, index): if int(index) >= int(self._size): raise IndexError('Array index "%d" should not be >= %d.' % ((int(index), self._size))) return obj['_M_elems'][index] class ArraySubscriptWorker(ArrayWorkerBase): def __init__(self, val_type, size): ArrayWorkerBase.__init__(self, val_type, size) def get_arg_types(self): return get_std_size_type() def get_result_type(self, obj, index): return self._val_type def __call__(self, obj, index): if int(self._size) > 0: return obj['_M_elems'][index] else: return self.null_value() class ArrayMethodsMatcher(gdb.xmethod.XMethodMatcher): def __init__(self): gdb.xmethod.XMethodMatcher.__init__(self, matcher_name_prefix + 'array') self._method_dict = { 'size': LibStdCxxXMethod('size', ArraySizeWorker), 'empty': LibStdCxxXMethod('empty', ArrayEmptyWorker), 'front': LibStdCxxXMethod('front', ArrayFrontWorker), 'back': LibStdCxxXMethod('back', ArrayBackWorker), 'at': LibStdCxxXMethod('at', ArrayAtWorker), 'operator[]': LibStdCxxXMethod('operator[]', ArraySubscriptWorker), } self.methods = [self._method_dict[m] for m in self._method_dict] def match(self, class_type, method_name): if not re.match('^std::array<.*>$', class_type.tag): return None method = self._method_dict.get(method_name) if method is None or not method.enabled: return None try: value_type = class_type.template_argument(0) size = class_type.template_argument(1) except: return None return method.worker_class(value_type, size) # Xmethods for std::deque class DequeWorkerBase(gdb.xmethod.XMethodWorker): def __init__(self, val_type): self._val_type = val_type self._bufsize = (512 / val_type.sizeof) or 1 def size(self, obj): first_node = obj['_M_impl']['_M_start']['_M_node'] last_node = obj['_M_impl']['_M_finish']['_M_node'] cur = obj['_M_impl']['_M_finish']['_M_cur'] first = obj['_M_impl']['_M_finish']['_M_first'] return (last_node - first_node) * self._bufsize + (cur - first) def index(self, obj, index): first_node = obj['_M_impl']['_M_start']['_M_node'] index_node = first_node + index / self._bufsize return index_node[0][index % self._bufsize] class DequeEmptyWorker(DequeWorkerBase): def get_arg_types(self): return None def get_result_type(self, obj): return get_bool_type() def __call__(self, obj): return (obj['_M_impl']['_M_start']['_M_cur'] == obj['_M_impl']['_M_finish']['_M_cur']) class DequeSizeWorker(DequeWorkerBase): def get_arg_types(self): return None def get_result_type(self, obj): return get_std_size_type() def __call__(self, obj): return self.size(obj) class DequeFrontWorker(DequeWorkerBase): def get_arg_types(self): return None def get_result_type(self, obj): return self._val_type def __call__(self, obj): return obj['_M_impl']['_M_start']['_M_cur'][0] class DequeBackWorker(DequeWorkerBase): def get_arg_types(self): return None def get_result_type(self, obj): return self._val_type def __call__(self, obj): if (obj['_M_impl']['_M_finish']['_M_cur'] == obj['_M_impl']['_M_finish']['_M_first']): prev_node = obj['_M_impl']['_M_finish']['_M_node'] - 1 return prev_node[0][self._bufsize - 1] else: return obj['_M_impl']['_M_finish']['_M_cur'][-1] class DequeSubscriptWorker(DequeWorkerBase): def get_arg_types(self): return get_std_size_type() def get_result_type(self, obj, subscript): return self._val_type def __call__(self, obj, subscript): return self.index(obj, subscript) class DequeAtWorker(DequeWorkerBase): def get_arg_types(self): return get_std_size_type() def get_result_type(self, obj, index): return self._val_type def __call__(self, obj, index): deque_size = int(self.size(obj)) if int(index) >= deque_size: raise IndexError('Deque index "%d" should not be >= %d.' % (int(index), deque_size)) else: return self.index(obj, index) class DequeMethodsMatcher(gdb.xmethod.XMethodMatcher): def __init__(self): gdb.xmethod.XMethodMatcher.__init__(self, matcher_name_prefix + 'deque') self._method_dict = { 'empty': LibStdCxxXMethod('empty', DequeEmptyWorker), 'size': LibStdCxxXMethod('size', DequeSizeWorker), 'front': LibStdCxxXMethod('front', DequeFrontWorker), 'back': LibStdCxxXMethod('back', DequeBackWorker), 'operator[]': LibStdCxxXMethod('operator[]', DequeSubscriptWorker), 'at': LibStdCxxXMethod('at', DequeAtWorker) } self.methods = [self._method_dict[m] for m in self._method_dict] def match(self, class_type, method_name): if not re.match('^std::deque<.*>$', class_type.tag): return None method = self._method_dict.get(method_name) if method is None or not method.enabled: return None return method.worker_class(class_type.template_argument(0)) # Xmethods for std::forward_list class ForwardListWorkerBase(gdb.xmethod.XMethodMatcher): def __init__(self, val_type, node_type): self._val_type = val_type self._node_type = node_type def get_arg_types(self): return None class ForwardListEmptyWorker(ForwardListWorkerBase): def get_result_type(self, obj): return get_bool_type() def __call__(self, obj): return obj['_M_impl']['_M_head']['_M_next'] == 0 class ForwardListFrontWorker(ForwardListWorkerBase): def get_result_type(self, obj): return self._val_type def __call__(self, obj): node = obj['_M_impl']['_M_head']['_M_next'].cast(self._node_type) val_address = node['_M_storage']['_M_storage'].address return val_address.cast(self._val_type.pointer()).dereference() class ForwardListMethodsMatcher(gdb.xmethod.XMethodMatcher): def __init__(self): matcher_name = matcher_name_prefix + 'forward_list' gdb.xmethod.XMethodMatcher.__init__(self, matcher_name) self._method_dict = { 'empty': LibStdCxxXMethod('empty', ForwardListEmptyWorker), 'front': LibStdCxxXMethod('front', ForwardListFrontWorker) } self.methods = [self._method_dict[m] for m in self._method_dict] def match(self, class_type, method_name): if not re.match('^std::forward_list<.*>$', class_type.tag): return None method = self._method_dict.get(method_name) if method is None or not method.enabled: return None val_type = class_type.template_argument(0) node_type = gdb.lookup_type(str(class_type) + '::_Node').pointer() return method.worker_class(val_type, node_type) # Xmethods for std::list class ListWorkerBase(gdb.xmethod.XMethodWorker): def __init__(self, val_type, node_type): self._val_type = val_type self._node_type = node_type def get_arg_types(self): return None class ListEmptyWorker(ListWorkerBase): def get_result_type(self, obj): return get_bool_type() def __call__(self, obj): base_node = obj['_M_impl']['_M_node'] if base_node['_M_next'] == base_node.address: return True else: return False class ListSizeWorker(ListWorkerBase): def get_result_type(self, obj): return get_std_size_type() def __call__(self, obj): begin_node = obj['_M_impl']['_M_node']['_M_next'] end_node = obj['_M_impl']['_M_node'].address size = 0 while begin_node != end_node: begin_node = begin_node['_M_next'] size += 1 return size class ListFrontWorker(ListWorkerBase): def get_result_type(self, obj): return self._val_type def __call__(self, obj): node = obj['_M_impl']['_M_node']['_M_next'].cast(self._node_type) return node['_M_data'] class ListBackWorker(ListWorkerBase): def get_result_type(self, obj): return self._val_type def __call__(self, obj): prev_node = obj['_M_impl']['_M_node']['_M_prev'].cast(self._node_type) return prev_node['_M_data'] class ListMethodsMatcher(gdb.xmethod.XMethodMatcher): def __init__(self): gdb.xmethod.XMethodMatcher.__init__(self, matcher_name_prefix + 'list') self._method_dict = { 'empty': LibStdCxxXMethod('empty', ListEmptyWorker), 'size': LibStdCxxXMethod('size', ListSizeWorker), 'front': LibStdCxxXMethod('front', ListFrontWorker), 'back': LibStdCxxXMethod('back', ListBackWorker) } self.methods = [self._method_dict[m] for m in self._method_dict] def match(self, class_type, method_name): if not re.match('^std::list<.*>$', class_type.tag): return None method = self._method_dict.get(method_name) if method is None or not method.enabled: return None val_type = class_type.template_argument(0) node_type = gdb.lookup_type(str(class_type) + '::_Node').pointer() return method.worker_class(val_type, node_type) # Xmethods for std::vector class VectorWorkerBase(gdb.xmethod.XMethodWorker): def __init__(self, val_type): self._val_type = val_type def size(self, obj): if self._val_type.code == gdb.TYPE_CODE_BOOL: start = obj['_M_impl']['_M_start']['_M_p'] finish = obj['_M_impl']['_M_finish']['_M_p'] finish_offset = obj['_M_impl']['_M_finish']['_M_offset'] bit_size = start.dereference().type.sizeof * 8 return (finish - start) * bit_size + finish_offset else: return obj['_M_impl']['_M_finish'] - obj['_M_impl']['_M_start'] def get(self, obj, index): if self._val_type.code == gdb.TYPE_CODE_BOOL: start = obj['_M_impl']['_M_start']['_M_p'] bit_size = start.dereference().type.sizeof * 8 valp = start + index / bit_size offset = index % bit_size return (valp.dereference() & (1 << offset)) > 0 else: return obj['_M_impl']['_M_start'][index] class VectorEmptyWorker(VectorWorkerBase): def get_arg_types(self): return None def get_result_type(self, obj): return get_bool_type() def __call__(self, obj): return int(self.size(obj)) == 0 class VectorSizeWorker(VectorWorkerBase): def get_arg_types(self): return None def get_result_type(self, obj): return get_std_size_type() def __call__(self, obj): return self.size(obj) class VectorFrontWorker(VectorWorkerBase): def get_arg_types(self): return None def get_result_type(self, obj): return self._val_type def __call__(self, obj): return self.get(obj, 0) class VectorBackWorker(VectorWorkerBase): def get_arg_types(self): return None def get_result_type(self, obj): return self._val_type def __call__(self, obj): return self.get(obj, int(self.size(obj)) - 1) class VectorAtWorker(VectorWorkerBase): def get_arg_types(self): return get_std_size_type() def get_result_type(self, obj, index): return self._val_type def __call__(self, obj, index): size = int(self.size(obj)) if int(index) >= size: raise IndexError('Vector index "%d" should not be >= %d.' % ((int(index), size))) return self.get(obj, int(index)) class VectorSubscriptWorker(VectorWorkerBase): def get_arg_types(self): return get_std_size_type() def get_result_type(self, obj, subscript): return self._val_type def __call__(self, obj, subscript): return self.get(obj, int(subscript)) class VectorMethodsMatcher(gdb.xmethod.XMethodMatcher): def __init__(self): gdb.xmethod.XMethodMatcher.__init__(self, matcher_name_prefix + 'vector') self._method_dict = { 'size': LibStdCxxXMethod('size', VectorSizeWorker), 'empty': LibStdCxxXMethod('empty', VectorEmptyWorker), 'front': LibStdCxxXMethod('front', VectorFrontWorker), 'back': LibStdCxxXMethod('back', VectorBackWorker), 'at': LibStdCxxXMethod('at', VectorAtWorker), 'operator[]': LibStdCxxXMethod('operator[]', VectorSubscriptWorker), } self.methods = [self._method_dict[m] for m in self._method_dict] def match(self, class_type, method_name): if not re.match('^std::vector<.*>$', class_type.tag): return None method = self._method_dict.get(method_name) if method is None or not method.enabled: return None return method.worker_class(class_type.template_argument(0)) # Xmethods for associative containers class AssociativeContainerWorkerBase(gdb.xmethod.XMethodWorker): def __init__(self, unordered): self._unordered = unordered def node_count(self, obj): if self._unordered: return obj['_M_h']['_M_element_count'] else: return obj['_M_t']['_M_impl']['_M_node_count'] def get_arg_types(self): return None class AssociativeContainerEmptyWorker(AssociativeContainerWorkerBase): def get_result_type(self, obj): return get_bool_type() def __call__(self, obj): return int(self.node_count(obj)) == 0 class AssociativeContainerSizeWorker(AssociativeContainerWorkerBase): def get_result_type(self, obj): return get_std_size_type() def __call__(self, obj): return self.node_count(obj) class AssociativeContainerMethodsMatcher(gdb.xmethod.XMethodMatcher): def __init__(self, name): gdb.xmethod.XMethodMatcher.__init__(self, matcher_name_prefix + name) self._name = name self._method_dict = { 'size': LibStdCxxXMethod('size', AssociativeContainerSizeWorker), 'empty': LibStdCxxXMethod('empty', AssociativeContainerEmptyWorker), } self.methods = [self._method_dict[m] for m in self._method_dict] def match(self, class_type, method_name): if not re.match('^std::%s<.*>$' % self._name, class_type.tag): return None method = self._method_dict.get(method_name) if method is None or not method.enabled: return None unordered = 'unordered' in self._name return method.worker_class(unordered) # Xmethods for std::unique_ptr class UniquePtrGetWorker(gdb.xmethod.XMethodWorker): def __init__(self, elem_type): self._elem_type = elem_type def get_arg_types(self): return None def get_result_type(self, obj): return self._elem_type.pointer() def __call__(self, obj): return obj['_M_t']['_M_head_impl'] class UniquePtrDerefWorker(UniquePtrGetWorker): def __init__(self, elem_type): UniquePtrGetWorker.__init__(self, elem_type) def get_result_type(self, obj): return self._elem_type def __call__(self, obj): return UniquePtrGetWorker.__call__(self, obj).dereference() class UniquePtrMethodsMatcher(gdb.xmethod.XMethodMatcher): def __init__(self): gdb.xmethod.XMethodMatcher.__init__(self, matcher_name_prefix + 'unique_ptr') self._method_dict = { 'get': LibStdCxxXMethod('get', UniquePtrGetWorker), 'operator->': LibStdCxxXMethod('operator->', UniquePtrGetWorker), 'operator*': LibStdCxxXMethod('operator*', UniquePtrDerefWorker), } self.methods = [self._method_dict[m] for m in self._method_dict] def match(self, class_type, method_name): if not re.match('^std::unique_ptr<.*>$', class_type.tag): return None method = self._method_dict.get(method_name) if method is None or not method.enabled: return None return method.worker_class(class_type.template_argument(0)) def register_libstdcxx_xmethods(locus): gdb.xmethod.register_xmethod_matcher(locus, ArrayMethodsMatcher()) gdb.xmethod.register_xmethod_matcher(locus, ForwardListMethodsMatcher()) gdb.xmethod.register_xmethod_matcher(locus, DequeMethodsMatcher()) gdb.xmethod.register_xmethod_matcher(locus, ListMethodsMatcher()) gdb.xmethod.register_xmethod_matcher(locus, VectorMethodsMatcher()) gdb.xmethod.register_xmethod_matcher( locus, AssociativeContainerMethodsMatcher('set')) gdb.xmethod.register_xmethod_matcher( locus, AssociativeContainerMethodsMatcher('map')) gdb.xmethod.register_xmethod_matcher( locus, AssociativeContainerMethodsMatcher('multiset')) gdb.xmethod.register_xmethod_matcher( locus, AssociativeContainerMethodsMatcher('multimap')) gdb.xmethod.register_xmethod_matcher( locus, AssociativeContainerMethodsMatcher('unordered_set')) gdb.xmethod.register_xmethod_matcher( locus, AssociativeContainerMethodsMatcher('unordered_map')) gdb.xmethod.register_xmethod_matcher( locus, AssociativeContainerMethodsMatcher('unordered_multiset')) gdb.xmethod.register_xmethod_matcher( locus, AssociativeContainerMethodsMatcher('unordered_multimap')) gdb.xmethod.register_xmethod_matcher(locus, UniquePtrMethodsMatcher())
gpl-2.0
vosgus/phpmyadmin
libraries/plugins/import/ImportXml.php
10723
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * XML import plugin for phpMyAdmin * * @todo Improve efficiency * @package PhpMyAdmin-Import * @subpackage XML */ namespace PMA\libraries\plugins\import; use PMA\libraries\properties\plugins\ImportPluginProperties; use PMA; use PMA\libraries\plugins\ImportPlugin; use SimpleXMLElement; /** * Handles the import for the XML format * * @package PhpMyAdmin-Import * @subpackage XML */ class ImportXml extends ImportPlugin { /** * Constructor */ public function __construct() { $this->setProperties(); } /** * Sets the import plugin properties. * Called in the constructor. * * @return void */ protected function setProperties() { $importPluginProperties = new ImportPluginProperties(); $importPluginProperties->setText(__('XML')); $importPluginProperties->setExtension('xml'); $importPluginProperties->setMimeType('text/xml'); $importPluginProperties->setOptions(array()); $importPluginProperties->setOptionsText(__('Options')); $this->properties = $importPluginProperties; } /** * Handles the whole import logic * * @param array &$sql_data 2-element array with sql data * * @return void */ public function doImport(&$sql_data = array()) { global $error, $timeout_passed, $finished, $db; $i = 0; $len = 0; $buffer = ""; /** * Read in the file via PMA_importGetNextChunk so that * it can process compressed files */ while (!($finished && $i >= $len) && !$error && !$timeout_passed) { $data = PMA_importGetNextChunk(); if ($data === false) { /* subtract data we didn't handle yet and stop processing */ $GLOBALS['offset'] -= strlen($buffer); break; } elseif ($data === true) { /* Handle rest of buffer */ } else { /* Append new data to buffer */ $buffer .= $data; unset($data); } } unset($data); /** * Disable loading of external XML entities. */ libxml_disable_entity_loader(); /** * Load the XML string * * The option LIBXML_COMPACT is specified because it can * result in increased performance without the need to * alter the code in any way. It's basically a freebee. */ $xml = @simplexml_load_string($buffer, "SimpleXMLElement", LIBXML_COMPACT); unset($buffer); /** * The XML was malformed */ if ($xml === false) { PMA\libraries\Message::error( __( 'The XML file specified was either malformed or incomplete.' . ' Please correct the issue and try again.' ) ) ->display(); unset($xml); $GLOBALS['finished'] = false; return; } /** * Table accumulator */ $tables = array(); /** * Row accumulator */ $rows = array(); /** * Temp arrays */ $tempRow = array(); $tempCells = array(); /** * CREATE code included (by default: no) */ $struct_present = false; /** * Analyze the data in each table */ $namespaces = $xml->getNameSpaces(true); /** * Get the database name, collation and charset */ $db_attr = $xml->children($namespaces['pma']) ->{'structure_schemas'}->{'database'}; if ($db_attr instanceof SimpleXMLElement) { $db_attr = $db_attr->attributes(); $db_name = (string)$db_attr['name']; $collation = (string)$db_attr['collation']; $charset = (string)$db_attr['charset']; } else { /** * If the structure section is not present * get the database name from the data section */ $db_attr = $xml->children() ->attributes(); $db_name = (string)$db_attr['name']; $collation = null; $charset = null; } /** * The XML was malformed */ if ($db_name === null) { PMA\libraries\Message::error( __( 'The XML file specified was either malformed or incomplete.' . ' Please correct the issue and try again.' ) ) ->display(); unset($xml); $GLOBALS['finished'] = false; return; } /** * Retrieve the structure information */ if (isset($namespaces['pma'])) { /** * Get structures for all tables * * @var SimpleXMLElement $struct */ $struct = $xml->children($namespaces['pma']); $create = array(); /** @var SimpleXMLElement $val1 */ foreach ($struct as $val1) { /** @var SimpleXMLElement $val2 */ foreach ($val1 as $val2) { // Need to select the correct database for the creation of // tables, views, triggers, etc. /** * @todo Generating a USE here blocks importing of a table * into another database. */ $attrs = $val2->attributes(); $create[] = "USE " . PMA\libraries\Util::backquote( $attrs["name"] ); foreach ($val2 as $val3) { /** * Remove the extra cosmetic spacing */ $val3 = str_replace(" ", "", (string)$val3); $create[] = $val3; } } } $struct_present = true; } /** * Move down the XML tree to the actual data */ $xml = $xml->children() ->children(); $data_present = false; /** * Only attempt to analyze/collect data if there is data present */ if ($xml && @count($xml->children())) { $data_present = true; /** * Process all database content */ foreach ($xml as $v1) { $tbl_attr = $v1->attributes(); $isInTables = false; $num_tables = count($tables); for ($i = 0; $i < $num_tables; ++$i) { if (!strcmp($tables[$i][TBL_NAME], (string)$tbl_attr['name'])) { $isInTables = true; break; } } if (!$isInTables) { $tables[] = array((string)$tbl_attr['name']); } foreach ($v1 as $v2) { $row_attr = $v2->attributes(); if (!array_search((string)$row_attr['name'], $tempRow)) { $tempRow[] = (string)$row_attr['name']; } $tempCells[] = (string)$v2; } $rows[] = array((string)$tbl_attr['name'], $tempRow, $tempCells); $tempRow = array(); $tempCells = array(); } unset($tempRow); unset($tempCells); unset($xml); /** * Bring accumulated rows into the corresponding table */ $num_tables = count($tables); for ($i = 0; $i < $num_tables; ++$i) { $num_rows = count($rows); for ($j = 0; $j < $num_rows; ++$j) { if (!strcmp($tables[$i][TBL_NAME], $rows[$j][TBL_NAME])) { if (!isset($tables[$i][COL_NAMES])) { $tables[$i][] = $rows[$j][COL_NAMES]; } $tables[$i][ROWS][] = $rows[$j][ROWS]; } } } unset($rows); if (!$struct_present) { $analyses = array(); $len = count($tables); for ($i = 0; $i < $len; ++$i) { $analyses[] = PMA_analyzeTable($tables[$i]); } } } unset($xml); unset($tempCells); unset($rows); /** * Only build SQL from data if there is data present */ if ($data_present) { /** * Set values to NULL if they were not present * to maintain PMA_buildSQL() call integrity */ if (!isset($analyses)) { $analyses = null; if (!$struct_present) { $create = null; } } } /** * string $db_name (no backquotes) * * array $table = array(table_name, array() column_names, array()() rows) * array $tables = array of "$table"s * * array $analysis = array(array() column_types, array() column_sizes) * array $analyses = array of "$analysis"s * * array $create = array of SQL strings * * array $options = an associative array of options */ /* Set database name to the currently selected one, if applicable */ if (strlen($db)) { /* Override the database name in the XML file, if one is selected */ $db_name = $db; $options = array('create_db' => false); } else { if ($db_name === null) { $db_name = 'XML_DB'; } /* Set database collation/charset */ $options = array( 'db_collation' => $collation, 'db_charset' => $charset, ); } /* Created and execute necessary SQL statements from data */ PMA_buildSQL($db_name, $tables, $analyses, $create, $options, $sql_data); unset($analyses); unset($tables); unset($create); /* Commit any possible data in buffers */ PMA_importRunQuery('', '', $sql_data); } }
gpl-2.0
stewart-ibm/mysql-server
storage/ndb/nodejs/samples/loader/lib/LoaderJob.js
10100
/* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ "use strict"; var assert = require("assert"), udebug = require(mynode.api.unified_debug).getLogger("LoaderJob.js"), machine = require("./control_file.js"), Controller = require("./Controller.js").Controller; /* Specification for a Loader Job */ // Define a single column of a destination table function ColumnDefinition(columnName) { this.name = columnName; this.startPos = null; // For fixed-width input this.endPos = null; }; // Define a destination: Database, Table, columns, and mapped class function LoaderJobDestination() { this.database = null; this.table = ""; this.columnDefinitions = []; this.rowConstructor = null; }; LoaderJobDestination.prototype.addColumnDefinition = function(name) { assert(typeof name === 'string'); var defn = new ColumnDefinition(name); this.columnDefinitions.push(defn); return defn; }; LoaderJobDestination.prototype.createTableMapping = function() { if(this.table.length === 0) { throw new Error("No table specified in loader job."); } var literalMapping, mapping; literalMapping = { table : this.table, database : this.database, mapAllColumns : (this.columnDefinitions.length === 0) }; mapping = new mynode.TableMapping(literalMapping); /* A ``function() {}'' for constructing mapped objects */ this.rowConstructor = new Function(); this.columnDefinitions.forEach(function(column) { mapping.mapField(column.name); }); mapping.applyToClass(this.rowConstructor); return this.rowConstructor; }; LoaderJobDestination.prototype.setColumnsFromArray = function(columnArray) { udebug.log("setColumnsFromArray length:", columnArray.length); var i; for(i = 0 ; i < columnArray.length ; i++) { this.columnDefinitions.push(new ColumnDefinition(columnArray[i])); } this.createTableMapping(); // Causes the default TableHandler to be discarded }; LoaderJobDestination.prototype.getTableHandler = function() { // FIXME this uses undocumented path to access the dbTableHandler: return this.rowConstructor.prototype.mynode.tableHandler; }; // LoaderJob function LoaderJob() { this.plugin = null; this.destination = new LoaderJobDestination(); this.ctlFileDescriptor = null; this.controller = { randomData : false, badfile : "", maxRows : null, speedMeasure : null, speedFast : true, workerId : 0, nWorkers : 1, skipRows : 0, inOneTransaction : false }; this.dataSource = { file : "", useControlFile : null, isJSON : false, commentStart : null, fieldSep : "\t", fieldSepOnWhitespace : false, fieldQuoteStart : "\"", fieldQuoteEnd : "\"", fieldQuoteEsc : "\\", fieldQuoteOptional : false, lineStartString : "", lineEndString : "\n", columnsInHeader : false }; this.dataLoader = { replaceMode : false, requireEmpty : false, doTruncate : false }; this.setInsertMode("APPEND"); } LoaderJob.prototype.setPlugin = function(plugin) { this.plugin = plugin; }; LoaderJob.prototype.initializeFromFile = function(filename) { // Get the SQL text. The control file may also contain data. var ctlMaxReadLen, ctlReadBuffer, size, sqlText; ctlMaxReadLen = 16 * 1024; ctlReadBuffer = new Buffer(ctlMaxReadLen); this.ctlFileDescriptor = fs.openSync(filename, 'r'); size = fs.readSync(this.ctlFileDescriptor, ctlReadBuffer, 0, ctlMaxReadLen); sqlText = ctlReadBuffer.toString('utf8', 0, size); this.initializeFromSQL(sqlText); if(this.dataSource.useControlFile) { this.dataSource.useControlFile.text = sqlText; } else { fs.closeSync(this.ctlFileDescriptor); } }; LoaderJob.prototype.BeginDataAtControlFileLine = function(lineNo) { this.dataSource.useControlFile = { openFd : this.ctlFileDescriptor, text : null, inlineSkip : lineNo }; }; LoaderJob.prototype.initializeFromSQL = function(text) { var tokens, tree, error; if(text) { error = null; try { tokens = machine.scan(text); } catch(e) { error = e; } this.plugin.onSqlScan(error, tokens); error = null; // try { tree = machine.parse(tokens); // } catch(e) { // error = e; // } this.plugin.onSqlParse(error, tree); } error = null; try { machine.analyze(tree, this); } catch(e) { error = e; } this.plugin.onLoaderJob(error, this); }; LoaderJob.prototype.run = function(session, finalCallback) { var controller = new Controller(this, session, finalCallback); controller.run(); }; LoaderJob.prototype.setWorkerId = function(id, nWorkers) { assert(typeof id === 'number' && typeof nWorkers === 'number' && id > 0 && id <= nWorkers); this.controller.workerId = id - 1; this.controller.nWorkers = nWorkers; }; LoaderJob.prototype.setDataFile = function(fileName) { assert(typeof fileName === 'string'); this.dataSource.file = fileName; }; LoaderJob.prototype.generateRandomData = function() { this.controller.randomData = true; }; LoaderJob.prototype.dataSourceIsJSON = function() { this.dataSource.isJSON = true; }; LoaderJob.prototype.dataSourceIsCSV = function() { this.setFieldSeparator(","); this.setColumnsInHeader(); }; /* [ INSERT | REPLACE | APPEND | TRUNCATE | IGNORE ] This is the union of keywords supported by Oracle SQL*Loader and by MySQL. APPEND allows the table to have existing data. This is the default behavior. INSERT requires the table to empty before loading. TRUNCATE instructs the loader to delete all rows before loading data. REPLACE has the meaning, as in MySQL, that existing rows will be updated with values from the data file. (This is quite different from the semantics of REPLACE in SQL*Loader). With REPLACE, all rows are written with the semantics of save() ("update or insert") rather than persist(). IGNORE is present for compatibility with MySQL, but is ignored. */ LoaderJob.prototype.setInsertMode = function(mode) { mode = mode.toUpperCase(); switch(mode) { case "INSERT": this.dataLoader.requireEmpty = true; this.dataLoader.replaceMode = false; this.dataLoader.doTruncate = false; throw new Error("INSERT mode is not yet implemented"); break; case "REPLACE": this.dataLoader.requireEmpty = false; this.dataLoader.replaceMode = true; this.dataLoader.doTruncate = false; break; case "APPEND": this.dataLoader.requireEmpty = false; this.dataLoader.replaceMode = false; this.dataLoader.doTruncate = false; break; case "TRUNCATE": this.dataLoader.requireEmpty = false; this.dataLoader.replaceMode = false; this.dataLoader.doTruncate = true; throw new Error("TRUNCATE mode is not yet implemented"); break; case "IGNORE": // log a warning that IGNORE is ignored? break; default: throw new Error("Illegal insert mode:" + mode); } }; LoaderJob.prototype.setFieldQuoteOptional = function() { this.dataSource.fieldQuoteOptional = true; }; LoaderJob.prototype.setFieldQuoteStartAndEnd = function(start, end) { assert(typeof start === 'string' && typeof end === 'string' && start.length === 1 && end.length === 1); this.dataSource.fieldQuoteStart = start; this.dataSource.fieldQuoteEnd = end; }; LoaderJob.prototype.setFieldSeparator = function(sep) { assert(typeof sep === 'string' && sep.length === 1); this.dataSource.fieldSep = sep; }; LoaderJob.prototype.setFieldSeparatorToWhitespace = function() { this.dataSource.fieldSepOnWhitespace = true; }; LoaderJob.prototype.setFieldQuoteEsc = function(escChar) { assert(typeof escChar === 'string' && escChar.length === 1); this.dataSource.fieldQuoteEsc = escChar; }; LoaderJob.prototype.setTable = function(name) { this.destination.table = name; }; LoaderJob.prototype.setDatabase = function(db) { this.destination.database = db; }; LoaderJob.prototype.setBadFile = function(file) { assert(typeof file === 'string'); this.controller.badfile = file; }; LoaderJob.prototype.inOneTransaction = function() { this.controller.inOneTransaction = true; }; LoaderJob.prototype.setSkipRows = function(n) { assert(typeof n === 'number' && n >= 0); this.controller.skipRows = n; }; LoaderJob.prototype.setMaxRows = function(n) { assert(typeof n === 'number' && n >= 0); this.controller.maxRows = n; }; LoaderJob.prototype.setCommentStart = function(str) { assert(typeof str === 'string' && str.length > 0); this.dataSource.commentStart = str; }; LoaderJob.prototype.setLineStart = function(str) { assert(typeof str === 'string' && str.length > 0); this.dataSource.lineStartString = str; }; LoaderJob.prototype.setLineEnd = function(str) { assert(typeof str === 'string' && str.length > 0); this.dataSource.lineEndString = str; }; LoaderJob.prototype.setColumnsInHeader = function() { this.dataSource.columnsInHeader = true; }; exports.LoaderJob = LoaderJob;
gpl-2.0
izeye/spring-boot
spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java
2704
/* * Copyright 2012-2016 the original author or 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. */ package org.springframework.boot.autoconfigure; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ImportAutoConfiguration}. * * @author Phillip Webb */ public class ImportAutoConfigurationTests { @Test public void multipleAnnotationsShouldMergeCorrectly() { testConfigImports(Config.class); testConfigImports(AnotherConfig.class); } private void testConfigImports(Class<?> config) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( config); String shortName = ClassUtils.getShortName(ImportAutoConfigurationTests.class); int beginIndex = shortName.length() + 1; List<String> orderedConfigBeans = new ArrayList<String>(); for (String bean : context.getBeanDefinitionNames()) { if (bean.contains("$Config")) { String shortBeanName = ClassUtils.getShortName(bean); orderedConfigBeans.add(shortBeanName.substring(beginIndex)); } } assertThat(orderedConfigBeans).containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD"); context.close(); } @ImportAutoConfiguration({ ConfigD.class, ConfigB.class }) @MetaImportAutoConfiguration static class Config { } @MetaImportAutoConfiguration @ImportAutoConfiguration({ ConfigB.class, ConfigD.class }) static class AnotherConfig { } @Retention(RetentionPolicy.RUNTIME) @ImportAutoConfiguration({ ConfigC.class, ConfigA.class }) @interface MetaImportAutoConfiguration { } @Configuration static class ConfigA { } @Configuration @AutoConfigureAfter(ConfigA.class) static class ConfigB { } @Configuration @AutoConfigureAfter(ConfigB.class) static class ConfigC { } @Configuration @AutoConfigureAfter(ConfigC.class) static class ConfigD { } }
apache-2.0
matthewrez/phabricator
src/applications/diviner/storage/DivinerLiveBook.php
4046
<?php final class DivinerLiveBook extends DivinerDAO implements PhabricatorPolicyInterface, PhabricatorProjectInterface, PhabricatorDestructibleInterface, PhabricatorApplicationTransactionInterface { protected $name; protected $repositoryPHID; protected $viewPolicy; protected $editPolicy; protected $configurationData = array(); private $projectPHIDs = self::ATTACHABLE; private $repository = self::ATTACHABLE; protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_SERIALIZATION => array( 'configurationData' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'name' => 'text64', 'repositoryPHID' => 'phid?', ), self::CONFIG_KEY_SCHEMA => array( 'key_phid' => null, 'phid' => array( 'columns' => array('phid'), 'unique' => true, ), 'name' => array( 'columns' => array('name'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function getConfig($key, $default = null) { return idx($this->configurationData, $key, $default); } public function setConfig($key, $value) { $this->configurationData[$key] = $value; return $this; } public function generatePHID() { return PhabricatorPHID::generateNewPHID(DivinerBookPHIDType::TYPECONST); } public function getTitle() { return $this->getConfig('title', $this->getName()); } public function getShortTitle() { return $this->getConfig('short', $this->getTitle()); } public function getPreface() { return $this->getConfig('preface'); } public function getGroupName($group) { $groups = $this->getConfig('groups', array()); $spec = idx($groups, $group, array()); return idx($spec, 'name', $group); } public function attachRepository(PhabricatorRepository $repository = null) { $this->repository = $repository; return $this; } public function getRepository() { return $this->assertAttached($this->repository); } public function attachProjectPHIDs(array $project_phids) { $this->projectPHIDs = $project_phids; return $this; } public function getProjectPHIDs() { return $this->assertAttached($this->projectPHIDs); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return $this->getViewPolicy(); case PhabricatorPolicyCapability::CAN_EDIT: return $this->getEditPolicy(); } } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return false; } public function describeAutomaticCapability($capability) { return null; } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->openTransaction(); $atoms = id(new DivinerAtomQuery()) ->setViewer($engine->getViewer()) ->withBookPHIDs(array($this->getPHID())) ->execute(); foreach ($atoms as $atom) { $engine->destroyObject($atom); } $this->delete(); $this->saveTransaction(); } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new DivinerLiveBookEditor(); } public function getApplicationTransactionObject() { return $this; } public function getApplicationTransactionTemplate() { return new DivinerLiveBookTransaction(); } public function willRenderTimeline( PhabricatorApplicationTransactionView $timeline, AphrontRequest $request) { return $timeline; } }
apache-2.0
priyatransbit/aws-sdk-java
aws-java-sdk-core/src/test/java/com/amazonaws/regions/RegionUtilsIntegrationTest.java
2413
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is * distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either * express or implied. See the License for the specific language * governing * permissions and limitations under the License. */ package com.amazonaws.regions; import static com.amazonaws.SDKGlobalConfiguration.REGIONS_FILE_OVERRIDE_SYSTEM_PROPERTY; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Unit tests for RegionUtils class. */ public class RegionUtilsIntegrationTest { @Before @After public void clearProperties() { System.clearProperty(REGIONS_FILE_OVERRIDE_SYSTEM_PROPERTY); } @Test public void testGetRegionByEndpoint() { RegionUtils.initialize(); assertEquals("/com/amazonaws/regions/regions.xml", RegionUtils.getSource()); assertEquals("us-east-1", RegionUtils.getRegionByEndpoint("redshift.us-east-1.amazonaws.com/bla").getName()); assertEquals("us-east-1", RegionUtils.getRegionByEndpoint("http://redshift.us-east-1.amazonaws.com").getName()); } /** * Tests that region file override could be properly loaded, and the * endpoint verification is also disabled so that invalid (not owned by AWS) * endpoints don't trigger RuntimeException. */ @Test public void testRegionFileOverride() { String fakeRegionFilePath = RegionUtilsIntegrationTest.class.getResource("fake-regions.xml").getPath(); System.setProperty(REGIONS_FILE_OVERRIDE_SYSTEM_PROPERTY, fakeRegionFilePath); RegionUtils.initialize(); assertEquals(fakeRegionFilePath, RegionUtils.getSource()); assertEquals(2, RegionUtils.getRegions().size()); assertEquals("hostname.com", RegionUtils.getRegion("us-east-1").getDomain()); assertEquals("fake.hostname.com", RegionUtils.getRegion("us-east-1").getServiceEndpoint("cloudformation")); assertEquals("amazonaws.com", RegionUtils.getRegion("us-west-1").getDomain()); } }
apache-2.0
priyatransbit/aws-sdk-java
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/CopySnapshotResultStaxUnmarshaller.java
2395
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.ec2.model.transform; import java.util.Map; import java.util.Map.Entry; import javax.xml.stream.events.XMLEvent; import com.amazonaws.services.ec2.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.MapEntry; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * Copy Snapshot Result StAX Unmarshaller */ public class CopySnapshotResultStaxUnmarshaller implements Unmarshaller<CopySnapshotResult, StaxUnmarshallerContext> { public CopySnapshotResult unmarshall(StaxUnmarshallerContext context) throws Exception { CopySnapshotResult copySnapshotResult = new CopySnapshotResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return copySnapshotResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("snapshotId", targetDepth)) { copySnapshotResult.setSnapshotId(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return copySnapshotResult; } } } } private static CopySnapshotResultStaxUnmarshaller instance; public static CopySnapshotResultStaxUnmarshaller getInstance() { if (instance == null) instance = new CopySnapshotResultStaxUnmarshaller(); return instance; } }
apache-2.0
mtcode/autoscaler
cluster-autoscaler/vendor/k8s.io/kubernetes/pkg/volume/cinder/doc.go
660
/* Copyright 2015 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. */ // Package cinder contains the internal representation of cinder volumes. package cinder
apache-2.0
perotinus/kubernetes
federation/pkg/dnsprovider/providers/google/clouddns/internal/changes_service.go
1540
/* Copyright 2016 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. */ package internal import ( dns "google.golang.org/api/dns/v1" "k8s.io/kubernetes/federation/pkg/dnsprovider/providers/google/clouddns/internal/interfaces" ) // Compile time check for interface adherence var _ interfaces.ChangesService = ChangesService{} type ChangesService struct{ impl *dns.ChangesService } func (c ChangesService) Create(project string, managedZone string, change interfaces.Change) interfaces.ChangesCreateCall { return &ChangesCreateCall{c.impl.Create(project, managedZone, change.(*Change).impl)} } func (c ChangesService) NewChange(additions, deletions []interfaces.ResourceRecordSet) interfaces.Change { adds := make([]*dns.ResourceRecordSet, len(additions)) deletes := make([]*dns.ResourceRecordSet, len(deletions)) for i, a := range additions { adds[i] = a.(*ResourceRecordSet).impl } for i, d := range deletions { deletes[i] = d.(*ResourceRecordSet).impl } return &Change{&dns.Change{Additions: adds, Deletions: deletes}} }
apache-2.0
chongsheng/pro1
vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php
1266
<?php /* * This file is part of SwiftMailer. * (c) 2004-2009 Chris Corbyn * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * A HTML output reporter for the Reporter plugin. * * @package Swift * @subpackage Plugins * @author Chris Corbyn */ class Swift_Plugins_Reporters_HtmlReporter implements Swift_Plugins_Reporter { /** * Notifies this ReportNotifier that $address failed or succeeded. * * @param Swift_Mime_Message $message * @param string $address * @param integer $result from {@see RESULT_PASS, RESULT_FAIL} */ public function notify(Swift_Mime_Message $message, $address, $result) { if (self::RESULT_PASS == $result) { echo "<div style=\"color: #fff; background: #006600; padding: 2px; margin: 2px;\">" . PHP_EOL; echo "PASS " . $address . PHP_EOL; echo "</div>" . PHP_EOL; flush(); } else { echo "<div style=\"color: #fff; background: #880000; padding: 2px; margin: 2px;\">" . PHP_EOL; echo "FAIL " . $address . PHP_EOL; echo "</div>" . PHP_EOL; flush(); } } }
mit
FarmGeek4Life/jenkins
core/src/main/java/hudson/util/CyclicGraphDetector.java
2367
package hudson.util; import hudson.Util; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Stack; /** * Traverses a directed graph and if it contains any cycle, throw an exception. * * @author Kohsuke Kawaguchi */ public abstract class CyclicGraphDetector<N> { private final Set<N> visited = new HashSet<N>(); private final Set<N> visiting = new HashSet<N>(); private final Stack<N> path = new Stack<N>(); private final List<N> topologicalOrder = new ArrayList<N>(); public void run(Iterable<? extends N> allNodes) throws CycleDetectedException { for (N n : allNodes){ visit(n); } } /** * Returns all the nodes in the topologically sorted order. * That is, if there's an edge a->b, b always come earlier than a. */ public List<N> getSorted() { return topologicalOrder; } /** * List up edges from the given node (by listing nodes that those edges point to.) * * @return * Never null. */ protected abstract Iterable<? extends N> getEdges(N n); private void visit(N p) throws CycleDetectedException { if (!visited.add(p)) return; visiting.add(p); path.push(p); for (N q : getEdges(p)) { if (q==null) continue; // ignore unresolved references if (visiting.contains(q)) detectedCycle(q); visit(q); } visiting.remove(p); path.pop(); topologicalOrder.add(p); } private void detectedCycle(N q) throws CycleDetectedException { int i = path.indexOf(q); path.push(q); reactOnCycle(q, path.subList(i, path.size())); } /** * React on detected cycles - default implementation throws an exception. * @param q * @param cycle * @throws CycleDetectedException */ protected void reactOnCycle(N q, List<N> cycle) throws CycleDetectedException{ throw new CycleDetectedException(cycle); } public static final class CycleDetectedException extends Exception { public final List cycle; public CycleDetectedException(List cycle) { super("Cycle detected: "+Util.join(cycle," -> ")); this.cycle = cycle; } } }
mit
mprobst/angular
aio/content/examples/getting-started-v0/src/app/product-list/product-list.component.ts
355
import { Component } from '@angular/core'; import { products } from '../products'; @Component({ selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'] }) export class ProductListComponent { products = products; share() { window.alert('The product has been shared!'); } }
mit
roemervandermeij/fieldtrip
realtime/src/buffer/java/nl/fcdonders/fieldtrip/DataType.java
2327
/* * Copyright (C) 2010, Stefan Klanke * Donders Institute for Donders Institute for Brain, Cognition and Behaviour, * Centre for Cognitive Neuroimaging, Radboud University Nijmegen, * Kapittelweg 29, 6525 EN Nijmegen, The Netherlands */ package nl.fcdonders.fieldtrip; import java.nio.*; /** A class for defining FieldTrip data types and routines for conversion to Java objects. */ public class DataType { public static final int UNKNOWN = -1; public static final int CHAR = 0; public static final int UINT8 = 1; public static final int UINT16 = 2; public static final int UINT32 = 3; public static final int UINT64 = 4; public static final int INT8 = 5; public static final int INT16 = 6; public static final int INT32 = 7; public static final int INT64 = 8; public static final int FLOAT32 = 9; public static final int FLOAT64 = 10; public static final int[] wordSize = {1,1,2,4,8,1,2,4,8,4,8}; public static Object getObject(int type, int numel, ByteBuffer buf) { switch(type) { case CHAR: byte[] strBytes = new byte[numel]; buf.get(strBytes); return new String(strBytes); case INT8: case UINT8: byte[] int8array = new byte[numel]; buf.get(int8array); return int8array; case INT16: case UINT16: short[] int16array = new short[numel]; // The following would be faster, but DOES NOT // increment the position of the original ByteBuffer!!! // buf.asShortBuffer().get(int16array); for (int i=0;i<numel;i++) int16array[i] = buf.getShort(); return int16array; case INT32: case UINT32: int[] int32array = new int[numel]; for (int i=0;i<numel;i++) int32array[i] = buf.getInt(); return int32array; case INT64: case UINT64: long[] int64array = new long[numel]; for (int i=0;i<numel;i++) int64array[i] = buf.getLong(); return int64array; case FLOAT32: float[] float32array = new float[numel]; for (int i=0;i<numel;i++) float32array[i] = buf.getFloat(); return float32array; case FLOAT64: double[] float64array = new double[numel]; for (int i=0;i<numel;i++) float64array[i] = buf.getDouble(); return float64array; default: return null; } } }
gpl-2.0
johnparker007/mame
3rdparty/asio/include/asio/detail/variadic_templates.hpp
4012
// // detail/variadic_templates.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_DETAIL_VARIADIC_TEMPLATES_HPP #define ASIO_DETAIL_VARIADIC_TEMPLATES_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_HAS_VARIADIC_TEMPLATES) # define ASIO_VARIADIC_TPARAMS(n) ASIO_VARIADIC_TPARAMS_##n # define ASIO_VARIADIC_TPARAMS_1 \ typename T1 # define ASIO_VARIADIC_TPARAMS_2 \ typename T1, typename T2 # define ASIO_VARIADIC_TPARAMS_3 \ typename T1, typename T2, typename T3 # define ASIO_VARIADIC_TPARAMS_4 \ typename T1, typename T2, typename T3, typename T4 # define ASIO_VARIADIC_TPARAMS_5 \ typename T1, typename T2, typename T3, typename T4, typename T5 # define ASIO_VARIADIC_TARGS(n) ASIO_VARIADIC_TARGS_##n # define ASIO_VARIADIC_TARGS_1 T1 # define ASIO_VARIADIC_TARGS_2 T1, T2 # define ASIO_VARIADIC_TARGS_3 T1, T2, T3 # define ASIO_VARIADIC_TARGS_4 T1, T2, T3, T4 # define ASIO_VARIADIC_TARGS_5 T1, T2, T3, T4, T5 # define ASIO_VARIADIC_BYVAL_PARAMS(n) \ ASIO_VARIADIC_BYVAL_PARAMS_##n # define ASIO_VARIADIC_BYVAL_PARAMS_1 T1 x1 # define ASIO_VARIADIC_BYVAL_PARAMS_2 T1 x1, T2 x2 # define ASIO_VARIADIC_BYVAL_PARAMS_3 T1 x1, T2 x2, T3 x3 # define ASIO_VARIADIC_BYVAL_PARAMS_4 T1 x1, T2 x2, T3 x3, T4 x4 # define ASIO_VARIADIC_BYVAL_PARAMS_5 T1 x1, T2 x2, T3 x3, T4 x4, T5 x5 # define ASIO_VARIADIC_BYVAL_ARGS(n) \ ASIO_VARIADIC_BYVAL_ARGS_##n # define ASIO_VARIADIC_BYVAL_ARGS_1 x1 # define ASIO_VARIADIC_BYVAL_ARGS_2 x1, x2 # define ASIO_VARIADIC_BYVAL_ARGS_3 x1, x2, x3 # define ASIO_VARIADIC_BYVAL_ARGS_4 x1, x2, x3, x4 # define ASIO_VARIADIC_BYVAL_ARGS_5 x1, x2, x3, x4, x5 # define ASIO_VARIADIC_MOVE_PARAMS(n) \ ASIO_VARIADIC_MOVE_PARAMS_##n # define ASIO_VARIADIC_MOVE_PARAMS_1 \ ASIO_MOVE_ARG(T1) x1 # define ASIO_VARIADIC_MOVE_PARAMS_2 \ ASIO_MOVE_ARG(T1) x1, ASIO_MOVE_ARG(T2) x2 # define ASIO_VARIADIC_MOVE_PARAMS_3 \ ASIO_MOVE_ARG(T1) x1, ASIO_MOVE_ARG(T2) x2, \ ASIO_MOVE_ARG(T3) x3 # define ASIO_VARIADIC_MOVE_PARAMS_4 \ ASIO_MOVE_ARG(T1) x1, ASIO_MOVE_ARG(T2) x2, \ ASIO_MOVE_ARG(T3) x3, ASIO_MOVE_ARG(T4) x4 # define ASIO_VARIADIC_MOVE_PARAMS_5 \ ASIO_MOVE_ARG(T1) x1, ASIO_MOVE_ARG(T2) x2, \ ASIO_MOVE_ARG(T3) x3, ASIO_MOVE_ARG(T4) x4, \ ASIO_MOVE_ARG(T5) x5 # define ASIO_VARIADIC_MOVE_ARGS(n) \ ASIO_VARIADIC_MOVE_ARGS_##n # define ASIO_VARIADIC_MOVE_ARGS_1 \ ASIO_MOVE_CAST(T1)(x1) # define ASIO_VARIADIC_MOVE_ARGS_2 \ ASIO_MOVE_CAST(T1)(x1), ASIO_MOVE_CAST(T2)(x2) # define ASIO_VARIADIC_MOVE_ARGS_3 \ ASIO_MOVE_CAST(T1)(x1), ASIO_MOVE_CAST(T2)(x2), \ ASIO_MOVE_CAST(T3)(x3) # define ASIO_VARIADIC_MOVE_ARGS_4 \ ASIO_MOVE_CAST(T1)(x1), ASIO_MOVE_CAST(T2)(x2), \ ASIO_MOVE_CAST(T3)(x3), ASIO_MOVE_CAST(T4)(x4) # define ASIO_VARIADIC_MOVE_ARGS_5 \ ASIO_MOVE_CAST(T1)(x1), ASIO_MOVE_CAST(T2)(x2), \ ASIO_MOVE_CAST(T3)(x3), ASIO_MOVE_CAST(T4)(x4), \ ASIO_MOVE_CAST(T5)(x5) # define ASIO_VARIADIC_DECAY(n) \ ASIO_VARIADIC_DECAY_##n # define ASIO_VARIADIC_DECAY_1 \ typename decay<T1>::type # define ASIO_VARIADIC_DECAY_2 \ typename decay<T1>::type, typename decay<T2>::type # define ASIO_VARIADIC_DECAY_3 \ typename decay<T1>::type, typename decay<T2>::type, \ typename decay<T3>::type # define ASIO_VARIADIC_DECAY_4 \ typename decay<T1>::type, typename decay<T2>::type, \ typename decay<T3>::type, typename decay<T4>::type # define ASIO_VARIADIC_DECAY_5 \ typename decay<T1>::type, typename decay<T2>::type, \ typename decay<T3>::type, typename decay<T4>::type, \ typename decay<T5>::type # define ASIO_VARIADIC_GENERATE(m) m(1) m(2) m(3) m(4) m(5) #endif // !defined(ASIO_HAS_VARIADIC_TEMPLATES) #endif // ASIO_DETAIL_VARIADIC_TEMPLATES_HPP
gpl-2.0
shinose/kodi-qplay
xbmc/video/videosync/VideoSyncAndroid.cpp
2596
/* * Copyright (C) 2015 Team Kodi * http://kodi.tv * * 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(TARGET_ANDROID) #include "utils/log.h" #include "VideoSyncAndroid.h" #include "video/VideoReferenceClock.h" #include "utils/TimeUtils.h" #include "platform/android/activity/XBMCApp.h" #include "windowing/WindowingFactory.h" #include "guilib/GraphicContext.h" #include "utils/MathUtils.h" #include "linux/XTimeUtils.h" bool CVideoSyncAndroid::Setup(PUPDATECLOCK func) { CLog::Log(LOGDEBUG, "CVideoSyncAndroid::%s setting up", __FUNCTION__); //init the vblank timestamp m_LastVBlankTime = CurrentHostCounter(); UpdateClock = func; m_abort = false; CXBMCApp::InitFrameCallback(this); g_Windowing.Register(this); return true; } void CVideoSyncAndroid::Run(std::atomic<bool>& stop) { while(!stop && !m_abort) { Sleep(100); } } void CVideoSyncAndroid::Cleanup() { CLog::Log(LOGDEBUG, "CVideoSyncAndroid::%s cleaning up", __FUNCTION__); CXBMCApp::DeinitFrameCallback(); g_Windowing.Unregister(this); } float CVideoSyncAndroid::GetFps() { m_fps = g_graphicsContext.GetFPS(); CLog::Log(LOGDEBUG, "CVideoSyncAndroid::%s Detected refreshrate: %f hertz", __FUNCTION__, m_fps); return m_fps; } void CVideoSyncAndroid::OnResetDisplay() { m_abort = true; } void CVideoSyncAndroid::FrameCallback(int64_t frameTimeNanos) { int NrVBlanks; double VBlankTime; int64_t nowtime = CurrentHostCounter(); //calculate how many vblanks happened VBlankTime = (double)(nowtime - m_LastVBlankTime) / (double)CurrentHostFrequency(); NrVBlanks = MathUtils::round_int(VBlankTime * m_fps); //save the timestamp of this vblank so we can calculate how many happened next time m_LastVBlankTime = nowtime; //update the vblank timestamp, update the clock and send a signal that we got a vblank UpdateClock(NrVBlanks, nowtime, m_refClock); } #endif //TARGET_ANDROID
gpl-2.0
famelo/TYPO3-Base
typo3/vendor/facebook/webdriver/lib/Interactions/Touch/WebDriverMoveAction.php
1173
<?php // Copyright 2004-present Facebook. 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. namespace Facebook\WebDriver\Interactions\Touch; use Facebook\WebDriver\WebDriverAction; class WebDriverMoveAction extends WebDriverTouchAction implements WebDriverAction { private $x; private $y; /** * @param WebDriverTouchScreen $touch_screen * @param int $x * @param int $y */ public function __construct(WebDriverTouchScreen $touch_screen, $x, $y) { $this->x = $x; $this->y = $y; parent::__construct($touch_screen); } public function perform() { $this->touchScreen->move($this->x, $this->y); } }
gpl-2.0
csusm-library/mysqladmin
libraries/config/messages.inc.php
44556
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Messages for phpMyAdmin. * * This file defines variables in a special format suited for the * configuration subsystem, with $strConfig as a prefix, _desc or _name * as a suffix, and the directive name in between. * * @package PhpMyAdmin */ if (!function_exists('__')) { PMA_fatalError('Bad invocation!'); } $strConfigAllowArbitraryServer_desc = __('If enabled user can enter any MySQL server in login form for cookie auth'); $strConfigAllowArbitraryServer_name = __('Allow login to any MySQL server'); $strConfigAllowThirdPartyFraming_desc = __('Enabling this allows a page located on a different domain to call phpMyAdmin inside a frame, and is a potential [strong]security hole[/strong] allowing cross-frame scripting attacks'); $strConfigAllowThirdPartyFraming_name = __('Allow third party framing'); $strConfigAllowUserDropDatabase_name = __('Show &quot;Drop database&quot; link to normal users'); $strConfigblowfish_secret_desc = __('Secret passphrase used for encrypting cookies in [kbd]cookie[/kbd] authentication'); $strConfigblowfish_secret_name = __('Blowfish secret'); $strConfigBrowseMarkerEnable_desc = __('Highlight selected rows'); $strConfigBrowseMarkerEnable_name = __('Row marker'); $strConfigBrowsePointerEnable_desc = __('Highlight row pointed by the mouse cursor'); $strConfigBrowsePointerEnable_name = __('Highlight pointer'); $strConfigBZipDump_desc = __('Enable [a@http://en.wikipedia.org/wiki/Bzip2]bzip2[/a] compression for import operations'); $strConfigBZipDump_name = __('Bzip2'); $strConfigCharEditing_desc = __('Defines which type of editing controls should be used for CHAR and VARCHAR columns; [kbd]input[/kbd] - allows limiting of input length, [kbd]textarea[/kbd] - allows newlines in columns'); $strConfigCharEditing_name = __('CHAR columns editing'); $strConfigCodemirrorEnable_desc = __('Use user-friendly editor for editing SQL queries ([a@http://codemirror.net/]CodeMirror[/a]) with syntax highlighting and line numbers'); $strConfigCodemirrorEnable_name = __('Enable CodeMirror'); $strConfigMinSizeForInputField_desc = __('Defines the minimum size for input fields generated for CHAR and VARCHAR columns'); $strConfigMinSizeForInputField_name = __('Minimum size for input field'); $strConfigMaxSizeForInputField_desc = __('Defines the maximum size for input fields generated for CHAR and VARCHAR columns'); $strConfigMaxSizeForInputField_name = __('Maximum size for input field'); $strConfigCharTextareaCols_desc = __('Number of columns for CHAR/VARCHAR textareas'); $strConfigCharTextareaCols_name = __('CHAR textarea columns'); $strConfigCharTextareaRows_desc = __('Number of rows for CHAR/VARCHAR textareas'); $strConfigCharTextareaRows_name = __('CHAR textarea rows'); $strConfigCheckConfigurationPermissions_name = __('Check config file permissions'); $strConfigCompressOnFly_desc = __('Compress gzip exports on the fly without the need for much memory; if you encounter problems with created gzip files disable this feature'); $strConfigCompressOnFly_name = __('Compress on the fly'); $strConfigConfigurationFile = __('Configuration file'); $strConfigConfirm_desc = __('Whether a warning (&quot;Are your really sure…&quot;) should be displayed when you\'re about to lose data'); $strConfigConfirm_name = __('Confirm DROP queries'); $strConfigDBG_sql_name = __('Debug SQL'); $strConfigDefaultDisplay_name = __('Default display direction'); $strConfigDefaultTabDatabase_desc = __('Tab that is displayed when entering a database'); $strConfigDefaultTabDatabase_name = __('Default database tab'); $strConfigDefaultTabServer_desc = __('Tab that is displayed when entering a server'); $strConfigDefaultTabServer_name = __('Default server tab'); $strConfigDefaultTabTable_desc = __('Tab that is displayed when entering a table'); $strConfigDefaultTabTable_name = __('Default table tab'); $strConfigHideStructureActions_desc = __('Whether the table structure actions should be hidden'); $strConfigHideStructureActions_name = __('Hide table structure actions'); $strConfigDisplayBinaryAsHex_desc = __('Show binary contents as HEX by default'); $strConfigDisplayBinaryAsHex_name = __('Show binary contents as HEX'); $strConfigDisplayServersList_desc = __('Show server listing as a list instead of a drop down'); $strConfigDisplayServersList_name = __('Display servers as a list'); $strConfigDisableMultiTableMaintenance_desc = __('Disable the table maintenance mass operations, like optimizing or repairing the selected tables of a database.'); $strConfigDisableMultiTableMaintenance_name = __('Disable multi table maintenance'); $strConfigEditInWindow_desc = __('Edit SQL queries in popup window'); $strConfigEditInWindow_name = __('Edit in window'); $strConfigError_Handler_display_name = __('Display errors'); $strConfigExecTimeLimit_desc = __('Set the number of seconds a script is allowed to run ([kbd]0[/kbd] for no limit)'); $strConfigExecTimeLimit_name = __('Maximum execution time'); $strConfigExport_asfile_name = __('Save as file'); $strConfigExport_charset_name = __('Character set of the file'); $strConfigExport_codegen_format_name = __('Format'); $strConfigExport_compression_name = __('Compression'); $strConfigExport_csv_columns_name = __('Put columns names in the first row'); $strConfigExport_csv_enclosed_name = __('Columns enclosed with'); $strConfigExport_csv_escaped_name = __('Columns escaped with'); $strConfigExport_csv_null_name = __('Replace NULL with'); $strConfigExport_csv_removeCRLF_name = __('Remove CRLF characters within columns'); $strConfigExport_csv_separator_name = __('Columns terminated with'); $strConfigExport_csv_terminated_name = __('Lines terminated with'); $strConfigExport_excel_columns_name = __('Put columns names in the first row'); $strConfigExport_excel_edition_name = __('Excel edition'); $strConfigExport_excel_null_name = __('Replace NULL with'); $strConfigExport_excel_removeCRLF_name = __('Remove CRLF characters within columns'); $strConfigExport_file_template_database_name = __('Database name template'); $strConfigExport_file_template_server_name = __('Server name template'); $strConfigExport_file_template_table_name = __('Table name template'); $strConfigExport_format_name = __('Format'); $strConfigExport_htmlword_columns_name = __('Put columns names in the first row'); $strConfigExport_htmlword_null_name = __('Replace NULL with'); $strConfigExport_htmlword_structure_or_data_name = __('Dump table'); $strConfigExport_latex_caption_name = __('Include table caption'); $strConfigExport_latex_columns_name = __('Put columns names in the first row'); $strConfigExport_latex_comments_name = __('Comments'); $strConfigExport_latex_data_caption_name = __('Table caption'); $strConfigExport_latex_data_continued_caption_name = __('Continued table caption'); $strConfigExport_latex_data_label_name = __('Label key'); $strConfigExport_latex_mime_name = __('MIME type'); $strConfigExport_latex_null_name = __('Replace NULL with'); $strConfigExport_latex_relation_name = __('Relations'); $strConfigExport_latex_structure_caption_name = __('Table caption'); $strConfigExport_latex_structure_continued_caption_name = __('Continued table caption'); $strConfigExport_latex_structure_label_name = __('Label key'); $strConfigExport_latex_structure_or_data_name = __('Dump table'); $strConfigExport_method_name = __('Export method'); $strConfigExport_ods_columns_name = __('Put columns names in the first row'); $strConfigExport_ods_null_name = __('Replace NULL with'); $strConfigExport_odt_columns_name = __('Put columns names in the first row'); $strConfigExport_odt_comments_name = __('Comments'); $strConfigExport_odt_mime_name = __('MIME type'); $strConfigExport_odt_null_name = __('Replace NULL with'); $strConfigExport_odt_relation_name = __('Relations'); $strConfigExport_odt_structure_or_data_name = __('Dump table'); $strConfigExport_onserver_name = __('Save on server'); $strConfigExport_onserver_overwrite_name = __('Overwrite existing file(s)'); $strConfigExport_quick_export_onserver_name = __('Save on server'); $strConfigExport_quick_export_onserver_overwrite_name = __('Overwrite existing file(s)'); $strConfigExport_remember_file_template_name = __('Remember file name template'); $strConfigExport_sql_auto_increment_name = __('Add AUTO_INCREMENT value'); $strConfigExport_sql_backquotes_name = __('Enclose table and column names with backquotes'); $strConfigExport_sql_compatibility_name = __('SQL compatibility mode'); $strConfigExport_sql_create_table_statements_name = __('<code>CREATE TABLE</code> options:'); $strConfigExport_sql_dates_name = __('Creation/Update/Check dates'); $strConfigExport_sql_delayed_name = __('Use delayed inserts'); $strConfigExport_sql_disable_fk_name = __('Disable foreign key checks'); $strConfigExport_sql_views_as_tables_name = __('Export views as tables'); $strConfigExport_sql_drop_database_name = sprintf(__('Add %s'), 'DROP DATABASE'); $strConfigExport_sql_drop_table_name = sprintf(__('Add %s'), 'DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT'); $strConfigExport_sql_hex_for_blob_name = __('Use hexadecimal for BLOB'); $strConfigExport_sql_if_not_exists_name = sprintf(__('Add %s'), 'IF NOT EXISTS'); $strConfigExport_sql_ignore_name = __('Use ignore inserts'); $strConfigExport_sql_include_comments_name = __('Comments'); $strConfigExport_sql_insert_syntax_name = __('Syntax to use when inserting data'); $strConfigExport_sql_max_query_size_name = __('Maximal length of created query'); $strConfigExport_sql_mime_name = __('MIME type'); $strConfigExport_sql_procedure_function_name = sprintf(__('Add %s'), 'CREATE PROCEDURE / FUNCTION / EVENT'); $strConfigExport_sql_relation_name = __('Relations'); $strConfigExport_sql_structure_or_data_name = __('Dump table'); $strConfigExport_sql_type_name = __('Export type'); $strConfigExport_sql_use_transaction_name = __('Enclose export in a transaction'); $strConfigExport_sql_utc_time_name = __('Export time in UTC'); $strConfigExport_texytext_columns_name = __('Put columns names in the first row'); $strConfigExport_texytext_null_name = __('Replace NULL with'); $strConfigExport_texytext_structure_or_data_name = __('Dump table'); $strConfigExport_xls_columns_name = __('Put columns names in the first row'); $strConfigExport_xls_null_name = __('Replace NULL with'); $strConfigExport_xlsx_columns_name = __('Put columns names in the first row'); $strConfigExport_xlsx_null_name = __('Replace NULL with'); $strConfigForceSSL_desc = __('Force secured connection while using phpMyAdmin'); $strConfigForceSSL_name = __('Force SSL connection'); $strConfigForeignKeyDropdownOrder_desc = __('Sort order for items in a foreign-key dropdown box; [kbd]content[/kbd] is the referenced data, [kbd]id[/kbd] is the key value'); $strConfigForeignKeyDropdownOrder_name = __('Foreign key dropdown order'); $strConfigForeignKeyMaxLimit_desc = __('A dropdown will be used if fewer items are present'); $strConfigForeignKeyMaxLimit_name = __('Foreign key limit'); $strConfigForm_Browse = __('Browse mode'); $strConfigForm_Browse_desc = __('Customize browse mode'); $strConfigForm_CodeGen = 'CodeGen'; $strConfigForm_CodeGen_desc = __('Customize default options'); $strConfigForm_Csv = __('CSV'); $strConfigForm_Csv_desc = __('Customize default options'); $strConfigForm_Developer = __('Developer'); $strConfigForm_Developer_desc = __('Settings for phpMyAdmin developers'); $strConfigForm_Edit = __('Edit mode'); $strConfigForm_Edit_desc = __('Customize edit mode'); $strConfigForm_Export = __('Export'); $strConfigForm_Export_defaults = __('Export defaults'); $strConfigForm_Export_defaults_desc = __('Customize default export options'); $strConfigForm_Features = __('Features'); $strConfigForm_General = __('General'); $strConfigForm_General_desc = __('Set some commonly used options'); $strConfigForm_Import = __('Import'); $strConfigForm_Import_defaults = __('Import defaults'); $strConfigForm_Import_defaults_desc = __('Customize default common import options'); $strConfigForm_Import_export = __('Import / export'); $strConfigForm_Import_export_desc = __('Set import and export directories and compression options'); $strConfigForm_Latex = __('LaTeX'); $strConfigForm_Latex_desc = __('Customize default options'); $strConfigForm_Navi_databases = __('Databases'); $strConfigForm_Navi_databases_desc = __('Databases display options'); $strConfigForm_Navi_panel = __('Navigation panel'); $strConfigForm_Navi_panel_desc = __('Customize appearance of the navigation panel'); $strConfigForm_Navi_servers = __('Servers'); $strConfigForm_Navi_servers_desc = __('Servers display options'); $strConfigForm_Navi_tables = __('Tables'); $strConfigForm_Navi_tables_desc = __('Tables display options'); $strConfigForm_Main_panel = __('Main panel'); $strConfigForm_Microsoft_Office = __('Microsoft Office'); $strConfigForm_Microsoft_Office_desc = __('Customize default options'); $strConfigForm_Open_Document = 'OpenDocument'; $strConfigForm_Open_Document_desc = __('Customize default options'); $strConfigForm_Other_core_settings = __('Other core settings'); $strConfigForm_Other_core_settings_desc = __('Settings that didn\'t fit anywhere else'); $strConfigForm_Page_titles = __('Page titles'); $strConfigForm_Page_titles_desc = __('Specify browser\'s title bar text. Refer to [doc@cfg_TitleTable]documentation[/doc] for magic strings that can be used to get special values.'); $strConfigForm_Query_window = __('Query window'); $strConfigForm_Query_window_desc = __('Customize query window options'); $strConfigForm_Security = __('Security'); $strConfigForm_Security_desc = __('Please note that phpMyAdmin is just a user interface and its features do not limit MySQL'); $strConfigForm_Server = __('Basic settings'); $strConfigForm_Server_auth = __('Authentication'); $strConfigForm_Server_auth_desc = __('Authentication settings'); $strConfigForm_Server_config = __('Server configuration'); $strConfigForm_Server_config_desc = __('Advanced server configuration, do not change these options unless you know what they are for'); $strConfigForm_Server_desc = __('Enter server connection parameters'); $strConfigForm_Server_pmadb = __('Configuration storage'); $strConfigForm_Server_pmadb_desc = __('Configure phpMyAdmin configuration storage to gain access to additional features, see [doc@linked-tables]phpMyAdmin configuration storage[/doc] in documentation'); $strConfigForm_Server_tracking = __('Changes tracking'); $strConfigForm_Server_tracking_desc = __('Tracking of changes made in database. Requires the phpMyAdmin configuration storage.'); $strConfigFormset_Export = __('Customize export options'); $strConfigFormset_Features = __('Features'); $strConfigFormset_Import = __('Customize import defaults'); $strConfigFormset_Navi_panel = __('Customize navigation panel'); $strConfigFormset_Main_panel = __('Customize main panel'); $strConfigFormset_Sql_queries = __('SQL queries'); $strConfigForm_Sql = __('SQL'); $strConfigForm_Sql_box = __('SQL Query box'); $strConfigForm_Sql_box_desc = __('Customize links shown in SQL Query boxes'); $strConfigForm_Sql_desc = __('Customize default options'); $strConfigForm_Sql_queries = __('SQL queries'); $strConfigForm_Sql_queries_desc = __('SQL queries settings'); $strConfigForm_Sql_validator = __('SQL Validator'); $strConfigForm_Sql_validator_desc = __('If you wish to use the SQL Validator service, you should be aware that [strong]all SQL statements are stored anonymously for statistical purposes[/strong].[br][em][a@http://sqlvalidator.mimer.com/]Mimer SQL Validator[/a], Copyright 2002 Upright Database Technology. All rights reserved.[/em]'); $strConfigForm_Startup = __('Startup'); $strConfigForm_Startup_desc = __('Customize startup page'); $strConfigForm_DbStructure = __('Database structure'); $strConfigForm_DbStructure_desc = __('Choose which details to show in the database structure (list of tables)'); $strConfigForm_TableStructure = __('Table structure'); $strConfigForm_TableStructure_desc = __('Settings for the table structure (list of columns)'); $strConfigForm_Tabs = __('Tabs'); $strConfigForm_Tabs_desc = __('Choose how you want tabs to work'); $strConfigForm_DisplayRelationalSchema = __('Display relational schema'); $strConfigForm_DisplayRelationalSchema_desc = ''; $strConfigPDFDefaultPageSize_name = __('Paper size'); $strConfigPDFDefaultPageSize_desc = ''; $strConfigForm_Text_fields = __('Text fields'); $strConfigForm_Text_fields_desc = __('Customize text input fields'); $strConfigForm_Texy = __('Texy! text'); $strConfigForm_Texy_desc = __('Customize default options'); $strConfigForm_Warnings = __('Warnings'); $strConfigForm_Warnings_desc = __('Disable some of the warnings shown by phpMyAdmin'); $strConfigGZipDump_desc = __('Enable [a@http://en.wikipedia.org/wiki/Gzip]gzip[/a] compression for import and export operations'); $strConfigGZipDump_name = __('GZip'); $strConfigIconvExtraParams_name = __('Extra parameters for iconv'); $strConfigIgnoreMultiSubmitErrors_desc = __('If enabled, phpMyAdmin continues computing multiple-statement queries even if one of the queries failed'); $strConfigIgnoreMultiSubmitErrors_name = __('Ignore multiple statement errors'); $strConfigImport_allow_interrupt_desc = __('Allow interrupt of import in case script detects it is close to time limit. This might be a good way to import large files, however it can break transactions.'); $strConfigImport_allow_interrupt_name = __('Partial import: allow interrupt'); $strConfigImport_charset_name = __('Character set of the file'); $strConfigImport_csv_col_names_name = __('Lines terminated with'); $strConfigImport_csv_enclosed_name = __('Columns enclosed with'); $strConfigImport_csv_escaped_name = __('Columns escaped with'); $strConfigImport_csv_ignore_name = __('Do not abort on INSERT error'); $strConfigImport_csv_replace_name = __('Replace table data with file'); $strConfigImport_csv_terminated_name = __('Columns terminated with'); $strConfigImport_format_desc = __('Default format; be aware that this list depends on location (database, table) and only SQL is always available'); $strConfigImport_format_name = __('Format of imported file'); $strConfigImport_ldi_enclosed_name = __('Columns enclosed with'); $strConfigImport_ldi_escaped_name = __('Columns escaped with'); $strConfigImport_ldi_ignore_name = __('Do not abort on INSERT error'); $strConfigImport_ldi_local_option_name = __('Use LOCAL keyword'); $strConfigImport_ldi_replace_name = __('Replace table data with file'); $strConfigImport_ldi_terminated_name = __('Columns terminated with'); $strConfigImport_ods_col_names_name = __('Column names in first row'); $strConfigImport_ods_empty_rows_name = __('Do not import empty rows'); $strConfigImport_ods_recognize_currency_name = __('Import currencies ($5.00 to 5.00)'); $strConfigImport_ods_recognize_percentages_name = __('Import percentages as proper decimals (12.00% to .12)'); $strConfigImport_skip_queries_desc = __('Number of queries to skip from start'); $strConfigImport_skip_queries_name = __('Partial import: skip queries'); $strConfigImport_sql_compatibility_name = __('SQL compatibility mode'); $strConfigImport_sql_no_auto_value_on_zero_name = __('Do not use AUTO_INCREMENT for zero values'); $strConfigImport_xls_col_names_name = __('Column names in first row'); $strConfigImport_xlsx_col_names_name = __('Column names in first row'); $strConfigInitialSlidersState_name = __('Initial state for sliders'); $strConfigInsertRows_desc = __('How many rows can be inserted at one time'); $strConfigInsertRows_name = __('Number of inserted rows'); $strConfigLimitChars_desc = __('Maximum number of characters shown in any non-numeric column on browse view'); $strConfigLimitChars_name = __('Limit column characters'); $strConfigLoginCookieDeleteAll_desc = __('If TRUE, logout deletes cookies for all servers; when set to FALSE, logout only occurs for the current server. Setting this to FALSE makes it easy to forget to log out from other servers when connected to multiple servers.'); $strConfigLoginCookieDeleteAll_name = __('Delete all cookies on logout'); $strConfigLoginCookieRecall_desc = __('Define whether the previous login should be recalled or not in cookie authentication mode'); $strConfigLoginCookieRecall_name = __('Recall user name'); $strConfigLoginCookieStore_desc = __('Defines how long (in seconds) a login cookie should be stored in browser. The default of 0 means that it will be kept for the existing session only, and will be deleted as soon as you close the browser window. This is recommended for non-trusted environments.'); $strConfigLoginCookieStore_name = __('Login cookie store'); $strConfigLoginCookieValidity_desc = __('Define how long (in seconds) a login cookie is valid'); $strConfigLoginCookieValidity_name = __('Login cookie validity'); $strConfigLongtextDoubleTextarea_desc = __('Double size of textarea for LONGTEXT columns'); $strConfigLongtextDoubleTextarea_name = __('Bigger textarea for LONGTEXT'); $strConfigMaxCharactersInDisplayedSQL_desc = __('Maximum number of characters used when a SQL query is displayed'); $strConfigMaxCharactersInDisplayedSQL_name = __('Maximum displayed SQL length'); $strConfigMaxDbList_cmt = __('Users cannot set a higher value'); $strConfigMaxDbList_desc = __('Maximum number of databases displayed in database list'); $strConfigMaxDbList_name = __('Maximum databases'); $strConfigMaxNavigationItems_desc = __('The number of items that can be displayed on each page of the navigation tree'); $strConfigMaxNavigationItems_name = __('Maximum items in branch'); $strConfigMaxRows_desc = __('Number of rows displayed when browsing a result set. If the result set contains more rows, &quot;Previous&quot; and &quot;Next&quot; links will be shown.'); $strConfigMaxRows_name = __('Maximum number of rows to display'); $strConfigMaxTableList_cmt = __('Users cannot set a higher value'); $strConfigMaxTableList_desc = __('Maximum number of tables displayed in table list'); $strConfigMaxTableList_name = __('Maximum tables'); $strConfigMcryptDisableWarning_desc = __('Disable the default warning that is displayed if mcrypt is missing for cookie authentication'); $strConfigMcryptDisableWarning_name = __('mcrypt warning'); $strConfigMemoryLimit_desc = __('The number of bytes a script is allowed to allocate, eg. [kbd]32M[/kbd] ([kbd]0[/kbd] for no limit)'); $strConfigMemoryLimit_name = __('Memory limit'); $strConfigNavigationDisplayLogo_desc = __('Show logo in navigation panel'); $strConfigNavigationDisplayLogo_name = __('Display logo'); $strConfigNavigationLogoLink_desc = __('URL where logo in the navigation panel will point to'); $strConfigNavigationLogoLink_name = __('Logo link URL'); $strConfigNavigationLogoLinkWindow_desc = __('Open the linked page in the main window ([kbd]main[/kbd]) or in a new one ([kbd]new[/kbd])'); $strConfigNavigationLogoLinkWindow_name = __('Logo link target'); $strConfigNavigationDisplayServers_desc = __('Display server choice at the top of the navigation panel'); $strConfigNavigationDisplayServers_name = __('Display servers selection'); $strConfigNavigationTreeDefaultTabTable_name = __('Target for quick access icon'); $strConfigNavigationTreeDisplayItemFilterMinimum_desc = __('Defines the minimum number of items (tables, views, routines and events) to display a filter box.'); $strConfigNavigationTreeDisplayItemFilterMinimum_name = __('Minimum number of items to display the filter box'); $strConfigNavigationTreeDisplayDbFilterMinimum_name = __('Minimum number of databases to display the database filter box'); $strConfigNavigationTreeEnableGrouping_desc = __('Group items in the navigation tree (determined by the separator defined below)'); $strConfigNavigationTreeEnableGrouping_name = __('Group items in the tree'); $strConfigNavigationTreeDbSeparator_desc = __('String that separates databases into different tree levels'); $strConfigNavigationTreeDbSeparator_name = __('Database tree separator'); $strConfigNavigationTreeTableSeparator_desc = __('String that separates tables into different tree levels'); $strConfigNavigationTreeTableSeparator_name = __('Table tree separator'); $strConfigNavigationTreeTableLevel_name = __('Maximum table tree depth'); $strConfigNavigationTreePointerEnable_desc = __('Highlight server under the mouse cursor'); $strConfigNavigationTreePointerEnable_name = __('Enable highlighting'); $strConfigNumRecentTables_desc = __('Maximum number of recently used tables; set 0 to disable'); $strConfigNumRecentTables_name = __('Recently used tables'); $strConfigRowActionLinks_desc = __('These are Edit, Copy and Delete links'); $strConfigRowActionLinks_name = __('Where to show the table row links'); $strConfigNaturalOrder_desc = __('Use natural order for sorting table and database names'); $strConfigNaturalOrder_name = __('Natural order'); $strConfigTableNavigationLinksMode_desc = __('Use only icons, only text or both'); $strConfigTableNavigationLinksMode_name = __('Table navigation bar'); $strConfigOBGzip_desc = __('use GZip output buffering for increased speed in HTTP transfers'); $strConfigOBGzip_name = __('GZip output buffering'); $strConfigOrder_desc = __('[kbd]SMART[/kbd] - i.e. descending order for columns of type TIME, DATE, DATETIME and TIMESTAMP, ascending order otherwise'); $strConfigOrder_name = __('Default sorting order'); $strConfigPersistentConnections_desc = __('Use persistent connections to MySQL databases'); $strConfigPersistentConnections_name = __('Persistent connections'); $strConfigPmaNoRelation_DisableWarning_desc = __('Disable the default warning that is displayed on the database details Structure page if any of the required tables for the phpMyAdmin configuration storage could not be found'); $strConfigPmaNoRelation_DisableWarning_name = __('Missing phpMyAdmin configuration storage tables'); $strConfigServerLibraryDifference_DisableWarning_desc = __('Disable the default warning that is displayed if a difference between the MySQL library and server is detected'); $strConfigServerLibraryDifference_DisableWarning_name = __('Server/library difference warning'); $strConfigReservedWordDisableWarning_desc = __('Disable the default warning that is displayed on the Structure page if column names in a table are reserved MySQL words'); $strConfigReservedWordDisableWarning_name = __('MySQL reserved word warning'); $strConfigTabsMode_desc = __('Use only icons, only text or both'); $strConfigTabsMode_name = __('How to display the menu tabs'); $strConfigActionLinksMode_desc = __('Use only icons, only text or both'); $strConfigActionLinksMode_name = __('How to display various action links'); $strConfigProtectBinary_desc = __('Disallow BLOB and BINARY columns from editing'); $strConfigProtectBinary_name = __('Protect binary columns'); $strConfigQueryHistoryDB_desc = __('Enable if you want DB-based query history (requires phpMyAdmin configuration storage). If disabled, this utilizes JS-routines to display query history (lost by window close).'); $strConfigQueryHistoryDB_name = __('Permanent query history'); $strConfigQueryHistoryMax_cmt = __('Users cannot set a higher value'); $strConfigQueryHistoryMax_desc = __('How many queries are kept in history'); $strConfigQueryHistoryMax_name = __('Query history length'); $strConfigQueryWindowDefTab_desc = __('Tab displayed when opening a new query window'); $strConfigQueryWindowDefTab_name = __('Default query window tab'); $strConfigQueryWindowHeight_desc = __('Query window height (in pixels)'); $strConfigQueryWindowHeight_name = __('Query window height'); $strConfigQueryWindowWidth_desc = __('Query window width (in pixels)'); $strConfigQueryWindowWidth_name = __('Query window width'); $strConfigRecodingEngine_desc = __('Select which functions will be used for character set conversion'); $strConfigRecodingEngine_name = __('Recoding engine'); $strConfigRememberSorting_desc = __('When browsing tables, the sorting of each table is remembered'); $strConfigRememberSorting_name = __('Remember table\'s sorting'); $strConfigRepeatCells_desc = __('Repeat the headers every X cells, [kbd]0[/kbd] deactivates this feature'); $strConfigRepeatCells_name = __('Repeat headers'); $strConfigRestoreDefaultValue = __('Restore default value'); $strConfigGridEditing_name = __('Grid editing: trigger action'); $strConfigSaveCellsAtOnce_name = __('Grid editing: save all edited cells at once'); $strConfigSaveDir_desc = __('Directory where exports can be saved on server'); $strConfigSaveDir_name = __('Save directory'); $strConfigServers_AllowDeny_order_desc = __('Leave blank if not used'); $strConfigServers_AllowDeny_order_name = __('Host authorization order'); $strConfigServers_AllowDeny_rules_desc = __('Leave blank for defaults'); $strConfigServers_AllowDeny_rules_name = __('Host authorization rules'); $strConfigServers_AllowNoPassword_name = __('Allow logins without a password'); $strConfigServers_AllowRoot_name = __('Allow root login'); $strConfigServers_auth_http_realm_desc = __('HTTP Basic Auth Realm name to display when doing HTTP Auth'); $strConfigServers_auth_http_realm_name = __('HTTP Realm'); $strConfigServers_auth_swekey_config_desc = __('The path for the config file for [a@http://swekey.com]SweKey hardware authentication[/a] (not located in your document root; suggested: /etc/swekey.conf)'); $strConfigServers_auth_swekey_config_name = __('SweKey config file'); $strConfigServers_auth_type_desc = __('Authentication method to use'); $strConfigServers_auth_type_name = __('Authentication type'); $strConfigServers_bookmarktable_desc = __('Leave blank for no [a@http://wiki.phpmyadmin.net/pma/bookmark]bookmark[/a] support, suggested: [kbd]pma__bookmark[/kbd]'); $strConfigServers_bookmarktable_name = __('Bookmark table'); $strConfigServers_column_info_desc = __('Leave blank for no column comments/mime types, suggested: [kbd]pma__column_info[/kbd]'); $strConfigServers_column_info_name = __('Column information table'); $strConfigServers_compress_desc = __('Compress connection to MySQL server'); $strConfigServers_compress_name = __('Compress connection'); $strConfigServers_connect_type_desc = __('How to connect to server, keep [kbd]tcp[/kbd] if unsure'); $strConfigServers_connect_type_name = __('Connection type'); $strConfigServers_controlpass_name = __('Control user password'); $strConfigServers_controluser_desc = __('A special MySQL user configured with limited permissions, more information available on [a@http://wiki.phpmyadmin.net/pma/controluser]wiki[/a]'); $strConfigServers_controluser_name = __('Control user'); $strConfigServers_controlhost_desc = __('An alternate host to hold the configuration storage; leave blank to use the already defined host'); $strConfigServers_controlhost_name = __('Control host'); $strConfigServers_controlport_desc = __('An alternate port to connect to the host that holds the configuration storage; leave blank to use the default port, or the already defined port, if the controlhost equals host'); $strConfigServers_controlport_name = __('Control port'); $strConfigServers_designer_coords_desc = __('Leave blank for no Designer support, suggested: [kbd]pma__designer_coords[/kbd]'); $strConfigServers_designer_coords_name = __('Designer table'); $strConfigServers_extension_desc = __('What PHP extension to use; you should use mysqli if supported'); $strConfigServers_extension_name = __('PHP extension to use'); $strConfigServers_hide_db_desc = __('Hide databases matching regular expression (PCRE)'); $strConfigServers_hide_db_name = __('Hide databases'); $strConfigServers_history_desc = __('Leave blank for no SQL query history support, suggested: [kbd]pma__history[/kbd]'); $strConfigServers_history_name = __('SQL query history table'); $strConfigServers_host_desc = __('Hostname where MySQL server is running'); $strConfigServers_host_name = __('Server hostname'); $strConfigServers_LogoutURL_name = __('Logout URL'); $strConfigServers_MaxTableUiprefs_desc = __('Limits number of table preferences which are stored in database, the oldest records are automatically removed'); $strConfigServers_MaxTableUiprefs_name = __('Maximal number of table preferences to store'); $strConfigServers_nopassword_desc = __('Try to connect without password'); $strConfigServers_nopassword_name = __('Connect without password'); $strConfigServers_only_db_desc = __('You can use MySQL wildcard characters (% and _), escape them if you want to use their literal instances, i.e. use [kbd]\'my\_db\'[/kbd] and not [kbd]\'my_db\'[/kbd].'); $strConfigServers_only_db_name = __('Show only listed databases'); $strConfigServers_password_desc = __('Leave empty if not using config auth'); $strConfigServers_password_name = __('Password for config auth'); $strConfigServers_pdf_pages_desc = __('Leave blank for no PDF schema support, suggested: [kbd]pma__pdf_pages[/kbd]'); $strConfigServers_pdf_pages_name = __('PDF schema: pages table'); $strConfigServers_pmadb_desc = __('Database used for relations, bookmarks, and PDF features. See [a@http://wiki.phpmyadmin.net/pma/pmadb]pmadb[/a] for complete information. Leave blank for no support. Suggested: [kbd]phpmyadmin[/kbd]'); $strConfigServers_pmadb_name = __('Database name'); $strConfigServers_port_desc = __('Port on which MySQL server is listening, leave empty for default'); $strConfigServers_port_name = __('Server port'); $strConfigServers_recent_desc = __('Leave blank for no "persistent" recently used tables across sessions, suggested: [kbd]pma__recent[/kbd]'); $strConfigServers_recent_name = __('Recently used table'); $strConfigServers_relation_desc = __('Leave blank for no [a@http://wiki.phpmyadmin.net/pma/relation]relation-links[/a] support, suggested: [kbd]pma__relation[/kbd]'); $strConfigServers_relation_name = __('Relation table'); $strConfigServers_SignonSession_desc = __('See [a@http://wiki.phpmyadmin.net/pma/auth_types#signon]authentication types[/a] for an example'); $strConfigServers_SignonSession_name = __('Signon session name'); $strConfigServers_SignonURL_name = __('Signon URL'); $strConfigServers_socket_desc = __('Socket on which MySQL server is listening, leave empty for default'); $strConfigServers_socket_name = __('Server socket'); $strConfigServers_ssl_desc = __('Enable SSL for connection to MySQL server'); $strConfigServers_ssl_name = __('Use SSL'); $strConfigServers_table_coords_desc = __('Leave blank for no PDF schema support, suggested: [kbd]pma__table_coords[/kbd]'); $strConfigServers_table_coords_name = __('PDF schema: table coordinates'); $strConfigServers_table_info_desc = __('Table to describe the display columns, leave blank for no support; suggested: [kbd]pma__table_info[/kbd]'); $strConfigServers_table_info_name = __('Display columns table'); $strConfigServers_table_uiprefs_desc = __('Leave blank for no "persistent" tables\' UI preferences across sessions, suggested: [kbd]pma__table_uiprefs[/kbd]'); $strConfigServers_table_uiprefs_name = __('UI preferences table'); $strConfigServers_tracking_add_drop_database_desc = __('Whether a DROP DATABASE IF EXISTS statement will be added as first line to the log when creating a database.'); $strConfigServers_tracking_add_drop_database_name = __('Add DROP DATABASE'); $strConfigServers_tracking_add_drop_table_desc = __('Whether a DROP TABLE IF EXISTS statement will be added as first line to the log when creating a table.'); $strConfigServers_tracking_add_drop_table_name = __('Add DROP TABLE'); $strConfigServers_tracking_add_drop_view_desc = __('Whether a DROP VIEW IF EXISTS statement will be added as first line to the log when creating a view.'); $strConfigServers_tracking_add_drop_view_name = __('Add DROP VIEW'); $strConfigServers_tracking_default_statements_desc = __('Defines the list of statements the auto-creation uses for new versions.'); $strConfigServers_tracking_default_statements_name = __('Statements to track'); $strConfigServers_tracking_desc = __('Leave blank for no SQL query tracking support, suggested: [kbd]pma__tracking[/kbd]'); $strConfigServers_tracking_name = __('SQL query tracking table'); $strConfigServers_tracking_version_auto_create_desc = __('Whether the tracking mechanism creates versions for tables and views automatically.'); $strConfigServers_tracking_version_auto_create_name = __('Automatically create versions'); $strConfigServers_userconfig_desc = __('Leave blank for no user preferences storage in database, suggested: [kbd]pma__userconfig[/kbd]'); $strConfigServers_userconfig_name = __('User preferences storage table'); $strConfigServers_users_desc = __('Leave blank to disable configurable menus feature, suggested: [kbd]pma__users[/kbd]'); $strConfigServers_users_name = __('Users table'); $strConfigServers_usergroups_desc = __('Leave blank to disable configurable menus feature, suggested: [kbd]pma__usergroups[/kbd]'); $strConfigServers_usergroups_name = __('User groups table'); $strConfigServers_navigationhiding_desc = __('Leave blank to disable the feature to hide and show navigation items, suggested: [kbd]pma__navigationhiding[/kbd]'); $strConfigServers_navigationhiding_name = __('Hidden navigation items table'); $strConfigServers_user_desc = __('Leave empty if not using config auth'); $strConfigServers_user_name = __('User for config auth'); $strConfigServers_verbose_desc = __('A user-friendly description of this server. Leave blank to display the hostname instead.'); $strConfigServers_verbose_name = __('Verbose name of this server'); $strConfigShowAll_desc = __('Whether a user should be displayed a &quot;show all (rows)&quot; button'); $strConfigShowAll_name = __('Allow to display all the rows'); $strConfigShowChgPassword_desc = __('Please note that enabling this has no effect with [kbd]config[/kbd] authentication mode because the password is hard coded in the configuration file; this does not limit the ability to execute the same command directly'); $strConfigShowChgPassword_name = __('Show password change form'); $strConfigShowCreateDb_name = __('Show create database form'); $strConfigShowDbStructureCreation_desc = __('Show or hide a column displaying the Creation timestamp for all tables'); $strConfigShowDbStructureCreation_name = __('Show Creation timestamp'); $strConfigShowDbStructureLastUpdate_desc = __('Show or hide a column displaying the Last update timestamp for all tables'); $strConfigShowDbStructureLastUpdate_name = __('Show Last update timestamp'); $strConfigShowDbStructureLastCheck_desc = __('Show or hide a column displaying the Last check timestamp for all tables'); $strConfigShowDbStructureLastCheck_name = __('Show Last check timestamp'); $strConfigShowDisplayDirection_desc = __('Defines whether or not type display direction option is shown when browsing a table'); $strConfigShowDisplayDirection_name = __('Show display direction'); $strConfigShowFieldTypesInDataEditView_desc = __('Defines whether or not type fields should be initially displayed in edit/insert mode'); $strConfigShowFieldTypesInDataEditView_name = __('Show field types'); $strConfigShowFunctionFields_desc = __('Display the function fields in edit/insert mode'); $strConfigShowFunctionFields_name = __('Show function fields'); $strConfigShowHint_desc = __('Whether to show hint or not'); $strConfigShowHint_name = __('Show hint'); $strConfigShowPhpInfo_desc = __('Shows link to [a@http://php.net/manual/function.phpinfo.php]phpinfo()[/a] output'); $strConfigShowPhpInfo_name = __('Show phpinfo() link'); $strConfigShowServerInfo_name = __('Show detailed MySQL server information'); $strConfigShowSQL_desc = __('Defines whether SQL queries generated by phpMyAdmin should be displayed'); $strConfigShowSQL_name = __('Show SQL queries'); $strConfigRetainQueryBox_desc = __('Defines whether the query box should stay on-screen after its submission'); $strConfigRetainQueryBox_name = __('Retain query box'); $strConfigShowStats_desc = __('Allow to display database and table statistics (eg. space usage)'); $strConfigShowStats_name = __('Show statistics'); $strConfigSkipLockedTables_desc = __('Mark used tables and make it possible to show databases with locked tables'); $strConfigSkipLockedTables_name = __('Skip locked tables'); $strConfigSQLQuery_Edit_name = __('Edit'); $strConfigSQLQuery_Explain_name = __('Explain SQL'); $strConfigSQLQuery_Refresh_name = __('Refresh'); $strConfigSQLQuery_ShowAsPHP_name = __('Create PHP Code'); $strConfigSQLQuery_Validate_desc = __('Requires SQL Validator to be enabled'); $strConfigSQLQuery_Validate_name = __('Validate SQL'); $strConfigSQLValidator_password_name = __('Password'); $strConfigSQLValidator_use_desc = __('[strong]Warning:[/strong] requires PHP SOAP extension or PEAR SOAP to be installed'); $strConfigSQLValidator_use_name = __('Enable SQL Validator'); $strConfigSQLValidator_username_desc = __('If you have a custom username, specify it here (defaults to [kbd]anonymous[/kbd])'); $strConfigSQLValidator_username_name = __('Username'); $strConfigSuhosinDisableWarning_desc = __('A warning is displayed on the main page if Suhosin is detected'); $strConfigSuhosinDisableWarning_name = __('Suhosin warning'); $strConfigTextareaCols_desc = __('Textarea size (columns) in edit mode, this value will be emphasized for SQL query textareas (*2) and for query window (*1.25)'); $strConfigTextareaCols_name = __('Textarea columns'); $strConfigTextareaRows_desc = __('Textarea size (rows) in edit mode, this value will be emphasized for SQL query textareas (*2) and for query window (*1.25)'); $strConfigTextareaRows_name = __('Textarea rows'); $strConfigTitleDatabase_desc = __('Title of browser window when a database is selected'); $strConfigTitleDatabase_name = __('Database'); $strConfigTitleDefault_desc = __('Title of browser window when nothing is selected'); $strConfigTitleDefault_name = __('Default title'); $strConfigTitleServer_desc = __('Title of browser window when a server is selected'); $strConfigTitleServer_name = __('Server'); $strConfigTitleTable_desc = __('Title of browser window when a table is selected'); $strConfigTitleTable_name = __('Table'); $strConfigTrustedProxies_desc = __('Input proxies as [kbd]IP: trusted HTTP header[/kbd]. The following example specifies that phpMyAdmin should trust a HTTP_X_FORWARDED_FOR (X-Forwarded-For) header coming from the proxy 1.2.3.4:[br][kbd]1.2.3.4: HTTP_X_FORWARDED_FOR[/kbd]'); $strConfigTrustedProxies_name = __('List of trusted proxies for IP allow/deny'); $strConfigUploadDir_desc = __('Directory on server where you can upload files for import'); $strConfigUploadDir_name = __('Upload directory'); $strConfigUseDbSearch_desc = __('Allow for searching inside the entire database'); $strConfigUseDbSearch_name = __('Use database search'); $strConfigUserprefsDeveloperTab_desc = __('When disabled, users cannot set any of the options below, regardless of the checkbox on the right'); $strConfigUserprefsDeveloperTab_name = __('Enable the Developer tab in settings'); $strConfigVersionCheckLink = __('Check for latest version'); $strConfigVersionCheck_desc = __('Enables check for latest version on main phpMyAdmin page'); $strConfigVersionCheck_name = __('Version check'); $strConfigProxyUrl_desc = __('The url of the proxy to be used when retrieving the information about the latest version of phpMyAdmin or when submitting error reports. You need this if the server where phpMyAdmin is installed does not have direct access to the internet. The format is: "hostname:portnumber"'); $strConfigProxyUrl_name = __('Proxy url'); $strConfigProxyUser_desc = __('The username for authenticating with the proxy. By default, no authentication is performed. If a username is supplied, Basic Authentication will be performed. No other types of authentication are currently supported.'); $strConfigProxyUser_name = __('Proxy username'); $strConfigProxyPass_desc = __('The password for authenticating with the proxy'); $strConfigProxyPass_name = __('Proxy password'); $strConfigZipDump_desc = __('Enable [a@http://en.wikipedia.org/wiki/ZIP_(file_format)]ZIP[/a] compression for import and export operations'); $strConfigZipDump_name = __('ZIP'); $strConfigCaptchaLoginPublicKey_desc = __('Enter your public key for your domain reCaptcha service'); $strConfigCaptchaLoginPublicKey_name = __('Public key for reCaptcha'); $strConfigCaptchaLoginPrivateKey_desc = __('Enter your private key for your domain reCaptcha service'); $strConfigCaptchaLoginPrivateKey_name = __('Private key for reCaptcha'); $strConfigSendErrorReports_desc = __('Choose the default action when sending error reports'); $strConfigSendErrorReports_name = __('Send error reports'); ?>
gpl-2.0
SketchMagento/mage_crowdfunding
lib/Zend/Pdf/Element/Numeric.php
2272
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Pdf * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** Zend_Pdf_Element */ #require_once 'Zend/Pdf/Element.php'; /** * PDF file 'numeric' element implementation * * @category Zend * @package Zend_Pdf * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Pdf_Element_Numeric extends Zend_Pdf_Element { /** * Object value * * @var numeric */ public $value; /** * Object constructor * * @param numeric $val * @throws Zend_Pdf_Exception */ public function __construct($val) { if ( !is_numeric($val) ) { #require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Argument must be numeric'); } $this->value = $val; } /** * Return type of the element. * * @return integer */ public function getType() { return Zend_Pdf_Element::TYPE_NUMERIC; } /** * Return object as string * * @param Zend_Pdf_Factory $factory * @return string */ public function toString($factory = null) { if (is_integer($this->value)) { return (string)$this->value; } /** * PDF doesn't support exponental format. * Fixed point format must be used instead */ $prec = 0; $v = $this->value; while (abs( floor($v) - $v ) > 1e-10) { $prec++; $v *= 10; } return sprintf("%.{$prec}F", $this->value); } }
gpl-3.0
dvitme/odoomrp-wip
product_purchase_warrant/models/stock.py
2973
# -*- encoding: utf-8 -*- ############################################################################## # # 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/. # ############################################################################## from openerp import fields, models, api from dateutil.relativedelta import relativedelta class StockProductionLot(models.Model): _inherit = "stock.production.lot" warrant_limit = fields.Datetime(string="Warranty") @api.model def create(self, vals): if vals.get('product_id'): product = self.env["product.product"].browse(vals["product_id"]) create_date = ( 'create_date' in vals and vals['create_date'] or fields.Datetime.from_string( fields.Datetime.now())) if 'sup_warrant' not in self.env.context: warrant_limit = ( product.warranty and (create_date + relativedelta(months=int(product.warranty)))) else: warrant_limit = ( create_date + relativedelta(months=self.env.context['sup_warrant'])) if warrant_limit: vals.update({'warrant_limit': warrant_limit}) return super(StockProductionLot, self).create(vals) class StockPackOperation(models.Model): _inherit = "stock.pack.operation" def create_and_assign_lot(self, cr, uid, pack_oper_id, name, context=None): if context is None: context = {} ctx = context.copy() pack_oper = self.browse(cr, uid, pack_oper_id, context=context) if pack_oper.picking_id.location_id.usage == 'supplier': sup_obj = self.pool['product.supplierinfo'] suppinfo_id = sup_obj.search( cr, uid, [('name', '=', pack_oper.picking_id.partner_id.id), ('product_tmpl_id', '=', pack_oper.product_id.product_tmpl_id.id)], context=context) sup = sup_obj.browse(cr, uid, suppinfo_id, context=context) sup_warrant = sup and sup[0].warrant_months ctx.update({'sup_warrant': sup_warrant}) return super(StockPackOperation, self).create_and_assign_lot( cr, uid, pack_oper_id, name, context=ctx)
agpl-3.0
nilabhsagar/elasticsearch
core/src/main/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolver.java
44554
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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 org.elasticsearch.cluster.metadata; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.joda.DateMathParser; import org.elasticsearch.common.joda.FormatDateTimeFormatter; import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.indices.IndexClosedException; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class IndexNameExpressionResolver extends AbstractComponent { private final List<ExpressionResolver> expressionResolvers; private final DateMathExpressionResolver dateMathExpressionResolver; public IndexNameExpressionResolver(Settings settings) { super(settings); expressionResolvers = Arrays.asList( dateMathExpressionResolver = new DateMathExpressionResolver(settings), new WildcardExpressionResolver() ); } /** * Same as {@link #concreteIndexNames(ClusterState, IndicesOptions, String...)}, but the index expressions and options * are encapsulated in the specified request. */ public String[] concreteIndexNames(ClusterState state, IndicesRequest request) { Context context = new Context(state, request.indicesOptions()); return concreteIndexNames(context, request.indices()); } /** * Same as {@link #concreteIndices(ClusterState, IndicesOptions, String...)}, but the index expressions and options * are encapsulated in the specified request. */ public Index[] concreteIndices(ClusterState state, IndicesRequest request) { Context context = new Context(state, request.indicesOptions()); return concreteIndices(context, request.indices()); } /** * Translates the provided index expression into actual concrete indices, properly deduplicated. * * @param state the cluster state containing all the data to resolve to expressions to concrete indices * @param options defines how the aliases or indices need to be resolved to concrete indices * @param indexExpressions expressions that can be resolved to alias or index names. * @return the resolved concrete indices based on the cluster state, indices options and index expressions * @throws IndexNotFoundException if one of the index expressions is pointing to a missing index or alias and the * provided indices options in the context don't allow such a case, or if the final result of the indices resolution * contains no indices and the indices options in the context don't allow such a case. * @throws IllegalArgumentException if one of the aliases resolve to multiple indices and the provided * indices options in the context don't allow such a case. */ public String[] concreteIndexNames(ClusterState state, IndicesOptions options, String... indexExpressions) { Context context = new Context(state, options); return concreteIndexNames(context, indexExpressions); } /** * Translates the provided index expression into actual concrete indices, properly deduplicated. * * @param state the cluster state containing all the data to resolve to expressions to concrete indices * @param options defines how the aliases or indices need to be resolved to concrete indices * @param indexExpressions expressions that can be resolved to alias or index names. * @return the resolved concrete indices based on the cluster state, indices options and index expressions * @throws IndexNotFoundException if one of the index expressions is pointing to a missing index or alias and the * provided indices options in the context don't allow such a case, or if the final result of the indices resolution * contains no indices and the indices options in the context don't allow such a case. * @throws IllegalArgumentException if one of the aliases resolve to multiple indices and the provided * indices options in the context don't allow such a case. */ public Index[] concreteIndices(ClusterState state, IndicesOptions options, String... indexExpressions) { Context context = new Context(state, options); return concreteIndices(context, indexExpressions); } /** * Translates the provided index expression into actual concrete indices, properly deduplicated. * * @param state the cluster state containing all the data to resolve to expressions to concrete indices * @param options defines how the aliases or indices need to be resolved to concrete indices * @param startTime The start of the request where concrete indices is being invoked for * @param indexExpressions expressions that can be resolved to alias or index names. * @return the resolved concrete indices based on the cluster state, indices options and index expressions * provided indices options in the context don't allow such a case, or if the final result of the indices resolution * contains no indices and the indices options in the context don't allow such a case. * @throws IllegalArgumentException if one of the aliases resolve to multiple indices and the provided * indices options in the context don't allow such a case. */ public Index[] concreteIndices(ClusterState state, IndicesOptions options, long startTime, String... indexExpressions) { Context context = new Context(state, options, startTime); return concreteIndices(context, indexExpressions); } String[] concreteIndexNames(Context context, String... indexExpressions) { Index[] indexes = concreteIndices(context, indexExpressions); String[] names = new String[indexes.length]; for (int i = 0; i < indexes.length; i++) { names[i] = indexes[i].getName(); } return names; } Index[] concreteIndices(Context context, String... indexExpressions) { if (indexExpressions == null || indexExpressions.length == 0) { indexExpressions = new String[]{MetaData.ALL}; } MetaData metaData = context.getState().metaData(); IndicesOptions options = context.getOptions(); boolean failClosed = options.forbidClosedIndices() && options.ignoreUnavailable() == false; boolean failNoIndices = options.ignoreUnavailable() == false; // If only one index is specified then whether we fail a request if an index is missing depends on the allow_no_indices // option. At some point we should change this, because there shouldn't be a reason why whether a single index // or multiple indices are specified yield different behaviour. if (indexExpressions.length == 1) { failNoIndices = options.allowNoIndices() == false; } List<String> expressions = Arrays.asList(indexExpressions); for (ExpressionResolver expressionResolver : expressionResolvers) { expressions = expressionResolver.resolve(context, expressions); } if (expressions.isEmpty()) { if (!options.allowNoIndices()) { IndexNotFoundException infe = new IndexNotFoundException((String)null); infe.setResources("index_expression", indexExpressions); throw infe; } else { return Index.EMPTY_ARRAY; } } final Set<Index> concreteIndices = new HashSet<>(expressions.size()); for (String expression : expressions) { AliasOrIndex aliasOrIndex = metaData.getAliasAndIndexLookup().get(expression); if (aliasOrIndex == null) { if (failNoIndices) { IndexNotFoundException infe = new IndexNotFoundException(expression); infe.setResources("index_expression", expression); throw infe; } else { continue; } } Collection<IndexMetaData> resolvedIndices = aliasOrIndex.getIndices(); if (resolvedIndices.size() > 1 && !options.allowAliasesToMultipleIndices()) { String[] indexNames = new String[resolvedIndices.size()]; int i = 0; for (IndexMetaData indexMetaData : resolvedIndices) { indexNames[i++] = indexMetaData.getIndex().getName(); } throw new IllegalArgumentException("Alias [" + expression + "] has more than one indices associated with it [" + Arrays.toString(indexNames) + "], can't execute a single index op"); } for (IndexMetaData index : resolvedIndices) { if (index.getState() == IndexMetaData.State.CLOSE) { if (failClosed) { throw new IndexClosedException(index.getIndex()); } else { if (options.forbidClosedIndices() == false) { concreteIndices.add(index.getIndex()); } } } else if (index.getState() == IndexMetaData.State.OPEN) { concreteIndices.add(index.getIndex()); } else { throw new IllegalStateException("index state [" + index.getState() + "] not supported"); } } } if (options.allowNoIndices() == false && concreteIndices.isEmpty()) { IndexNotFoundException infe = new IndexNotFoundException((String)null); infe.setResources("index_expression", indexExpressions); throw infe; } return concreteIndices.toArray(new Index[concreteIndices.size()]); } /** * Utility method that allows to resolve an index expression to its corresponding single concrete index. * Callers should make sure they provide proper {@link org.elasticsearch.action.support.IndicesOptions} * that require a single index as a result. The indices resolution must in fact return a single index when * using this method, an {@link IllegalArgumentException} gets thrown otherwise. * * @param state the cluster state containing all the data to resolve to expression to a concrete index * @param request The request that defines how the an alias or an index need to be resolved to a concrete index * and the expression that can be resolved to an alias or an index name. * @throws IllegalArgumentException if the index resolution lead to more than one index * @return the concrete index obtained as a result of the index resolution */ public Index concreteSingleIndex(ClusterState state, IndicesRequest request) { String indexExpression = request.indices() != null && request.indices().length > 0 ? request.indices()[0] : null; Index[] indices = concreteIndices(state, request.indicesOptions(), indexExpression); if (indices.length != 1) { throw new IllegalArgumentException("unable to return a single index as the index and options provided got resolved to multiple indices"); } return indices[0]; } /** * @return whether the specified alias or index exists. If the alias or index contains datemath then that is resolved too. */ public boolean hasIndexOrAlias(String aliasOrIndex, ClusterState state) { Context context = new Context(state, IndicesOptions.lenientExpandOpen()); String resolvedAliasOrIndex = dateMathExpressionResolver.resolveExpression(aliasOrIndex, context); return state.metaData().getAliasAndIndexLookup().containsKey(resolvedAliasOrIndex); } /** * @return If the specified string is data math expression then this method returns the resolved expression. */ public String resolveDateMathExpression(String dateExpression) { // The data math expression resolver doesn't rely on cluster state or indices options, because // it just resolves the date math to an actual date. return dateMathExpressionResolver.resolveExpression(dateExpression, new Context(null, null)); } /** * Iterates through the list of indices and selects the effective list of filtering aliases for the * given index. * <p>Only aliases with filters are returned. If the indices list contains a non-filtering reference to * the index itself - null is returned. Returns <tt>null</tt> if no filtering is required. */ public String[] filteringAliases(ClusterState state, String index, String... expressions) { // expand the aliases wildcard List<String> resolvedExpressions = expressions != null ? Arrays.asList(expressions) : Collections.<String>emptyList(); Context context = new Context(state, IndicesOptions.lenientExpandOpen(), true); for (ExpressionResolver expressionResolver : expressionResolvers) { resolvedExpressions = expressionResolver.resolve(context, resolvedExpressions); } if (isAllIndices(resolvedExpressions)) { return null; } // optimize for the most common single index/alias scenario if (resolvedExpressions.size() == 1) { String alias = resolvedExpressions.get(0); IndexMetaData indexMetaData = state.metaData().getIndices().get(index); if (indexMetaData == null) { // Shouldn't happen throw new IndexNotFoundException(index); } AliasMetaData aliasMetaData = indexMetaData.getAliases().get(alias); boolean filteringRequired = aliasMetaData != null && aliasMetaData.filteringRequired(); if (!filteringRequired) { return null; } return new String[]{alias}; } List<String> filteringAliases = null; for (String alias : resolvedExpressions) { if (alias.equals(index)) { return null; } IndexMetaData indexMetaData = state.metaData().getIndices().get(index); if (indexMetaData == null) { // Shouldn't happen throw new IndexNotFoundException(index); } AliasMetaData aliasMetaData = indexMetaData.getAliases().get(alias); // Check that this is an alias for the current index // Otherwise - skip it if (aliasMetaData != null) { boolean filteringRequired = aliasMetaData.filteringRequired(); if (filteringRequired) { // If filtering required - add it to the list of filters if (filteringAliases == null) { filteringAliases = new ArrayList<>(); } filteringAliases.add(alias); } else { // If not, we have a non filtering alias for this index - no filtering needed return null; } } } if (filteringAliases == null) { return null; } return filteringAliases.toArray(new String[filteringAliases.size()]); } /** * Resolves the search routing if in the expression aliases are used. If expressions point to concrete indices * or aliases with no routing defined the specified routing is used. * * @return routing values grouped by concrete index */ public Map<String, Set<String>> resolveSearchRouting(ClusterState state, @Nullable String routing, String... expressions) { List<String> resolvedExpressions = expressions != null ? Arrays.asList(expressions) : Collections.<String>emptyList(); Context context = new Context(state, IndicesOptions.lenientExpandOpen()); for (ExpressionResolver expressionResolver : expressionResolvers) { resolvedExpressions = expressionResolver.resolve(context, resolvedExpressions); } if (isAllIndices(resolvedExpressions)) { return resolveSearchRoutingAllIndices(state.metaData(), routing); } Map<String, Set<String>> routings = null; Set<String> paramRouting = null; // List of indices that don't require any routing Set<String> norouting = new HashSet<>(); if (routing != null) { paramRouting = Strings.splitStringByCommaToSet(routing); } for (String expression : resolvedExpressions) { AliasOrIndex aliasOrIndex = state.metaData().getAliasAndIndexLookup().get(expression); if (aliasOrIndex != null && aliasOrIndex.isAlias()) { AliasOrIndex.Alias alias = (AliasOrIndex.Alias) aliasOrIndex; for (Tuple<String, AliasMetaData> item : alias.getConcreteIndexAndAliasMetaDatas()) { String concreteIndex = item.v1(); AliasMetaData aliasMetaData = item.v2(); if (!norouting.contains(concreteIndex)) { if (!aliasMetaData.searchRoutingValues().isEmpty()) { // Routing alias if (routings == null) { routings = new HashMap<>(); } Set<String> r = routings.get(concreteIndex); if (r == null) { r = new HashSet<>(); routings.put(concreteIndex, r); } r.addAll(aliasMetaData.searchRoutingValues()); if (paramRouting != null) { r.retainAll(paramRouting); } if (r.isEmpty()) { routings.remove(concreteIndex); } } else { // Non-routing alias if (!norouting.contains(concreteIndex)) { norouting.add(concreteIndex); if (paramRouting != null) { Set<String> r = new HashSet<>(paramRouting); if (routings == null) { routings = new HashMap<>(); } routings.put(concreteIndex, r); } else { if (routings != null) { routings.remove(concreteIndex); } } } } } } } else { // Index if (!norouting.contains(expression)) { norouting.add(expression); if (paramRouting != null) { Set<String> r = new HashSet<>(paramRouting); if (routings == null) { routings = new HashMap<>(); } routings.put(expression, r); } else { if (routings != null) { routings.remove(expression); } } } } } if (routings == null || routings.isEmpty()) { return null; } return routings; } /** * Sets the same routing for all indices */ private Map<String, Set<String>> resolveSearchRoutingAllIndices(MetaData metaData, String routing) { if (routing != null) { Set<String> r = Strings.splitStringByCommaToSet(routing); Map<String, Set<String>> routings = new HashMap<>(); String[] concreteIndices = metaData.getConcreteAllIndices(); for (String index : concreteIndices) { routings.put(index, r); } return routings; } return null; } /** * Identifies whether the array containing index names given as argument refers to all indices * The empty or null array identifies all indices * * @param aliasesOrIndices the array containing index names * @return true if the provided array maps to all indices, false otherwise */ public static boolean isAllIndices(List<String> aliasesOrIndices) { return aliasesOrIndices == null || aliasesOrIndices.isEmpty() || isExplicitAllPattern(aliasesOrIndices); } /** * Identifies whether the array containing index names given as argument explicitly refers to all indices * The empty or null array doesn't explicitly map to all indices * * @param aliasesOrIndices the array containing index names * @return true if the provided array explicitly maps to all indices, false otherwise */ static boolean isExplicitAllPattern(List<String> aliasesOrIndices) { return aliasesOrIndices != null && aliasesOrIndices.size() == 1 && MetaData.ALL.equals(aliasesOrIndices.get(0)); } /** * Identifies whether the first argument (an array containing index names) is a pattern that matches all indices * * @param indicesOrAliases the array containing index names * @param concreteIndices array containing the concrete indices that the first argument refers to * @return true if the first argument is a pattern that maps to all available indices, false otherwise */ boolean isPatternMatchingAllIndices(MetaData metaData, String[] indicesOrAliases, String[] concreteIndices) { // if we end up matching on all indices, check, if its a wildcard parameter, or a "-something" structure if (concreteIndices.length == metaData.getConcreteAllIndices().length && indicesOrAliases.length > 0) { //we might have something like /-test1,+test1 that would identify all indices //or something like /-test1 with test1 index missing and IndicesOptions.lenient() if (indicesOrAliases[0].charAt(0) == '-') { return true; } //otherwise we check if there's any simple regex for (String indexOrAlias : indicesOrAliases) { if (Regex.isSimpleMatchPattern(indexOrAlias)) { return true; } } } return false; } static final class Context { private final ClusterState state; private final IndicesOptions options; private final long startTime; private final boolean preserveAliases; Context(ClusterState state, IndicesOptions options) { this(state, options, System.currentTimeMillis()); } Context(ClusterState state, IndicesOptions options, boolean preserveAliases) { this(state, options, System.currentTimeMillis(), preserveAliases); } Context(ClusterState state, IndicesOptions options, long startTime) { this(state, options, startTime, false); } Context(ClusterState state, IndicesOptions options, long startTime, boolean preserveAliases) { this.state = state; this.options = options; this.startTime = startTime; this.preserveAliases = preserveAliases; } public ClusterState getState() { return state; } public IndicesOptions getOptions() { return options; } public long getStartTime() { return startTime; } /** * This is used to prevent resolving aliases to concrete indices but this also means * that we might return aliases that point to a closed index. This is currently only used * by {@link #filteringAliases(ClusterState, String, String...)} since it's the only one that needs aliases */ boolean isPreserveAliases() { return preserveAliases; } } private interface ExpressionResolver { /** * Resolves the list of expressions into other expressions if possible (possible concrete indices and aliases, but * that isn't required). The provided implementations can also be left untouched. * * @return a new list with expressions based on the provided expressions */ List<String> resolve(Context context, List<String> expressions); } /** * Resolves alias/index name expressions with wildcards into the corresponding concrete indices/aliases */ static final class WildcardExpressionResolver implements ExpressionResolver { @Override public List<String> resolve(Context context, List<String> expressions) { IndicesOptions options = context.getOptions(); MetaData metaData = context.getState().metaData(); if (options.expandWildcardsClosed() == false && options.expandWildcardsOpen() == false) { return expressions; } if (isEmptyOrTrivialWildcard(expressions)) { return resolveEmptyOrTrivialWildcard(options, metaData, true); } Set<String> result = innerResolve(context, expressions, options, metaData); if (result == null) { return expressions; } if (result.isEmpty() && !options.allowNoIndices()) { IndexNotFoundException infe = new IndexNotFoundException((String)null); infe.setResources("index_or_alias", expressions.toArray(new String[0])); throw infe; } return new ArrayList<>(result); } private Set<String> innerResolve(Context context, List<String> expressions, IndicesOptions options, MetaData metaData) { Set<String> result = null; boolean wildcardSeen = false; for (int i = 0; i < expressions.size(); i++) { String expression = expressions.get(i); if (aliasOrIndexExists(metaData, expression)) { if (result != null) { result.add(expression); } continue; } if (Strings.isEmpty(expression)) { throw infe(expression); } boolean add = true; if (expression.charAt(0) == '+') { // if its the first, add empty result set if (i == 0) { result = new HashSet<>(); } expression = expression.substring(1); } else if (expression.charAt(0) == '-') { // if there is a negation without a wildcard being previously seen, add it verbatim, // otherwise return the expression if (wildcardSeen) { add = false; expression = expression.substring(1); } else { add = true; } } if (result == null) { // add all the previous ones... result = new HashSet<>(expressions.subList(0, i)); } if (!Regex.isSimpleMatchPattern(expression)) { if (!unavailableIgnoredOrExists(options, metaData, expression)) { throw infe(expression); } if (add) { result.add(expression); } else { result.remove(expression); } continue; } final IndexMetaData.State excludeState = excludeState(options); final Map<String, AliasOrIndex> matches = matches(metaData, expression); Set<String> expand = expand(context, excludeState, matches); if (add) { result.addAll(expand); } else { result.removeAll(expand); } if (!noIndicesAllowedOrMatches(options, matches)) { throw infe(expression); } if (Regex.isSimpleMatchPattern(expression)) { wildcardSeen = true; } } return result; } private boolean noIndicesAllowedOrMatches(IndicesOptions options, Map<String, AliasOrIndex> matches) { return options.allowNoIndices() || !matches.isEmpty(); } private boolean unavailableIgnoredOrExists(IndicesOptions options, MetaData metaData, String expression) { return options.ignoreUnavailable() || aliasOrIndexExists(metaData, expression); } private boolean aliasOrIndexExists(MetaData metaData, String expression) { return metaData.getAliasAndIndexLookup().containsKey(expression); } private static IndexNotFoundException infe(String expression) { IndexNotFoundException infe = new IndexNotFoundException(expression); infe.setResources("index_or_alias", expression); return infe; } private static IndexMetaData.State excludeState(IndicesOptions options) { final IndexMetaData.State excludeState; if (options.expandWildcardsOpen() && options.expandWildcardsClosed()) { excludeState = null; } else if (options.expandWildcardsOpen() && options.expandWildcardsClosed() == false) { excludeState = IndexMetaData.State.CLOSE; } else if (options.expandWildcardsClosed() && options.expandWildcardsOpen() == false) { excludeState = IndexMetaData.State.OPEN; } else { assert false : "this shouldn't get called if wildcards expand to none"; excludeState = null; } return excludeState; } private static Map<String, AliasOrIndex> matches(MetaData metaData, String expression) { if (Regex.isMatchAllPattern(expression)) { // Can only happen if the expressions was initially: '-*' return metaData.getAliasAndIndexLookup(); } else if (expression.indexOf("*") == expression.length() - 1) { return suffixWildcard(metaData, expression); } else { return otherWildcard(metaData, expression); } } private static Map<String, AliasOrIndex> suffixWildcard(MetaData metaData, String expression) { assert expression.length() >= 2 : "expression [" + expression + "] should have at least a length of 2"; String fromPrefix = expression.substring(0, expression.length() - 1); char[] toPrefixCharArr = fromPrefix.toCharArray(); toPrefixCharArr[toPrefixCharArr.length - 1]++; String toPrefix = new String(toPrefixCharArr); return metaData.getAliasAndIndexLookup().subMap(fromPrefix, toPrefix); } private static Map<String, AliasOrIndex> otherWildcard(MetaData metaData, String expression) { final String pattern = expression; return metaData.getAliasAndIndexLookup() .entrySet() .stream() .filter(e -> Regex.simpleMatch(pattern, e.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private static Set<String> expand(Context context, IndexMetaData.State excludeState, Map<String, AliasOrIndex> matches) { Set<String> expand = new HashSet<>(); for (Map.Entry<String, AliasOrIndex> entry : matches.entrySet()) { AliasOrIndex aliasOrIndex = entry.getValue(); if (context.isPreserveAliases() && aliasOrIndex.isAlias()) { expand.add(entry.getKey()); } else { for (IndexMetaData meta : aliasOrIndex.getIndices()) { if (excludeState == null || meta.getState() != excludeState) { expand.add(meta.getIndex().getName()); } } } } return expand; } private boolean isEmptyOrTrivialWildcard(List<String> expressions) { return expressions.isEmpty() || (expressions.size() == 1 && (MetaData.ALL.equals(expressions.get(0)) || Regex.isMatchAllPattern(expressions.get(0)))); } private List<String> resolveEmptyOrTrivialWildcard(IndicesOptions options, MetaData metaData, boolean assertEmpty) { if (options.expandWildcardsOpen() && options.expandWildcardsClosed()) { return Arrays.asList(metaData.getConcreteAllIndices()); } else if (options.expandWildcardsOpen()) { return Arrays.asList(metaData.getConcreteAllOpenIndices()); } else if (options.expandWildcardsClosed()) { return Arrays.asList(metaData.getConcreteAllClosedIndices()); } else { assert assertEmpty : "Shouldn't end up here"; return Collections.emptyList(); } } } static final class DateMathExpressionResolver implements ExpressionResolver { private static final String EXPRESSION_LEFT_BOUND = "<"; private static final String EXPRESSION_RIGHT_BOUND = ">"; private static final char LEFT_BOUND = '{'; private static final char RIGHT_BOUND = '}'; private static final char ESCAPE_CHAR = '\\'; private static final char TIME_ZONE_BOUND = '|'; private final DateTimeZone defaultTimeZone; private final String defaultDateFormatterPattern; private final DateTimeFormatter defaultDateFormatter; DateMathExpressionResolver(Settings settings) { String defaultTimeZoneId = settings.get("date_math_expression_resolver.default_time_zone", "UTC"); this.defaultTimeZone = DateTimeZone.forID(defaultTimeZoneId); defaultDateFormatterPattern = settings.get("date_math_expression_resolver.default_date_format", "YYYY.MM.dd"); this.defaultDateFormatter = DateTimeFormat.forPattern(defaultDateFormatterPattern); } @Override public List<String> resolve(final Context context, List<String> expressions) { List<String> result = new ArrayList<>(expressions.size()); for (String expression : expressions) { result.add(resolveExpression(expression, context)); } return result; } @SuppressWarnings("fallthrough") String resolveExpression(String expression, final Context context) { if (expression.startsWith(EXPRESSION_LEFT_BOUND) == false || expression.endsWith(EXPRESSION_RIGHT_BOUND) == false) { return expression; } boolean escape = false; boolean inDateFormat = false; boolean inPlaceHolder = false; final StringBuilder beforePlaceHolderSb = new StringBuilder(); StringBuilder inPlaceHolderSb = new StringBuilder(); final char[] text = expression.toCharArray(); final int from = 1; final int length = text.length - 1; for (int i = from; i < length; i++) { boolean escapedChar = escape; if (escape) { escape = false; } char c = text[i]; if (c == ESCAPE_CHAR) { if (escapedChar) { beforePlaceHolderSb.append(c); escape = false; } else { escape = true; } continue; } if (inPlaceHolder) { switch (c) { case LEFT_BOUND: if (inDateFormat && escapedChar) { inPlaceHolderSb.append(c); } else if (!inDateFormat) { inDateFormat = true; inPlaceHolderSb.append(c); } else { throw new ElasticsearchParseException("invalid dynamic name expression [{}]. invalid character in placeholder at position [{}]", new String(text, from, length), i); } break; case RIGHT_BOUND: if (inDateFormat && escapedChar) { inPlaceHolderSb.append(c); } else if (inDateFormat) { inDateFormat = false; inPlaceHolderSb.append(c); } else { String inPlaceHolderString = inPlaceHolderSb.toString(); int dateTimeFormatLeftBoundIndex = inPlaceHolderString.indexOf(LEFT_BOUND); String mathExpression; String dateFormatterPattern; DateTimeFormatter dateFormatter; final DateTimeZone timeZone; if (dateTimeFormatLeftBoundIndex < 0) { mathExpression = inPlaceHolderString; dateFormatterPattern = defaultDateFormatterPattern; dateFormatter = defaultDateFormatter; timeZone = defaultTimeZone; } else { if (inPlaceHolderString.lastIndexOf(RIGHT_BOUND) != inPlaceHolderString.length() - 1) { throw new ElasticsearchParseException("invalid dynamic name expression [{}]. missing closing `}` for date math format", inPlaceHolderString); } if (dateTimeFormatLeftBoundIndex == inPlaceHolderString.length() - 2) { throw new ElasticsearchParseException("invalid dynamic name expression [{}]. missing date format", inPlaceHolderString); } mathExpression = inPlaceHolderString.substring(0, dateTimeFormatLeftBoundIndex); String dateFormatterPatternAndTimeZoneId = inPlaceHolderString.substring(dateTimeFormatLeftBoundIndex + 1, inPlaceHolderString.length() - 1); int formatPatternTimeZoneSeparatorIndex = dateFormatterPatternAndTimeZoneId.indexOf(TIME_ZONE_BOUND); if (formatPatternTimeZoneSeparatorIndex != -1) { dateFormatterPattern = dateFormatterPatternAndTimeZoneId.substring(0, formatPatternTimeZoneSeparatorIndex); timeZone = DateTimeZone.forID(dateFormatterPatternAndTimeZoneId.substring(formatPatternTimeZoneSeparatorIndex + 1)); } else { dateFormatterPattern = dateFormatterPatternAndTimeZoneId; timeZone = defaultTimeZone; } dateFormatter = DateTimeFormat.forPattern(dateFormatterPattern); } DateTimeFormatter parser = dateFormatter.withZone(timeZone); FormatDateTimeFormatter formatter = new FormatDateTimeFormatter(dateFormatterPattern, parser, Locale.ROOT); DateMathParser dateMathParser = new DateMathParser(formatter); long millis = dateMathParser.parse(mathExpression, context::getStartTime, false, timeZone); String time = formatter.printer().print(millis); beforePlaceHolderSb.append(time); inPlaceHolderSb = new StringBuilder(); inPlaceHolder = false; } break; default: inPlaceHolderSb.append(c); } } else { switch (c) { case LEFT_BOUND: if (escapedChar) { beforePlaceHolderSb.append(c); } else { inPlaceHolder = true; } break; case RIGHT_BOUND: if (!escapedChar) { throw new ElasticsearchParseException("invalid dynamic name expression [{}]. invalid character at position [{}]. " + "`{` and `}` are reserved characters and should be escaped when used as part of the index name using `\\` (e.g. `\\{text\\}`)", new String(text, from, length), i); } default: beforePlaceHolderSb.append(c); } } } if (inPlaceHolder) { throw new ElasticsearchParseException("invalid dynamic name expression [{}]. date math placeholder is open ended", new String(text, from, length)); } if (beforePlaceHolderSb.length() == 0) { throw new ElasticsearchParseException("nothing captured"); } return beforePlaceHolderSb.toString(); } } /** * Returns <code>true</code> iff the given expression resolves to the given index name otherwise <code>false</code> */ public final boolean matchesIndex(String indexName, String expression, ClusterState state) { final String[] concreteIndices = concreteIndexNames(state, IndicesOptions.lenientExpandOpen(), expression); for (String index : concreteIndices) { if (Regex.simpleMatch(index, indexName)) { return true; } } return indexName.equals(expression); } }
apache-2.0
nilabhsagar/elasticsearch
core/src/main/java/org/elasticsearch/index/mapper/BooleanFieldMapper.java
10504
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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 org.elasticsearch.index.mapper; import org.apache.lucene.document.Field; import org.apache.lucene.document.SortedNumericDocValuesField; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermRangeQuery; import org.apache.lucene.util.BytesRef; import org.elasticsearch.Version; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.IndexNumericFieldData.NumericType; import org.elasticsearch.index.fielddata.plain.DocValuesIndexFieldData; import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.search.DocValueFormat; import org.joda.time.DateTimeZone; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.elasticsearch.index.mapper.TypeParsers.parseField; /** * A field mapper for boolean fields. */ public class BooleanFieldMapper extends FieldMapper { private static final DeprecationLogger deprecationLogger = new DeprecationLogger(Loggers.getLogger(BooleanFieldMapper.class)); public static final String CONTENT_TYPE = "boolean"; public static class Defaults { public static final MappedFieldType FIELD_TYPE = new BooleanFieldType(); static { FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.setIndexOptions(IndexOptions.DOCS); FIELD_TYPE.setTokenized(false); FIELD_TYPE.setIndexAnalyzer(Lucene.KEYWORD_ANALYZER); FIELD_TYPE.setSearchAnalyzer(Lucene.KEYWORD_ANALYZER); FIELD_TYPE.freeze(); } } public static class Values { public static final BytesRef TRUE = new BytesRef("T"); public static final BytesRef FALSE = new BytesRef("F"); } public static class Builder extends FieldMapper.Builder<Builder, BooleanFieldMapper> { public Builder(String name) { super(name, Defaults.FIELD_TYPE, Defaults.FIELD_TYPE); this.builder = this; } @Override public Builder tokenized(boolean tokenized) { if (tokenized) { throw new IllegalArgumentException("bool field can't be tokenized"); } return super.tokenized(tokenized); } @Override public BooleanFieldMapper build(BuilderContext context) { setupFieldType(context); return new BooleanFieldMapper(name, fieldType, defaultFieldType, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { BooleanFieldMapper.Builder builder = new BooleanFieldMapper.Builder(name); parseField(builder, name, node, parserContext); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String propName = entry.getKey(); Object propNode = entry.getValue(); if (propName.equals("null_value")) { if (propNode == null) { throw new MapperParsingException("Property [null_value] cannot be null."); } builder.nullValue(TypeParsers.nodeBooleanValue(name, "null_value", propNode, parserContext)); iterator.remove(); } } return builder; } } public static final class BooleanFieldType extends TermBasedFieldType { public BooleanFieldType() {} protected BooleanFieldType(BooleanFieldType ref) { super(ref); } @Override public MappedFieldType clone() { return new BooleanFieldType(this); } @Override public String typeName() { return CONTENT_TYPE; } @Override public Boolean nullValue() { return (Boolean)super.nullValue(); } @Override public BytesRef indexedValueForSearch(Object value) { if (value == null) { return Values.FALSE; } if (value instanceof Boolean) { return ((Boolean) value) ? Values.TRUE : Values.FALSE; } String sValue; if (value instanceof BytesRef) { sValue = ((BytesRef) value).utf8ToString(); } else { sValue = value.toString(); } switch (sValue) { case "true": return Values.TRUE; case "false": return Values.FALSE; default: throw new IllegalArgumentException("Can't parse boolean value [" + sValue + "], expected [true] or [false]"); } } @Override public Boolean valueForDisplay(Object value) { if (value == null) { return null; } switch(value.toString()) { case "F": return false; case "T": return true; default: throw new IllegalArgumentException("Expected [T] or [F] but got [" + value + "]"); } } @Override public IndexFieldData.Builder fielddataBuilder() { failIfNoDocValues(); return new DocValuesIndexFieldData.Builder().numericType(NumericType.BOOLEAN); } @Override public DocValueFormat docValueFormat(@Nullable String format, DateTimeZone timeZone) { if (format != null) { throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName() + "] does not support custom formats"); } if (timeZone != null) { throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName() + "] does not support custom time zones"); } return DocValueFormat.BOOLEAN; } @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, QueryShardContext context) { failIfNotIndexed(); return new TermRangeQuery(name(), lowerTerm == null ? null : indexedValueForSearch(lowerTerm), upperTerm == null ? null : indexedValueForSearch(upperTerm), includeLower, includeUpper); } } protected BooleanFieldMapper(String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) { super(simpleName, fieldType, defaultFieldType, indexSettings, multiFields, copyTo); } @Override public BooleanFieldType fieldType() { return (BooleanFieldType) super.fieldType(); } @Override protected void parseCreateField(ParseContext context, List<IndexableField> fields) throws IOException { if (fieldType().indexOptions() == IndexOptions.NONE && !fieldType().stored() && !fieldType().hasDocValues()) { return; } Boolean value = context.parseExternalValue(Boolean.class); if (value == null) { XContentParser.Token token = context.parser().currentToken(); if (token == XContentParser.Token.VALUE_NULL) { if (fieldType().nullValue() != null) { value = fieldType().nullValue(); } } else { if (indexCreatedVersion.onOrAfter(Version.V_6_0_0_alpha1_UNRELEASED)) { value = context.parser().booleanValue(); } else { value = context.parser().booleanValueLenient(); if (context.parser().isBooleanValueLenient() != context.parser().isBooleanValue()) { String rawValue = context.parser().text(); deprecationLogger.deprecated("Expected a boolean for property [{}] but got [{}]", fieldType().name(), rawValue); } } } } if (value == null) { return; } if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) { fields.add(new Field(fieldType().name(), value ? "T" : "F", fieldType())); } if (fieldType().hasDocValues()) { fields.add(new SortedNumericDocValuesField(fieldType().name(), value ? 1 : 0)); } } @Override protected String contentType() { return CONTENT_TYPE; } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || fieldType().nullValue() != null) { builder.field("null_value", fieldType().nullValue()); } } }
apache-2.0
myelin/elasticsearch
core/src/main/java/org/elasticsearch/search/suggest/Suggester.java
2068
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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 org.elasticsearch.search.suggest; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.util.CharsRefBuilder; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.index.query.QueryParseContext; import java.io.IOException; public abstract class Suggester<T extends SuggestionSearchContext.SuggestionContext> implements Writeable.Reader<SuggestionBuilder<?>> { protected abstract Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> innerExecute(String name, T suggestion, IndexSearcher searcher, CharsRefBuilder spare) throws IOException; /** * Read the SuggestionBuilder paired with this Suggester XContent. */ public abstract SuggestionBuilder<?> innerFromXContent(QueryParseContext context) throws IOException; public Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> execute(String name, T suggestion, IndexSearcher searcher, CharsRefBuilder spare) throws IOException { // #3469 We want to ignore empty shards if (searcher.getIndexReader().numDocs() == 0) { return null; } return innerExecute(name, suggestion, searcher, spare); } }
apache-2.0
naveedaz/azure-powershell
src/ResourceManager/AzureBackup/Commands.AzureBackup/Cmdlets/ProtectionPolicy/NewAzureRMBackupProtectionPolicy.cs
5516
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.AzureBackup.Helpers; using Microsoft.Azure.Commands.AzureBackup.Models; using Microsoft.Azure.Commands.AzureBackup.Properties; using Microsoft.Azure.Management.BackupServices.Models; using System; using System.Management.Automation; namespace Microsoft.Azure.Commands.AzureBackup.Cmdlets { /// <summary> /// Create new protection policy /// </summary> [Cmdlet(VerbsCommon.New, "AzureRmBackupProtectionPolicy", DefaultParameterSetName = NoScheduleParamSet), OutputType(typeof(AzureRMBackupProtectionPolicy))] public class NewAzureRMBackupProtectionPolicy : AzureBackupVaultCmdletBase { protected const string WeeklyScheduleParamSet = "WeeklyScheduleParamSet"; protected const string DailyScheduleParamSet = "DailyScheduleParamSet"; protected const string NoScheduleParamSet = "NoScheduleParamSet"; [Parameter(Position = 1, Mandatory = true, HelpMessage = AzureBackupCmdletHelpMessage.PolicyName)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(Position = 2, Mandatory = true, HelpMessage = AzureBackupCmdletHelpMessage.WorkloadType, ValueFromPipelineByPropertyName = true)] [ValidateSet("AzureVM", IgnoreCase = true)] public string Type { get; set; } [Parameter(ParameterSetName = DailyScheduleParamSet, Position = 3, Mandatory = false, HelpMessage = AzureBackupCmdletHelpMessage.DailyScheduleType)] public SwitchParameter Daily { get; set; } [Parameter(ParameterSetName = WeeklyScheduleParamSet, Position = 4, Mandatory = true, HelpMessage = AzureBackupCmdletHelpMessage.WeeklyScheduleType)] public SwitchParameter Weekly { get; set; } [Parameter(Position = 5, Mandatory = true, HelpMessage = AzureBackupCmdletHelpMessage.ScheduleRunTimes, ValueFromPipelineByPropertyName = true)] public DateTime BackupTime { get; set; } [Parameter(ParameterSetName = WeeklyScheduleParamSet, Position = 6, Mandatory = true, HelpMessage = AzureBackupCmdletHelpMessage.ScheduleRunDays, ValueFromPipelineByPropertyName = true)] [Parameter(ParameterSetName = NoScheduleParamSet, Position = 6, Mandatory = false, HelpMessage = AzureBackupCmdletHelpMessage.ScheduleRunDays, ValueFromPipelineByPropertyName = true)] [AllowEmptyCollection] [ValidateSet("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", IgnoreCase = true)] public string[] DaysOfWeek { get; set; } [Parameter(Position = 7, Mandatory = true, HelpMessage = AzureBackupCmdletHelpMessage.RetentionPolicyList, ValueFromPipelineByPropertyName = true)] public AzureRMBackupRetentionPolicy[] RetentionPolicy { get; set; } public override void ExecuteCmdlet() { ExecutionBlock(() => { base.ExecuteCmdlet(); WriteDebug("Making client call"); ProtectionPolicyHelpers.ValidateProtectionPolicyName(Name); AzureBackupClient.CheckProtectionPolicyNameAvailability(Vault.ResourceGroupName, Vault.Name, this.Name); var ScheduleType = ProtectionPolicyHelpers.GetScheduleType(DaysOfWeek, this.ParameterSetName, DailyScheduleParamSet, WeeklyScheduleParamSet); var backupSchedule = ProtectionPolicyHelpers.FillCSMBackupSchedule(ScheduleType, BackupTime, DaysOfWeek); ProtectionPolicyHelpers.ValidateRetentionPolicy(RetentionPolicy, backupSchedule); var addCSMProtectionPolicyRequest = new CSMAddProtectionPolicyRequest(); addCSMProtectionPolicyRequest.PolicyName = this.Name; addCSMProtectionPolicyRequest.Properties = new CSMAddProtectionPolicyRequestProperties(); addCSMProtectionPolicyRequest.Properties.PolicyName = this.Name; addCSMProtectionPolicyRequest.Properties.BackupSchedule = backupSchedule; addCSMProtectionPolicyRequest.Properties.WorkloadType = ProtectionPolicyHelpers.ConvertToCSMWorkLoadType(this.Type); addCSMProtectionPolicyRequest.Properties.LtrRetentionPolicy = ProtectionPolicyHelpers.ConvertToCSMRetentionPolicyObject(RetentionPolicy, backupSchedule); AzureBackupClient.AddProtectionPolicy(Vault.ResourceGroupName, Vault.Name, this.Name, addCSMProtectionPolicyRequest); WriteDebug(Resources.ProtectionPolicyCreated); var policyInfo = AzureBackupClient.GetProtectionPolicyByName(Vault.ResourceGroupName, Vault.Name, Name); WriteObject(ProtectionPolicyHelpers.GetCmdletPolicy(Vault, policyInfo)); }); } } }
apache-2.0
adairtaosy/spring-security
web/src/main/java/org/springframework/security/web/context/SecurityContextRepository.java
2621
package org.springframework.security.web.context; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.context.SecurityContext; /** * Strategy used for persisting a {@link SecurityContext} between requests. * <p> * Used by {@link SecurityContextPersistenceFilter} to obtain the context which should be * used for the current thread of execution and to store the context once it has been * removed from thread-local storage and the request has completed. * <p> * The persistence mechanism used will depend on the implementation, but most commonly the * <tt>HttpSession</tt> will be used to store the context. * * @author Luke Taylor * @since 3.0 * * @see SecurityContextPersistenceFilter * @see HttpSessionSecurityContextRepository * @see SaveContextOnUpdateOrErrorResponseWrapper */ public interface SecurityContextRepository { /** * Obtains the security context for the supplied request. For an unauthenticated user, * an empty context implementation should be returned. This method should not return * null. * <p> * The use of the <tt>HttpRequestResponseHolder</tt> parameter allows implementations * to return wrapped versions of the request or response (or both), allowing them to * access implementation-specific state for the request. The values obtained from the * holder will be passed on to the filter chain and also to the <tt>saveContext</tt> * method when it is finally called. Implementations may wish to return a subclass of * {@link SaveContextOnUpdateOrErrorResponseWrapper} as the response object, which * guarantees that the context is persisted when an error or redirect occurs. * * @param requestResponseHolder holder for the current request and response for which * the context should be loaded. * * @return The security context which should be used for the current request, never * null. */ SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder); /** * Stores the security context on completion of a request. * * @param context the non-null context which was obtained from the holder. * @param request * @param response */ void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response); /** * Allows the repository to be queried as to whether it contains a security context * for the current request. * * @param request the current request * @return true if a context is found for the request, false otherwise */ boolean containsContext(HttpServletRequest request); }
apache-2.0
michaKFromParis/octokit.net
Octokit.Reactive/Clients/ObservableGistCommentsClient.cs
3519
using System; using System.Reactive; using System.Reactive.Threading.Tasks; using Octokit.Reactive.Internal; namespace Octokit.Reactive { public class ObservableGistCommentsClient : IObservableGistCommentsClient { readonly IGistCommentsClient _client; readonly IConnection _connection; public ObservableGistCommentsClient(IGitHubClient client) { Ensure.ArgumentNotNull(client, "client"); _client = client.Gist.Comment; _connection = client.Connection; } /// <summary> /// Gets a single comment by gist- and comment id. /// </summary> /// <remarks>http://developer.github.com/v3/gists/comments/#get-a-single-comment</remarks> /// <param name="gistId">The id of the gist</param> /// <param name="commentId">The id of the comment</param> /// <returns>IObservable{GistComment}.</returns> public IObservable<GistComment> Get(string gistId, int commentId) { return _client.Get(gistId, commentId).ToObservable(); } /// <summary> /// Gets all comments for the gist with the specified id. /// </summary> /// <remarks>http://developer.github.com/v3/gists/comments/#list-comments-on-a-gist</remarks> /// <param name="gistId">The id of the gist</param> /// <returns>IObservable{GistComment}.</returns> public IObservable<GistComment> GetAllForGist(string gistId) { return _connection.GetAndFlattenAllPages<GistComment>(ApiUrls.GistComments(gistId)); } /// <summary> /// Creates a comment for the gist with the specified id. /// </summary> /// <remarks>http://developer.github.com/v3/gists/comments/#create-a-comment</remarks> /// <param name="gistId">The id of the gist</param> /// <param name="comment">The body of the comment</param> /// <returns>IObservable{GistComment}.</returns> public IObservable<GistComment> Create(string gistId, string comment) { Ensure.ArgumentNotNullOrEmptyString(comment, "comment"); return _client.Create(gistId, comment).ToObservable(); } /// <summary> /// Updates the comment with the specified gist- and comment id. /// </summary> /// <remarks>http://developer.github.com/v3/gists/comments/#edit-a-comment</remarks> /// <param name="gistId">The id of the gist</param> /// <param name="commentId">The id of the comment</param> /// <param name="comment">The updated body of the comment</param> /// <returns>IObservable{GistComment}.</returns> public IObservable<GistComment> Update(string gistId, int commentId, string comment) { Ensure.ArgumentNotNullOrEmptyString(comment, "comment"); return _client.Update(gistId, commentId, comment).ToObservable(); } /// <summary> /// Deletes the comment with the specified gist- and comment id. /// </summary> /// <remarks>http://developer.github.com/v3/gists/comments/#delete-a-comment</remarks> /// <param name="gistId">The id of the gist</param> /// <param name="commentId">The id of the comment</param> /// <returns>IObservable{Unit}.</returns> public IObservable<Unit> Delete(string gistId, int commentId) { return _client.Delete(gistId, commentId).ToObservable(); } } }
mit
luke-siedle/wp-base
wp-content/plugins/buddypress/bp-groups/bp-groups-actions.php
18984
<?php /** * BuddyPress Groups Actions * * Action functions are exactly the same as screen functions, however they do * not have a template screen associated with them. Usually they will send the * user back to the default screen after execution. * * @package BuddyPress * @subpackage GroupsActions */ // Exit if accessed directly if ( !defined( 'ABSPATH' ) ) exit; /** * Protect access to single groups. * * @since BuddyPress (2.1.0) */ function bp_groups_group_access_protection() { if ( ! bp_is_group() ) { return; } $current_group = groups_get_current_group(); $user_has_access = $current_group->user_has_access; $no_access_args = array(); if ( ! $user_has_access && 'hidden' !== $current_group->status ) { // Always allow access to home and request-membership if ( bp_is_current_action( 'home' ) || bp_is_current_action( 'request-membership' ) ) { $user_has_access = true; // User doesn't have access, so set up redirect args } else if ( is_user_logged_in() ) { $no_access_args = array( 'message' => __( 'You do not have access to this group.', 'buddypress' ), 'root' => bp_get_group_permalink( $current_group ) . 'home/', 'redirect' => false ); } } // Protect the admin tab from non-admins if ( bp_is_current_action( 'admin' ) && ! bp_is_item_admin() ) { $user_has_access = false; $no_access_args = array( 'message' => __( 'You are not an admin of this group.', 'buddypress' ), 'root' => bp_get_group_permalink( $current_group ), 'redirect' => false ); } /** * Allow plugins to filter whether the current user has access to this group content. * * Note that if a plugin sets $user_has_access to false, it may also * want to change the $no_access_args, to avoid problems such as * logged-in users being redirected to wp-login.php. * * @since BuddyPress (2.1.0) * * @param bool $user_has_access True if the user has access to the * content, otherwise false. * @param array $no_access_args Arguments to be passed to * bp_core_no_access() in case of no access. Note that this * value is passed by reference, so it can be modified by the * filter callback. */ $user_has_access = apply_filters_ref_array( 'bp_group_user_has_access', array( $user_has_access, &$no_access_args ) ); // If user has access, we return rather than redirect if ( $user_has_access ) { return; } // Hidden groups should return a 404 for non-members. // Unset the current group so that you're not redirected // to the default group tab if ( 'hidden' == $current_group->status ) { buddypress()->groups->current_group = 0; buddypress()->is_single_item = false; bp_do_404(); return; } else { bp_core_no_access( $no_access_args ); } } add_action( 'bp_actions', 'bp_groups_group_access_protection' ); /** * Catch and process group creation form submissions. */ function groups_action_create_group() { global $bp; // If we're not at domain.org/groups/create/ then return false if ( !bp_is_groups_component() || !bp_is_current_action( 'create' ) ) return false; if ( !is_user_logged_in() ) return false; if ( !bp_user_can_create_groups() ) { bp_core_add_message( __( 'Sorry, you are not allowed to create groups.', 'buddypress' ), 'error' ); bp_core_redirect( trailingslashit( bp_get_root_domain() . '/' . bp_get_groups_root_slug() ) ); } // Make sure creation steps are in the right order groups_action_sort_creation_steps(); // If no current step is set, reset everything so we can start a fresh group creation $bp->groups->current_create_step = bp_action_variable( 1 ); if ( !bp_get_groups_current_create_step() ) { unset( $bp->groups->current_create_step ); unset( $bp->groups->completed_create_steps ); setcookie( 'bp_new_group_id', false, time() - 1000, COOKIEPATH ); setcookie( 'bp_completed_create_steps', false, time() - 1000, COOKIEPATH ); $reset_steps = true; $keys = array_keys( $bp->groups->group_creation_steps ); bp_core_redirect( bp_get_root_domain() . '/' . bp_get_groups_root_slug() . '/create/step/' . array_shift( $keys ) . '/' ); } // If this is a creation step that is not recognized, just redirect them back to the first screen if ( bp_get_groups_current_create_step() && empty( $bp->groups->group_creation_steps[bp_get_groups_current_create_step()] ) ) { bp_core_add_message( __('There was an error saving group details. Please try again.', 'buddypress'), 'error' ); bp_core_redirect( bp_get_root_domain() . '/' . bp_get_groups_root_slug() . '/create/' ); } // Fetch the currently completed steps variable if ( isset( $_COOKIE['bp_completed_create_steps'] ) && !isset( $reset_steps ) ) $bp->groups->completed_create_steps = json_decode( base64_decode( stripslashes( $_COOKIE['bp_completed_create_steps'] ) ) ); // Set the ID of the new group, if it has already been created in a previous step if ( isset( $_COOKIE['bp_new_group_id'] ) ) { $bp->groups->new_group_id = (int) $_COOKIE['bp_new_group_id']; $bp->groups->current_group = groups_get_group( array( 'group_id' => $bp->groups->new_group_id ) ); // Only allow the group creator to continue to edit the new group if ( ! bp_is_group_creator( $bp->groups->current_group, bp_loggedin_user_id() ) ) { bp_core_add_message( __( 'Only the group creator may continue editing this group.', 'buddypress' ), 'error' ); bp_core_redirect( bp_get_root_domain() . '/' . bp_get_groups_root_slug() . '/create/' ); } } // If the save, upload or skip button is hit, lets calculate what we need to save if ( isset( $_POST['save'] ) ) { // Check the nonce check_admin_referer( 'groups_create_save_' . bp_get_groups_current_create_step() ); if ( 'group-details' == bp_get_groups_current_create_step() ) { if ( empty( $_POST['group-name'] ) || empty( $_POST['group-desc'] ) || !strlen( trim( $_POST['group-name'] ) ) || !strlen( trim( $_POST['group-desc'] ) ) ) { bp_core_add_message( __( 'Please fill in all of the required fields', 'buddypress' ), 'error' ); bp_core_redirect( bp_get_root_domain() . '/' . bp_get_groups_root_slug() . '/create/step/' . bp_get_groups_current_create_step() . '/' ); } $new_group_id = isset( $bp->groups->new_group_id ) ? $bp->groups->new_group_id : 0; if ( !$bp->groups->new_group_id = groups_create_group( array( 'group_id' => $new_group_id, 'name' => $_POST['group-name'], 'description' => $_POST['group-desc'], 'slug' => groups_check_slug( sanitize_title( esc_attr( $_POST['group-name'] ) ) ), 'date_created' => bp_core_current_time(), 'status' => 'public' ) ) ) { bp_core_add_message( __( 'There was an error saving group details, please try again.', 'buddypress' ), 'error' ); bp_core_redirect( bp_get_root_domain() . '/' . bp_get_groups_root_slug() . '/create/step/' . bp_get_groups_current_create_step() . '/' ); } } if ( 'group-settings' == bp_get_groups_current_create_step() ) { $group_status = 'public'; $group_enable_forum = 1; if ( !isset($_POST['group-show-forum']) ) { $group_enable_forum = 0; } else { // Create the forum if enable_forum = 1 if ( bp_is_active( 'forums' ) && !groups_get_groupmeta( $bp->groups->new_group_id, 'forum_id' ) ) { groups_new_group_forum(); } } if ( 'private' == $_POST['group-status'] ) $group_status = 'private'; else if ( 'hidden' == $_POST['group-status'] ) $group_status = 'hidden'; if ( !$bp->groups->new_group_id = groups_create_group( array( 'group_id' => $bp->groups->new_group_id, 'status' => $group_status, 'enable_forum' => $group_enable_forum ) ) ) { bp_core_add_message( __( 'There was an error saving group details, please try again.', 'buddypress' ), 'error' ); bp_core_redirect( bp_get_root_domain() . '/' . bp_get_groups_root_slug() . '/create/step/' . bp_get_groups_current_create_step() . '/' ); } // Set the invite status // Checked against a whitelist for security $allowed_invite_status = apply_filters( 'groups_allowed_invite_status', array( 'members', 'mods', 'admins' ) ); $invite_status = !empty( $_POST['group-invite-status'] ) && in_array( $_POST['group-invite-status'], (array) $allowed_invite_status ) ? $_POST['group-invite-status'] : 'members'; groups_update_groupmeta( $bp->groups->new_group_id, 'invite_status', $invite_status ); } if ( 'group-invites' === bp_get_groups_current_create_step() ) { if ( ! empty( $_POST['friends'] ) ) { foreach ( (array) $_POST['friends'] as $friend ) { groups_invite_user( array( 'user_id' => $friend, 'group_id' => $bp->groups->new_group_id, ) ); } } groups_send_invites( bp_loggedin_user_id(), $bp->groups->new_group_id ); } do_action( 'groups_create_group_step_save_' . bp_get_groups_current_create_step() ); do_action( 'groups_create_group_step_complete' ); // Mostly for clearing cache on a generic action name /** * Once we have successfully saved the details for this step of the creation process * we need to add the current step to the array of completed steps, then update the cookies * holding the information */ $completed_create_steps = isset( $bp->groups->completed_create_steps ) ? $bp->groups->completed_create_steps : array(); if ( !in_array( bp_get_groups_current_create_step(), $completed_create_steps ) ) $bp->groups->completed_create_steps[] = bp_get_groups_current_create_step(); // Reset cookie info setcookie( 'bp_new_group_id', $bp->groups->new_group_id, time()+60*60*24, COOKIEPATH ); setcookie( 'bp_completed_create_steps', base64_encode( json_encode( $bp->groups->completed_create_steps ) ), time()+60*60*24, COOKIEPATH ); // If we have completed all steps and hit done on the final step we // can redirect to the completed group $keys = array_keys( $bp->groups->group_creation_steps ); if ( count( $bp->groups->completed_create_steps ) == count( $keys ) && bp_get_groups_current_create_step() == array_pop( $keys ) ) { unset( $bp->groups->current_create_step ); unset( $bp->groups->completed_create_steps ); // Once we compelete all steps, record the group creation in the activity stream. groups_record_activity( array( 'type' => 'created_group', 'item_id' => $bp->groups->new_group_id ) ); do_action( 'groups_group_create_complete', $bp->groups->new_group_id ); bp_core_redirect( bp_get_group_permalink( $bp->groups->current_group ) ); } else { /** * Since we don't know what the next step is going to be (any plugin can insert steps) * we need to loop the step array and fetch the next step that way. */ foreach ( $keys as $key ) { if ( $key == bp_get_groups_current_create_step() ) { $next = 1; continue; } if ( isset( $next ) ) { $next_step = $key; break; } } bp_core_redirect( bp_get_root_domain() . '/' . bp_get_groups_root_slug() . '/create/step/' . $next_step . '/' ); } } // Remove invitations if ( 'group-invites' === bp_get_groups_current_create_step() && ! empty( $_REQUEST['user_id'] ) && is_numeric( $_REQUEST['user_id'] ) ) { if ( ! check_admin_referer( 'groups_invite_uninvite_user' ) ) { return false; } $message = __( 'Invite successfully removed', 'buddypress' ); $error = false; if( ! groups_uninvite_user( (int) $_REQUEST['user_id'], $bp->groups->new_group_id ) ) { $message = __( 'There was an error removing the invite', 'buddypress' ); $error = 'error'; } bp_core_add_message( $message, $error ); bp_core_redirect( bp_get_root_domain() . '/' . bp_get_groups_root_slug() . '/create/step/group-invites/' ); } // Group avatar is handled separately if ( 'group-avatar' == bp_get_groups_current_create_step() && isset( $_POST['upload'] ) ) { if ( ! isset( $bp->avatar_admin ) ) { $bp->avatar_admin = new stdClass(); } if ( !empty( $_FILES ) && isset( $_POST['upload'] ) ) { // Normally we would check a nonce here, but the group save nonce is used instead // Pass the file to the avatar upload handler if ( bp_core_avatar_handle_upload( $_FILES, 'groups_avatar_upload_dir' ) ) { $bp->avatar_admin->step = 'crop-image'; // Make sure we include the jQuery jCrop file for image cropping add_action( 'wp_print_scripts', 'bp_core_add_jquery_cropper' ); } } // If the image cropping is done, crop the image and save a full/thumb version if ( isset( $_POST['avatar-crop-submit'] ) && isset( $_POST['upload'] ) ) { // Normally we would check a nonce here, but the group save nonce is used instead if ( !bp_core_avatar_handle_crop( array( 'object' => 'group', 'avatar_dir' => 'group-avatars', 'item_id' => $bp->groups->current_group->id, 'original_file' => $_POST['image_src'], 'crop_x' => $_POST['x'], 'crop_y' => $_POST['y'], 'crop_w' => $_POST['w'], 'crop_h' => $_POST['h'] ) ) ) bp_core_add_message( __( 'There was an error saving the group profile photo, please try uploading again.', 'buddypress' ), 'error' ); else bp_core_add_message( __( 'The group profile photo was uploaded successfully!', 'buddypress' ) ); } } bp_core_load_template( apply_filters( 'groups_template_create_group', 'groups/create' ) ); } add_action( 'bp_actions', 'groups_action_create_group' ); /** * Catch and process "Join Group" button clicks. */ function groups_action_join_group() { global $bp; if ( !bp_is_single_item() || !bp_is_groups_component() || !bp_is_current_action( 'join' ) ) return false; // Nonce check if ( !check_admin_referer( 'groups_join_group' ) ) return false; // Skip if banned or already a member if ( !groups_is_user_member( bp_loggedin_user_id(), $bp->groups->current_group->id ) && !groups_is_user_banned( bp_loggedin_user_id(), $bp->groups->current_group->id ) ) { // User wants to join a group that is not public if ( $bp->groups->current_group->status != 'public' ) { if ( !groups_check_user_has_invite( bp_loggedin_user_id(), $bp->groups->current_group->id ) ) { bp_core_add_message( __( 'There was an error joining the group.', 'buddypress' ), 'error' ); bp_core_redirect( bp_get_group_permalink( $bp->groups->current_group ) ); } } // User wants to join any group if ( !groups_join_group( $bp->groups->current_group->id ) ) bp_core_add_message( __( 'There was an error joining the group.', 'buddypress' ), 'error' ); else bp_core_add_message( __( 'You joined the group!', 'buddypress' ) ); bp_core_redirect( bp_get_group_permalink( $bp->groups->current_group ) ); } bp_core_load_template( apply_filters( 'groups_template_group_home', 'groups/single/home' ) ); } add_action( 'bp_actions', 'groups_action_join_group' ); /** * Catch and process "Leave Group" button clicks. * * When a group member clicks on the "Leave Group" button from a group's page, * this function is run. * * Note: When leaving a group from the group directory, AJAX is used and * another function handles this. See {@link bp_legacy_theme_ajax_joinleave_group()}. * * @since BuddyPress (1.2.4) */ function groups_action_leave_group() { if ( ! bp_is_single_item() || ! bp_is_groups_component() || ! bp_is_current_action( 'leave-group' ) ) { return false; } // Nonce check if ( ! check_admin_referer( 'groups_leave_group' ) ) { return false; } // User wants to leave any group if ( groups_is_user_member( bp_loggedin_user_id(), bp_get_current_group_id() ) ) { $bp = buddypress(); // Stop sole admins from abandoning their group $group_admins = groups_get_group_admins( bp_get_current_group_id() ); if ( 1 == count( $group_admins ) && $group_admins[0]->user_id == bp_loggedin_user_id() ) { bp_core_add_message( __( 'This group must have at least one admin', 'buddypress' ), 'error' ); } elseif ( ! groups_leave_group( $bp->groups->current_group->id ) ) { bp_core_add_message( __( 'There was an error leaving the group.', 'buddypress' ), 'error' ); } else { bp_core_add_message( __( 'You successfully left the group.', 'buddypress' ) ); } $redirect = bp_get_group_permalink( groups_get_current_group() ); if( 'hidden' == $bp->groups->current_group->status ) { $redirect = trailingslashit( bp_loggedin_user_domain() . bp_get_groups_slug() ); } bp_core_redirect( $redirect ); } bp_core_load_template( apply_filters( 'groups_template_group_home', 'groups/single/home' ) ); } add_action( 'bp_actions', 'groups_action_leave_group' ); /** * Sort the group creation steps. * * @return bool|null False on failure. */ function groups_action_sort_creation_steps() { global $bp; if ( !bp_is_groups_component() || !bp_is_current_action( 'create' ) ) return false; if ( !is_array( $bp->groups->group_creation_steps ) ) return false; foreach ( (array) $bp->groups->group_creation_steps as $slug => $step ) { while ( !empty( $temp[$step['position']] ) ) $step['position']++; $temp[$step['position']] = array( 'name' => $step['name'], 'slug' => $slug ); } // Sort the steps by their position key ksort($temp); unset($bp->groups->group_creation_steps); foreach( (array) $temp as $position => $step ) $bp->groups->group_creation_steps[$step['slug']] = array( 'name' => $step['name'], 'position' => $position ); } /** * Catch requests for a random group page (example.com/groups/?random-group) and redirect. */ function groups_action_redirect_to_random_group() { if ( bp_is_groups_component() && isset( $_GET['random-group'] ) ) { $group = BP_Groups_Group::get_random( 1, 1 ); bp_core_redirect( bp_get_root_domain() . '/' . bp_get_groups_root_slug() . '/' . $group['groups'][0]->slug . '/' ); } } add_action( 'bp_actions', 'groups_action_redirect_to_random_group' ); /** * Load the activity feed for the current group. * * @since BuddyPress (1.2.0) * * @return bool|null False on failure. */ function groups_action_group_feed() { // get current group $group = groups_get_current_group(); if ( ! bp_is_active( 'activity' ) || ! bp_is_groups_component() || ! $group || ! bp_is_current_action( 'feed' ) ) return false; // if group isn't public or if logged-in user is not a member of the group, do // not output the group activity feed if ( ! bp_group_is_visible( $group ) ) { return false; } // setup the feed buddypress()->activity->feed = new BP_Activity_Feed( array( 'id' => 'group', /* translators: Group activity RSS title - "[Site Name] | [Group Name] | Activity" */ 'title' => sprintf( __( '%1$s | %2$s | Activity', 'buddypress' ), bp_get_site_name(), bp_get_current_group_name() ), 'link' => bp_get_group_permalink( $group ), 'description' => sprintf( __( "Activity feed for the group, %s.", 'buddypress' ), bp_get_current_group_name() ), 'activity_args' => array( 'object' => buddypress()->groups->id, 'primary_id' => bp_get_current_group_id(), 'display_comments' => 'threaded' ) ) ); } add_action( 'bp_actions', 'groups_action_group_feed' );
gpl-2.0
alvarpoon/silverheritage.com
wp-content/plugins/contact-form-7-to-database-extension/ShortCodeLoader.php
2370
<?php /* "Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com) This file is part of Contact Form to Database. Contact Form to Database 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. Contact Form to Database 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 Contact Form to Database. If not, see <http://www.gnu.org/licenses/>. */ abstract class ShortCodeLoader { /** * @param $shortcodeName mixed either string name of the shortcode * (as it would appear in a post, e.g. [shortcodeName]) * or an array of such names in case you want to have more than one name * for the same shortcode * @return void */ public function register($shortcodeName) { $this->registerShortcodeToFunction($shortcodeName, 'handleShortcode'); } /** * @param $shortcodeName string|array name of the shortcode * as it would appear in a post, e.g. [shortcodeName] * or an array of such names in case you want to have more than one name * for the same shortcode * @param $functionName string name of public function in this class to call as the * shortcode handler * @return void */ protected function registerShortcodeToFunction($shortcodeName, $functionName) { if (is_array($shortcodeName)) { foreach ($shortcodeName as $aName) { add_shortcode($aName, array($this, $functionName)); } } else { add_shortcode($shortcodeName, array($this, $functionName)); } } /** * @abstract Override this function and add actual shortcode handling here * @param $atts array (associative) of shortcode inputs * @return string shortcode content */ public abstract function handleShortcode($atts); }
gpl-2.0
ryanleong/wp_base
wp-content/plugins/advanced-custom-fields-pro/includes/admin/views/install-network.php
5125
<?php // vars $button = __('Upgrade Sites'); ?> <div id="acf-upgrade-wrap" class="wrap"> <h1><?php _e("Advanced Custom Fields Database Upgrade",'acf'); ?></h1> <p><?php echo sprintf( __("The following sites require a DB upgrade. Check the ones you want to update and then click %s.", 'acf'), '"' . $button . '"'); ?></p> <p><input type="submit" name="upgrade" value="<?php echo $button; ?>" class="button" id="upgrade-sites"></p> <table class="wp-list-table widefat"> <thead> <tr> <td class="manage-column check-column" scope="col"><input type="checkbox" id="sites-select-all"></td> <th class="manage-column" scope="col" style="width:33%;"><label for="sites-select-all"><?php _e("Site", 'acf'); ?></label></th> <th><?php _e("Description", 'acf'); ?></th> </tr> </thead> <tfoot> <tr> <td class="manage-column check-column" scope="col"><input type="checkbox" id="sites-select-all-2"></td> <th class="manage-column" scope="col"><label for="sites-select-all-2"><?php _e("Site", 'acf'); ?></label></th> <th><?php _e("Description", 'acf'); ?></th> </tr> </tfoot> <tbody id="the-list"> <?php foreach( $sites as $i => $site ): ?> <tr<?php if( $i % 2 == 0 ): ?> class="alternate"<?php endif; ?>> <th class="check-column" scope="row"> <?php if( $site['updates'] ): ?> <input type="checkbox" value="<?php echo $site['blog_id']; ?>" name="checked[]"> <?php endif; ?> </th> <td> <strong><?php echo $site['name']; ?></strong><br /><?php echo $site['url']; ?> </td> <td> <?php if( $site['updates'] ): ?> <span class="response"><?php printf(__('Site requires database upgrade from %s to %s', 'acf'), $site['acf_version'], $plugin_version); ?></span> <?php else: ?> <?php _e("Site is up to date", 'acf'); ?> <?php endif; ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <p><input type="submit" name="upgrade" value="<?php echo $button; ?>" class="button" id="upgrade-sites-2"></p> <p class="show-on-complete"><?php echo sprintf( __('Database Upgrade complete. <a href="%s">Return to network dashboard</a>', 'acf'), network_admin_url() ); ?></p> <style type="text/css"> /* hide show */ .show-on-complete { display: none; } </style> <script type="text/javascript"> (function($) { var upgrader = { $buttons: null, $inputs: null, i: 0, init : function(){ // reference var self = this; // vars this.$buttons = $('#upgrade-sites, #upgrade-sites-2'); // events this.$buttons.on('click', function( e ){ // prevent default e.preventDefault(); // confirm var answer = confirm("<?php _e('It is strongly recommended that you backup your database before proceeding. Are you sure you wish to run the updater now?', 'acf'); ?>"); // bail early if no confirm if( !answer ) { return; } // populate inputs self.$inputs = $('#the-list input:checked'); // upgrade self.upgrade(); }); // return return this; }, upgrade: function(){ // reference var self = this; // bail early if no sites if( !this.$inputs.length ) { return; } // complete if( this.i >= this.$inputs.length ) { this.complete(); return; } // disable buttons this.$buttons.attr('disabled', 'disabled'); // vars var $input = this.$inputs.eq( this.i ), $tr = $input.closest('tr'), text = '<?php _e('Upgrade complete', 'acf'); ?>'; // add loading $tr.find('.response').html('<i class="acf-loading"></i></span> <?php printf(__('Upgrading data to version %s', 'acf'), $plugin_version); ?>'); // get results var xhr = $.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', dataType: 'json', type: 'post', data: { action: 'acf/admin/db_update', nonce: '<?php echo wp_create_nonce('acf_db_update'); ?>', blog_id: $input.val(), }, success: function( json ){ // remove input $input.prop('checked', false); $input.remove(); // vars var message = acf.get_ajax_message(json); // bail early if no message text if( !message.text ) { return; } // update text text = '<pre>' + message.text + '</pre>'; }, complete: function(){ $tr.find('.response').html( text ); // upgrade next site self.next(); } }); }, next: function(){ this.i++; this.upgrade(); }, complete: function(){ // enable buttons this.$buttons.removeAttr('disabled'); // show message $('.show-on-complete').show(); } }.init(); })(jQuery); </script> </div>
gpl-2.0
rcav/rcav
wp-content/plugins/backwpup/sdk/Aws/Aws/Common/Exception/Parser/ExceptionParserInterface.php
1276
<?php /** * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ namespace Aws\Common\Exception\Parser; use Guzzle\Http\Message\Response; /** * Interface used to parse exceptions into an associative array of data */ interface ExceptionParserInterface { /** * Parses an exception into an array of data containing at minimum the * following array keys: * - type: Exception type * - code: Exception code * - message: Exception message * - request_id: Request ID * - parsed: The parsed representation of the data (array, SimpleXMLElement, etc) * * @param Response $response Unsuccessful response * * @return array */ public function parse(Response $response); }
gpl-2.0
tanghongfa/booked
lib/external/pear/Config/Container/PHPConstants.php
6755
<?php // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2003 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.0 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Authors: Phillip Oertel <me@phillipoertel.com> | // +----------------------------------------------------------------------+ // // $Id: PHPConstants.php,v 1.3 2005/12/24 02:24:30 aashley Exp $ /** * Config parser for PHP constant files * * @author Phillip Oertel <me@phillipoertel.com> * @package Config * @version 0.1 (not submitted) */ require_once 'Config/Container.php'; class Config_Container_PHPConstants extends Config_Container { /** * This class options * Not used at the moment * * @var array */ var $options = array(); /** * Constructor * * @access public * @param string $options (optional)Options to be used by renderer */ function Config_Container_PHPConstants($options = array()) { $this->options = $options; } // end constructor /** * Parses the data of the given configuration file * * @access public * @param string $datasrc path to the configuration file * @param object $obj reference to a config object * @return mixed returns a PEAR_ERROR, if error occurs or true if ok */ function &parseDatasrc($datasrc, &$obj) { $return = true; if (!file_exists($datasrc)) { return PEAR::raiseError("Datasource file does not exist.", null, PEAR_ERROR_RETURN); } $fileContent = file_get_contents($datasrc, true); if (!$fileContent) { return PEAR::raiseError("File '$datasrc' could not be read.", null, PEAR_ERROR_RETURN); } $rows = explode("\n", $fileContent); for ($i=0, $max=count($rows); $i<$max; $i++) { $line = $rows[$i]; //blanks? // sections if (preg_match("/^\/\/\s*$/", $line)) { preg_match("/^\/\/\s*(.+)$/", $rows[$i+1], $matches); $obj->container->createSection(trim($matches[1])); $i += 2; continue; } // comments if (preg_match("/^\/\/\s*(.+)$/", $line, $matches) || preg_match("/^#\s*(.+)$/", $line, $matches)) { $obj->container->createComment(trim($matches[1])); continue; } // directives $regex = "/^\s*define\s*\('([A-Z1-9_]+)',\s*'*(.[^\']*)'*\)/"; preg_match($regex, $line, $matches); if (!empty($matches)) { $obj->container->createDirective(trim($matches[1]), trim($matches[2])); } } return $return; } // end func parseDatasrc /** * Returns a formatted string of the object * @param object $obj Container object to be output as string * @access public * @return string */ function toString(&$obj) { $string = ''; switch ($obj->type) { case 'blank': $string = "\n"; break; case 'comment': $string = '// '.$obj->content."\n"; break; case 'directive': $content = $obj->content; // don't quote numeric values, true/false and constants if (!is_numeric($content) && !in_array($content, array('false', 'true')) && !preg_match('/^[A-Z_]+$/', $content)) { $content = "'".$content."'"; } $string = 'define(\''.$obj->name.'\', '.$content.');'.chr(10); break; case 'section': if (!$obj->isRoot()) { $string = chr(10); $string .= '//'.chr(10); $string .= '// '.$obj->name.chr(10); $string .= '//'.chr(10); } if (count($obj->children) > 0) { for ($i = 0, $max = count($obj->children); $i < $max; $i++) { $string .= $this->toString($obj->getChild($i)); } } break; default: $string = ''; } return $string; } // end func toString /** * Writes the configuration to a file * * @param mixed datasrc info on datasource such as path to the file * @param string configType (optional)type of configuration * @access public * @return string */ function writeDatasrc($datasrc, &$obj) { $fp = @fopen($datasrc, 'w'); if ($fp) { $string = "<?php"; $string .= "\n\n"; $string .= '/**' . chr(10); $string .= ' *' . chr(10); $string .= ' * AUTOMATICALLY GENERATED CODE - DO NOT EDIT BY HAND' . chr(10); $string .= ' *' . chr(10); $string .= '**/' . chr(10); $string .= $this->toString($obj); $string .= "\n?>"; // <? : Fix my syntax coloring $len = strlen($string); @flock($fp, LOCK_EX); @fwrite($fp, $string, $len); @flock($fp, LOCK_UN); @fclose($fp); // need an error check here return true; } else { return PEAR::raiseError('Cannot open datasource for writing.', 1, PEAR_ERROR_RETURN); } } // end func writeDatasrc } // end class Config_Container_PHPConstants ?>
gpl-3.0
OpenSID/OpenSID
vendor/google-api-php-client/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php
1305
<?php declare(strict_types=1); /* * This file is part of the Monolog package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Monolog\Formatter; /** * Encodes message information into JSON in a format compatible with Loggly. * * @author Adam Pancutt <adam@pancutt.com> */ class LogglyFormatter extends JsonFormatter { /** * Overrides the default batch mode to new lines for compatibility with the * Loggly bulk API. */ public function __construct(int $batchMode = self::BATCH_MODE_NEWLINES, bool $appendNewline = false) { parent::__construct($batchMode, $appendNewline); } /** * Appends the 'timestamp' parameter for indexing by Loggly. * * @see https://www.loggly.com/docs/automated-parsing/#json * @see \Monolog\Formatter\JsonFormatter::format() */ public function format(array $record): string { if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTimeInterface)) { $record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO"); unset($record["datetime"]); } return parent::format($record); } }
gpl-3.0
gitTerebi/OpenRA
OpenRA.Mods.Common/Scripting/Global/MapGlobal.cs
4043
#region Copyright & License Information /* * Copyright 2007-2015 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using System; using System.Linq; using Eluant; using OpenRA.Mods.Common.Traits; using OpenRA.Scripting; namespace OpenRA.Mods.Common.Scripting { [ScriptGlobal("Map")] public class MapGlobal : ScriptGlobal { SpawnMapActors sma; public MapGlobal(ScriptContext context) : base(context) { sma = context.World.WorldActor.Trait<SpawnMapActors>(); // Register map actors as globals (yuck!) foreach (var kv in sma.Actors) context.RegisterMapActor(kv.Key, kv.Value); } [Desc("Returns a table of all actors within the requested region, filtered using the specified function.")] public Actor[] ActorsInCircle(WPos location, WDist radius, LuaFunction filter = null) { var actors = Context.World.FindActorsInCircle(location, radius); if (filter != null) { actors = actors.Where(a => { using (var f = filter.Call(a.ToLuaValue(Context))) return f.First().ToBoolean(); }); } return actors.ToArray(); } [Desc("Returns a table of all actors within the requested rectangle, filtered using the specified function.")] public Actor[] ActorsInBox(WPos topLeft, WPos bottomRight, LuaFunction filter = null) { var actors = Context.World.ActorMap.ActorsInBox(topLeft, bottomRight); if (filter != null) { actors = actors.Where(a => { using (var f = filter.Call(a.ToLuaValue(Context))) return f.First().ToBoolean(); }); } return actors.ToArray(); } [Desc("Returns the location of the top-left corner of the map (assuming zero terrain height).")] public WPos TopLeft { get { // HACK: This api method abuses the coordinate system, and should be removed // in favour of proper actor queries. See #8549. return Context.World.Map.ProjectedTopLeft; } } [Desc("Returns the location of the bottom-right corner of the map (assuming zero terrain height).")] public WPos BottomRight { get { // HACK: This api method abuses the coordinate system, and should be removed // in favour of proper actor queries. See #8549. return Context.World.Map.ProjectedBottomRight; } } [Desc("Returns a random cell inside the visible region of the map.")] public CPos RandomCell() { return Context.World.Map.ChooseRandomCell(Context.World.SharedRandom); } [Desc("Returns a random cell on the visible border of the map.")] public CPos RandomEdgeCell() { return Context.World.Map.ChooseRandomEdgeCell(Context.World.SharedRandom); } [Desc("Returns the center of a cell in world coordinates.")] public WPos CenterOfCell(CPos cell) { return Context.World.Map.CenterOfCell(cell); } [Desc("Returns true if there is only one human player.")] public bool IsSinglePlayer { get { return Context.World.LobbyInfo.IsSinglePlayer; } } [Desc("Returns the difficulty selected by the player before starting the mission.")] public string Difficulty { get { return Context.World.LobbyInfo.GlobalSettings.Difficulty; } } [Desc("Returns a table of all the actors that were specified in the map file.")] public Actor[] NamedActors { get { return sma.Actors.Values.ToArray(); } } [Desc("Returns the actor that was specified with a given name in " + "the map file (or nil, if the actor is dead or not found).")] public Actor NamedActor(string actorName) { Actor ret; if (!sma.Actors.TryGetValue(actorName, out ret)) return null; if (ret.Disposed) return null; return ret; } [Desc("Returns true if actor was originally specified in the map file.")] public bool IsNamedActor(Actor actor) { return actor.ActorID <= sma.LastMapActorID && actor.ActorID > sma.LastMapActorID - sma.Actors.Count; } } }
gpl-3.0
REI-Systems/GovDashboard-Community
webapp/sites/all/libraries/phpexcel/Classes/PHPExcel/CachedObjectStorage/CacheBase.php
6347
<?php /** * PHPExcel * * Copyright (c) 2006 - 2012 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel_CachedObjectStorage * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version 1.7.7, 2012-05-19 */ /** * PHPExcel_CachedObjectStorage_CacheBase * * @category PHPExcel * @package PHPExcel_CachedObjectStorage * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_CachedObjectStorage_CacheBase { /** * Parent worksheet * * @var PHPExcel_Worksheet */ protected $_parent; /** * The currently active Cell * * @var PHPExcel_Cell */ protected $_currentObject = null; /** * Coordinate address of the currently active Cell * * @var string */ protected $_currentObjectID = null; /** * Flag indicating whether the currently active Cell requires saving * * @var boolean */ protected $_currentCellIsDirty = true; /** * An array of cells or cell pointers for the worksheet cells held in this cache, * and indexed by their coordinate address within the worksheet * * @var array of mixed */ protected $_cellCache = array(); /** * Initialise this new cell collection * * @param PHPExcel_Worksheet $parent The worksheet for this cell collection */ public function __construct(PHPExcel_Worksheet $parent) { // Set our parent worksheet. // This is maintained within the cache controller to facilitate re-attaching it to PHPExcel_Cell objects when // they are woken from a serialized state $this->_parent = $parent; } // function __construct() /** * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell? * * @param string $pCoord Coordinate address of the cell to check * @return boolean */ public function isDataSet($pCoord) { if ($pCoord === $this->_currentObjectID) { return true; } // Check if the requested entry exists in the cache return isset($this->_cellCache[$pCoord]); } // function isDataSet() /** * Add or Update a cell in cache * * @param PHPExcel_Cell $cell Cell to update * @return void * @throws Exception */ public function updateCacheData(PHPExcel_Cell $cell) { return $this->addCacheData($cell->getCoordinate(),$cell); } // function updateCacheData() /** * Delete a cell in cache identified by coordinate address * * @param string $pCoord Coordinate address of the cell to delete * @throws Exception */ public function deleteCacheData($pCoord) { if ($pCoord === $this->_currentObjectID) { $this->_currentObject->detach(); $this->_currentObjectID = $this->_currentObject = null; } if (is_object($this->_cellCache[$pCoord])) { $this->_cellCache[$pCoord]->detach(); unset($this->_cellCache[$pCoord]); } $this->_currentCellIsDirty = false; } // function deleteCacheData() /** * Get a list of all cell addresses currently held in cache * * @return array of string */ public function getCellList() { return array_keys($this->_cellCache); } // function getCellList() /** * Sort the list of all cell addresses currently held in cache by row and column * * @return void */ public function getSortedCellList() { $sortKeys = array(); foreach ($this->getCellList() as $coord) { list($column,$row) = sscanf($coord,'%[A-Z]%d'); $sortKeys[sprintf('%09d%3s',$row,$column)] = $coord; } ksort($sortKeys); return array_values($sortKeys); } // function sortCellList() /** * Get highest worksheet column and highest row that have cell records * * @return array Highest column name and highest row number */ public function getHighestRowAndColumn() { // Lookup highest column and highest row $col = array('A' => '1A'); $row = array(1); foreach ($this->getCellList() as $coord) { list($c,$r) = sscanf($coord,'%[A-Z]%d'); $row[$r] = $r; $col[$c] = strlen($c).$c; } if (!empty($row)) { // Determine highest column and row $highestRow = max($row); $highestColumn = substr(max($col),1); } return array( 'row' => $highestRow, 'column' => $highestColumn ); } /** * Get highest worksheet column * * @return string Highest column name */ public function getHighestColumn() { $colRow = $this->getHighestRowAndColumn(); return $colRow['column']; } /** * Get highest worksheet row * * @return int Highest row number */ public function getHighestRow() { $colRow = $this->getHighestRowAndColumn(); return $colRow['row']; } /** * Generate a unique ID for cache referencing * * @return string Unique Reference */ protected function _getUniqueID() { if (function_exists('posix_getpid')) { $baseUnique = posix_getpid(); } else { $baseUnique = mt_rand(); } return uniqid($baseUnique,true); } /** * Clone the cell collection * * @param PHPExcel_Worksheet $parent The new worksheet * @return void */ public function copyCellCollection(PHPExcel_Worksheet $parent) { $this->_parent = $parent; if (($this->_currentObject !== NULL) && (is_object($this->_currentObject))) { $this->_currentObject->attach($parent); } } // function copyCellCollection() /** * Identify whether the caching method is currently available * Some methods are dependent on the availability of certain extensions being enabled in the PHP build * * @return boolean */ public static function cacheMethodIsAvailable() { return true; } }
gpl-3.0
hackbuteer59/sakai
common/common-composite-component/src/java/org/sakaiproject/component/common/manager/PersistableHelper.java
4204
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation. * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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 org.sakaiproject.component.common.manager; import java.lang.reflect.InvocationTargetException; import java.util.Date; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.api.common.manager.Persistable; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.SessionManager; /** * @author <a href="mailto:lance@indiana.edu">Lance Speelmon</a> */ public class PersistableHelper { private static final String SYSTEM = "SYSTEM"; private static final Log LOG = LogFactory.getLog(PersistableHelper.class); private static final String LASTMODIFIEDDATE = "lastModifiedDate"; private static final String LASTMODIFIEDBY = "lastModifiedBy"; private static final String CREATEDDATE = "createdDate"; private static final String CREATEDBY = "createdBy"; private SessionManager sessionManager; // dep inj public void modifyPersistableFields(Persistable persistable) { Date now = new Date(); // time sensitive if (LOG.isDebugEnabled()) { LOG.debug("modifyPersistableFields(Persistable " + persistable + ")"); } if (persistable == null) throw new IllegalArgumentException("Illegal persistable argument passed!"); try { String actor = getActor(); PropertyUtils.setProperty(persistable, LASTMODIFIEDBY, actor); PropertyUtils.setProperty(persistable, LASTMODIFIEDDATE, now); } catch (NoSuchMethodException e) { LOG.error(e); throw new RuntimeException(e); } catch (IllegalAccessException e) { LOG.error(e); throw new RuntimeException(e); } catch (InvocationTargetException e) { LOG.error(e); throw new RuntimeException(e); } } public void createPersistableFields(Persistable persistable) { Date now = new Date(); // time sensitive if (LOG.isDebugEnabled()) { LOG.debug("modifyPersistableFields(Persistable " + persistable + ")"); } if (persistable == null) throw new IllegalArgumentException("Illegal persistable argument passed!"); try { String actor = getActor(); PropertyUtils.setProperty(persistable, LASTMODIFIEDBY, actor); PropertyUtils.setProperty(persistable, LASTMODIFIEDDATE, now); PropertyUtils.setProperty(persistable, CREATEDBY, actor); PropertyUtils.setProperty(persistable, CREATEDDATE, now); } catch (NoSuchMethodException e) { LOG.error(e); throw new RuntimeException(e); } catch (IllegalAccessException e) { LOG.error(e); throw new RuntimeException(e); } catch (InvocationTargetException e) { LOG.error(e); throw new RuntimeException(e); } } private String getActor() { LOG.debug("getActor()"); String actor = null; Session session = sessionManager.getCurrentSession(); if (session != null) { actor = session.getUserId(); } else { return SYSTEM; } if (actor == null || actor.length() < 1) { return SYSTEM; } else { return actor; } } /** * Dependency injection. * * @param sessionManager * The sessionManager to set. */ public void setSessionManager(SessionManager sessionManager) { if (LOG.isDebugEnabled()) { LOG.debug("setSessionManager(SessionManager " + sessionManager + ")"); } this.sessionManager = sessionManager; } }
apache-2.0
trajano/maven
maven-model-builder/src/test/java/org/apache/maven/model/profile/activation/PropertyProfileActivatorTest.java
6063
package org.apache.maven.model.profile.activation; /* * 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. */ import java.util.Properties; import org.apache.maven.model.Activation; import org.apache.maven.model.ActivationProperty; import org.apache.maven.model.Profile; /** * Tests {@link PropertyProfileActivator}. * * @author Benjamin Bentmann */ public class PropertyProfileActivatorTest extends AbstractProfileActivatorTest<PropertyProfileActivator> { public PropertyProfileActivatorTest() { super( PropertyProfileActivator.class ); } private Profile newProfile( String key, String value ) { ActivationProperty ap = new ActivationProperty(); ap.setName( key ); ap.setValue( value ); Activation a = new Activation(); a.setProperty( ap ); Profile p = new Profile(); p.setActivation( a ); return p; } private Properties newProperties( String key, String value ) { Properties props = new Properties(); props.setProperty( key, value ); return props; } public void testNullSafe() throws Exception { Profile p = new Profile(); assertActivation( false, p, newContext( null, null ) ); p.setActivation( new Activation() ); assertActivation( false, p, newContext( null, null ) ); } public void testWithNameOnly_UserProperty() throws Exception { Profile profile = newProfile( "prop", null ); assertActivation( true, profile, newContext( newProperties( "prop", "value" ), null ) ); assertActivation( false, profile, newContext( newProperties( "prop", "" ), null ) ); assertActivation( false, profile, newContext( newProperties( "other", "value" ), null ) ); } public void testWithNameOnly_SystemProperty() throws Exception { Profile profile = newProfile( "prop", null ); assertActivation( true, profile, newContext( null, newProperties( "prop", "value" ) ) ); assertActivation( false, profile, newContext( null, newProperties( "prop", "" ) ) ); assertActivation( false, profile, newContext( null, newProperties( "other", "value" ) ) ); } public void testWithNegatedNameOnly_UserProperty() throws Exception { Profile profile = newProfile( "!prop", null ); assertActivation( false, profile, newContext( newProperties( "prop", "value" ), null ) ); assertActivation( true, profile, newContext( newProperties( "prop", "" ), null ) ); assertActivation( true, profile, newContext( newProperties( "other", "value" ), null ) ); } public void testWithNegatedNameOnly_SystemProperty() throws Exception { Profile profile = newProfile( "!prop", null ); assertActivation( false, profile, newContext( null, newProperties( "prop", "value" ) ) ); assertActivation( true, profile, newContext( null, newProperties( "prop", "" ) ) ); assertActivation( true, profile, newContext( null, newProperties( "other", "value" ) ) ); } public void testWithValue_UserProperty() throws Exception { Profile profile = newProfile( "prop", "value" ); assertActivation( true, profile, newContext( newProperties( "prop", "value" ), null ) ); assertActivation( false, profile, newContext( newProperties( "prop", "other" ), null ) ); assertActivation( false, profile, newContext( newProperties( "prop", "" ), null ) ); } public void testWithValue_SystemProperty() throws Exception { Profile profile = newProfile( "prop", "value" ); assertActivation( true, profile, newContext( null, newProperties( "prop", "value" ) ) ); assertActivation( false, profile, newContext( null, newProperties( "prop", "other" ) ) ); assertActivation( false, profile, newContext( null, newProperties( "other", "" ) ) ); } public void testWithNegatedValue_UserProperty() throws Exception { Profile profile = newProfile( "prop", "!value" ); assertActivation( false, profile, newContext( newProperties( "prop", "value" ), null ) ); assertActivation( true, profile, newContext( newProperties( "prop", "other" ), null ) ); assertActivation( true, profile, newContext( newProperties( "prop", "" ), null ) ); } public void testWithNegatedValue_SystemProperty() throws Exception { Profile profile = newProfile( "prop", "!value" ); assertActivation( false, profile, newContext( null, newProperties( "prop", "value" ) ) ); assertActivation( true, profile, newContext( null, newProperties( "prop", "other" ) ) ); assertActivation( true, profile, newContext( null, newProperties( "other", "" ) ) ); } public void testWithValue_UserPropertyDominantOverSystemProperty() throws Exception { Profile profile = newProfile( "prop", "value" ); Properties props1 = newProperties( "prop", "value" ); Properties props2 = newProperties( "prop", "other" ); assertActivation( true, profile, newContext( props1, props2 ) ); assertActivation( false, profile, newContext( props2, props1 ) ); } }
apache-2.0
Vizaxo/Terasology
modules/Core/src/main/java/org/terasology/rendering/nui/layers/ingame/inventory/InventoryCellRendered.java
985
/* * Copyright 2014 MovingBlocks * * 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 org.terasology.rendering.nui.layers.ingame.inventory; import org.terasology.entitySystem.event.Event; import org.terasology.rendering.nui.Canvas; public class InventoryCellRendered implements Event { private Canvas canvas; public InventoryCellRendered(Canvas canvas) { this.canvas = canvas; } public Canvas getCanvas() { return canvas; } }
apache-2.0
stevechlin/mobilecloud-15
examples/4-VideoControllerWithDependencyInjection/src/main/java/org/magnum/mobilecloud/video/controller/Video.java
1577
package org.magnum.mobilecloud.video.controller; import com.google.common.base.Objects; /** * A simple object to represent a video and its URL for viewing. * * @author jules * */ public class Video { private String name; private String url; private long duration; public Video(){} public Video(String name, String url, long duration) { super(); this.name = name; this.url = url; this.duration = duration; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } /** * Two Videos will generate the same hashcode if they have exactly * the same values for their name, url, and duration. * */ @Override public int hashCode() { // Google Guava provides great utilities for hashing return Objects.hashCode(name,url,duration); } /** * Two Videos are considered equal if they have exactly * the same values for their name, url, and duration. * */ @Override public boolean equals(Object obj) { if(obj instanceof Video){ Video other = (Video)obj; // Google Guava provides great utilities for equals too! return Objects.equal(name, other.name) && Objects.equal(url, other.url) && duration == other.duration; } else { return false; } } }
apache-2.0
vinodkc/spark
sql/catalyst/src/test/scala/org/apache/spark/sql/RowTest.scala
4573
/* * 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 org.apache.spark.sql import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers import org.scalatest.matchers.should.Matchers._ import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.{GenericRow, GenericRowWithSchema} import org.apache.spark.sql.types._ class RowTest extends AnyFunSpec with Matchers { val schema = StructType( StructField("col1", StringType) :: StructField("col2", StringType) :: StructField("col3", IntegerType) :: Nil) val values = Array("value1", "value2", 1) val valuesWithoutCol3 = Array[Any](null, "value2", null) val sampleRow: Row = new GenericRowWithSchema(values, schema) val sampleRowWithoutCol3: Row = new GenericRowWithSchema(valuesWithoutCol3, schema) val noSchemaRow: Row = new GenericRow(values) describe("Row (without schema)") { it("throws an exception when accessing by fieldName") { intercept[UnsupportedOperationException] { noSchemaRow.fieldIndex("col1") } intercept[UnsupportedOperationException] { noSchemaRow.getAs("col1") } } } describe("Row (with schema)") { it("fieldIndex(name) returns field index") { sampleRow.fieldIndex("col1") shouldBe 0 sampleRow.fieldIndex("col3") shouldBe 2 } it("getAs[T] retrieves a value by fieldname") { sampleRow.getAs[String]("col1") shouldBe "value1" sampleRow.getAs[Int]("col3") shouldBe 1 } it("Accessing non existent field throws an exception") { intercept[IllegalArgumentException] { sampleRow.getAs[String]("non_existent") } } it("getValuesMap() retrieves values of multiple fields as a Map(field -> value)") { val expected = Map( "col1" -> "value1", "col2" -> "value2" ) sampleRow.getValuesMap(List("col1", "col2")) shouldBe expected } it("getValuesMap() retrieves null value on non AnyVal Type") { val expected = Map( "col1" -> null, "col2" -> "value2" ) sampleRowWithoutCol3.getValuesMap[String](List("col1", "col2")) shouldBe expected } it("getAs() on type extending AnyVal throws an exception when accessing field that is null") { intercept[NullPointerException] { sampleRowWithoutCol3.getInt(sampleRowWithoutCol3.fieldIndex("col3")) } } it("getAs() on type extending AnyVal does not throw exception when value is null") { sampleRowWithoutCol3.getAs[String](sampleRowWithoutCol3.fieldIndex("col1")) shouldBe null } } describe("row equals") { val externalRow = Row(1, 2) val externalRow2 = Row(1, 2) val internalRow = InternalRow(1, 2) val internalRow2 = InternalRow(1, 2) it("equality check for external rows") { externalRow shouldEqual externalRow2 } it("equality check for internal rows") { internalRow shouldEqual internalRow2 } } describe("row immutability") { val values = Seq(1, 2, "3", "IV", 6L) val externalRow = Row.fromSeq(values) val internalRow = InternalRow.fromSeq(values) def modifyValues(values: Seq[Any]): Seq[Any] = { val array = values.toArray array(2) = "42" array } it("copy should return same ref for external rows") { externalRow should be theSameInstanceAs externalRow.copy() } it("toSeq should not expose internal state for external rows") { val modifiedValues = modifyValues(externalRow.toSeq) externalRow.toSeq should not equal modifiedValues } it("toSeq should not expose internal state for internal rows") { val modifiedValues = modifyValues(internalRow.toSeq(Seq.empty)) internalRow.toSeq(Seq.empty) should not equal modifiedValues } } }
apache-2.0
kesfun/designscookwebsite
vendor/predis/predis/tests/Predis/Command/StringGetRangeTest.php
2966
<?php /* * This file is part of the Predis package. * * (c) Daniele Alessandri <suppakilla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Predis\Command; /** * @group commands * @group realm-string */ class StringGetRangeTest extends PredisCommandTestCase { /** * {@inheritdoc} */ protected function getExpectedCommand() { return 'Predis\Command\StringGetRange'; } /** * {@inheritdoc} */ protected function getExpectedId() { return 'GETRANGE'; } /** * @group disconnected */ public function testFilterArguments() { $arguments = array('key', 5, 10); $expected = array('key', 5, 10); $command = $this->getCommand(); $command->setArguments($arguments); $this->assertSame($expected, $command->getArguments()); } /** * @group disconnected */ public function testParseResponse() { $this->assertSame('substring',$this->getCommand()->parseResponse('substring')); } /** * @group disconnected */ public function testPrefixKeys() { $arguments = array('key', 5, 10); $expected = array('prefix:key', 5, 10); $command = $this->getCommandWithArgumentsArray($arguments); $command->prefixKeys('prefix:'); $this->assertSame($expected, $command->getArguments()); } /** * @group disconnected */ public function testPrefixKeysIgnoredOnEmptyArguments() { $command = $this->getCommand(); $command->prefixKeys('prefix:'); $this->assertSame(array(), $command->getArguments()); } /** * @group connected */ public function testReturnsSubstring() { $redis = $this->getClient(); $redis->set('string', 'this is a string'); $this->assertSame('this', $redis->getrange('string', 0, 3)); $this->assertSame('ing', $redis->getrange('string', -3, -1)); $this->assertSame('this is a string', $redis->getrange('string', 0, -1)); $this->assertSame('string', $redis->getrange('string', 10, 100)); $this->assertSame('t', $redis->getrange('string', 0, 0)); $this->assertSame('', $redis->getrange('string', -1, 0)); } /** * @group connected */ public function testReturnsEmptyStringOnNonExistingKey() { $redis = $this->getClient(); $this->assertSame('', $redis->getrange('string', 0, 3)); } /** * @group connected * @expectedException Predis\ServerException * @expectedExceptionMessage Operation against a key holding the wrong kind of value */ public function testThrowsExceptionOnWrongType() { $redis = $this->getClient(); $redis->lpush('metavars', 'foo'); $redis->getrange('metavars', 0, 5); } }
gpl-2.0
BlakeRxxk/keystone
fields/types/cloudinaryimage/CloudinaryImageType.js
11685
/*! * Module dependencies. */ var _ = require('underscore'), keystone = require('../../../'), util = require('util'), cloudinary = require('cloudinary'), MPromise = require('mpromise'), utils = require('keystone-utils'), super_ = require('../Type'); /** * CloudinaryImage FieldType Constructor * @extends Field * @api public */ function cloudinaryimage(list, path, options) { this._underscoreMethods = ['format']; this._fixedSize = 'full'; this._properties = ['select', 'selectPrefix', 'autoCleanup', 'publicID', 'folder', 'filenameAsPublicID']; // TODO: implement filtering, usage disabled for now options.nofilter = true; // TODO: implement initial form, usage disabled for now if (options.initial) { throw new Error( 'Invalid Configuration\n\n' + 'CloudinaryImage fields (' + list.key + '.' + path + ') do not currently support being used as initial fields.\n' ); } cloudinaryimage.super_.call(this, list, path, options); // validate cloudinary config if (!keystone.get('cloudinary config')) { throw new Error( 'Invalid Configuration\n\n' + 'CloudinaryImage fields (' + list.key + '.' + this.path + ') require the "cloudinary config" option to be set.\n\n' + 'See http://keystonejs.com/docs/configuration/#services-cloudinary for more information.\n' ); } } /*! * Inherit from Field */ util.inherits(cloudinaryimage, super_); /** * Registers the field on the List's Mongoose Schema. * * @api public */ cloudinaryimage.prototype.addToSchema = function() { var field = this, schema = this.list.schema; var paths = this.paths = { // cloudinary fields public_id: this._path.append('.public_id'), version: this._path.append('.version'), signature: this._path.append('.signature'), format: this._path.append('.format'), resource_type: this._path.append('.resource_type'), url: this._path.append('.url'), width: this._path.append('.width'), height: this._path.append('.height'), secure_url: this._path.append('.secure_url'), // virtuals exists: this._path.append('.exists'), folder: this._path.append('.folder'), // form paths upload: this._path.append('_upload'), action: this._path.append('_action'), select: this._path.append('_select') }; var schemaPaths = this._path.addTo({}, { public_id: String, version: Number, signature: String, format: String, resource_type: String, url: String, width: Number, height: Number, secure_url: String }); schema.add(schemaPaths); var exists = function(item) { return (item.get(paths.public_id) ? true : false); }; // The .exists virtual indicates whether an image is stored schema.virtual(paths.exists).get(function() { return schemaMethods.exists.apply(this); }); var folder = function(item) {//eslint-disable-line no-unused-vars var folderValue = null; if (keystone.get('cloudinary folders')) { if (field.options.folder) { folderValue = field.options.folder; } else { var folderList = keystone.get('cloudinary prefix') ? [keystone.get('cloudinary prefix')] : []; folderList.push(field.list.path); folderList.push(field.path); folderValue = folderList.join('/'); } } return folderValue; }; // The .folder virtual returns the cloudinary folder used to upload/select images schema.virtual(paths.folder).get(function() { return schemaMethods.folder.apply(this); }); var src = function(item, options) { if (!exists(item)) { return ''; } options = ('object' === typeof options) ? options : {}; if (!('fetch_format' in options) && keystone.get('cloudinary webp') !== false) { options.fetch_format = 'auto'; } if (!('progressive' in options) && keystone.get('cloudinary progressive') !== false) { options.progressive = true; } if (!('secure' in options) && keystone.get('cloudinary secure')) { options.secure = true; } options.version = item.get(paths.version); return cloudinary.url(item.get(paths.public_id) + '.' + item.get(paths.format), options); }; var reset = function(item) { item.set(field.path, { public_id: '', version: 0, signature: '', format: '', resource_type: '', url: '', width: 0, height: 0, secure_url: '' }); }; var addSize = function(options, width, height, other) { if (width) options.width = width; if (height) options.height = height; if ('object' === typeof other) { _.extend(options, other); } return options; }; var schemaMethods = { exists: function() { return exists(this); }, folder: function() { return folder(this); }, src: function(options) { return src(this, options); }, tag: function(options) { return exists(this) ? cloudinary.image(this.get(field.path), options) : ''; }, scale: function(width, height, options) { return src(this, addSize({ crop: 'scale' }, width, height, options)); }, fill: function(width, height, options) { return src(this, addSize({ crop: 'fill', gravity: 'faces' }, width, height, options)); }, lfill: function(width, height, options) { return src(this, addSize({ crop: 'lfill', gravity: 'faces' }, width, height, options)); }, fit: function(width, height, options) { return src(this, addSize({ crop: 'fit' }, width, height, options)); }, limit: function(width, height, options) { return src(this, addSize({ crop: 'limit' }, width, height, options)); }, pad: function(width, height, options) { return src(this, addSize({ crop: 'pad' }, width, height, options)); }, lpad: function(width, height, options) { return src(this, addSize({ crop: 'lpad' }, width, height, options)); }, crop: function(width, height, options) { return src(this, addSize({ crop: 'crop', gravity: 'faces' }, width, height, options)); }, thumbnail: function(width, height, options) { return src(this, addSize({ crop: 'thumb', gravity: 'faces' }, width, height, options)); }, /** * Resets the value of the field * * @api public */ reset: function() { reset(this); }, /** * Deletes the image from Cloudinary and resets the field * * @api public */ delete: function() { var promise = new MPromise(); cloudinary.uploader.destroy(this.get(paths.public_id), function(result) { promise.fulfill(result); }); reset(this); return promise; }, /** * Uploads the image to Cloudinary * * @api public */ upload: function(file, options) { var promise = new MPromise(); cloudinary.uploader.upload(file, function(result) { promise.fulfill(result); }, options); return promise; } }; _.each(schemaMethods, function(fn, key) { field.underscoreMethod(key, fn); }); // expose a method on the field to call schema methods this.apply = function(item, method) { return schemaMethods[method].apply(item, Array.prototype.slice.call(arguments, 2)); }; this.bindUnderscoreMethods(); }; /** * Formats the field value * * @api public */ cloudinaryimage.prototype.format = function(item) { return item.get(this.paths.url); }; /** * Detects whether the field has been modified * * @api public */ cloudinaryimage.prototype.isModified = function(item) { return item.isModified(this.paths.url); }; /** * Validates that a value for this field has been provided in a data object * * @api public */ cloudinaryimage.prototype.validateInput = function(data) {//eslint-disable-line no-unused-vars // TODO - how should image field input be validated? return true; }; /** * Updates the value for this field in the item from a data object * * @api public */ cloudinaryimage.prototype.updateItem = function(item, data) { var paths = this.paths; var setValue = function(key) { if (paths[key]) { var index = paths[key].indexOf('.'); var field = paths[key].substr(0, index); // Note we allow implicit conversion here so that numbers submitted as strings in the data object // aren't treated as different values to the stored Number values if (data[field] && data[field][key] && data[field][key] != item.get(paths[key])) { // eslint-disable-line eqeqeq item.set(paths[key], data[field][key] || null); } } }; _.each(['public_id', 'version', 'signature', 'format', 'resource_type', 'url', 'width', 'height', 'secure_url'], setValue); }; /** * Returns a callback that handles a standard form submission for the field * * Expected form parts are * - `field.paths.action` in `req.body` (`clear` or `delete`) * - `field.paths.upload` in `req.files` (uploads the image to cloudinary) * * @api public */ cloudinaryimage.prototype.getRequestHandler = function(item, req, paths, callback) { var field = this; if (utils.isFunction(paths)) { callback = paths; paths = field.paths; } else if (!paths) { paths = field.paths; } callback = callback || function() {}; return function() { if (req.body) { var action = req.body[paths.action]; if (/^(delete|reset)$/.test(action)) { field.apply(item, action); } } if (req.body && req.body[paths.select]) { cloudinary.api.resource(req.body[paths.select], function(result) { if (result.error) { callback(result.error); } else { item.set(field.path, result); callback(); } }); } else if (req.files && req.files[paths.upload] && req.files[paths.upload].size) { var tp = keystone.get('cloudinary prefix') || ''; var imageDelete; if (tp.length) { tp += '_'; } var uploadOptions = { tags: [tp + field.list.path + '_' + field.path, tp + field.list.path + '_' + field.path + '_' + item.id] }; if (keystone.get('cloudinary folders')) { uploadOptions.folder = item.get(paths.folder); } if (keystone.get('cloudinary prefix')) { uploadOptions.tags.push(keystone.get('cloudinary prefix')); } if (keystone.get('env') !== 'production') { uploadOptions.tags.push(tp + 'dev'); } if (field.options.publicID) { var publicIdValue = item.get(field.options.publicID); if (publicIdValue) { uploadOptions.public_id = publicIdValue; } } else if (field.options.filenameAsPublicID) { uploadOptions.public_id = req.files[paths.upload].originalname.substring(0, req.files[paths.upload].originalname.lastIndexOf('.')); } if (field.options.autoCleanup && item.get(field.paths.exists)) { // capture image delete promise imageDelete = field.apply(item, 'delete'); } // callback to be called upon completion of the 'upload' method var uploadComplete = function(result) { if (result.error) { callback(result.error); } else { item.set(field.path, result); callback(); } }; // upload immediately if image is not being delete if (typeof imageDelete === 'undefined') { field.apply(item, 'upload', req.files[paths.upload].path, uploadOptions).onFulfill(uploadComplete); } else { // otherwise wait until image is deleted before uploading // this avoids problems when deleting/uploading images with the same public_id (issue #598) imageDelete.onFulfill(function(result) { if (result.error) { callback(result.error); } else { field.apply(item, 'upload', req.files[paths.upload].path, uploadOptions).onFulfill(uploadComplete); } }); } } else { callback(); } }; }; /** * Immediately handles a standard form submission for the field (see `getRequestHandler()`) * * @api public */ cloudinaryimage.prototype.handleRequest = function(item, req, paths, callback) { this.getRequestHandler(item, req, paths, callback)(); }; /*! * Export class */ exports = module.exports = cloudinaryimage;
mit
vijaycs85/PHP-CS-Fixer
Symfony/CS/Fixer/Symfony/NoBlankLinesAfterClassOpeningFixer.php
1757
<?php /* * This file is part of the PHP CS utility. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Symfony\CS\Fixer\Symfony; use Symfony\CS\AbstractFixer; use Symfony\CS\Tokenizer\Token; use Symfony\CS\Tokenizer\Tokens; use Symfony\CS\Utils; /** * @author Ceeram <ceeram@cakephp.org> */ class NoBlankLinesAfterClassOpeningFixer extends AbstractFixer { /** * {@inheritdoc} */ public function fix(\SplFileInfo $file, $content) { $tokens = Tokens::fromCode($content); foreach ($tokens as $index => $token) { if (!$token->isClassy()) { continue; } $startBraceIndex = $tokens->getNextTokenOfKind($index, array('{')); if (!$tokens[$startBraceIndex + 1]->isWhitespace()) { continue; } $this->fixWhitespace($tokens[$startBraceIndex + 1]); } return $tokens->generateCode(); } /** * Cleanup a whitespace token. * * @param Token $token */ private function fixWhitespace(Token $token) { $content = $token->getContent(); // if there is more than one new line in the whitespace, then we need to fix it if (substr_count($content, "\n") > 1) { // the final bit of the whitespace must be the next statement's indentation $lines = Utils::splitLines($content); $token->setContent("\n".end($lines)); } } /** * {@inheritdoc} */ public function getDescription() { return 'There should be no empty lines after class opening brace.'; } }
mit
sergeybykov/orleans
src/Orleans.TestingHost/Utils/ThreadSafeRandom.cs
1274
using System; using System.Runtime.CompilerServices; using System.Security.Cryptography; namespace Orleans.TestingHost.Utils { /// <summary> /// Thread-safe random number generator. /// Similar to the implementation by Steven Toub: http://blogs.msdn.com/b/pfxteam/archive/2014/10/20/9434171.aspx /// </summary> internal static class ThreadSafeRandom { private static readonly RandomNumberGenerator globalCryptoProvider = RandomNumberGenerator.Create(); [ThreadStatic] private static Random random; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Random GetRandom() { if (random == null) { byte[] buffer = new byte[4]; globalCryptoProvider.GetBytes(buffer); random = new Random(BitConverter.ToInt32(buffer, 0)); } return random; } public static int Next() { return GetRandom().Next(); } public static int Next(int maxValue) { return GetRandom().Next(maxValue); } public static int Next(int minValue, int maxValue) { return GetRandom().Next(minValue, maxValue); } } }
mit
Anirudhk94/mysql
storage/ndb/ndbapi-examples/ndbapi_event/ndbapi_event.cpp
10848
/* Copyright (c) 2003, 2005, 2006 MySQL AB Use is subject to license terms 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /** * ndbapi_event.cpp: Using API level events in NDB API * * Classes and methods used in this example: * * Ndb_cluster_connection * connect() * wait_until_ready() * * Ndb * init() * getDictionary() * createEventOperation() * dropEventOperation() * pollEvents() * nextEvent() * * NdbDictionary * createEvent() * dropEvent() * * NdbDictionary::Event * setTable() * addTableEvent() * addEventColumn() * * NdbEventOperation * getValue() * getPreValue() * execute() * getEventType() * */ #include <NdbApi.hpp> // Used for cout #include <stdio.h> #include <iostream> #include <unistd.h> #ifdef VM_TRACE #include <my_global.h> #endif #ifndef assert #include <assert.h> #endif /** * Assume that there is a table which is being updated by * another process (e.g. flexBench -l 0 -stdtables). * We want to monitor what happens with column values. * * Or using the mysql client: * * shell> mysql -u root * mysql> create database TEST_DB; * mysql> use TEST_DB; * mysql> create table t0 * (c0 int, c1 int, c2 char(4), c3 char(4), c4 text, * primary key(c0, c2)) engine ndb charset latin1; * * In another window start ndbapi_event, wait until properly started insert into t0 values (1, 2, 'a', 'b', null); insert into t0 values (3, 4, 'c', 'd', null); update t0 set c3 = 'e' where c0 = 1 and c2 = 'a'; -- use pk update t0 set c3 = 'f'; -- use scan update t0 set c3 = 'F'; -- use scan update to 'same' update t0 set c2 = 'g' where c0 = 1; -- update pk part update t0 set c2 = 'G' where c0 = 1; -- update pk part to 'same' update t0 set c0 = 5, c2 = 'H' where c0 = 3; -- update full PK delete from t0; insert ...; update ...; -- see events w/ same pk merged (if -m option) delete ...; insert ...; -- there are 5 combinations ID IU DI UD UU update ...; update ...; -- text requires -m flag set @a = repeat('a',256); -- inline size set @b = repeat('b',2000); -- part size set @c = repeat('c',2000*30); -- 30 parts -- update the text field using combinations of @a, @b, @c ... * you should see the data popping up in the example window * */ #define APIERROR(error) \ { std::cout << "Error in " << __FILE__ << ", line:" << __LINE__ << ", code:" \ << error.code << ", msg: " << error.message << "." << std::endl; \ exit(-1); } int myCreateEvent(Ndb* myNdb, const char *eventName, const char *eventTableName, const char **eventColumnName, const int noEventColumnName, bool merge_events); int main(int argc, char** argv) { if (argc < 3) { std::cout << "Arguments are <connect_string cluster> <timeout> [m(merge events)|d(debug)].\n"; exit(-1); } const char *connectstring = argv[1]; int timeout = atoi(argv[2]); ndb_init(); bool merge_events = argc > 3 && strchr(argv[3], 'm') != 0; #ifdef VM_TRACE bool dbug = argc > 3 && strchr(argv[3], 'd') != 0; if (dbug) DBUG_PUSH("d:t:"); if (dbug) putenv("API_SIGNAL_LOG=-"); #endif Ndb_cluster_connection *cluster_connection= new Ndb_cluster_connection(connectstring); // Object representing the cluster int r= cluster_connection->connect(5 /* retries */, 3 /* delay between retries */, 1 /* verbose */); if (r > 0) { std::cout << "Cluster connect failed, possibly resolved with more retries.\n"; exit(-1); } else if (r < 0) { std::cout << "Cluster connect failed.\n"; exit(-1); } if (cluster_connection->wait_until_ready(30,30)) { std::cout << "Cluster was not ready within 30 secs." << std::endl; exit(-1); } Ndb* myNdb= new Ndb(cluster_connection, "TEST_DB"); // Object representing the database if (myNdb->init() == -1) APIERROR(myNdb->getNdbError()); const char *eventName= "CHNG_IN_t0"; const char *eventTableName= "t0"; const int noEventColumnName= 5; const char *eventColumnName[noEventColumnName]= {"c0", "c1", "c2", "c3", "c4" }; // Create events myCreateEvent(myNdb, eventName, eventTableName, eventColumnName, noEventColumnName, merge_events); // Normal values and blobs are unfortunately handled differently.. typedef union { NdbRecAttr* ra; NdbBlob* bh; } RA_BH; int i, j, k, l; j = 0; while (j < timeout) { // Start "transaction" for handling events NdbEventOperation* op; printf("create EventOperation\n"); if ((op = myNdb->createEventOperation(eventName)) == NULL) APIERROR(myNdb->getNdbError()); op->mergeEvents(merge_events); printf("get values\n"); RA_BH recAttr[noEventColumnName]; RA_BH recAttrPre[noEventColumnName]; // primary keys should always be a part of the result for (i = 0; i < noEventColumnName; i++) { if (i < 4) { recAttr[i].ra = op->getValue(eventColumnName[i]); recAttrPre[i].ra = op->getPreValue(eventColumnName[i]); } else if (merge_events) { recAttr[i].bh = op->getBlobHandle(eventColumnName[i]); recAttrPre[i].bh = op->getPreBlobHandle(eventColumnName[i]); } } // set up the callbacks printf("execute\n"); // This starts changes to "start flowing" if (op->execute()) APIERROR(op->getNdbError()); NdbEventOperation* the_op = op; i= 0; while (i < timeout) { // printf("now waiting for event...\n"); int r = myNdb->pollEvents(1000); // wait for event or 1000 ms if (r > 0) { // printf("got data! %d\n", r); while ((op= myNdb->nextEvent())) { assert(the_op == op); i++; switch (op->getEventType()) { case NdbDictionary::Event::TE_INSERT: printf("%u INSERT", i); break; case NdbDictionary::Event::TE_DELETE: printf("%u DELETE", i); break; case NdbDictionary::Event::TE_UPDATE: printf("%u UPDATE", i); break; default: abort(); // should not happen } printf(" gci=%d\n", (int)op->getGCI()); for (k = 0; k <= 1; k++) { printf(k == 0 ? "post: " : "pre : "); for (l = 0; l < noEventColumnName; l++) { if (l < 4) { NdbRecAttr* ra = k == 0 ? recAttr[l].ra : recAttrPre[l].ra; if (ra->isNULL() >= 0) { // we have a value if (ra->isNULL() == 0) { // we have a non-null value if (l < 2) printf("%-5u", ra->u_32_value()); else printf("%-5.4s", ra->aRef()); } else printf("%-5s", "NULL"); } else printf("%-5s", "-"); // no value } else if (merge_events) { int isNull; NdbBlob* bh = k == 0 ? recAttr[l].bh : recAttrPre[l].bh; bh->getDefined(isNull); if (isNull >= 0) { // we have a value if (! isNull) { // we have a non-null value Uint64 length = 0; bh->getLength(length); // read into buffer unsigned char* buf = new unsigned char [length]; memset(buf, 'X', length); Uint32 n = length; bh->readData(buf, n); // n is in/out assert(n == length); // pretty-print bool first = true; Uint32 i = 0; while (i < n) { unsigned char c = buf[i++]; Uint32 m = 1; while (i < n && buf[i] == c) i++, m++; if (! first) printf("+"); printf("%u%c", m, c); first = false; } printf("[%u]", n); delete [] buf; } else printf("%-5s", "NULL"); } else printf("%-5s", "-"); // no value } } printf("\n"); } } } else printf("timed out (%i)\n", timeout); } // don't want to listen to events anymore if (myNdb->dropEventOperation(the_op)) APIERROR(myNdb->getNdbError()); the_op = 0; j++; } { NdbDictionary::Dictionary *myDict = myNdb->getDictionary(); if (!myDict) APIERROR(myNdb->getNdbError()); // remove event from database if (myDict->dropEvent(eventName)) APIERROR(myDict->getNdbError()); } delete myNdb; delete cluster_connection; ndb_end(0); return 0; } int myCreateEvent(Ndb* myNdb, const char *eventName, const char *eventTableName, const char **eventColumnNames, const int noEventColumnNames, bool merge_events) { NdbDictionary::Dictionary *myDict= myNdb->getDictionary(); if (!myDict) APIERROR(myNdb->getNdbError()); const NdbDictionary::Table *table= myDict->getTable(eventTableName); if (!table) APIERROR(myDict->getNdbError()); NdbDictionary::Event myEvent(eventName, *table); myEvent.addTableEvent(NdbDictionary::Event::TE_ALL); // myEvent.addTableEvent(NdbDictionary::Event::TE_INSERT); // myEvent.addTableEvent(NdbDictionary::Event::TE_UPDATE); // myEvent.addTableEvent(NdbDictionary::Event::TE_DELETE); myEvent.addEventColumns(noEventColumnNames, eventColumnNames); myEvent.mergeEvents(merge_events); // Add event to database if (myDict->createEvent(myEvent) == 0) myEvent.print(); else if (myDict->getNdbError().classification == NdbError::SchemaObjectExists) { printf("Event creation failed, event exists\n"); printf("dropping Event...\n"); if (myDict->dropEvent(eventName)) APIERROR(myDict->getNdbError()); // try again // Add event to database if ( myDict->createEvent(myEvent)) APIERROR(myDict->getNdbError()); } else APIERROR(myDict->getNdbError()); return 0; }
gpl-2.0
LeChuck42/or1k-gcc
libstdc++-v3/testsuite/20_util/ratio/operations/53840.cc
1171
// { dg-options "-std=gnu++0x" } // { dg-require-cstdint "" } // { dg-do compile } // Copyright (C) 2012-2014 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <chrono> std::chrono::duration<long, std::ratio_divide<std::kilo, std::milli>> d1; std::chrono::duration<long, std::ratio_multiply<std::kilo, std::milli>> d2; std::chrono::duration<long, std::ratio_add<std::kilo, std::milli>> d3; std::chrono::duration<long, std::ratio_subtract<std::kilo, std::milli>> d4;
gpl-2.0
zuborawka/studing-eccube
data/module/Calendar/tests/all_tests.php
1046
<?php // $Id: all_tests.php,v 1.2 2004/08/16 08:55:24 hfuecks Exp $ require_once('simple_include.php'); require_once('calendar_include.php'); define("TEST_RUNNING", true); require_once('./calendar_tests.php'); require_once('./calendar_tabular_tests.php'); require_once('./validator_tests.php'); require_once('./calendar_engine_tests.php'); require_once('./calendar_engine_tests.php'); require_once('./table_helper_tests.php'); require_once('./decorator_tests.php'); require_once('./util_tests.php'); class AllTests extends GroupTest { function AllTests() { $this->GroupTest('All PEAR::Calendar Tests'); $this->AddTestCase(new CalendarTests()); $this->AddTestCase(new CalendarTabularTests()); $this->AddTestCase(new ValidatorTests()); $this->AddTestCase(new CalendarEngineTests()); $this->AddTestCase(new TableHelperTests()); $this->AddTestCase(new DecoratorTests()); $this->AddTestCase(new UtilTests()); } } $test = &new AllTests(); $test->run(new HtmlReporter()); ?>
gpl-2.0
ern/elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Log.java
1136
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; import org.elasticsearch.xpack.ql.expression.Expression; import org.elasticsearch.xpack.ql.tree.NodeInfo; import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; /** * <a href="https://en.wikipedia.org/wiki/Natural_logarithm">Natural logarithm</a> * function. */ public class Log extends MathFunction { public Log(Source source, Expression field) { super(source, field); } @Override protected NodeInfo<Log> info() { return NodeInfo.create(this, Log::new, field()); } @Override protected Log replaceChild(Expression newChild) { return new Log(source(), newChild); } @Override protected MathOperation operation() { return MathOperation.LOG; } }
apache-2.0
keedio/hue
desktop/core/ext-py/pysaml2-2.4.0/example/idp2_repoze/modules/login.mako.py
2690
# -*- encoding:utf-8 -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 6 _modified_time = 1367126126.936375 _template_filename='htdocs/login.mako' _template_uri='login.mako' _template_cache=cache.Cache(__name__, _modified_time) _source_encoding='utf-8' _exports = [] def _mako_get_namespace(context, name): try: return context.namespaces[(__name__, name)] except KeyError: _mako_generate_namespaces(context) return context.namespaces[(__name__, name)] def _mako_generate_namespaces(context): pass def _mako_inherit(template, context): _mako_generate_namespaces(context) return runtime._inherit_from(context, u'root.mako', _template_uri) def render_body(context,**pageargs): context.caller_stack._push_frame() try: __M_locals = __M_dict_builtin(pageargs=pageargs) redirect_uri = context.get('redirect_uri', UNDEFINED) key = context.get('key', UNDEFINED) action = context.get('action', UNDEFINED) authn_reference = context.get('authn_reference', UNDEFINED) login = context.get('login', UNDEFINED) password = context.get('password', UNDEFINED) __M_writer = context.writer() # SOURCE LINE 1 __M_writer(u'\n\n<h1>Please log in</h1>\n<p class="description">\n To register it\'s quite simple: enter a login and a password\n</p>\n\n<form action="') # SOURCE LINE 8 __M_writer(unicode(action)) __M_writer(u'" method="post">\n <input type="hidden" name="key" value="') # SOURCE LINE 9 __M_writer(unicode(key)) __M_writer(u'"/>\n <input type="hidden" name="authn_reference" value="') # SOURCE LINE 10 __M_writer(unicode(authn_reference)) __M_writer(u'"/>\n <input type="hidden" name="redirect_uri" value="') # SOURCE LINE 11 __M_writer(unicode(redirect_uri)) __M_writer(u'"/>\n\n <div class="label">\n <label for="login">Username</label>\n </div>\n <div>\n <input type="text" name="login" value="') # SOURCE LINE 17 __M_writer(unicode(login)) __M_writer(u'"/><br/>\n </div>\n\n <div class="label">\n <label for="password">Password</label>\n </div>\n <div>\n <input type="password" name="password"\n value="') # SOURCE LINE 25 __M_writer(unicode(password)) __M_writer(u'"/>\n </div>\n\n <input class="submit" type="submit" name="form.submitted" value="Log In"/>\n</form>\n') return '' finally: context.caller_stack._pop_frame()
apache-2.0
dinglixiang/spree_bootstrap_frontend
spec/spec_helper.rb
2655
# Run Coverage report require 'simplecov' SimpleCov.start do add_filter 'spec/dummy' add_group 'Controllers', 'app/controllers' add_group 'Helpers', 'app/helpers' add_group 'Mailers', 'app/mailers' add_group 'Models', 'app/models' add_group 'Views', 'app/views' add_group 'Libraries', 'lib' end # Configure Rails Environment ENV['RAILS_ENV'] = 'test' require File.expand_path('../dummy/config/environment.rb', __FILE__) require 'rspec/rails' require 'database_cleaner' require 'ffaker' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each { |f| require f } # Requires factories defined in spree_core require 'spree/testing_support/factories' require 'spree/testing_support/controller_requests' require 'spree/testing_support/authorization_helpers' require 'spree/testing_support/url_helpers' # Requires factories defined in lib/spree_bootstrap_frontend/factories.rb require 'spree_bootstrap_frontend/factories' RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods # == URL Helpers # # Allows access to Spree's routes in specs: # # visit spree.admin_path # current_path.should eql(spree.products_path) config.include Spree::TestingSupport::UrlHelpers # == Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr config.mock_with :rspec config.color = true # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # Capybara javascript drivers require transactional fixtures set to false, and we use DatabaseCleaner # to cleanup after each test instead. Without transactional fixtures set to false the records created # to setup a test will be unavailable to the browser, which runs under a seperate server instance. config.use_transactional_fixtures = false # Ensure Suite is set to use transactions for speed. config.before :suite do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with :truncation end # Before each spec check if it is a Javascript test and switch between using database transactions or not where necessary. config.before :each do DatabaseCleaner.strategy = example.metadata[:js] ? :truncation : :transaction DatabaseCleaner.start end # After each spec clean the database. config.after :each do DatabaseCleaner.clean end config.fail_fast = ENV['FAIL_FAST'] || false end
bsd-2-clause
jucapj/psutil
psutil/_psosx.py
9795
#!/usr/bin/env python # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """OSX platform implementation.""" import errno import os import sys from psutil import _common from psutil import _psposix from psutil._common import conn_tmap, usage_percent, isfile_strict from psutil._compat import namedtuple, wraps import _psutil_osx as cext import _psutil_posix __extra__all__ = [] # --- constants PAGESIZE = os.sysconf("SC_PAGE_SIZE") # http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h TCP_STATUSES = { cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED, cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT, cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV, cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1, cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2, cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT, cext.TCPS_CLOSED: _common.CONN_CLOSE, cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK, cext.TCPS_LISTEN: _common.CONN_LISTEN, cext.TCPS_CLOSING: _common.CONN_CLOSING, cext.PSUTIL_CONN_NONE: _common.CONN_NONE, } PROC_STATUSES = { cext.SIDL: _common.STATUS_IDLE, cext.SRUN: _common.STATUS_RUNNING, cext.SSLEEP: _common.STATUS_SLEEPING, cext.SSTOP: _common.STATUS_STOPPED, cext.SZOMB: _common.STATUS_ZOMBIE, } scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle']) svmem = namedtuple( 'svmem', ['total', 'available', 'percent', 'used', 'free', 'active', 'inactive', 'wired']) pextmem = namedtuple('pextmem', ['rss', 'vms', 'pfaults', 'pageins']) pmmap_grouped = namedtuple( 'pmmap_grouped', 'path rss private swapped dirtied ref_count shadow_depth') pmmap_ext = namedtuple( 'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields)) # set later from __init__.py NoSuchProcess = None AccessDenied = None TimeoutExpired = None # --- functions def virtual_memory(): """System virtual memory as a namedtuple.""" total, active, inactive, wired, free = cext.virtual_mem() avail = inactive + free used = active + inactive + wired percent = usage_percent((total - avail), total, _round=1) return svmem(total, avail, percent, used, free, active, inactive, wired) def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" total, used, free, sin, sout = cext.swap_mem() percent = usage_percent(used, total, _round=1) return _common.sswap(total, used, free, percent, sin, sout) def cpu_times(): """Return system CPU times as a namedtuple.""" user, nice, system, idle = cext.cpu_times() return scputimes(user, nice, system, idle) def per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in cext.per_cpu_times(): user, nice, system, idle = cpu_t item = scputimes(user, nice, system, idle) ret.append(item) return ret def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical() def cpu_count_physical(): """Return the number of physical CPUs in the system.""" return cext.cpu_count_phys() def boot_time(): """The system boot time expressed in seconds since the epoch.""" return cext.boot_time() def disk_partitions(all=False): retlist = [] partitions = cext.disk_partitions() for partition in partitions: device, mountpoint, fstype, opts = partition if device == 'none': device = '' if not all: if not os.path.isabs(device) or not os.path.exists(device): continue ntuple = _common.sdiskpart(device, mountpoint, fstype, opts) retlist.append(ntuple) return retlist def users(): retlist = [] rawlist = cext.users() for item in rawlist: user, tty, hostname, tstamp = item if tty == '~': continue # reboot or shutdown if not tstamp: continue nt = _common.suser(user, tty or None, hostname or None, tstamp) retlist.append(nt) return retlist def net_connections(kind='inet'): # Note: on OSX this will fail with AccessDenied unless # the process is owned by root. ret = [] for pid in pids(): try: cons = Process(pid).connections(kind) except NoSuchProcess: continue else: if cons: for c in cons: c = list(c) + [pid] ret.append(_common.sconn(*c)) return ret pids = cext.pids pid_exists = _psposix.pid_exists disk_usage = _psposix.disk_usage net_io_counters = cext.net_io_counters disk_io_counters = cext.disk_io_counters def wrap_exceptions(fun): """Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied. """ @wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except OSError: # support for private module import if NoSuchProcess is None or AccessDenied is None: raise err = sys.exc_info()[1] if err.errno == errno.ESRCH: raise NoSuchProcess(self.pid, self._name) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._name) raise return wrapper class Process(object): """Wrapper class around underlying C implementation.""" __slots__ = ["pid", "_name"] def __init__(self, pid): self.pid = pid self._name = None @wrap_exceptions def name(self): return cext.proc_name(self.pid) @wrap_exceptions def exe(self): return cext.proc_exe(self.pid) @wrap_exceptions def cmdline(self): if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._name) return cext.proc_cmdline(self.pid) @wrap_exceptions def ppid(self): return cext.proc_ppid(self.pid) @wrap_exceptions def cwd(self): return cext.proc_cwd(self.pid) @wrap_exceptions def uids(self): real, effective, saved = cext.proc_uids(self.pid) return _common.puids(real, effective, saved) @wrap_exceptions def gids(self): real, effective, saved = cext.proc_gids(self.pid) return _common.pgids(real, effective, saved) @wrap_exceptions def terminal(self): tty_nr = cext.proc_tty_nr(self.pid) tmap = _psposix._get_terminal_map() try: return tmap[tty_nr] except KeyError: return None @wrap_exceptions def memory_info(self): rss, vms = cext.proc_memory_info(self.pid)[:2] return _common.pmem(rss, vms) @wrap_exceptions def memory_info_ex(self): rss, vms, pfaults, pageins = cext.proc_memory_info(self.pid) return pextmem(rss, vms, pfaults * PAGESIZE, pageins * PAGESIZE) @wrap_exceptions def cpu_times(self): user, system = cext.proc_cpu_times(self.pid) return _common.pcputimes(user, system) @wrap_exceptions def create_time(self): return cext.proc_create_time(self.pid) @wrap_exceptions def num_ctx_switches(self): return _common.pctxsw(*cext.proc_num_ctx_switches(self.pid)) @wrap_exceptions def num_threads(self): return cext.proc_num_threads(self.pid) @wrap_exceptions def open_files(self): if self.pid == 0: return [] files = [] rawlist = cext.proc_open_files(self.pid) for path, fd in rawlist: if isfile_strict(path): ntuple = _common.popenfile(path, fd) files.append(ntuple) return files @wrap_exceptions def connections(self, kind='inet'): if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] rawlist = cext.proc_connections(self.pid, families, types) ret = [] for item in rawlist: fd, fam, type, laddr, raddr, status = item status = TCP_STATUSES[status] nt = _common.pconn(fd, fam, type, laddr, raddr, status) ret.append(nt) return ret @wrap_exceptions def num_fds(self): if self.pid == 0: return 0 return cext.proc_num_fds(self.pid) @wrap_exceptions def wait(self, timeout=None): try: return _psposix.wait_pid(self.pid, timeout) except _psposix.TimeoutExpired: # support for private module import if TimeoutExpired is None: raise raise TimeoutExpired(timeout, self.pid, self._name) @wrap_exceptions def nice_get(self): return _psutil_posix.getpriority(self.pid) @wrap_exceptions def nice_set(self, value): return _psutil_posix.setpriority(self.pid, value) @wrap_exceptions def status(self): code = cext.proc_status(self.pid) # XXX is '?' legit? (we're not supposed to return it anyway) return PROC_STATUSES.get(code, '?') @wrap_exceptions def threads(self): rawlist = cext.proc_threads(self.pid) retlist = [] for thread_id, utime, stime in rawlist: ntuple = _common.pthread(thread_id, utime, stime) retlist.append(ntuple) return retlist @wrap_exceptions def memory_maps(self): return cext.proc_memory_maps(self.pid)
bsd-3-clause
CaeruleusAqua/gitea
modules/log/smtp.go
2242
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package log import ( "encoding/json" "fmt" "net/smtp" "strings" "time" ) const ( subjectPhrase = "Diagnostic message from server" ) // SMTPWriter implements LoggerInterface and is used to send emails via given SMTP-server. type SMTPWriter struct { Username string `json:"Username"` Password string `json:"password"` Host string `json:"Host"` Subject string `json:"subject"` RecipientAddresses []string `json:"sendTos"` Level int `json:"level"` } // NewSMTPWriter creates smtp writer. func NewSMTPWriter() LoggerInterface { return &SMTPWriter{Level: TRACE} } // Init smtp writer with json config. // config like: // { // "Username":"example@gmail.com", // "password:"password", // "host":"smtp.gmail.com:465", // "subject":"email title", // "sendTos":["email1","email2"], // "level":LevelError // } func (sw *SMTPWriter) Init(jsonconfig string) error { return json.Unmarshal([]byte(jsonconfig), sw) } // WriteMsg writes message in smtp writer. // it will send an email with subject and only this message. func (sw *SMTPWriter) WriteMsg(msg string, skip, level int) error { if level < sw.Level { return nil } hp := strings.Split(sw.Host, ":") // Set up authentication information. auth := smtp.PlainAuth( "", sw.Username, sw.Password, hp[0], ) // Connect to the server, authenticate, set the sender and recipient, // and send the email all in one step. contentType := "Content-Type: text/plain" + "; charset=UTF-8" mailmsg := []byte("To: " + strings.Join(sw.RecipientAddresses, ";") + "\r\nFrom: " + sw.Username + "<" + sw.Username + ">\r\nSubject: " + sw.Subject + "\r\n" + contentType + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg) return smtp.SendMail( sw.Host, auth, sw.Username, sw.RecipientAddresses, mailmsg, ) } // Flush when log should be flushed func (sw *SMTPWriter) Flush() { } // Destroy when writer is destroy func (sw *SMTPWriter) Destroy() { } func init() { Register("smtp", NewSMTPWriter) }
mit
pminutillo/pentaho-kettle
ui/src/main/java/org/pentaho/di/ui/trans/steps/mergejoin/MergeJoinDialog.java
17164
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.trans.steps.mergejoin; import java.util.List; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.errorhandling.StreamInterface; import org.pentaho.di.trans.steps.mergejoin.MergeJoinMeta; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.trans.step.BaseStepDialog; public class MergeJoinDialog extends BaseStepDialog implements StepDialogInterface { private static Class<?> PKG = MergeJoinMeta.class; // for i18n purposes, needed by Translator2!! public static final String STRING_SORT_WARNING_PARAMETER = "MergeJoinSortWarning"; private Label wlStep1; private CCombo wStep1; private FormData fdlStep1, fdStep1; private Label wlStep2; private CCombo wStep2; private FormData fdlStep2, fdStep2; private Label wlType; private CCombo wType; private FormData fdlType, fdType; private Label wlKeys1; private TableView wKeys1; private Button wbKeys1; private FormData fdlKeys1, fdKeys1, fdbKeys1; private Label wlKeys2; private TableView wKeys2; private Button wbKeys2; private FormData fdlKeys2, fdKeys2, fdbKeys2; private MergeJoinMeta input; public MergeJoinDialog( Shell parent, Object in, TransMeta tr, String sname ) { super( parent, (BaseStepMeta) in, tr, sname ); input = (MergeJoinMeta) in; } public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX ); props.setLook( shell ); setShellImage( shell, input ); ModifyListener lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { input.setChanged(); } }; backupChanged = input.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "MergeJoinDialog.Shell.Label" ) ); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Stepname line wlStepname = new Label( shell, SWT.RIGHT ); wlStepname.setText( BaseMessages.getString( PKG, "MergeJoinDialog.Stepname.Label" ) ); props.setLook( wlStepname ); fdlStepname = new FormData(); fdlStepname.left = new FormAttachment( 0, 0 ); fdlStepname.right = new FormAttachment( middle, -margin ); fdlStepname.top = new FormAttachment( 0, margin ); wlStepname.setLayoutData( fdlStepname ); wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wStepname.setText( stepname ); props.setLook( wStepname ); wStepname.addModifyListener( lsMod ); fdStepname = new FormData(); fdStepname.left = new FormAttachment( middle, 0 ); fdStepname.top = new FormAttachment( 0, margin ); fdStepname.right = new FormAttachment( 100, 0 ); wStepname.setLayoutData( fdStepname ); // Get the previous steps... String[] previousSteps = transMeta.getPrevStepNames( stepname ); // First step wlStep1 = new Label( shell, SWT.RIGHT ); wlStep1.setText( BaseMessages.getString( PKG, "MergeJoinDialog.Step1.Label" ) ); props.setLook( wlStep1 ); fdlStep1 = new FormData(); fdlStep1.left = new FormAttachment( 0, 0 ); fdlStep1.right = new FormAttachment( middle, -margin ); fdlStep1.top = new FormAttachment( wStepname, margin ); wlStep1.setLayoutData( fdlStep1 ); wStep1 = new CCombo( shell, SWT.BORDER ); props.setLook( wStep1 ); if ( previousSteps != null ) { wStep1.setItems( previousSteps ); } wStep1.addModifyListener( lsMod ); fdStep1 = new FormData(); fdStep1.left = new FormAttachment( middle, 0 ); fdStep1.top = new FormAttachment( wStepname, margin ); fdStep1.right = new FormAttachment( 100, 0 ); wStep1.setLayoutData( fdStep1 ); // Second step wlStep2 = new Label( shell, SWT.RIGHT ); wlStep2.setText( BaseMessages.getString( PKG, "MergeJoinDialog.Step2.Label" ) ); props.setLook( wlStep2 ); fdlStep2 = new FormData(); fdlStep2.left = new FormAttachment( 0, 0 ); fdlStep2.right = new FormAttachment( middle, -margin ); fdlStep2.top = new FormAttachment( wStep1, margin ); wlStep2.setLayoutData( fdlStep2 ); wStep2 = new CCombo( shell, SWT.BORDER ); props.setLook( wStep2 ); if ( previousSteps != null ) { wStep2.setItems( previousSteps ); } wStep2.addModifyListener( lsMod ); fdStep2 = new FormData(); fdStep2.top = new FormAttachment( wStep1, margin ); fdStep2.left = new FormAttachment( middle, 0 ); fdStep2.right = new FormAttachment( 100, 0 ); wStep2.setLayoutData( fdStep2 ); // Join type wlType = new Label( shell, SWT.RIGHT ); wlType.setText( BaseMessages.getString( PKG, "MergeJoinDialog.Type.Label" ) ); props.setLook( wlType ); fdlType = new FormData(); fdlType.left = new FormAttachment( 0, 0 ); fdlType.right = new FormAttachment( middle, -margin ); fdlType.top = new FormAttachment( wStep2, margin ); wlType.setLayoutData( fdlType ); wType = new CCombo( shell, SWT.BORDER ); props.setLook( wType ); wType.setItems( MergeJoinMeta.join_types ); wType.addModifyListener( lsMod ); fdType = new FormData(); fdType.top = new FormAttachment( wStep2, margin ); fdType.left = new FormAttachment( middle, 0 ); fdType.right = new FormAttachment( 100, 0 ); wType.setLayoutData( fdType ); // THE KEYS TO MATCH for first step... wlKeys1 = new Label( shell, SWT.NONE ); wlKeys1.setText( BaseMessages.getString( PKG, "MergeJoinDialog.Keys1.Label" ) ); props.setLook( wlKeys1 ); fdlKeys1 = new FormData(); fdlKeys1.left = new FormAttachment( 0, 0 ); fdlKeys1.top = new FormAttachment( wType, margin ); wlKeys1.setLayoutData( fdlKeys1 ); int nrKeyRows1 = ( input.getKeyFields1() != null ? input.getKeyFields1().length : 1 ); ColumnInfo[] ciKeys1 = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString( PKG, "MergeJoinDialog.ColumnInfo.KeyField1" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), }; wKeys1 = new TableView( transMeta, shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL, ciKeys1, nrKeyRows1, lsMod, props ); fdKeys1 = new FormData(); fdKeys1.top = new FormAttachment( wlKeys1, margin ); fdKeys1.left = new FormAttachment( 0, 0 ); fdKeys1.bottom = new FormAttachment( 100, -70 ); fdKeys1.right = new FormAttachment( 50, -margin ); wKeys1.setLayoutData( fdKeys1 ); wbKeys1 = new Button( shell, SWT.PUSH ); wbKeys1.setText( BaseMessages.getString( PKG, "MergeJoinDialog.KeyFields1.Button" ) ); fdbKeys1 = new FormData(); fdbKeys1.top = new FormAttachment( wKeys1, margin ); fdbKeys1.left = new FormAttachment( 0, 0 ); fdbKeys1.right = new FormAttachment( 50, -margin ); wbKeys1.setLayoutData( fdbKeys1 ); wbKeys1.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { getKeys1(); } } ); // THE KEYS TO MATCH for second step wlKeys2 = new Label( shell, SWT.NONE ); wlKeys2.setText( BaseMessages.getString( PKG, "MergeJoinDialog.Keys2.Label" ) ); props.setLook( wlKeys2 ); fdlKeys2 = new FormData(); fdlKeys2.left = new FormAttachment( 50, 0 ); fdlKeys2.top = new FormAttachment( wType, margin ); wlKeys2.setLayoutData( fdlKeys2 ); int nrKeyRows2 = ( input.getKeyFields2() != null ? input.getKeyFields2().length : 1 ); ColumnInfo[] ciKeys2 = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString( PKG, "MergeJoinDialog.ColumnInfo.KeyField2" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), }; wKeys2 = new TableView( transMeta, shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL, ciKeys2, nrKeyRows2, lsMod, props ); fdKeys2 = new FormData(); fdKeys2.top = new FormAttachment( wlKeys2, margin ); fdKeys2.left = new FormAttachment( 50, 0 ); fdKeys2.bottom = new FormAttachment( 100, -70 ); fdKeys2.right = new FormAttachment( 100, 0 ); wKeys2.setLayoutData( fdKeys2 ); wbKeys2 = new Button( shell, SWT.PUSH ); wbKeys2.setText( BaseMessages.getString( PKG, "MergeJoinDialog.KeyFields2.Button" ) ); fdbKeys2 = new FormData(); fdbKeys2.top = new FormAttachment( wKeys2, margin ); fdbKeys2.left = new FormAttachment( 50, 0 ); fdbKeys2.right = new FormAttachment( 100, 0 ); wbKeys2.setLayoutData( fdbKeys2 ); wbKeys2.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { getKeys2(); } } ); // Some buttons wOK = new Button( shell, SWT.PUSH ); wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) ); wCancel = new Button( shell, SWT.PUSH ); wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) ); setButtonPositions( new Button[] { wOK, wCancel }, margin, wbKeys1 ); // Add listeners lsCancel = new Listener() { public void handleEvent( Event e ) { cancel(); } }; lsOK = new Listener() { public void handleEvent( Event e ) { ok(); } }; wCancel.addListener( SWT.Selection, lsCancel ); wOK.addListener( SWT.Selection, lsOK ); lsDef = new SelectionAdapter() { public void widgetDefaultSelected( SelectionEvent e ) { ok(); } }; wStepname.addSelectionListener( lsDef ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); // Set the shell size, based upon previous time... setSize(); getData(); input.setChanged( backupChanged ); shell.open(); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return stepname; } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { List<StreamInterface> infoStreams = input.getStepIOMeta().getInfoStreams(); wStep1.setText( Const.NVL( infoStreams.get( 0 ).getStepname(), "" ) ); wStep2.setText( Const.NVL( infoStreams.get( 1 ).getStepname(), "" ) ); String joinType = input.getJoinType(); if ( joinType != null && joinType.length() > 0 ) { wType.setText( joinType ); } else { wType.setText( MergeJoinMeta.join_types[0] ); } for ( int i = 0; i < input.getKeyFields1().length; i++ ) { TableItem item = wKeys1.table.getItem( i ); if ( input.getKeyFields1()[i] != null ) { item.setText( 1, input.getKeyFields1()[i] ); } } for ( int i = 0; i < input.getKeyFields2().length; i++ ) { TableItem item = wKeys2.table.getItem( i ); if ( input.getKeyFields2()[i] != null ) { item.setText( 1, input.getKeyFields2()[i] ); } } wStepname.selectAll(); wStepname.setFocus(); } private void cancel() { stepname = null; input.setChanged( backupChanged ); dispose(); } private void getMeta( MergeJoinMeta meta ) { List<StreamInterface> infoStreams = meta.getStepIOMeta().getInfoStreams(); infoStreams.get( 0 ).setStepMeta( transMeta.findStep( wStep1.getText() ) ); infoStreams.get( 1 ).setStepMeta( transMeta.findStep( wStep2.getText() ) ); meta.setJoinType( wType.getText() ); int nrKeys1 = wKeys1.nrNonEmpty(); int nrKeys2 = wKeys2.nrNonEmpty(); meta.allocate( nrKeys1, nrKeys2 ); //CHECKSTYLE:Indentation:OFF for ( int i = 0; i < nrKeys1; i++ ) { TableItem item = wKeys1.getNonEmpty( i ); meta.getKeyFields1()[i] = item.getText( 1 ); } //CHECKSTYLE:Indentation:OFF for ( int i = 0; i < nrKeys2; i++ ) { TableItem item = wKeys2.getNonEmpty( i ); meta.getKeyFields2()[i] = item.getText( 1 ); } } private void ok() { if ( Utils.isEmpty( wStepname.getText() ) ) { return; } getMeta( input ); // Show a warning (optional) // if ( "Y".equalsIgnoreCase( props.getCustomParameter( STRING_SORT_WARNING_PARAMETER, "Y" ) ) ) { MessageDialogWithToggle md = new MessageDialogWithToggle( shell, BaseMessages.getString( PKG, "MergeJoinDialog.InputNeedSort.DialogTitle" ), null, BaseMessages.getString( PKG, "MergeJoinDialog.InputNeedSort.DialogMessage", Const.CR ) + Const.CR, MessageDialog.WARNING, new String[] { BaseMessages.getString( PKG, "MergeJoinDialog.InputNeedSort.Option1" ) }, 0, BaseMessages.getString( PKG, "MergeJoinDialog.InputNeedSort.Option2" ), "N".equalsIgnoreCase( props.getCustomParameter( STRING_SORT_WARNING_PARAMETER, "Y" ) ) ); MessageDialogWithToggle.setDefaultImage( GUIResource.getInstance().getImageSpoon() ); md.open(); props.setCustomParameter( STRING_SORT_WARNING_PARAMETER, md.getToggleState() ? "N" : "Y" ); props.saveProps(); } stepname = wStepname.getText(); // return value dispose(); } private void getKeys1() { MergeJoinMeta joinMeta = new MergeJoinMeta(); getMeta( joinMeta ); try { List<StreamInterface> infoStreams = joinMeta.getStepIOMeta().getInfoStreams(); StepMeta stepMeta = infoStreams.get( 0 ).getStepMeta(); if ( stepMeta != null ) { RowMetaInterface prev = transMeta.getStepFields( stepMeta ); if ( prev != null ) { BaseStepDialog.getFieldsFromPrevious( prev, wKeys1, 1, new int[] { 1 }, new int[] {}, -1, -1, null ); } } } catch ( KettleException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "MergeJoinDialog.ErrorGettingFields.DialogTitle" ), BaseMessages .getString( PKG, "MergeJoinDialog.ErrorGettingFields.DialogMessage" ), e ); } } private void getKeys2() { MergeJoinMeta joinMeta = new MergeJoinMeta(); getMeta( joinMeta ); try { List<StreamInterface> infoStreams = joinMeta.getStepIOMeta().getInfoStreams(); StepMeta stepMeta = infoStreams.get( 1 ).getStepMeta(); if ( stepMeta != null ) { RowMetaInterface prev = transMeta.getStepFields( stepMeta ); if ( prev != null ) { BaseStepDialog.getFieldsFromPrevious( prev, wKeys2, 1, new int[] { 1 }, new int[] {}, -1, -1, null ); } } } catch ( KettleException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "MergeJoinDialog.ErrorGettingFields.DialogTitle" ), BaseMessages .getString( PKG, "MergeJoinDialog.ErrorGettingFields.DialogMessage" ), e ); } } }
apache-2.0
mglukhikh/intellij-community
plugins/InspectionGadgets/test/com/siyeh/igfixes/migration/convert_to_varargs_method/CStyle.after.java
86
class CStyle { public void foo(final String... arg) { } { foo("one"); } }
apache-2.0
cdjackson/dBlockly
dojo/tests/_base/loader/requirejs/uno.js
228
define("uno", ["dos", "tres"], function(dos, tres){ return { name: "uno", doSomething: function(){ return { dosName: dos.name, tresName: tres.name }; } }; } );
apache-2.0
abarisain/circ
package/bin/third_party/forge/form.js
3949
/** * Functions for manipulating web forms. * * @author David I. Lehn <dlehn@digitalbazaar.com> * @author Dave Longley * @author Mike Johnson * * Copyright (c) 2011-2012 Digital Bazaar, Inc. All rights reserved. */ (function($) { /** * The form namespace. */ var form = {}; /** * Regex for parsing a single name property (handles array brackets). */ var _regex = /(.*?)\[(.*?)\]/g; /** * Parses a single name property into an array with the name and any * array indices. * * @param name the name to parse. * * @return the array of the name and its array indices in order. */ var _parseName = function(name) { var rval = []; var matches; while(!!(matches = _regex.exec(name))) { if(matches[1].length > 0) { rval.push(matches[1]); } if(matches.length >= 2) { rval.push(matches[2]); } } if(rval.length === 0) { rval.push(name); } return rval; }; /** * Adds a field from the given form to the given object. * * @param obj the object. * @param names the field as an array of object property names. * @param value the value of the field. * @param dict a dictionary of names to replace. */ var _addField = function(obj, names, value, dict) { // combine array names that fall within square brackets var tmp = []; for(var i = 0; i < names.length; ++i) { // check name for starting square bracket but no ending one var name = names[i]; if(name.indexOf('[') !== -1 && name.indexOf(']') === -1 && i < names.length - 1) { do { name += '.' + names[++i]; } while(i < names.length - 1 && names[i].indexOf(']') === -1); } tmp.push(name); } names = tmp; // split out array indexes var tmp = []; $.each(names, function(n, name) { tmp = tmp.concat(_parseName(name)); }); names = tmp; // iterate over object property names until value is set $.each(names, function(n, name) { // do dictionary name replacement if(dict && name.length !== 0 && name in dict) { name = dict[name]; } // blank name indicates appending to an array, set name to // new last index of array if(name.length === 0) { name = obj.length; } // value already exists, append value if(obj[name]) { // last name in the field if(n == names.length - 1) { // more than one value, so convert into an array if(!$.isArray(obj[name])) { obj[name] = [obj[name]]; } obj[name].push(value); } // not last name, go deeper into object else { obj = obj[name]; } } // new value, last name in the field, set value else if(n == names.length - 1) { obj[name] = value; } // new value, not last name, go deeper else { // get next name var next = names[n + 1]; // blank next value indicates array-appending, so create array if(next.length === 0) { obj[name] = []; } // if next name is a number create an array, otherwise a map else { var isNum = ((next - 0) == next && next.length > 0); obj[name] = isNum ? [] : {}; } obj = obj[name]; } }); }; /** * Serializes a form to a JSON object. Object properties will be separated * using the given separator (defaults to '.') and by square brackets. * * @param input the jquery form to serialize. * @param sep the object-property separator (defaults to '.'). * @param dict a dictionary of names to replace (name=replace). * * @return the JSON-serialized form. */ form.serialize = function(input, sep, dict) { var rval = {}; // add all fields in the form to the object sep = sep || '.'; $.each(input.serializeArray(), function() { _addField(rval, this.name.split(sep), this.value || '', dict); }); return rval; }; /** * The forge namespace and form API. */ if(typeof forge === 'undefined') { forge = {}; } forge.form = form; })(jQuery);
bsd-3-clause
shafiqissani/EmarketingMena
components/com_user/views/reset/view.html.php
2221
<?php /** * @version $Id: view.html.php 10752 2008-08-23 01:53:31Z eddieajau $ * @package Joomla * @subpackage User * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant to the * GNU General Public License, and as distributed it includes or is derivative * of works licensed under the GNU General Public License or other free or open * source software licenses. See COPYRIGHT.php for copyright notices and * details. */ // No direct access defined('_JEXEC') or die; jimport('joomla.application.component.view'); /** * HTML View class for the Users component * * @package Joomla * @subpackage User * @since 1.5 */ class UserViewReset extends JView { /** * Registry namespace prefix * * @var string */ var $_namespace = 'com_user.reset.'; /** * Display function * * @since 1.5 */ function display($tpl = null) { jimport('joomla.html.html'); global $mainframe; // Load the form validation behavior JHTML::_('behavior.formvalidation'); // Add the tooltip behavior JHTML::_('behavior.tooltip'); // Get the layout $layout = $this->getLayout(); if ($layout == 'complete') { $id = $mainframe->getUserState($this->_namespace.'id'); $token = $mainframe->getUserState($this->_namespace.'token'); if (is_null($id) || is_null($token)) { $mainframe->redirect('index.php?option=com_user&view=reset'); } } // Get the page/component configuration $params = &$mainframe->getParams(); $menus = &JSite::getMenu(); $menu = $menus->getActive(); // because the application sets a default page title, we need to get it // right from the menu item itself if (is_object( $menu )) { $menu_params = new JParameter( $menu->params ); if (!$menu_params->get( 'page_title')) { $params->set('page_title', JText::_( 'FORGOT_YOUR_PASSWORD' )); } } else { $params->set('page_title', JText::_( 'FORGOT_YOUR_PASSWORD' )); } $document = &JFactory::getDocument(); $document->setTitle( $params->get( 'page_title' ) ); $this->assignRef('params', $params); parent::display($tpl); } }
gpl-2.0
anhyeuviolet/module-videos
vendor/google/apiclient-services/src/Google/Service/Dfareporting/Placement.php
10839
<?php /* * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_Dfareporting_Placement extends Google_Collection { protected $collection_key = 'tagFormats'; public $accountId; public $advertiserId; protected $advertiserIdDimensionValueType = 'Google_Service_Dfareporting_DimensionValue'; protected $advertiserIdDimensionValueDataType = ''; public $archived; public $campaignId; protected $campaignIdDimensionValueType = 'Google_Service_Dfareporting_DimensionValue'; protected $campaignIdDimensionValueDataType = ''; public $comment; public $compatibility; public $contentCategoryId; protected $createInfoType = 'Google_Service_Dfareporting_LastModifiedInfo'; protected $createInfoDataType = ''; public $directorySiteId; protected $directorySiteIdDimensionValueType = 'Google_Service_Dfareporting_DimensionValue'; protected $directorySiteIdDimensionValueDataType = ''; public $externalId; public $id; protected $idDimensionValueType = 'Google_Service_Dfareporting_DimensionValue'; protected $idDimensionValueDataType = ''; public $keyName; public $kind; protected $lastModifiedInfoType = 'Google_Service_Dfareporting_LastModifiedInfo'; protected $lastModifiedInfoDataType = ''; protected $lookbackConfigurationType = 'Google_Service_Dfareporting_LookbackConfiguration'; protected $lookbackConfigurationDataType = ''; public $name; public $paymentApproved; public $paymentSource; public $placementGroupId; protected $placementGroupIdDimensionValueType = 'Google_Service_Dfareporting_DimensionValue'; protected $placementGroupIdDimensionValueDataType = ''; public $placementStrategyId; protected $pricingScheduleType = 'Google_Service_Dfareporting_PricingSchedule'; protected $pricingScheduleDataType = ''; public $primary; protected $publisherUpdateInfoType = 'Google_Service_Dfareporting_LastModifiedInfo'; protected $publisherUpdateInfoDataType = ''; public $siteId; protected $siteIdDimensionValueType = 'Google_Service_Dfareporting_DimensionValue'; protected $siteIdDimensionValueDataType = ''; protected $sizeType = 'Google_Service_Dfareporting_Size'; protected $sizeDataType = ''; public $sslRequired; public $status; public $subaccountId; public $tagFormats; protected $tagSettingType = 'Google_Service_Dfareporting_TagSetting'; protected $tagSettingDataType = ''; public $videoActiveViewOptOut; protected $videoSettingsType = 'Google_Service_Dfareporting_VideoSettings'; protected $videoSettingsDataType = ''; public $vpaidAdapterChoice; public function setAccountId($accountId) { $this->accountId = $accountId; } public function getAccountId() { return $this->accountId; } public function setAdvertiserId($advertiserId) { $this->advertiserId = $advertiserId; } public function getAdvertiserId() { return $this->advertiserId; } public function setAdvertiserIdDimensionValue(Google_Service_Dfareporting_DimensionValue $advertiserIdDimensionValue) { $this->advertiserIdDimensionValue = $advertiserIdDimensionValue; } public function getAdvertiserIdDimensionValue() { return $this->advertiserIdDimensionValue; } public function setArchived($archived) { $this->archived = $archived; } public function getArchived() { return $this->archived; } public function setCampaignId($campaignId) { $this->campaignId = $campaignId; } public function getCampaignId() { return $this->campaignId; } public function setCampaignIdDimensionValue(Google_Service_Dfareporting_DimensionValue $campaignIdDimensionValue) { $this->campaignIdDimensionValue = $campaignIdDimensionValue; } public function getCampaignIdDimensionValue() { return $this->campaignIdDimensionValue; } public function setComment($comment) { $this->comment = $comment; } public function getComment() { return $this->comment; } public function setCompatibility($compatibility) { $this->compatibility = $compatibility; } public function getCompatibility() { return $this->compatibility; } public function setContentCategoryId($contentCategoryId) { $this->contentCategoryId = $contentCategoryId; } public function getContentCategoryId() { return $this->contentCategoryId; } public function setCreateInfo(Google_Service_Dfareporting_LastModifiedInfo $createInfo) { $this->createInfo = $createInfo; } public function getCreateInfo() { return $this->createInfo; } public function setDirectorySiteId($directorySiteId) { $this->directorySiteId = $directorySiteId; } public function getDirectorySiteId() { return $this->directorySiteId; } public function setDirectorySiteIdDimensionValue(Google_Service_Dfareporting_DimensionValue $directorySiteIdDimensionValue) { $this->directorySiteIdDimensionValue = $directorySiteIdDimensionValue; } public function getDirectorySiteIdDimensionValue() { return $this->directorySiteIdDimensionValue; } public function setExternalId($externalId) { $this->externalId = $externalId; } public function getExternalId() { return $this->externalId; } public function setId($id) { $this->id = $id; } public function getId() { return $this->id; } public function setIdDimensionValue(Google_Service_Dfareporting_DimensionValue $idDimensionValue) { $this->idDimensionValue = $idDimensionValue; } public function getIdDimensionValue() { return $this->idDimensionValue; } public function setKeyName($keyName) { $this->keyName = $keyName; } public function getKeyName() { return $this->keyName; } public function setKind($kind) { $this->kind = $kind; } public function getKind() { return $this->kind; } public function setLastModifiedInfo(Google_Service_Dfareporting_LastModifiedInfo $lastModifiedInfo) { $this->lastModifiedInfo = $lastModifiedInfo; } public function getLastModifiedInfo() { return $this->lastModifiedInfo; } public function setLookbackConfiguration(Google_Service_Dfareporting_LookbackConfiguration $lookbackConfiguration) { $this->lookbackConfiguration = $lookbackConfiguration; } public function getLookbackConfiguration() { return $this->lookbackConfiguration; } public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } public function setPaymentApproved($paymentApproved) { $this->paymentApproved = $paymentApproved; } public function getPaymentApproved() { return $this->paymentApproved; } public function setPaymentSource($paymentSource) { $this->paymentSource = $paymentSource; } public function getPaymentSource() { return $this->paymentSource; } public function setPlacementGroupId($placementGroupId) { $this->placementGroupId = $placementGroupId; } public function getPlacementGroupId() { return $this->placementGroupId; } public function setPlacementGroupIdDimensionValue(Google_Service_Dfareporting_DimensionValue $placementGroupIdDimensionValue) { $this->placementGroupIdDimensionValue = $placementGroupIdDimensionValue; } public function getPlacementGroupIdDimensionValue() { return $this->placementGroupIdDimensionValue; } public function setPlacementStrategyId($placementStrategyId) { $this->placementStrategyId = $placementStrategyId; } public function getPlacementStrategyId() { return $this->placementStrategyId; } public function setPricingSchedule(Google_Service_Dfareporting_PricingSchedule $pricingSchedule) { $this->pricingSchedule = $pricingSchedule; } public function getPricingSchedule() { return $this->pricingSchedule; } public function setPrimary($primary) { $this->primary = $primary; } public function getPrimary() { return $this->primary; } public function setPublisherUpdateInfo(Google_Service_Dfareporting_LastModifiedInfo $publisherUpdateInfo) { $this->publisherUpdateInfo = $publisherUpdateInfo; } public function getPublisherUpdateInfo() { return $this->publisherUpdateInfo; } public function setSiteId($siteId) { $this->siteId = $siteId; } public function getSiteId() { return $this->siteId; } public function setSiteIdDimensionValue(Google_Service_Dfareporting_DimensionValue $siteIdDimensionValue) { $this->siteIdDimensionValue = $siteIdDimensionValue; } public function getSiteIdDimensionValue() { return $this->siteIdDimensionValue; } public function setSize(Google_Service_Dfareporting_Size $size) { $this->size = $size; } public function getSize() { return $this->size; } public function setSslRequired($sslRequired) { $this->sslRequired = $sslRequired; } public function getSslRequired() { return $this->sslRequired; } public function setStatus($status) { $this->status = $status; } public function getStatus() { return $this->status; } public function setSubaccountId($subaccountId) { $this->subaccountId = $subaccountId; } public function getSubaccountId() { return $this->subaccountId; } public function setTagFormats($tagFormats) { $this->tagFormats = $tagFormats; } public function getTagFormats() { return $this->tagFormats; } public function setTagSetting(Google_Service_Dfareporting_TagSetting $tagSetting) { $this->tagSetting = $tagSetting; } public function getTagSetting() { return $this->tagSetting; } public function setVideoActiveViewOptOut($videoActiveViewOptOut) { $this->videoActiveViewOptOut = $videoActiveViewOptOut; } public function getVideoActiveViewOptOut() { return $this->videoActiveViewOptOut; } public function setVideoSettings(Google_Service_Dfareporting_VideoSettings $videoSettings) { $this->videoSettings = $videoSettings; } public function getVideoSettings() { return $this->videoSettings; } public function setVpaidAdapterChoice($vpaidAdapterChoice) { $this->vpaidAdapterChoice = $vpaidAdapterChoice; } public function getVpaidAdapterChoice() { return $this->vpaidAdapterChoice; } }
gpl-2.0
jlbethel/jb_portfolio
sites/all/themes/mayo/js/mayo-columns.js
10291
/** * jquery.matchHeight.js v0.5.2 * http://brm.io/jquery-match-height/ * License: MIT * https://github.com/liabru/jquery-match-height */ ;(function($) { /* * internal */ var _previousResizeWidth = -1, _updateTimeout = -1; /* * _rows * utility function returns array of jQuery selections representing each row * (as displayed after float wrapping applied by browser) */ var _rows = function(elements) { var tolerance = 1, $elements = $(elements), lastTop = null, rows = []; // group elements by their top position $elements.each(function(){ var $that = $(this), top = $that.offset().top - _parse($that.css('margin-top')), lastRow = rows.length > 0 ? rows[rows.length - 1] : null; if (lastRow === null) { // first item on the row, so just push it rows.push($that); } else { // if the row top is the same, add to the row group if (Math.floor(Math.abs(lastTop - top)) <= tolerance) { rows[rows.length - 1] = lastRow.add($that); } else { // otherwise start a new row group rows.push($that); } } // keep track of the last row top lastTop = top; }); return rows; }; /* * _parse * value parse utility function */ var _parse = function(value) { // parse value and convert NaN to 0 return parseFloat(value) || 0; }; /* * _parseOptions * handle plugin options */ var _parseOptions = function(options) { var opts = { byRow: true, remove: false, property: 'height' }; if (typeof options === 'object') { return $.extend(opts, options); } if (typeof options === 'boolean') { opts.byRow = options; } else if (options === 'remove') { opts.remove = true; } return opts; }; /* * matchHeight * plugin definition */ var matchHeight = $.fn.matchHeight = function(options) { var opts = _parseOptions(options); // handle remove if (opts.remove) { var that = this; // remove fixed height from all selected elements this.css(opts.property, ''); // remove selected elements from all groups $.each(matchHeight._groups, function(key, group) { group.elements = group.elements.not(that); }); // TODO: cleanup empty groups return this; } if (this.length <= 1) return this; // keep track of this group so we can re-apply later on load and resize events matchHeight._groups.push({ elements: this, options: opts }); // match each element's height to the tallest element in the selection matchHeight._apply(this, opts); return this; }; /* * plugin global options */ matchHeight._groups = []; matchHeight._throttle = 80; matchHeight._maintainScroll = false; matchHeight._beforeUpdate = null; matchHeight._afterUpdate = null; /* * matchHeight._apply * apply matchHeight to given elements */ matchHeight._apply = function(elements, options) { var opts = _parseOptions(options), $elements = $(elements), rows = [$elements]; // take note of scroll position var scrollTop = $(window).scrollTop(), htmlHeight = $('html').outerHeight(true); // get hidden parents var $hiddenParents = $elements.parents().filter(':hidden'); // cache the original inline style $hiddenParents.each(function() { var $that = $(this); $that.data('style-cache', $that.attr('style')); }); // temporarily must force hidden parents visible $hiddenParents.css('display', 'block'); // get rows if using byRow, otherwise assume one row if (opts.byRow) { // must first force an arbitrary equal height so floating elements break evenly $elements.each(function() { var $that = $(this), display = $that.css('display') === 'inline-block' ? 'inline-block' : 'block'; // cache the original inline style $that.data('style-cache', $that.attr('style')); $that.css({ 'display': display, 'padding-top': '0', 'padding-bottom': '0', 'margin-top': '0', 'margin-bottom': '0', 'border-top-width': '0', 'border-bottom-width': '0', 'height': '100px' }); }); // get the array of rows (based on element top position) rows = _rows($elements); // revert original inline styles $elements.each(function() { var $that = $(this); $that.attr('style', $that.data('style-cache') || ''); }); } $.each(rows, function(key, row) { var $row = $(row), maxHeight = 0; // skip apply to rows with only one item if (opts.byRow && $row.length <= 1) { $row.css(opts.property, ''); return; } // iterate the row and find the max height $row.each(function(){ var $that = $(this), display = $that.css('display') === 'inline-block' ? 'inline-block' : 'block'; // ensure we get the correct actual height (and not a previously set height value) var css = { 'display': display }; css[opts.property] = ''; $that.css(css); // find the max height (including padding, but not margin) if ($that.outerHeight(false) > maxHeight) maxHeight = $that.outerHeight(false); // revert display block $that.css('display', ''); }); // iterate the row and apply the height to all elements $row.each(function(){ var $that = $(this), verticalPadding = 0; // handle padding and border correctly (required when not using border-box) if ($that.css('box-sizing') !== 'border-box') { verticalPadding += _parse($that.css('border-top-width')) + _parse($that.css('border-bottom-width')); verticalPadding += _parse($that.css('padding-top')) + _parse($that.css('padding-bottom')); } // set the height (accounting for padding and border) $that.css(opts.property, maxHeight - verticalPadding); }); }); // revert hidden parents $hiddenParents.each(function() { var $that = $(this); $that.attr('style', $that.data('style-cache') || null); }); // restore scroll position if enabled if (matchHeight._maintainScroll) $(window).scrollTop((scrollTop / htmlHeight) * $('html').outerHeight(true)); return this; }; /* * matchHeight._applyDataApi * applies matchHeight to all elements with a data-match-height attribute */ matchHeight._applyDataApi = function() { var groups = {}; // generate groups by their groupId set by elements using data-match-height $('[data-match-height], [data-mh]').each(function() { var $this = $(this), groupId = $this.attr('data-match-height') || $this.attr('data-mh'); if (groupId in groups) { groups[groupId] = groups[groupId].add($this); } else { groups[groupId] = $this; } }); // apply matchHeight to each group $.each(groups, function() { this.matchHeight(true); }); }; /* * matchHeight._update * updates matchHeight on all current groups with their correct options */ var _update = function(event) { if (matchHeight._beforeUpdate) matchHeight._beforeUpdate(event, matchHeight._groups); $.each(matchHeight._groups, function() { matchHeight._apply(this.elements, this.options); }); if (matchHeight._afterUpdate) matchHeight._afterUpdate(event, matchHeight._groups); }; matchHeight._update = function(throttle, event) { // prevent update if fired from a resize event // where the viewport width hasn't actually changed // fixes an event looping bug in IE8 if (event && event.type === 'resize') { var windowWidth = $(window).width(); if (windowWidth === _previousResizeWidth) return; _previousResizeWidth = windowWidth; } // throttle updates if (!throttle) { _update(event); } else if (_updateTimeout === -1) { _updateTimeout = setTimeout(function() { _update(event); _updateTimeout = -1; }, matchHeight._throttle); } }; /* * bind events */ // apply on DOM ready event $(matchHeight._applyDataApi); // update heights on load and resize events $(window).bind('load', function(event) { matchHeight._update(false, event); }); // throttled update heights on resize events $(window).bind('resize orientationchange', function(event) { matchHeight._update(true, event); }); })(jQuery); // Added on to trigger the script above and give equal heights to some Mayo columns. (function ($) { $(document).ready(function() { $('#top-columns .column-block').matchHeight(); $('#bottom-columns .column-block').matchHeight(); }); })(jQuery);
gpl-2.0
kmangame0/stk
lib/irrlicht/source/Irrlicht/CGUIToolBar.cpp
4279
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "CGUIToolBar.h" #ifdef _IRR_COMPILE_WITH_GUI_ #include "IGUISkin.h" #include "IGUIEnvironment.h" #include "IVideoDriver.h" #include "IGUIButton.h" #include "IGUIFont.h" #include "CGUIButton.h" namespace irr { namespace gui { //! constructor CGUIToolBar::CGUIToolBar(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle) :IGUIToolBar(environment, parent, id, rectangle), ButtonX(5) { #ifdef _DEBUG setDebugName("CGUIToolBar"); #endif // calculate position and find other menubars s32 y = 0; s32 parentwidth = 100; if (parent) { parentwidth = Parent->getAbsolutePosition().getWidth(); const core::list<IGUIElement*>& children = parent->getChildren(); core::list<IGUIElement*>::ConstIterator it = children.begin(); for (; it != children.end(); ++it) { core::rect<s32> r = (*it)->getAbsolutePosition(); if (r.UpperLeftCorner.X == 0 && r.UpperLeftCorner.Y <= y && r.LowerRightCorner.X == parentwidth) y = r.LowerRightCorner.Y; } } core::rect<s32> rr; rr.UpperLeftCorner.X = 0; rr.UpperLeftCorner.Y = y; s32 height = Environment->getSkin()->getSize ( EGDS_MENU_HEIGHT ); /*IGUISkin* skin = Environment->getSkin(); IGUIFont* font = skin->getFont(); if (font) { s32 t = font->getDimension(L"A").Height + 5; if (t > height) height = t; }*/ rr.LowerRightCorner.X = parentwidth; rr.LowerRightCorner.Y = rr.UpperLeftCorner.Y + height; setRelativePosition(rr); } //! called if an event happened. bool CGUIToolBar::OnEvent(const SEvent& event) { if (isEnabled()) { if (event.EventType == EET_MOUSE_INPUT_EVENT && event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { if (AbsoluteClippingRect.isPointInside(core::position2di(event.MouseInput.X, event.MouseInput.Y))) return true; } } return IGUIElement::OnEvent(event); } //! draws the element and its children void CGUIToolBar::draw() { if (!IsVisible) return; IGUISkin* skin = Environment->getSkin(); if (!skin) return; core::rect<s32> rect = AbsoluteRect; core::rect<s32>* clip = &AbsoluteClippingRect; // draw frame skin->draw3DToolBar(this, rect, clip); IGUIElement::draw(); } //! Updates the absolute position. void CGUIToolBar::updateAbsolutePosition() { if (Parent) { DesiredRect.UpperLeftCorner.X = 0; DesiredRect.LowerRightCorner.X = Parent->getAbsolutePosition().getWidth(); } IGUIElement::updateAbsolutePosition(); } //! Adds a button to the tool bar IGUIButton* CGUIToolBar::addButton(s32 id, const wchar_t* text,const wchar_t* tooltiptext, video::ITexture* img, video::ITexture* pressed, bool isPushButton, bool useAlphaChannel) { ButtonX += 3; core::rect<s32> rectangle(ButtonX,2,ButtonX+1,3); if ( img ) { const core::dimension2du &size = img->getOriginalSize(); rectangle.LowerRightCorner.X = rectangle.UpperLeftCorner.X + size.Width + 8; rectangle.LowerRightCorner.Y = rectangle.UpperLeftCorner.Y + size.Height + 6; } if ( text ) { IGUISkin* skin = Environment->getSkin(); IGUIFont * font = skin->getFont(EGDF_BUTTON); if ( font ) { core::dimension2d<u32> dim = font->getDimension(text); if ( (s32)dim.Width > rectangle.getWidth() ) rectangle.LowerRightCorner.X = rectangle.UpperLeftCorner.X + dim.Width + 8; if ( (s32)dim.Height > rectangle.getHeight() ) rectangle.LowerRightCorner.Y = rectangle.UpperLeftCorner.Y + dim.Height + 6; } } ButtonX += rectangle.getWidth(); IGUIButton* button = new CGUIButton(Environment, this, id, rectangle); button->drop(); if (text) button->setText(text); if (tooltiptext) button->setToolTipText(tooltiptext); if (img) button->setImage(img); if (pressed) button->setPressedImage(pressed); if (isPushButton) button->setIsPushButton(isPushButton); if (useAlphaChannel) button->setUseAlphaChannel(useAlphaChannel); return button; } } // end namespace gui } // end namespace irr #endif // _IRR_COMPILE_WITH_GUI_
gpl-3.0
WiseUA/devguide
docroot/drupal8/core/modules/ckeditor/js/ckeditor.admin.js
18750
/** * @file * CKEditor button and group configuration user interface. */ (function ($, Drupal, drupalSettings, _) { 'use strict'; Drupal.ckeditor = Drupal.ckeditor || {}; /** * Sets config behaviour and creates config views for the CKEditor toolbar. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches admin behaviour to the CKEditor buttons. * @prop {Drupal~behaviorDetach} detach * Detaches admin behaviour from the CKEditor buttons on 'unload'. */ Drupal.behaviors.ckeditorAdmin = { attach: function (context) { // Process the CKEditor configuration fragment once. var $configurationForm = $(context).find('.ckeditor-toolbar-configuration').once('ckeditor-configuration'); if ($configurationForm.length) { var $textarea = $configurationForm // Hide the textarea that contains the serialized representation of the // CKEditor configuration. .find('.js-form-item-editor-settings-toolbar-button-groups') .hide() // Return the textarea child node from this expression. .find('textarea'); // The HTML for the CKEditor configuration is assembled on the server // and sent to the client as a serialized DOM fragment. $configurationForm.append(drupalSettings.ckeditor.toolbarAdmin); // Create a configuration model. var model = Drupal.ckeditor.models.Model = new Drupal.ckeditor.Model({ $textarea: $textarea, activeEditorConfig: JSON.parse($textarea.val()), hiddenEditorConfig: drupalSettings.ckeditor.hiddenCKEditorConfig }); // Create the configuration Views. var viewDefaults = { model: model, el: $('.ckeditor-toolbar-configuration') }; Drupal.ckeditor.views = { controller: new Drupal.ckeditor.ControllerView(viewDefaults), visualView: new Drupal.ckeditor.VisualView(viewDefaults), keyboardView: new Drupal.ckeditor.KeyboardView(viewDefaults), auralView: new Drupal.ckeditor.AuralView(viewDefaults) }; } }, detach: function (context, settings, trigger) { // Early-return if the trigger for detachment is something else than // unload. if (trigger !== 'unload') { return; } // We're detaching because CKEditor as text editor has been disabled; this // really means that all CKEditor toolbar buttons have been removed. // Hence,all editor features will be removed, so any reactions from // filters will be undone. var $configurationForm = $(context).find('.ckeditor-toolbar-configuration').findOnce('ckeditor-configuration'); if ($configurationForm.length && Drupal.ckeditor.models && Drupal.ckeditor.models.Model) { var config = Drupal.ckeditor.models.Model.toJSON().activeEditorConfig; var buttons = Drupal.ckeditor.views.controller.getButtonList(config); var $activeToolbar = $('.ckeditor-toolbar-configuration').find('.ckeditor-toolbar-active'); for (var i = 0; i < buttons.length; i++) { $activeToolbar.trigger('CKEditorToolbarChanged', ['removed', buttons[i]]); } } } }; /** * CKEditor configuration UI methods of Backbone objects. * * @namespace */ Drupal.ckeditor = { /** * A hash of View instances. * * @type {object} */ views: {}, /** * A hash of Model instances. * * @type {object} */ models: {}, /** * Translates changes in CKEditor config DOM structure to the config model. * * If the button is moved within an existing group, the DOM structure is * simply translated to a configuration model. If the button is moved into a * new group placeholder, then a process is launched to name that group * before the button move is translated into configuration. * * @param {Backbone.View} view * The Backbone View that invoked this function. * @param {jQuery} $button * A jQuery set that contains an li element that wraps a button element. * @param {function} callback * A callback to invoke after the button group naming modal dialog has * been closed. * */ registerButtonMove: function (view, $button, callback) { var $group = $button.closest('.ckeditor-toolbar-group'); // If dropped in a placeholder button group, the user must name it. if ($group.hasClass('placeholder')) { if (view.isProcessing) { return; } view.isProcessing = true; Drupal.ckeditor.openGroupNameDialog(view, $group, callback); } else { view.model.set('isDirty', true); callback(true); } }, /** * Translates changes in CKEditor config DOM structure to the config model. * * Each row has a placeholder group at the end of the row. A user may not * move an existing button group past the placeholder group at the end of a * row. * * @param {Backbone.View} view * The Backbone View that invoked this function. * @param {jQuery} $group * A jQuery set that contains an li element that wraps a group of buttons. */ registerGroupMove: function (view, $group) { // Remove placeholder classes if necessary. var $row = $group.closest('.ckeditor-row'); if ($row.hasClass('placeholder')) { $row.removeClass('placeholder'); } // If there are any rows with just a placeholder group, mark the row as a // placeholder. $row.parent().children().each(function () { $row = $(this); if ($row.find('.ckeditor-toolbar-group').not('.placeholder').length === 0) { $row.addClass('placeholder'); } }); view.model.set('isDirty', true); }, /** * Opens a dialog with a form for changing the title of a button group. * * @param {Backbone.View} view * The Backbone View that invoked this function. * @param {jQuery} $group * A jQuery set that contains an li element that wraps a group of buttons. * @param {function} callback * A callback to invoke after the button group naming modal dialog has * been closed. */ openGroupNameDialog: function (view, $group, callback) { callback = callback || function () {}; /** * Validates the string provided as a button group title. * * @param {HTMLElement} form * The form DOM element that contains the input with the new button * group title string. * * @return {bool} * Returns true when an error exists, otherwise returns false. */ function validateForm(form) { if (form.elements[0].value.length === 0) { var $form = $(form); if (!$form.hasClass('errors')) { $form .addClass('errors') .find('input') .addClass('error') .attr('aria-invalid', 'true'); $('<div class=\"description\" >' + Drupal.t('Please provide a name for the button group.') + '</div>').insertAfter(form.elements[0]); } return true; } return false; } /** * Attempts to close the dialog; Validates user input. * * @param {string} action * The dialog action chosen by the user: 'apply' or 'cancel'. * @param {HTMLElement} form * The form DOM element that contains the input with the new button * group title string. */ function closeDialog(action, form) { /** * Closes the dialog when the user cancels or supplies valid data. */ function shutdown() { dialog.close(action); // The processing marker can be deleted since the dialog has been // closed. delete view.isProcessing; } /** * Applies a string as the name of a CKEditor button group. * * @param {jQuery} $group * A jQuery set that contains an li element that wraps a group of * buttons. * @param {string} name * The new name of the CKEditor button group. */ function namePlaceholderGroup($group, name) { // If it's currently still a placeholder, then that means we're // creating a new group, and we must do some extra work. if ($group.hasClass('placeholder')) { // Remove all whitespace from the name, lowercase it and ensure // HTML-safe encoding, then use this as the group ID for CKEditor // configuration UI accessibility purposes only. var groupID = 'ckeditor-toolbar-group-aria-label-for-' + Drupal.checkPlain(name.toLowerCase().replace(/\s/g, '-')); $group // Update the group container. .removeAttr('aria-label') .attr('data-drupal-ckeditor-type', 'group') .attr('tabindex', 0) // Update the group heading. .children('.ckeditor-toolbar-group-name') .attr('id', groupID) .end() // Update the group items. .children('.ckeditor-toolbar-group-buttons') .attr('aria-labelledby', groupID); } $group .attr('data-drupal-ckeditor-toolbar-group-name', name) .children('.ckeditor-toolbar-group-name') .text(name); } // Invoke a user-provided callback and indicate failure. if (action === 'cancel') { shutdown(); callback(false, $group); return; } // Validate that a group name was provided. if (form && validateForm(form)) { return; } // React to application of a valid group name. if (action === 'apply') { shutdown(); // Apply the provided name to the button group label. namePlaceholderGroup($group, Drupal.checkPlain(form.elements[0].value)); // Remove placeholder classes so that new placeholders will be // inserted. $group.closest('.ckeditor-row.placeholder').addBack().removeClass('placeholder'); // Invoke a user-provided callback and indicate success. callback(true, $group); // Signal that the active toolbar DOM structure has changed. view.model.set('isDirty', true); } } // Create a Drupal dialog that will get a button group name from the user. var $ckeditorButtonGroupNameForm = $(Drupal.theme('ckeditorButtonGroupNameForm')); var dialog = Drupal.dialog($ckeditorButtonGroupNameForm.get(0), { title: Drupal.t('Button group name'), dialogClass: 'ckeditor-name-toolbar-group', resizable: false, buttons: [ { text: Drupal.t('Apply'), click: function () { closeDialog('apply', this); }, primary: true }, { text: Drupal.t('Cancel'), click: function () { closeDialog('cancel'); } } ], open: function () { var form = this; var $form = $(this); var $widget = $form.parent(); $widget.find('.ui-dialog-titlebar-close').remove(); // Set a click handler on the input and button in the form. $widget.on('keypress.ckeditor', 'input, button', function (event) { // React to enter key press. if (event.keyCode === 13) { var $target = $(event.currentTarget); var data = $target.data('ui-button'); var action = 'apply'; // Assume 'apply', but take into account that the user might have // pressed the enter key on the dialog buttons. if (data && data.options && data.options.label) { action = data.options.label.toLowerCase(); } closeDialog(action, form); event.stopPropagation(); event.stopImmediatePropagation(); event.preventDefault(); } }); // Announce to the user that a modal dialog is open. var text = Drupal.t('Editing the name of the new button group in a dialog.'); if (typeof $group.attr('data-drupal-ckeditor-toolbar-group-name') !== 'undefined') { text = Drupal.t('Editing the name of the "@groupName" button group in a dialog.', { '@groupName': $group.attr('data-drupal-ckeditor-toolbar-group-name') }); } Drupal.announce(text); }, close: function (event) { // Automatically destroy the DOM element that was used for the dialog. $(event.target).remove(); } }); // A modal dialog is used because the user must provide a button group // name or cancel the button placement before taking any other action. dialog.showModal(); $(document.querySelector('.ckeditor-name-toolbar-group').querySelector('input')) // When editing, set the "group name" input in the form to the current // value. .attr('value', $group.attr('data-drupal-ckeditor-toolbar-group-name')) // Focus on the "group name" input in the form. .trigger('focus'); } }; /** * Automatically shows/hides settings of buttons-only CKEditor plugins. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches show/hide behaviour to Plugin Settings buttons. */ Drupal.behaviors.ckeditorAdminButtonPluginSettings = { attach: function (context) { var $context = $(context); var $ckeditorPluginSettings = $context.find('#ckeditor-plugin-settings').once('ckeditor-plugin-settings'); if ($ckeditorPluginSettings.length) { // Hide all button-dependent plugin settings initially. $ckeditorPluginSettings.find('[data-ckeditor-buttons]').each(function () { var $this = $(this); if ($this.data('verticalTab')) { $this.data('verticalTab').tabHide(); } else { // On very narrow viewports, Vertical Tabs are disabled. $this.hide(); } $this.data('ckeditorButtonPluginSettingsActiveButtons', []); }); // Whenever a button is added or removed, check if we should show or // hide the corresponding plugin settings. (Note that upon // initialization, each button that already is part of the toolbar still // is considered "added", hence it also works correctly for buttons that // were added previously.) $context .find('.ckeditor-toolbar-active') .off('CKEditorToolbarChanged.ckeditorAdminPluginSettings') .on('CKEditorToolbarChanged.ckeditorAdminPluginSettings', function (event, action, button) { var $pluginSettings = $ckeditorPluginSettings .find('[data-ckeditor-buttons~=' + button + ']'); // No settings for this button. if ($pluginSettings.length === 0) { return; } var verticalTab = $pluginSettings.data('verticalTab'); var activeButtons = $pluginSettings.data('ckeditorButtonPluginSettingsActiveButtons'); if (action === 'added') { activeButtons.push(button); // Show this plugin's settings if >=1 of its buttons are active. if (verticalTab) { verticalTab.tabShow(); } else { // On very narrow viewports, Vertical Tabs remain fieldsets. $pluginSettings.show(); } } else { // Remove this button from the list of active buttons. activeButtons.splice(activeButtons.indexOf(button), 1); // Show this plugin's settings 0 of its buttons are active. if (activeButtons.length === 0) { if (verticalTab) { verticalTab.tabHide(); } else { // On very narrow viewports, Vertical Tabs are disabled. $pluginSettings.hide(); } } } $pluginSettings.data('ckeditorButtonPluginSettingsActiveButtons', activeButtons); }); } } }; /** * Themes a blank CKEditor row. * * @return {string} * A HTML string for a CKEditor row. */ Drupal.theme.ckeditorRow = function () { return '<li class="ckeditor-row placeholder" role="group"><ul class="ckeditor-toolbar-groups clearfix"></ul></li>'; }; /** * Themes a blank CKEditor button group. * * @return {string} * A HTML string for a CKEditor button group. */ Drupal.theme.ckeditorToolbarGroup = function () { var group = ''; group += '<li class="ckeditor-toolbar-group placeholder" role="presentation" aria-label="' + Drupal.t('Place a button to create a new button group.') + '">'; group += '<h3 class="ckeditor-toolbar-group-name">' + Drupal.t('New group') + '</h3>'; group += '<ul class="ckeditor-buttons ckeditor-toolbar-group-buttons" role="toolbar" data-drupal-ckeditor-button-sorting="target"></ul>'; group += '</li>'; return group; }; /** * Themes a form for changing the title of a CKEditor button group. * * @return {string} * A HTML string for the form for the title of a CKEditor button group. */ Drupal.theme.ckeditorButtonGroupNameForm = function () { return '<form><input name="group-name" required="required"></form>'; }; /** * Themes a button that will toggle the button group names in active config. * * @return {string} * A HTML string for the button to toggle group names. */ Drupal.theme.ckeditorButtonGroupNamesToggle = function () { return '<button class="link ckeditor-groupnames-toggle" aria-pressed="false"></button>'; }; /** * Themes a button that will prompt the user to name a new button group. * * @return {string} * A HTML string for the button to create a name for a new button group. */ Drupal.theme.ckeditorNewButtonGroup = function () { return '<li class="ckeditor-add-new-group"><button role="button" aria-label="' + Drupal.t('Add a CKEditor button group to the end of this row.') + '">' + Drupal.t('Add group') + '</button></li>'; }; })(jQuery, Drupal, drupalSettings, _);
gpl-3.0
avrem/ardupilot
libraries/AP_IRLock/IRLock.cpp
533
/* * IRLock.cpp * * Created on: Nov 12, 2014 * Author: MLandes */ #include "IRLock.h" // retrieve body frame unit vector in direction of target // returns true if data is available bool IRLock::get_unit_vector_body(Vector3f& ret) const { // return false if we have no target if (!_flags.healthy) { return false; } // use data from first (largest) object ret.x = -_target_info.pos_y; ret.y = _target_info.pos_x; ret.z = _target_info.pos_z; ret /= ret.length(); return true; }
gpl-3.0
u2takey/kubernetes
vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network/webapplicationfirewallpolicies.go
21780
package network // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // WebApplicationFirewallPoliciesClient is the network Client type WebApplicationFirewallPoliciesClient struct { BaseClient } // NewWebApplicationFirewallPoliciesClient creates an instance of the WebApplicationFirewallPoliciesClient client. func NewWebApplicationFirewallPoliciesClient(subscriptionID string) WebApplicationFirewallPoliciesClient { return NewWebApplicationFirewallPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewWebApplicationFirewallPoliciesClientWithBaseURI creates an instance of the WebApplicationFirewallPoliciesClient // client. func NewWebApplicationFirewallPoliciesClientWithBaseURI(baseURI string, subscriptionID string) WebApplicationFirewallPoliciesClient { return WebApplicationFirewallPoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates or update policy with specified rule set name within a resource group. // Parameters: // resourceGroupName - the name of the resource group. // policyName - the name of the policy. // parameters - policy to be created. func (client WebApplicationFirewallPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, policyName string, parameters WebApplicationFirewallPolicy) (result WebApplicationFirewallPolicy, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.CreateOrUpdate") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: policyName, Constraints: []validation.Constraint{{Target: "policyName", Name: validation.MaxLength, Rule: 128, Chain: nil}}}}); err != nil { return result, validation.NewError("network.WebApplicationFirewallPoliciesClient", "CreateOrUpdate", err.Error()) } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, policyName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "CreateOrUpdate", nil, "Failure preparing request") return } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "CreateOrUpdate", resp, "Failure sending request") return } result, err = client.CreateOrUpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client WebApplicationFirewallPoliciesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, policyName string, parameters WebApplicationFirewallPolicy) (*http.Request, error) { pathParameters := map[string]interface{}{ "policyName": autorest.Encode("path", policyName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client WebApplicationFirewallPoliciesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client WebApplicationFirewallPoliciesClient) CreateOrUpdateResponder(resp *http.Response) (result WebApplicationFirewallPolicy, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes Policy. // Parameters: // resourceGroupName - the name of the resource group. // policyName - the name of the policy. func (client WebApplicationFirewallPoliciesClient) Delete(ctx context.Context, resourceGroupName string, policyName string) (result WebApplicationFirewallPoliciesDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.Delete") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: policyName, Constraints: []validation.Constraint{{Target: "policyName", Name: validation.MaxLength, Rule: 128, Chain: nil}}}}); err != nil { return result, validation.NewError("network.WebApplicationFirewallPoliciesClient", "Delete", err.Error()) } req, err := client.DeletePreparer(ctx, resourceGroupName, policyName) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "Delete", result.Response(), "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client WebApplicationFirewallPoliciesClient) DeletePreparer(ctx context.Context, resourceGroupName string, policyName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "policyName": autorest.Encode("path", policyName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client WebApplicationFirewallPoliciesClient) DeleteSender(req *http.Request) (future WebApplicationFirewallPoliciesDeleteFuture, err error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client WebApplicationFirewallPoliciesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get retrieve protection policy with specified name within a resource group. // Parameters: // resourceGroupName - the name of the resource group. // policyName - the name of the policy. func (client WebApplicationFirewallPoliciesClient) Get(ctx context.Context, resourceGroupName string, policyName string) (result WebApplicationFirewallPolicy, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: policyName, Constraints: []validation.Constraint{{Target: "policyName", Name: validation.MaxLength, Rule: 128, Chain: nil}}}}); err != nil { return result, validation.NewError("network.WebApplicationFirewallPoliciesClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, resourceGroupName, policyName) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client WebApplicationFirewallPoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, policyName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "policyName": autorest.Encode("path", policyName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client WebApplicationFirewallPoliciesClient) GetSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client WebApplicationFirewallPoliciesClient) GetResponder(resp *http.Response) (result WebApplicationFirewallPolicy, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List lists all of the protection policies within a resource group. // Parameters: // resourceGroupName - the name of the resource group. func (client WebApplicationFirewallPoliciesClient) List(ctx context.Context, resourceGroupName string) (result WebApplicationFirewallPolicyListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.List") defer func() { sc := -1 if result.wafplr.Response.Response != nil { sc = result.wafplr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.wafplr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "List", resp, "Failure sending request") return } result.wafplr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client WebApplicationFirewallPoliciesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client WebApplicationFirewallPoliciesClient) ListSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client WebApplicationFirewallPoliciesClient) ListResponder(resp *http.Response) (result WebApplicationFirewallPolicyListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client WebApplicationFirewallPoliciesClient) listNextResults(ctx context.Context, lastResults WebApplicationFirewallPolicyListResult) (result WebApplicationFirewallPolicyListResult, err error) { req, err := lastResults.webApplicationFirewallPolicyListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client WebApplicationFirewallPoliciesClient) ListComplete(ctx context.Context, resourceGroupName string) (result WebApplicationFirewallPolicyListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName) return } // ListAll gets all the WAF policies in a subscription. func (client WebApplicationFirewallPoliciesClient) ListAll(ctx context.Context) (result WebApplicationFirewallPolicyListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.ListAll") defer func() { sc := -1 if result.wafplr.Response.Response != nil { sc = result.wafplr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listAllNextResults req, err := client.ListAllPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "ListAll", nil, "Failure preparing request") return } resp, err := client.ListAllSender(req) if err != nil { result.wafplr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "ListAll", resp, "Failure sending request") return } result.wafplr, err = client.ListAllResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "ListAll", resp, "Failure responding to request") } return } // ListAllPreparer prepares the ListAll request. func (client WebApplicationFirewallPoliciesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client WebApplicationFirewallPoliciesClient) ListAllSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListAllResponder handles the response to the ListAll request. The method always // closes the http.Response Body. func (client WebApplicationFirewallPoliciesClient) ListAllResponder(resp *http.Response) (result WebApplicationFirewallPolicyListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listAllNextResults retrieves the next set of results, if any. func (client WebApplicationFirewallPoliciesClient) listAllNextResults(ctx context.Context, lastResults WebApplicationFirewallPolicyListResult) (result WebApplicationFirewallPolicyListResult, err error) { req, err := lastResults.webApplicationFirewallPolicyListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listAllNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listAllNextResults", resp, "Failure sending next results request") } result, err = client.ListAllResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listAllNextResults", resp, "Failure responding to next results request") } return } // ListAllComplete enumerates all values, automatically crossing page boundaries as required. func (client WebApplicationFirewallPoliciesClient) ListAllComplete(ctx context.Context) (result WebApplicationFirewallPolicyListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.ListAll") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListAll(ctx) return }
apache-2.0
grizzlysmit/android-play-location
LocationUpdates/app/src/androidTest/java/com/google/android/gms/location/sample/locationupdates/MainActivityTest.java
8572
/** * Copyright 2014 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. */ package com.google.android.gms.location.sample.locationupdates; import android.location.Location; import android.os.Build; import android.os.SystemClock; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationServices; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Test showing use of mock location data to test code using the Google Play Location APIs. To * run this test, you must first check the "Allow mock locations" setting within * Settings -> Developer options. */ public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> { public static final String TAG = "MainActivityTest"; /** * The name of the mock location. */ public static final String NORTH_POLE = "com.google.android.gms.location.sample.locationupdates" + ".NORTH_POLE"; public static final float NORTH_POLE_LATITUDE = 90.0f; public static final float NORTH_POLE_LONGITUDE = 0.0f; public static final float ACCURACY_IN_METERS = 10.0f; public static final int AWAIT_TIMEOUT_IN_MILLISECONDS = 2000; /** * The activity under test. */ private MainActivity mMainActivity; public MainActivityTest() { super(MainActivity.class); } /** * Gets the activity under test, obtains a connection to GoogleApiClient if necessary, and * sets mock location. */ @Override protected void setUp() throws Exception { super.setUp(); mMainActivity = getActivity(); ensureGoogleApiClientConnection(); } /** * Tests location using a mock location object. */ public void testUsingMockLocation() { Log.v(TAG, "Testing current location"); // Use a Location object set to the coordinates of the North Pole to set the mock location. setMockLocation(createNorthPoleLocation()); // Make sure that the activity under test exists and GoogleApiClient is connected. confirmPreconditions(); // Simulate a Start Updates button click. clickStartUpdatesButton(); final Location testLocation = createNorthPoleLocation(); assertEquals(mMainActivity.mCurrentLocation.getLatitude(), testLocation.getLatitude(), 0.000001f); assertEquals(mMainActivity.mCurrentLocation.getLongitude(), testLocation.getLongitude(), 0.000001f); assertEquals(mMainActivity.mLatitudeTextView.getText().toString(), String.valueOf(testLocation.getLatitude())); assertEquals(mMainActivity.mLongitudeTextView.getText().toString(), String.valueOf(testLocation.getLongitude())); } /** * If a connection to GoogleApiClient is lost, attempts to reconnect. */ private void ensureGoogleApiClientConnection() { if (!mMainActivity.mGoogleApiClient.isConnected()) { mMainActivity.mGoogleApiClient.blockingConnect(); } } /** * Confirms that the activity under test exists and has a connected GoogleApiClient. */ private void confirmPreconditions() { assertNotNull("mMainActivity is null", mMainActivity); assertTrue("GoogleApiClient is not connected", mMainActivity.mGoogleApiClient.isConnected()); } /** * Simulates a Start Updates button click. */ private void clickStartUpdatesButton() { mMainActivity.runOnUiThread(new Runnable() { public void run() { mMainActivity.mStartUpdatesButton.performClick(); } }); } /** * Calls the asynchronous methods * {@link com.google.android.gms.location.FusedLocationProviderApi#setMockMode} and * {@link com.google.android.gms.location.FusedLocationProviderApi#setMockLocation} to set the * mock location. Uses nested callbacks when calling setMockMode() and setMockLocation(). * Each method returns a {@link Status} through a * {@link com.google.android.gms.common.api.PendingResult<>}, and setMockLocation() is called * only if setMockMode() is successful. Maintains a * {@link CountDownLatch} with a count of 1, which makes the current thread wait. Decrements * the CountDownLatch count only if the mock location is successfully set, allowing the set up * to complete. */ private void setMockLocation(final Location mockLocation) { // We use a CountDownLatch to ensure that all asynchronous tasks complete within setUp. We // set the CountDownLatch count to 1 and decrement this count only when we are certain that // mock location has been set. final CountDownLatch lock = new CountDownLatch(1); // First, ensure that the location provider is in mock mode. Using setMockMode() ensures // that only locations specified in setMockLocation(GoogleApiClient, Location) are used. LocationServices.FusedLocationApi.setMockMode(mMainActivity.mGoogleApiClient, true) .setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { if (status.isSuccess()) { Log.v(TAG, "Mock mode set"); // Set the mock location to be used for the location provider. This // location is used in place of any actual locations from the underlying // providers (network or gps). LocationServices.FusedLocationApi.setMockLocation( mMainActivity.mGoogleApiClient, mockLocation ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { if (status.isSuccess()) { Log.v(TAG, "Mock location set"); // Decrement the count of the latch, releasing the waiting // thread. This permits lock.await() to return. Log.v(TAG, "Decrementing latch count"); lock.countDown(); } else { Log.e(TAG, "Mock location not set"); } } }); } else { Log.e(TAG, "Mock mode not set"); } } }); try { // Make the current thread wait until the latch has counted down to zero. Log.v(TAG, "Waiting until the latch has counted down to zero"); lock.await(AWAIT_TIMEOUT_IN_MILLISECONDS, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { Log.i(TAG, "Waiting thread awakened prematurely", exception); } } /** * Creates and returns a Location object set to the coordinates of the North Pole. */ private Location createNorthPoleLocation() { Location mockLocation = new Location(NORTH_POLE); mockLocation.setLatitude(NORTH_POLE_LATITUDE); mockLocation.setLongitude(NORTH_POLE_LONGITUDE); mockLocation.setAccuracy(ACCURACY_IN_METERS); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos()); } mockLocation.setTime(System.currentTimeMillis()); return mockLocation; } }
apache-2.0
OpenCollabZA/sakai
msgcntr/messageforums-app/src/java/org/sakaiproject/tool/messageforums/ui/SiteGroupBean.java
2061
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/msgcntr/trunk/messageforums-app/src/java/org/sakaiproject/tool/messageforums/ui/SiteGroupBean.java $ * $Id: SiteGroupBean.java $ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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 org.sakaiproject.tool.messageforums.ui; import org.sakaiproject.site.api.Group; public class SiteGroupBean { private Group group; private boolean createForumForGroup; private boolean createTopicForGroup; public SiteGroupBean (Group group, boolean createTopicForGroup, boolean createForumForGroup) { this.group = group; this.createTopicForGroup = createTopicForGroup; this.createForumForGroup = createForumForGroup; } public Group getGroup() { return this.group; } public void setGroup(Group group) { this.group = group; } public boolean getCreateTopicForGroup() { return this.createTopicForGroup; } public void setCreateTopicForGroup(boolean createTopicForGroup) { this.createTopicForGroup = createTopicForGroup; } public boolean getCreateForumForGroup() { return this.createForumForGroup; } public void setCreateForumForGroup(boolean createForumForGroup) { this.createForumForGroup = createForumForGroup; } }
apache-2.0
mml/kubernetes
pkg/api/persistentvolumeclaim/util_test.go
9101
/* Copyright 2017 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. */ package persistentvolumeclaim import ( "fmt" "reflect" "testing" "k8s.io/apimachinery/pkg/util/diff" utilfeature "k8s.io/apiserver/pkg/util/feature" featuregatetesting "k8s.io/component-base/featuregate/testing" "k8s.io/kubernetes/pkg/apis/core" "k8s.io/kubernetes/pkg/features" ) func TestDropAlphaPVCVolumeMode(t *testing.T) { vmode := core.PersistentVolumeFilesystem pvcWithoutVolumeMode := func() *core.PersistentVolumeClaim { return &core.PersistentVolumeClaim{ Spec: core.PersistentVolumeClaimSpec{ VolumeMode: nil, }, } } pvcWithVolumeMode := func() *core.PersistentVolumeClaim { return &core.PersistentVolumeClaim{ Spec: core.PersistentVolumeClaimSpec{ VolumeMode: &vmode, }, } } pvcInfo := []struct { description string hasVolumeMode bool pvc func() *core.PersistentVolumeClaim }{ { description: "pvc without VolumeMode", hasVolumeMode: false, pvc: pvcWithoutVolumeMode, }, { description: "pvc with Filesystem VolumeMode", hasVolumeMode: true, pvc: pvcWithVolumeMode, }, { description: "is nil", hasVolumeMode: false, pvc: func() *core.PersistentVolumeClaim { return nil }, }, } for _, enabled := range []bool{true, false} { for _, oldpvcInfo := range pvcInfo { for _, newpvcInfo := range pvcInfo { oldpvcHasVolumeMode, oldpvc := oldpvcInfo.hasVolumeMode, oldpvcInfo.pvc() newpvcHasVolumeMode, newpvc := newpvcInfo.hasVolumeMode, newpvcInfo.pvc() if newpvc == nil { continue } t.Run(fmt.Sprintf("feature enabled=%v, old pvc %v, new pvc %v", enabled, oldpvcInfo.description, newpvcInfo.description), func(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.BlockVolume, enabled)() var oldpvcSpec *core.PersistentVolumeClaimSpec if oldpvc != nil { oldpvcSpec = &oldpvc.Spec } DropDisabledFields(&newpvc.Spec, oldpvcSpec) // old pvc should never be changed if !reflect.DeepEqual(oldpvc, oldpvcInfo.pvc()) { t.Errorf("old pvc changed: %v", diff.ObjectReflectDiff(oldpvc, oldpvcInfo.pvc())) } switch { case enabled || oldpvcHasVolumeMode: // new pvc should not be changed if the feature is enabled, or if the old pvc had BlockVolume if !reflect.DeepEqual(newpvc, newpvcInfo.pvc()) { t.Errorf("new pvc changed: %v", diff.ObjectReflectDiff(newpvc, newpvcInfo.pvc())) } case newpvcHasVolumeMode: // new pvc should be changed if reflect.DeepEqual(newpvc, newpvcInfo.pvc()) { t.Errorf("new pvc was not changed") } // new pvc should not have BlockVolume if !reflect.DeepEqual(newpvc, pvcWithoutVolumeMode()) { t.Errorf("new pvc had pvcBlockVolume: %v", diff.ObjectReflectDiff(newpvc, pvcWithoutVolumeMode())) } default: // new pvc should not need to be changed if !reflect.DeepEqual(newpvc, newpvcInfo.pvc()) { t.Errorf("new pvc changed: %v", diff.ObjectReflectDiff(newpvc, newpvcInfo.pvc())) } } }) } } } } func TestDropDisabledSnapshotDataSource(t *testing.T) { pvcWithoutDataSource := func() *core.PersistentVolumeClaim { return &core.PersistentVolumeClaim{ Spec: core.PersistentVolumeClaimSpec{ DataSource: nil, }, } } apiGroup := "snapshot.storage.k8s.io" pvcWithDataSource := func() *core.PersistentVolumeClaim { return &core.PersistentVolumeClaim{ Spec: core.PersistentVolumeClaimSpec{ DataSource: &core.TypedLocalObjectReference{ APIGroup: &apiGroup, Kind: "VolumeSnapshot", Name: "test_snapshot", }, }, } } pvcInfo := []struct { description string hasDataSource bool pvc func() *core.PersistentVolumeClaim }{ { description: "pvc without DataSource", hasDataSource: false, pvc: pvcWithoutDataSource, }, { description: "pvc with DataSource", hasDataSource: true, pvc: pvcWithDataSource, }, { description: "is nil", hasDataSource: false, pvc: func() *core.PersistentVolumeClaim { return nil }, }, } for _, enabled := range []bool{true, false} { for _, oldpvcInfo := range pvcInfo { for _, newpvcInfo := range pvcInfo { oldPvcHasDataSource, oldpvc := oldpvcInfo.hasDataSource, oldpvcInfo.pvc() newPvcHasDataSource, newpvc := newpvcInfo.hasDataSource, newpvcInfo.pvc() if newpvc == nil { continue } t.Run(fmt.Sprintf("feature enabled=%v, old pvc %v, new pvc %v", enabled, oldpvcInfo.description, newpvcInfo.description), func(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.VolumeSnapshotDataSource, enabled)() var oldpvcSpec *core.PersistentVolumeClaimSpec if oldpvc != nil { oldpvcSpec = &oldpvc.Spec } DropDisabledFields(&newpvc.Spec, oldpvcSpec) // old pvc should never be changed if !reflect.DeepEqual(oldpvc, oldpvcInfo.pvc()) { t.Errorf("old pvc changed: %v", diff.ObjectReflectDiff(oldpvc, oldpvcInfo.pvc())) } switch { case enabled || oldPvcHasDataSource: // new pvc should not be changed if the feature is enabled, or if the old pvc had DataSource if !reflect.DeepEqual(newpvc, newpvcInfo.pvc()) { t.Errorf("new pvc changed: %v", diff.ObjectReflectDiff(newpvc, newpvcInfo.pvc())) } case newPvcHasDataSource: // new pvc should be changed if reflect.DeepEqual(newpvc, newpvcInfo.pvc()) { t.Errorf("new pvc was not changed") } // new pvc should not have DataSource if !reflect.DeepEqual(newpvc, pvcWithoutDataSource()) { t.Errorf("new pvc had DataSource: %v", diff.ObjectReflectDiff(newpvc, pvcWithoutDataSource())) } default: // new pvc should not need to be changed if !reflect.DeepEqual(newpvc, newpvcInfo.pvc()) { t.Errorf("new pvc changed: %v", diff.ObjectReflectDiff(newpvc, newpvcInfo.pvc())) } } }) } } } } // TestPVCDataSourceSpecFilter checks to ensure the DropDisabledFields function behaves correctly for PVCDataSource featuregate func TestPVCDataSourceSpecFilter(t *testing.T) { apiGroup := "" validSpec := core.PersistentVolumeClaimSpec{ DataSource: &core.TypedLocalObjectReference{ APIGroup: &apiGroup, Kind: "PersistentVolumeClaim", Name: "test_clone", }, } validSpecNilAPIGroup := core.PersistentVolumeClaimSpec{ DataSource: &core.TypedLocalObjectReference{ Kind: "PersistentVolumeClaim", Name: "test_clone", }, } invalidAPIGroup := "invalid.pvc.api.group" invalidSpec := core.PersistentVolumeClaimSpec{ DataSource: &core.TypedLocalObjectReference{ APIGroup: &invalidAPIGroup, Kind: "PersistentVolumeClaim", Name: "test_clone_invalid", }, } var tests = map[string]struct { spec core.PersistentVolumeClaimSpec gateEnabled bool want *core.TypedLocalObjectReference }{ "enabled with empty ds": { spec: core.PersistentVolumeClaimSpec{}, gateEnabled: true, want: nil, }, "enabled with invalid spec": { spec: invalidSpec, gateEnabled: true, want: nil, }, "enabled with valid spec": { spec: validSpec, gateEnabled: true, want: validSpec.DataSource, }, "disabled with invalid spec": { spec: invalidSpec, gateEnabled: false, want: nil, }, "disabled with valid spec": { spec: validSpec, gateEnabled: false, want: nil, }, "diabled with empty ds": { spec: core.PersistentVolumeClaimSpec{}, gateEnabled: false, want: nil, }, "enabled with valid spec but nil APIGroup": { spec: validSpecNilAPIGroup, gateEnabled: true, want: validSpecNilAPIGroup.DataSource, }, "disabled with valid spec but nil APIGroup": { spec: validSpecNilAPIGroup, gateEnabled: false, want: nil, }, } for testName, test := range tests { t.Run(testName, func(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.VolumePVCDataSource, test.gateEnabled)() DropDisabledFields(&test.spec, nil) if test.spec.DataSource != test.want { t.Errorf("expected drop datasource condition was not met, test: %s, gateEnabled: %v, spec: %v, expected: %v", testName, test.gateEnabled, test.spec, test.want) } }) } }
apache-2.0
blindroot/django
django/contrib/staticfiles/management/commands/collectstatic.py
14419
from __future__ import unicode_literals import os from collections import OrderedDict from django.apps import apps from django.contrib.staticfiles.finders import get_finders from django.contrib.staticfiles.storage import staticfiles_storage from django.core.files.storage import FileSystemStorage from django.core.management.base import BaseCommand, CommandError from django.core.management.color import no_style from django.utils.encoding import smart_text from django.utils.functional import cached_property from django.utils.six.moves import input class Command(BaseCommand): """ Command that allows to copy or symlink static files from different locations to the settings.STATIC_ROOT. """ help = "Collect static files in a single location." requires_system_checks = False def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) self.copied_files = [] self.symlinked_files = [] self.unmodified_files = [] self.post_processed_files = [] self.storage = staticfiles_storage self.style = no_style() @cached_property def local(self): try: self.storage.path('') except NotImplementedError: return False return True def add_arguments(self, parser): parser.add_argument( '--noinput', '--no-input', action='store_false', dest='interactive', default=True, help="Do NOT prompt the user for input of any kind.", ) parser.add_argument( '--no-post-process', action='store_false', dest='post_process', default=True, help="Do NOT post process collected files.", ) parser.add_argument( '-i', '--ignore', action='append', default=[], dest='ignore_patterns', metavar='PATTERN', help="Ignore files or directories matching this glob-style " "pattern. Use multiple times to ignore more.", ) parser.add_argument( '-n', '--dry-run', action='store_true', dest='dry_run', default=False, help="Do everything except modify the filesystem.", ) parser.add_argument( '-c', '--clear', action='store_true', dest='clear', default=False, help="Clear the existing files using the storage " "before trying to copy or link the original file.", ) parser.add_argument( '-l', '--link', action='store_true', dest='link', default=False, help="Create a symbolic link to each file instead of copying.", ) parser.add_argument( '--no-default-ignore', action='store_false', dest='use_default_ignore_patterns', default=True, help="Don't ignore the common private glob-style patterns (defaults to 'CVS', '.*' and '*~').", ) def set_options(self, **options): """ Set instance variables based on an options dict """ self.interactive = options['interactive'] self.verbosity = options['verbosity'] self.symlink = options['link'] self.clear = options['clear'] self.dry_run = options['dry_run'] ignore_patterns = options['ignore_patterns'] if options['use_default_ignore_patterns']: ignore_patterns += apps.get_app_config('staticfiles').ignore_patterns self.ignore_patterns = list(set(ignore_patterns)) self.post_process = options['post_process'] def collect(self): """ Perform the bulk of the work of collectstatic. Split off from handle() to facilitate testing. """ if self.symlink and not self.local: raise CommandError("Can't symlink to a remote destination.") if self.clear: self.clear_dir('') if self.symlink: handler = self.link_file else: handler = self.copy_file found_files = OrderedDict() for finder in get_finders(): for path, storage in finder.list(self.ignore_patterns): # Prefix the relative path if the source storage contains it if getattr(storage, 'prefix', None): prefixed_path = os.path.join(storage.prefix, path) else: prefixed_path = path if prefixed_path not in found_files: found_files[prefixed_path] = (storage, path) handler(path, prefixed_path, storage) else: self.log( "Found another file with the destination path '%s'. It " "will be ignored since only the first encountered file " "is collected. If this is not what you want, make sure " "every static file has a unique path." % prefixed_path, level=1, ) # Here we check if the storage backend has a post_process # method and pass it the list of modified files. if self.post_process and hasattr(self.storage, 'post_process'): processor = self.storage.post_process(found_files, dry_run=self.dry_run) for original_path, processed_path, processed in processor: if isinstance(processed, Exception): self.stderr.write("Post-processing '%s' failed!" % original_path) # Add a blank line before the traceback, otherwise it's # too easy to miss the relevant part of the error message. self.stderr.write("") raise processed if processed: self.log("Post-processed '%s' as '%s'" % (original_path, processed_path), level=1) self.post_processed_files.append(original_path) else: self.log("Skipped post-processing '%s'" % original_path) return { 'modified': self.copied_files + self.symlinked_files, 'unmodified': self.unmodified_files, 'post_processed': self.post_processed_files, } def handle(self, **options): self.set_options(**options) message = ['\n'] if self.dry_run: message.append( 'You have activated the --dry-run option so no files will be modified.\n\n' ) message.append( 'You have requested to collect static files at the destination\n' 'location as specified in your settings' ) if self.is_local_storage() and self.storage.location: destination_path = self.storage.location message.append(':\n\n %s\n\n' % destination_path) else: destination_path = None message.append('.\n\n') if self.clear: message.append('This will DELETE ALL FILES in this location!\n') else: message.append('This will overwrite existing files!\n') message.append( 'Are you sure you want to do this?\n\n' "Type 'yes' to continue, or 'no' to cancel: " ) if self.interactive and input(''.join(message)) != 'yes': raise CommandError("Collecting static files cancelled.") collected = self.collect() modified_count = len(collected['modified']) unmodified_count = len(collected['unmodified']) post_processed_count = len(collected['post_processed']) if self.verbosity >= 1: template = ("\n%(modified_count)s %(identifier)s %(action)s" "%(destination)s%(unmodified)s%(post_processed)s.\n") summary = template % { 'modified_count': modified_count, 'identifier': 'static file' + ('' if modified_count == 1 else 's'), 'action': 'symlinked' if self.symlink else 'copied', 'destination': (" to '%s'" % destination_path if destination_path else ''), 'unmodified': (', %s unmodified' % unmodified_count if collected['unmodified'] else ''), 'post_processed': (collected['post_processed'] and ', %s post-processed' % post_processed_count or ''), } return summary def log(self, msg, level=2): """ Small log helper """ if self.verbosity >= level: self.stdout.write(msg) def is_local_storage(self): return isinstance(self.storage, FileSystemStorage) def clear_dir(self, path): """ Deletes the given relative path using the destination storage backend. """ if not self.storage.exists(path): return dirs, files = self.storage.listdir(path) for f in files: fpath = os.path.join(path, f) if self.dry_run: self.log("Pretending to delete '%s'" % smart_text(fpath), level=1) else: self.log("Deleting '%s'" % smart_text(fpath), level=1) try: full_path = self.storage.path(fpath) except NotImplementedError: self.storage.delete(fpath) else: if not os.path.exists(full_path) and os.path.lexists(full_path): # Delete broken symlinks os.unlink(full_path) else: self.storage.delete(fpath) for d in dirs: self.clear_dir(os.path.join(path, d)) def delete_file(self, path, prefixed_path, source_storage): """ Checks if the target file should be deleted if it already exists """ if self.storage.exists(prefixed_path): try: # When was the target file modified last time? target_last_modified = self.storage.get_modified_time(prefixed_path) except (OSError, NotImplementedError, AttributeError): # The storage doesn't support get_modified_time() or failed pass else: try: # When was the source file modified last time? source_last_modified = source_storage.get_modified_time(path) except (OSError, NotImplementedError, AttributeError): pass else: # The full path of the target file if self.local: full_path = self.storage.path(prefixed_path) else: full_path = None # Skip the file if the source file is younger # Avoid sub-second precision (see #14665, #19540) if (target_last_modified.replace(microsecond=0) >= source_last_modified.replace(microsecond=0) and full_path and not (self.symlink ^ os.path.islink(full_path))): if prefixed_path not in self.unmodified_files: self.unmodified_files.append(prefixed_path) self.log("Skipping '%s' (not modified)" % path) return False # Then delete the existing file if really needed if self.dry_run: self.log("Pretending to delete '%s'" % path) else: self.log("Deleting '%s'" % path) self.storage.delete(prefixed_path) return True def link_file(self, path, prefixed_path, source_storage): """ Attempt to link ``path`` """ # Skip this file if it was already copied earlier if prefixed_path in self.symlinked_files: return self.log("Skipping '%s' (already linked earlier)" % path) # Delete the target file if needed or break if not self.delete_file(path, prefixed_path, source_storage): return # The full path of the source file source_path = source_storage.path(path) # Finally link the file if self.dry_run: self.log("Pretending to link '%s'" % source_path, level=1) else: self.log("Linking '%s'" % source_path, level=1) full_path = self.storage.path(prefixed_path) try: os.makedirs(os.path.dirname(full_path)) except OSError: pass try: if os.path.lexists(full_path): os.unlink(full_path) os.symlink(source_path, full_path) except AttributeError: import platform raise CommandError("Symlinking is not supported by Python %s." % platform.python_version()) except NotImplementedError: import platform raise CommandError("Symlinking is not supported in this " "platform (%s)." % platform.platform()) except OSError as e: raise CommandError(e) if prefixed_path not in self.symlinked_files: self.symlinked_files.append(prefixed_path) def copy_file(self, path, prefixed_path, source_storage): """ Attempt to copy ``path`` with storage """ # Skip this file if it was already copied earlier if prefixed_path in self.copied_files: return self.log("Skipping '%s' (already copied earlier)" % path) # Delete the target file if needed or break if not self.delete_file(path, prefixed_path, source_storage): return # The full path of the source file source_path = source_storage.path(path) # Finally start copying if self.dry_run: self.log("Pretending to copy '%s'" % source_path, level=1) else: self.log("Copying '%s'" % source_path, level=1) with source_storage.open(path) as source_file: self.storage.save(prefixed_path, source_file) self.copied_files.append(prefixed_path)
bsd-3-clause
grshane/monthofmud
web/themes/custom/mom/node_modules/phpjs/tools/oldcode/pj_generator.php
24472
<?php require_once "inc/const.inc.php"; require_once "inc/db.inc.php"; require_once "inc/blog.inc.php"; require_once "inc/blog.functions.inc.php"; require_once "inc/class.JavaScriptPacker.php"; require_once "inc/jsmin-1.1.0.php"; require_once "pj_func.inc.php"; // security if( !in_array($_SERVER["REMOTE_ADDR"], $admin_ips) ){ die("no access for: ". $_SERVER["REMOTE_ADDR"]); } echo "<xmp>"; list($codefiles, $codefiles_InProgress, $authors) = indexCode($codedir); /****************************************************************************** *** compile thanksto html ******************************************************************************/ $thanks_to = array(); foreach($authors as $author=>$funcs){ $thanks_to[count($funcs)][$author] = $funcs; // sort by authorname ksort($thanks_to[count($funcs)]); } // sort by number of contributions krsort($thanks_to); $html_thanksto = ""; $html_thanksto .= "\n<h3>Credits</h3>\n"; $html_thanksto .= "<p>"; $html_thanksto .= "Respect &amp; awards go to everybody who has contributed in some way so far: <br />"; $html_thanksto .= "</p>"; //$html_thanksto .= "<p>"; $html_thanksto .= "<div style=\"width:100%; overflow: scroll; overflow-y: scroll; overflow-x: hidden; height:500px;\"><table style=\"width:100%;\">"; $cnt = 0; $all_authors = array(); foreach($thanks_to as $medals=>$authors){ foreach($authors as $author=>$functions){ if($author == "Kevin van Zonneveld (http://kevin.vanzonneveld.net)") continue; $cnt++; $all_authors[] = $author; $medal_pic = determineMedal($medals); if($cnt == 1) $highest_medal = $medal_pic; // author layout $parts = explode("(", $author); if(count($parts) == 1 || !trim(reset($parts))){ // one part if(substr($author,0,1)=="("){ // just a URL $author = str_replace( array("(",")"), "", $author); } else{ // just an author $author = "<strong>".$author."</strong>"; } } else{ // more parts $author = "<strong>".array_shift($parts)."</strong>(".implode("(", $parts); } // linkable $author = ereg_replace("[a-zA-Z]+://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "<a href=\"\\0\">link</a>", $author); // add html if($old_medal != $medal_pic && $old_medal == $highest_medal){ // extra space to divide gold medals $html_thanksto .= "<tr>"; $html_thanksto .= "<td colspan=\"2\">"; $html_thanksto .= "&nbsp;"; $html_thanksto .= "</td>"; $html_thanksto .= "</tr>"; } $html_thanksto .= "<tr>"; $html_thanksto .= "<td style=\"text-align:right;width:40px;white-space:nowrap;\">"; if($cnt == 1){ // extra medal $html_thanksto .= "<img src=\"/images/famsilk/".$medal_pic."\" class=\"icon\" alt=\"medal\" />"; } else{ $html_thanksto .= "<img src=\"/images/spacer.gif\" class=\"icon\" alt=\"space\" />"; } $html_thanksto .= "<img src=\"/images/famsilk/".$medal_pic."\" class=\"icon\" alt=\"medal\" />"; $html_thanksto .= "</td>"; $html_thanksto .= "<td style=\"padding-left:3px;width:99%;\">"; $html_thanksto .= $author." for contributing to: <br />"."\n"; $html_thanksto .= "</td>"; $html_thanksto .= "</tr>"; $html_thanksto .= "<tr>"; $html_thanksto .= "<td>"; $html_thanksto .= "&nbsp;"; $html_thanksto .= "</td>"; $html_thanksto .= "<td style=\"padding-left:5px;\">"; $html_thanksto .= ""; foreach($functions as $function){ $html_thanksto .= "<a href=\"/techblog/article/javascript_equivalent_for_phps_".$function."/\">".$function."</a>, "."\n"; } $html_thanksto = substr($html_thanksto,0,strlen($html_thanksto)-3); $html_thanksto .= "</td>"; $html_thanksto .= "</tr>"; $old_medal = $medal_pic; } } $html_thanksto .= "</table></div>"; //$html_thanksto .= "</p>\n"; $html_thanksto .= "\n<h4>Your name here?</h4>\n"; $html_thanksto .= "<p>Contributing is as <b>easy</b> as <a href=\"#add_comment\">adding a comment</a> with better code, or code for a new function. <br />"; $html_thanksto .= "Any contribution leading to improvement will directly get your name &amp; link here.\n"; $html_thanksto .= "</p>\n"; /****************************************************************************** *** compile download html ******************************************************************************/ // link to php.js $html_download = ""; $html_download .= "\n<h3>Download php.js</h3>\n"; $html_download .= "<p>"; $html_download .= "To easily include it in your code, every function currently available is stored in "; $html_download .= "</p>"; $html_download .= "<p>"; $html_download .= "<b>Normal</b>"; $html_download .= "</p>"; $html_download .= "\n<ul>"; $recommended = "php.min.js"; foreach(array( "uncompressed source"=>"php.js", "minified"=>"php.min.js", "compressed"=>"php.packed.js" ) as $descr=>$phpjsfile){ $size = round(filesize($codedir."/".$phpjsfile)/1000, 1)."kB"; $html_download .= "\n<li>"; $html_download .= $descr.": <a href=\"/code/php_equivalents/".$phpjsfile."\">".$phpjsfile."</a> (".$size.")"; if ($recommended == $phpjsfile) { $html_download .= " <strong>[recommended]</strong>"; } $html_download .= "</li>"; } $html_download .= "</ul>"; $html_download .= "<p>"; $html_download .= "<b>Namespaced</b> "; $html_download .= "<a href=\"http://kevin.vanzonneveld.net/techblog/article/phpjs_namespaced/\">What is 'namespaced?'</a>"; $html_download .= "</p>"; $html_download .= "\n<ul>"; foreach(array( "uncompressed source"=>"php.namespaced.js", "minified"=>"php.namespaced.min.js", "compressed"=>"php.namespaced.packed.js" ) as $descr=>$phpjsfile){ $size = round(filesize($codedir."/".$phpjsfile)/1000, 1)."kB"; $html_download .= "\n<li>"; $html_download .= $descr.": <a href=\"/code/php_equivalents/".$phpjsfile."\">".$phpjsfile."</a> (".$size.")"; $html_download .= "</li>"; } $html_download .= "</ul>"; $html_download .= "<p>"; $html_download .= "To download use Right click, Save Link As<br />"; $html_download .= "Generally the <a href=\"http://www.julienlecomte.net/blog/2007/08/13/\">best way</a> is to use a minified version and <a href=\"http://kevin.vanzonneveld.net/techblog/article/better_performance_with_mod_deflate/\">gzip it</a><br />"; $html_download .= "<br />"; $html_download .= "</p>"; /****************************************************************************** *** compile tester html ******************************************************************************/ $html_tester = ""; $html_tester .= "\n<h3>Testing the functions</h3>\n"; $html_tester .= "<p>"; $html_tester .= "The number of functions is growing fast and so it becomes hard to "; $html_tester .= "<strong>maintain quality</strong>."; $html_tester .= "</p>"; $html_tester .= "<p>"; $html_tester .= "To defeat that danger of bad code, syntax errors, etc, I've added "; $html_tester .= "a new feature: <strong><a href=\"http://kevin.vanzonneveld.net/pj_tester.php\">php.js tester</a></strong>."; $html_tester .= "</p>"; $html_tester .= "<p>"; $html_tester .= "It is an automatically generated page that includes ALL functions in your browser, and then "; $html_tester .= "extracts specific testing information from each function's comments. "; $html_tester .= "This info is then used to run the function, and the return value is compared to a "; $html_tester .= "predefined one."; $html_tester .= "</p>"; /* $html_tester .= "<p>"; $html_tester .= "This way code is always checked on syntax errors, and if it doesn't function correctly anymore "; $html_tester .= "after an update, we should also be able to detect it more easily."; $html_tester .= "</p>"; */ $html_tester .= "<p>"; $html_tester .= "If you want, <strong><a href=\"http://kevin.vanzonneveld.net/pj_tester.php\">go check it out</a></strong>."; $html_tester .= "</p>"; /****************************************************************************** *** compile under cunstruction html ******************************************************************************/ $html_construction = ""; if(count($codefiles_InProgress)){ $html_construction .= "\n<h3>Under Construction</h3>\n"; $html_construction .= "<p>"; $html_construction .= "To avoid duplicate effort as <a href=\"/techblog/article/javascript_equivalent_for_phps_str_pad/#comment_723\">suggested by Aaron Saray</a>, "; $html_construction .= "here is a list of functions that I am currently working on: \n"; $html_construction .= "</p>"; $html_construction .= "<ul>"; foreach($codefiles_InProgress as $func_InProgress=>$codefile_InProgress){ $html_construction .= "<li>"; $html_construction .= $func_InProgress."() <a title=\"Goto PHP Function manual\" href=\"http://www.php.net/".$func_InProgress."\">&raquo;</a>"; $html_construction .= "</li>"; } $html_construction .= "</ul>"; $html_construction .= "<p>"; $html_construction .= "If you would like to provide another function, or improve the current one, <a href=\"#add_comment\">leave a comment</a>!"; $html_construction .= "</p>"; } $html_construction .= "\n<h3>Coming Project features</h3>\n"; $html_construction .= "<p>"; $html_construction .= "Project features that we are currently working on: \n"; $html_construction .= "</p>"; $html_construction .= "<ul>"; $html_construction .= "<li>"; $html_construction .= "<strong>Versioning</strong>. Individual functions are versioned, but the entire library should be versioned as well."; $html_construction .= "</li>"; $html_construction .= "<li>"; $html_construction .= "<strong>Light</strong>. A lightweight version of php.js should be made available with only common functions in it."; $html_construction .= "</li>"; $html_construction .= "<li>"; $html_construction .= "<strong>Site</strong>. A place for PHP.JS of it's own. You can track our lame attempts at phpjs.org (not hyperlinked deliberately). If there are any CakePHP developers out there who would like to contribute, contact me."; $html_construction .= "</li>"; $html_construction .= "<li>"; $html_construction .= "<strong>Testsuite</strong>. A better test-suite that can be ran locally so developers can easily test before commiting. Also the testing itself should be more thorough."; $html_construction .= "</li>"; $html_construction .= "</ul>"; /****************************************************************************** *** update database ******************************************************************************/ $total_code = ""; $namespaced_code = ""; foreach($codefiles as $func=>$codefile){ $info = array(); $save = array(); $html = ""; // get php manual + function code list($manual, $descr1, $descrF, $syntax) = ($ret = getParseManual($func, $codefiles)); if($manual === false){ foreach($ret as $output){ if(substr_count($output, "#!#!#!#!#")){ echo "\n>>getParseManual Error: ".$output."\n"; } } } // get dependencies $func_deps = parseFuncDependencies($func, $codefile); // get dependencies $func_examples = parseFuncExamples($func, $codefile); // add header & description description $html .= "<p>This is a Javascript version of the PHP function: <a href=\"http://www.php.net/".$func."\">".$func."</a>.</p>\n"; $html .= "\n<h2>PHP ".$func."</h2>\n"; $html .= "\n<h3>Description</h3>\n"; if($descr1 && !substr_count($descr1, "#!#!#!#!#")) $html .= "<p>".$descr1."</p>\n"; if($manual && $syntax && !substr_count($syntax, "#!#!#!#!#")) $html .= "<pre>".$syntax."</pre>\n"; if($manual && $descrF && !substr_count($descrF, "#!#!#!#!#")) $html .= "<p>".$descrF."</p>\n"; // add manual if($manual) { $html .= $manual; } else{ #$html .= "Currently there is no proper function documentation available. <br />"; $html .= ""; } $html .= "\n<h2>Javascript ".$func."</h2>\n"; // add function source $html .= "\n<h3>Source</h3>\n"; $html .= "<p>This is the main source of the Javascript version of PHP's ".$func."</p>"; $html .= "<pre>&lt;?Javascript ".$codefile."?&gt;</pre>\n"; // add function dependencies if(count($func_deps)){ $html .= "<p>To run the Javascript ".$func.", you will also need the following dependencies:</p>"; //$html .= "<h3>Dependencies</h3>\n<ul>"; $html .= "<ul>"; foreach($func_deps as $func_dep){ $html .= "<li><a href=\"/techblog/article/javascript_equivalent_for_phps_".$func_dep."/\">".$func_dep."</a></li>\n"; } $html .= "</ul>"; } // add function examples $max_site_examples = 3; $cnt = 0; if(count($func_examples)){ $html .= "\n<h3>Examples</h3>\n"; if(count($func_examples)==1){ $html .= "<p>Currently there is 1 example</p>"; } else{ $html .= "<p>Currently there are ".count($func_examples)." examples</p>"; } foreach($func_examples as $test_number=>$tests){ $html .= "\n<h4>Example $test_number</h4>\n"; $html .= "<div style=\"padding-left:10px;margin-top:10px;\">"; /* if(($tests["returns"]=="0" || strlen(trim($tests["returns"])>0)) && $tests["returns"] != "null"){ $html .= "This is how you could call ".$func."()<br />"; $html .= highlight_js($tests["example"], 400, "margin-left:10px;"); $html .= "And that would return<br />"; $html .= highlight_js(stripslashes($tests["returns"]), 400, "margin-left:10px;"); } else{ $html .= "This is how you call ".$func."<br />"; $html .= highlight_js($tests["example"], 400, "margin-left:10px;"); }*/ $html .= "This is how you could call ".$func."()<br />"; $html .= highlight_js($tests["example"], 400, "margin-left:10px;"); $html .= "And that would return<br />"; $html .= highlight_js($tests["returns"], 400, "margin-left:10px;"); $html .= "</div>"; $cnt++; if($cnt >= $max_site_examples){ break; } } } $html .= "<br />\n<h2>More about this Project</h2>\n"; // add download $html .= "\n\n"; $html .= "<!-- download -->"; $html .= "\n\n"; $html .= $html_download; // add tester $html .= "<br />"; $html .= "\n\n"; $html .= "<!-- tester -->"; $html .= "\n\n"; $html .= "<br />"; $html .= $html_tester; // add thanks to header $html .= "\n\n"; $html .= "<!-- thanks to header -->"; $html .= "\n\n"; $html .= "<br />"; $html .= $html_thanksto; // add under construction $html .= "\n\n"; $html .= "<!-- under construction -->"; $html .= "\n\n"; $html .= "<br />"; $html .= $html_construction; // database fields $info["site_id"] = 2; $info["publish"] = 'yes'; $info["expires"] = 'no'; $info["user_id"] = 1; $info["category_id"] = 13; $info["expire"] = '0000-00-00'; $info["title"] = "Javascript equivalent for PHP's ".$func; $info["title_url"] = "javascript_equivalent_for_phps_".$func; $info["article"] = $html; $info["article_preview"] = extractArticlePreview($info["article"]); // add to php.js $total_code .= addCodeFunction($func, $codefile, $descr1); if($func == "define"){ $namespaced_code .= "\n// define() is not available in the namespaced version of php.js\n"; } else{ $function_last = (end($codefiles) == $codefile); $namespaced_code .= namespaceFunction(addCodeFunction($func, $codefile, $descr1), $function_last); } // sanitize foreach($info as $k=>$v){ $info[$k] = addslashes($v); } // update || insert echo $info["title_url"]." (".$descr1.")"; list($num, $res) = queryS("SELECT `article_id` FROM `article` WHERE `title_url`='".$info["title_url"]."'"); if($num){ $mode = "update"; $row = mysql_fetch_assoc($res); $save["article"] = $info["article"]; $sqle = updateSql($row["article_id"], $save, "article", "article_id"); echo "exists. updating... "; } else{ $mode = "insert"; $save = $info; $sqle = insertSql($save, "article"); echo "does not exist. inserting... "; } // report if(!queryE($sqle)){ echo "fail\n"; } else{ echo "sucess\n"; if($mode=="insert" && $article_id=mysql_insert_id()){ $tags = array("programming", "php", "javascript", "phpjs"); foreach($tags as $k=>$tag_raw){ $tag = substr(addslashes(preg_replace('/[^A-z0-9_\s]/', '', trim( preg_replace('/([\s][\s]*)/'," ", $tag_raw) ))),0,50); if(!trim($tag))continue; $tag_id = addTag($tag); // add article tag combination queryE(" INSERT INTO `".$tbl_article_tag."` SET `".$tbl_article."_id` = ".$article_id.", `".$tbl_tag."_id` = ".$tag_id.", `".$tbl_site."_id` = ".$info["site_id"]." "); } } } flush(); } /****************************************************************************** *** save php.js ******************************************************************************/ $copyright_portions = " * Portions copyright ".implode(", ", $all_authors); $copyright_portions = wordwrap( $copyright_portions, 75, "\n * ", false); // Determine version $version_file = dirname(__FILE__)."/pj_vers.dat"; $osource = file_get_contents($codedir."/php.js"); $nsource = $total_code; $overs = versionGet($version_file); $nvers = versionUpgrade($overs, $osource, $nsource); //echo $overs."\n"; //echo $nvers."\n"; versionPut($version_file, $nvers); $hvers = versionFormat($nvers); //echo $nvers."\n"; // Copyright Banner $copyright = ""; $copyright .= "/* \n"; $copyright .= " * More info at: http://kevin.vanzonneveld.net/techblog/article/phpjs_licensing/\n"; $copyright .= " * \n"; $copyright .= " * This is version: ".$hvers."\n"; $copyright .= " * php.js is copyright 2008 Kevin van Zonneveld.\n"; $copyright .= " * \n"; $copyright .= $copyright_portions."\n"; $copyright .= " * \n"; $copyright .= " * Dual licensed under the MIT (MIT-LICENSE.txt)\n"; $copyright .= " * and GPL (GPL-LICENSE.txt) licenses.\n"; $copyright .= " * \n"; $copyright .= " * Permission is hereby granted, free of charge, to any person obtaining a\n"; $copyright .= " * copy of this software and associated documentation files (the\n"; $copyright .= " * \"Software\"), to deal in the Software without restriction, including\n"; $copyright .= " * without limitation the rights to use, copy, modify, merge, publish,\n"; $copyright .= " * distribute, sublicense, and/or sell copies of the Software, and to\n"; $copyright .= " * permit persons to whom the Software is furnished to do so, subject to\n"; $copyright .= " * the following conditions:\n"; $copyright .= " * \n"; $copyright .= " * The above copyright notice and this permission notice shall be included\n"; $copyright .= " * in all copies or substantial portions of the Software.\n"; $copyright .= " * \n"; $copyright .= " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n"; $copyright .= " * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n"; $copyright .= " * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n"; $copyright .= " * IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES\n"; $copyright .= " * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n"; $copyright .= " * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n"; $copyright .= " * OTHER DEALINGS IN THE SOFTWARE.\n"; $copyright .= " */ \n"; $copyright .= "\n"; // Original echo "writing ".$codedir."/php.js...\n"; file_put_contents($codedir."/php.js", $copyright.$total_code); echo "writing ".$codedir."/php.namespaced.js...\n"; $namespaced_code = surroundNamespaced($namespaced_code); file_put_contents($codedir."/php.namespaced.js", "".$copyright.$namespaced_code); // Packer echo "writing ".$codedir."/php.packed.js...\n"; $myPacker = new JavaScriptPacker($total_code, 'Normal', true, false); $total_code_packed = $myPacker->pack(); file_put_contents($codedir."/php.packed.js", $copyright.$total_code_packed); echo "writing ".$codedir."/php.namespaced.packed.js...\n"; $myPacker = new JavaScriptPacker($namespaced_code, 'Normal', true, false); $total_code_packed = $myPacker->pack(); file_put_contents($codedir."/php.namespaced.packed.js", $copyright.$total_code_packed); // JSMIN echo "writing ".$codedir."/php.min.js...\n"; $total_code_min = JSMin::minify($total_code); file_put_contents($codedir."/php.min.js", $copyright.$total_code_min); echo "writing ".$codedir."/php.namespaced.min.js...\n"; $total_code_min = JSMin::minify($namespaced_code); file_put_contents($codedir."/php.namespaced.min.js", $copyright.$total_code_min); /* // Packer With newlines echo "writing ".$codedir."/php.packed.newline.js...\n"; $myPacker = new JavaScriptPacker($total_code, 'None', true, false); $total_code_packed = str_replace("function ", "\nfunction ", $myPacker->pack()); //$total_code_packed = str_replace("}", "}\n", $total_code_packed); file_put_contents($codedir."/php.packed.newline.js", $copyright.$total_code_packed); */ /****************************************************************************** *** save RSS ******************************************************************************/ echo "saving rss...\n"; saveXMLFeed(); echo "</xmp>"; ?>
mit
teohhanhui/symfony
src/Symfony/Component/Form/FormEvents.php
3436
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form; /** * To learn more about how form events work check the documentation * entry at {@link https://symfony.com/doc/any/components/form/form_events.html}. * * To learn how to dynamically modify forms using events check the cookbook * entry at {@link https://symfony.com/doc/any/cookbook/form/dynamic_form_modification.html}. * * @author Bernhard Schussek <bschussek@gmail.com> */ final class FormEvents { /** * The PRE_SUBMIT event is dispatched at the beginning of the Form::submit() method. * * It can be used to: * - Change data from the request, before submitting the data to the form. * - Add or remove form fields, before submitting the data to the form. * * @Event("Symfony\Component\Form\Event\PreSubmitEvent") */ const PRE_SUBMIT = 'form.pre_submit'; /** * The SUBMIT event is dispatched after the Form::submit() method * has changed the view data by the request data, or submitted and mapped * the children if the form is compound, and after reverse transformation * to normalized representation. * * It's also dispatched just before the Form::submit() method transforms back * the normalized data to the model and view data. * * So at this stage children of compound forms are submitted and synchronized, unless * their transformation failed, but a parent would still be at the PRE_SUBMIT level. * * Since the current form is not synchronized yet, it is still possible to add and * remove fields. * * @Event("Symfony\Component\Form\Event\SubmitEvent") */ const SUBMIT = 'form.submit'; /** * The FormEvents::POST_SUBMIT event is dispatched at the very end of the Form::submit(). * * It this stage the model and view data may have been denormalized. Otherwise the form * is desynchronized because transformation failed during submission. * * It can be used to fetch data after denormalization. * * The event attaches the current view data. To know whether this is the renormalized data * or the invalid request data, call Form::isSynchronized() first. * * @Event("Symfony\Component\Form\Event\PostSubmitEvent") */ const POST_SUBMIT = 'form.post_submit'; /** * The FormEvents::PRE_SET_DATA event is dispatched at the beginning of the Form::setData() method. * * It can be used to: * - Modify the data given during pre-population; * - Keep synchronized the form depending on the data (adding or removing fields dynamically). * * @Event("Symfony\Component\Form\Event\PreSetDataEvent") */ const PRE_SET_DATA = 'form.pre_set_data'; /** * The FormEvents::POST_SET_DATA event is dispatched at the end of the Form::setData() method. * * This event can be used to modify the form depending on the final state of the underlying data * accessible in every representation: model, normalized and view. * * @Event("Symfony\Component\Form\Event\PostSetDataEvent") */ const POST_SET_DATA = 'form.post_set_data'; private function __construct() { } }
mit
saurabh6790/omnisys-lib
webnotes/memc.py
739
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import memcache from webnotes import conf class MClient(memcache.Client): """memcache client that will automatically prefix conf.db_name""" def n(self, key): return (conf.db_name + ":" + key.replace(" ", "_")).encode('utf-8') def set_value(self, key, val): self.set(self.n(key), val) def get_value(self, key, builder=None): if builder and conf.get("auto_cache_clear") or False: return builder() val = self.get(self.n(key)) if not val and builder: val = builder() self.set_value(key, val) return val def delete_value(self, key): self.delete(self.n(key))
mit
koic/rails
railties/test/railties/generators_test.rb
3955
RAILS_ISOLATED_ENGINE = true require "isolation/abstract_unit" require "generators/generators_test_helper" require "rails/generators/test_case" module RailtiesTests class GeneratorTest < Rails::Generators::TestCase include ActiveSupport::Testing::Isolation def destination_root tmp_path "foo_bar" end def tmp_path(*args) @tmp_path ||= File.realpath(Dir.mktmpdir) File.join(@tmp_path, *args) end def engine_path tmp_path("foo_bar") end def bundled_rails(cmd) `bundle exec rails #{cmd}` end def rails(cmd) `#{Gem.ruby} #{RAILS_FRAMEWORK_ROOT}/railties/exe/rails #{cmd}` end def build_engine(is_mountable = false) FileUtils.rm_rf(engine_path) FileUtils.mkdir_p(engine_path) mountable = is_mountable ? "--mountable" : "" rails("plugin new #{engine_path} --full #{mountable}") Dir.chdir(engine_path) do File.open("Gemfile", "w") do |f| f.write <<-GEMFILE.gsub(/^ {12}/, "") source "https://rubygems.org" gem 'rails', path: '#{RAILS_FRAMEWORK_ROOT}' gem 'sqlite3' GEMFILE end end end def build_mountable_engine build_engine(true) end def test_controllers_are_correctly_namespaced_when_engine_is_mountable build_mountable_engine Dir.chdir(engine_path) do bundled_rails("g controller topics") assert_file "app/controllers/foo_bar/topics_controller.rb", /module FooBar\n class TopicsController/ assert_no_file "app/controllers/topics_controller.rb" end end def test_models_are_correctly_namespaced_when_engine_is_mountable build_mountable_engine Dir.chdir(engine_path) do bundled_rails("g model topic") assert_file "app/models/foo_bar/topic.rb", /module FooBar\n class Topic/ assert_no_file "app/models/topic.rb" end end def test_table_name_prefix_is_correctly_namespaced_when_engine_is_mountable build_mountable_engine Dir.chdir(engine_path) do bundled_rails("g model namespaced/topic") assert_file "app/models/foo_bar/namespaced.rb", /module FooBar\n module Namespaced/ do |content| assert_class_method :table_name_prefix, content do |method_content| assert_match(/'foo_bar_namespaced_'/, method_content) end end end end def test_helpers_are_correctly_namespaced_when_engine_is_mountable build_mountable_engine Dir.chdir(engine_path) do bundled_rails("g helper topics") assert_file "app/helpers/foo_bar/topics_helper.rb", /module FooBar\n module TopicsHelper/ assert_no_file "app/helpers/topics_helper.rb" end end def test_controllers_are_not_namespaced_when_engine_is_not_mountable build_engine Dir.chdir(engine_path) do bundled_rails("g controller topics") assert_file "app/controllers/topics_controller.rb", /class TopicsController/ assert_no_file "app/controllers/foo_bar/topics_controller.rb" end end def test_models_are_not_namespaced_when_engine_is_not_mountable build_engine Dir.chdir(engine_path) do bundled_rails("g model topic") assert_file "app/models/topic.rb", /class Topic/ assert_no_file "app/models/foo_bar/topic.rb" end end def test_helpers_are_not_namespaced_when_engine_is_not_mountable build_engine Dir.chdir(engine_path) do bundled_rails("g helper topics") assert_file "app/helpers/topics_helper.rb", /module TopicsHelper/ assert_no_file "app/helpers/foo_bar/topics_helper.rb" end end def test_assert_file_with_special_characters path = "#{app_path}/tmp" file_name = "#{path}/v0.1.4~alpha+nightly" FileUtils.mkdir_p path FileUtils.touch file_name assert_file file_name end end end
mit
relipo/xbmc
xbmc/filesystem/test/TestRarFile.cpp
24910
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "system.h" #ifdef HAS_FILESYSTEM_RAR #include "filesystem/Directory.h" #include "filesystem/File.h" #include "filesystem/RarManager.h" #include "URL.h" #include "utils/URIUtils.h" #include "FileItem.h" #include "test/TestUtils.h" #include "utils/StringUtils.h" #include <errno.h> #include "gtest/gtest.h" #ifndef S_IFLNK #define S_IFLNK 0120000 #endif TEST(TestRarFile, Read) { XFILE::CFile file; char buf[20]; memset(&buf, 0, sizeof(buf)); std::string reffile, strpathinrar; CFileItemList itemlist; reffile = XBMC_REF_FILE_PATH("xbmc/filesystem/test/reffile.txt.rar"); CURL rarUrl = URIUtils::CreateArchivePath("rar", CURL(reffile), ""); ASSERT_TRUE(XFILE::CDirectory::GetDirectory(rarUrl, itemlist, "", XFILE::DIR_FLAG_NO_FILE_DIRS)); strpathinrar = itemlist[0]->GetPath(); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(0, file.GetPosition()); EXPECT_EQ(1616, file.GetLength()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_TRUE(file.ReadString(buf, sizeof(buf))); EXPECT_EQ(39, file.GetPosition()); EXPECT_STREQ("an award-winning fr", buf); EXPECT_EQ(100, file.Seek(100)); EXPECT_EQ(100, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(120, file.GetPosition()); EXPECT_TRUE(!memcmp("ent hub for digital ", buf, sizeof(buf) - 1)); EXPECT_EQ(220, file.Seek(100, SEEK_CUR)); EXPECT_EQ(220, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(240, file.GetPosition()); EXPECT_TRUE(!memcmp("rs, XBMC is a non-pr", buf, sizeof(buf) - 1)); EXPECT_EQ(1596, file.Seek(-(int64_t)sizeof(buf), SEEK_END)); EXPECT_EQ(1596, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(1616, file.GetPosition()); EXPECT_TRUE(!memcmp("multimedia jukebox.\n", buf, sizeof(buf) - 1)); EXPECT_EQ(1716, file.Seek(100, SEEK_CUR)); EXPECT_EQ(1716, file.GetPosition()); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(-1, file.Seek(-100, SEEK_SET)); // Manual clear to avoid shutdown race g_RarManager.ClearCache(); file.Close(); } TEST(TestRarFile, Exists) { std::string reffile, strpathinrar; CFileItemList itemlist; reffile = XBMC_REF_FILE_PATH("xbmc/filesystem/test/reffile.txt.rar"); CURL rarUrl = URIUtils::CreateArchivePath("rar", CURL(reffile), ""); ASSERT_TRUE(XFILE::CDirectory::GetDirectory(rarUrl, itemlist, "", XFILE::DIR_FLAG_NO_FILE_DIRS)); strpathinrar = itemlist[0]->GetPath(); EXPECT_TRUE(XFILE::CFile::Exists(strpathinrar)); // Manual clear to avoid shutdown race g_RarManager.ClearCache(); } TEST(TestRarFile, Stat) { struct __stat64 buffer; std::string reffile, strpathinrar; CFileItemList itemlist; reffile = XBMC_REF_FILE_PATH("xbmc/filesystem/test/reffile.txt.rar"); CURL rarUrl = URIUtils::CreateArchivePath("rar", CURL(reffile), ""); ASSERT_TRUE(XFILE::CDirectory::GetDirectory(rarUrl, itemlist, "", XFILE::DIR_FLAG_NO_FILE_DIRS)); strpathinrar = itemlist[0]->GetPath(); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &buffer)); EXPECT_TRUE(buffer.st_mode | _S_IFREG); // Manual clear to avoid shutdown race g_RarManager.ClearCache(); } /* Test case to test for graceful handling of corrupted input. * NOTE: The test case is considered a "success" as long as the corrupted * file was successfully generated and the test case runs without a segfault. */ TEST(TestRarFile, CorruptedFile) { XFILE::CFile *file; char buf[16]; memset(&buf, 0, sizeof(buf)); std::string reffilepath, strpathinrar, str; CFileItemList itemlist; unsigned int size, i; int64_t count = 0; reffilepath = XBMC_REF_FILE_PATH("xbmc/filesystem/test/reffile.txt.rar"); ASSERT_TRUE((file = XBMC_CREATECORRUPTEDFILE(reffilepath, ".rar")) != NULL); std::cout << "Reference file generated at '" << XBMC_TEMPFILEPATH(file) << "'" << std::endl; CURL rarUrl = URIUtils::CreateArchivePath("rar", CURL(XBMC_TEMPFILEPATH(file)), ""); if (!XFILE::CDirectory::GetDirectory(rarUrl, itemlist, "", XFILE::DIR_FLAG_NO_FILE_DIRS)) { XBMC_DELETETEMPFILE(file); SUCCEED(); return; } if (itemlist.IsEmpty()) { XBMC_DELETETEMPFILE(file); SUCCEED(); return; } strpathinrar = itemlist[0]->GetPath(); if (!file->Open(strpathinrar)) { XBMC_DELETETEMPFILE(file); SUCCEED(); return; } std::cout << "file->GetLength(): " << testing::PrintToString(file->GetLength()) << std::endl; std::cout << "file->Seek(file->GetLength() / 2, SEEK_CUR) return value: " << testing::PrintToString(file->Seek(file->GetLength() / 2, SEEK_CUR)) << std::endl; std::cout << "file->Seek(0, SEEK_END) return value: " << testing::PrintToString(file->Seek(0, SEEK_END)) << std::endl; std::cout << "file->Seek(0, SEEK_SET) return value: " << testing::PrintToString(file->Seek(0, SEEK_SET)) << std::endl; std::cout << "File contents:" << std::endl; while ((size = file->Read(buf, sizeof(buf))) > 0) { str = StringUtils::Format(" %08llX", count); std::cout << str << " "; count += size; for (i = 0; i < size; i++) { str = StringUtils::Format("%02X ", buf[i]); std::cout << str; } while (i++ < sizeof(buf)) std::cout << " "; std::cout << " ["; for (i = 0; i < size; i++) { if (buf[i] >= ' ' && buf[i] <= '~') std::cout << buf[i]; else std::cout << "."; } std::cout << "]" << std::endl; } file->Close(); XBMC_DELETETEMPFILE(file); // Manual clear to avoid shutdown race g_RarManager.ClearCache(); } TEST(TestRarFile, StoredRAR) { XFILE::CFile file; char buf[20]; memset(&buf, 0, sizeof(buf)); std::string reffile, strpathinrar; CFileItemList itemlist, itemlistemptydir; struct __stat64 stat_buffer; reffile = XBMC_REF_FILE_PATH("xbmc/filesystem/test/refRARstored.rar"); CURL rarUrl = URIUtils::CreateArchivePath("rar", CURL(reffile), ""); ASSERT_TRUE(XFILE::CDirectory::GetDirectory(rarUrl, itemlist)); itemlist.Sort(SortByPath, SortOrderAscending); /* /reffile.txt */ /* * NOTE: Use of Seek gives inconsistent behavior from when seeking through * an uncompressed RAR archive. See TestRarFile.Read test case. */ strpathinrar = itemlist[1]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/reffile.txt")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFREG); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(0, file.GetPosition()); EXPECT_EQ(1616, file.GetLength()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_TRUE(file.ReadString(buf, sizeof(buf))); EXPECT_EQ(39, file.GetPosition()); EXPECT_STREQ("an award-winning fr", buf); EXPECT_EQ(100, file.Seek(100)); EXPECT_EQ(100, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(120, file.GetPosition()); EXPECT_TRUE(!memcmp("ent hub for digital ", buf, sizeof(buf) - 1)); EXPECT_EQ(220, file.Seek(100, SEEK_CUR)); EXPECT_EQ(220, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(240, file.GetPosition()); EXPECT_TRUE(!memcmp("rs, XBMC is a non-pr", buf, sizeof(buf) - 1)); EXPECT_EQ(1596, file.Seek(-(int64_t)sizeof(buf), SEEK_END)); EXPECT_EQ(1596, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(1616, file.GetPosition()); EXPECT_TRUE(!memcmp("multimedia jukebox.\n", buf, sizeof(buf) - 1)); EXPECT_EQ(-1, file.Seek(100, SEEK_CUR)); EXPECT_EQ(1616, file.GetPosition()); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(-100, file.Seek(-100, SEEK_SET)); file.Close(); /* /testsymlink -> testdir/reffile.txt */ strpathinrar = itemlist[2]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testsymlink")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFLNK); /* * FIXME: Reading symlinks in RARs is currently broken. It takes a long time * to read them and they produce erroneous results. The expected result is * the target paths of the symlinks. */ ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(19, file.GetLength()); file.Close(); /* /testsymlinksubdir -> testdir/testsubdir/reffile.txt */ strpathinrar = itemlist[3]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testsymlinksubdir")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFLNK); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(30, file.GetLength()); file.Close(); /* /testdir/ */ strpathinrar = itemlist[0]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFDIR); itemlist.Clear(); ASSERT_TRUE(XFILE::CDirectory::GetDirectory(strpathinrar, itemlist)); itemlist.Sort(SortByPath, SortOrderAscending); /* /testdir/reffile.txt */ strpathinrar = itemlist[1]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/reffile.txt")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFREG); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(0, file.GetPosition()); EXPECT_EQ(1616, file.GetLength()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_TRUE(file.ReadString(buf, sizeof(buf))); EXPECT_EQ(39, file.GetPosition()); EXPECT_STREQ("an award-winning fr", buf); EXPECT_EQ(100, file.Seek(100)); EXPECT_EQ(100, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(120, file.GetPosition()); EXPECT_TRUE(!memcmp("ent hub for digital ", buf, sizeof(buf) - 1)); EXPECT_EQ(220, file.Seek(100, SEEK_CUR)); EXPECT_EQ(220, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(240, file.GetPosition()); EXPECT_TRUE(!memcmp("rs, XBMC is a non-pr", buf, sizeof(buf) - 1)); EXPECT_EQ(1596, file.Seek(-(int64_t)sizeof(buf), SEEK_END)); EXPECT_EQ(1596, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(1616, file.GetPosition()); EXPECT_TRUE(!memcmp("multimedia jukebox.\n", buf, sizeof(buf) - 1)); EXPECT_EQ(-1, file.Seek(100, SEEK_CUR)); EXPECT_EQ(1616, file.GetPosition()); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(-100, file.Seek(-100, SEEK_SET)); file.Close(); /* /testdir/testemptysubdir */ strpathinrar = itemlist[2]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/testemptysubdir")); //! @todo Should this set the itemlist to an empty list instead? EXPECT_FALSE(XFILE::CDirectory::GetDirectory(strpathinrar, itemlistemptydir)); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFDIR); //! @todo FIXME: This directory appears a second time as a file strpathinrar = itemlist[3]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/testsubdir")); /* /testdir/testsymlink -> testsubdir/reffile.txt */ strpathinrar = itemlist[4]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/testsymlink")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFLNK); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(22, file.GetLength()); file.Close(); /* /testdir/testsubdir/ */ strpathinrar = itemlist[0]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/testsubdir/")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFDIR); itemlist.Clear(); ASSERT_TRUE(XFILE::CDirectory::GetDirectory(strpathinrar, itemlist)); itemlist.Sort(SortByPath, SortOrderAscending); /* /testdir/testsubdir/reffile.txt */ strpathinrar = itemlist[0]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/testsubdir/reffile.txt")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFREG); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(0, file.GetPosition()); EXPECT_EQ(1616, file.GetLength()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_TRUE(file.ReadString(buf, sizeof(buf))); EXPECT_EQ(39, file.GetPosition()); EXPECT_STREQ("an award-winning fr", buf); EXPECT_EQ(100, file.Seek(100)); EXPECT_EQ(100, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(120, file.GetPosition()); EXPECT_TRUE(!memcmp("ent hub for digital ", buf, sizeof(buf) - 1)); EXPECT_EQ(220, file.Seek(100, SEEK_CUR)); EXPECT_EQ(220, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(240, file.GetPosition()); EXPECT_TRUE(!memcmp("rs, XBMC is a non-pr", buf, sizeof(buf) - 1)); EXPECT_EQ(1596, file.Seek(-(int64_t)sizeof(buf), SEEK_END)); EXPECT_EQ(1596, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(1616, file.GetPosition()); EXPECT_TRUE(!memcmp("multimedia jukebox.\n", buf, sizeof(buf) - 1)); EXPECT_EQ(-1, file.Seek(100, SEEK_CUR)); EXPECT_EQ(1616, file.GetPosition()); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(-100, file.Seek(-100, SEEK_SET)); file.Close(); } TEST(TestRarFile, NormalRAR) { XFILE::CFile file; char buf[20]; memset(&buf, 0, sizeof(buf)); std::string reffile, strpathinrar; CFileItemList itemlist, itemlistemptydir; struct __stat64 stat_buffer; reffile = XBMC_REF_FILE_PATH("xbmc/filesystem/test/refRARnormal.rar"); CURL rarUrl = URIUtils::CreateArchivePath("rar", CURL(reffile), ""); ASSERT_TRUE(XFILE::CDirectory::GetDirectory(rarUrl, itemlist)); itemlist.Sort(SortByPath, SortOrderAscending); /* /reffile.txt */ strpathinrar = itemlist[1]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/reffile.txt")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFREG); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(0, file.GetPosition()); EXPECT_EQ(1616, file.GetLength()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_TRUE(file.ReadString(buf, sizeof(buf))); EXPECT_EQ(39, file.GetPosition()); EXPECT_STREQ("an award-winning fr", buf); EXPECT_EQ(100, file.Seek(100)); EXPECT_EQ(100, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(120, file.GetPosition()); EXPECT_TRUE(!memcmp("ent hub for digital ", buf, sizeof(buf) - 1)); EXPECT_EQ(220, file.Seek(100, SEEK_CUR)); EXPECT_EQ(220, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(240, file.GetPosition()); EXPECT_TRUE(!memcmp("rs, XBMC is a non-pr", buf, sizeof(buf) - 1)); EXPECT_EQ(1596, file.Seek(-(int64_t)sizeof(buf), SEEK_END)); EXPECT_EQ(1596, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(1616, file.GetPosition()); EXPECT_TRUE(!memcmp("multimedia jukebox.\n", buf, sizeof(buf) - 1)); EXPECT_EQ(1716, file.Seek(100, SEEK_CUR)); EXPECT_EQ(1716, file.GetPosition()); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(-1, file.Seek(-100, SEEK_SET)); file.Close(); /* /testsymlink -> testdir/reffile.txt */ strpathinrar = itemlist[2]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testsymlink")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFLNK); /* * FIXME: Reading symlinks in RARs is currently broken. It takes a long time * to read them and they produce erroneous results. The expected result is * the target paths of the symlinks. */ ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(19, file.GetLength()); file.Close(); /* /testsymlinksubdir -> testdir/testsubdir/reffile.txt */ strpathinrar = itemlist[3]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testsymlinksubdir")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFLNK); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(30, file.GetLength()); file.Close(); /* /testdir/ */ strpathinrar = itemlist[0]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFDIR); itemlist.Clear(); ASSERT_TRUE(XFILE::CDirectory::GetDirectory(strpathinrar, itemlist)); itemlist.Sort(SortByPath, SortOrderAscending); /* /testdir/reffile.txt */ strpathinrar = itemlist[1]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/reffile.txt")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFREG); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(0, file.GetPosition()); EXPECT_EQ(1616, file.GetLength()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_TRUE(file.ReadString(buf, sizeof(buf))); EXPECT_EQ(39, file.GetPosition()); EXPECT_STREQ("an award-winning fr", buf); EXPECT_EQ(100, file.Seek(100)); EXPECT_EQ(100, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(120, file.GetPosition()); EXPECT_TRUE(!memcmp("ent hub for digital ", buf, sizeof(buf) - 1)); EXPECT_EQ(220, file.Seek(100, SEEK_CUR)); EXPECT_EQ(220, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(240, file.GetPosition()); EXPECT_TRUE(!memcmp("rs, XBMC is a non-pr", buf, sizeof(buf) - 1)); EXPECT_EQ(1596, file.Seek(-(int64_t)sizeof(buf), SEEK_END)); EXPECT_EQ(1596, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(1616, file.GetPosition()); EXPECT_TRUE(!memcmp("multimedia jukebox.\n", buf, sizeof(buf) - 1)); EXPECT_EQ(1716, file.Seek(100, SEEK_CUR)); EXPECT_EQ(1716, file.GetPosition()); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(-1, file.Seek(-100, SEEK_SET)); file.Close(); /* /testdir/testemptysubdir */ strpathinrar = itemlist[2]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/testemptysubdir")); /* @todo Should this set the itemlist to an empty list instead? */ EXPECT_FALSE(XFILE::CDirectory::GetDirectory(strpathinrar, itemlistemptydir)); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFDIR); /* FIXME: This directory appears a second time as a file */ strpathinrar = itemlist[3]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/testsubdir")); /* /testdir/testsymlink -> testsubdir/reffile.txt */ strpathinrar = itemlist[4]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/testsymlink")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFLNK); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(22, file.GetLength()); file.Close(); /* /testdir/testsubdir/ */ strpathinrar = itemlist[0]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/testsubdir/")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFDIR); itemlist.Clear(); ASSERT_TRUE(XFILE::CDirectory::GetDirectory(strpathinrar, itemlist)); itemlist.Sort(SortByPath, SortOrderAscending); /* /testdir/testsubdir/reffile.txt */ strpathinrar = itemlist[0]->GetPath(); ASSERT_TRUE(StringUtils::EndsWith(strpathinrar, "/testdir/testsubdir/reffile.txt")); EXPECT_EQ(0, XFILE::CFile::Stat(strpathinrar, &stat_buffer)); EXPECT_TRUE((stat_buffer.st_mode & S_IFMT) | S_IFREG); ASSERT_TRUE(file.Open(strpathinrar)); EXPECT_EQ(0, file.GetPosition()); EXPECT_EQ(1616, file.GetLength()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_TRUE(file.ReadString(buf, sizeof(buf))); EXPECT_EQ(39, file.GetPosition()); EXPECT_STREQ("an award-winning fr", buf); EXPECT_EQ(100, file.Seek(100)); EXPECT_EQ(100, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(120, file.GetPosition()); EXPECT_TRUE(!memcmp("ent hub for digital ", buf, sizeof(buf) - 1)); EXPECT_EQ(220, file.Seek(100, SEEK_CUR)); EXPECT_EQ(220, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(240, file.GetPosition()); EXPECT_TRUE(!memcmp("rs, XBMC is a non-pr", buf, sizeof(buf) - 1)); EXPECT_EQ(1596, file.Seek(-(int64_t)sizeof(buf), SEEK_END)); EXPECT_EQ(1596, file.GetPosition()); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(1616, file.GetPosition()); EXPECT_TRUE(!memcmp("multimedia jukebox.\n", buf, sizeof(buf) - 1)); EXPECT_EQ(1716, file.Seek(100, SEEK_CUR)); EXPECT_EQ(1716, file.GetPosition()); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(sizeof(buf), file.Read(buf, sizeof(buf))); file.Flush(); EXPECT_EQ(20, file.GetPosition()); EXPECT_TRUE(!memcmp("About\n-----\nXBMC is ", buf, sizeof(buf) - 1)); EXPECT_EQ(0, file.Seek(0, SEEK_SET)); EXPECT_EQ(-1, file.Seek(-100, SEEK_SET)); file.Close(); // Manual clear to avoid shutdown race g_RarManager.ClearCache(); } #endif /*HAS_FILESYSTEM_RAR*/
gpl-2.0
omni86/ServUO-Test
Scripts/Mobiles/AI/BerserkAI.cs
2765
using System; namespace Server.Mobiles { public class BerserkAI : BaseAI { public BerserkAI(BaseCreature m) : base(m) { } public override bool DoActionWander() { this.m_Mobile.DebugSay("I have No Combatant"); if (this.AcquireFocusMob(this.m_Mobile.RangePerception, FightMode.Closest, false, true, true)) { if (this.m_Mobile.Debug) this.m_Mobile.DebugSay("I have detected " + this.m_Mobile.FocusMob.Name + " and I will attack"); this.m_Mobile.Combatant = this.m_Mobile.FocusMob; this.Action = ActionType.Combat; } else { base.DoActionWander(); } return true; } public override bool DoActionCombat() { if (this.m_Mobile.Combatant == null || this.m_Mobile.Combatant.Deleted) { this.m_Mobile.DebugSay("My combatant is deleted"); this.Action = ActionType.Guard; return true; } if (this.WalkMobileRange(this.m_Mobile.Combatant, 1, true, this.m_Mobile.RangeFight, this.m_Mobile.RangeFight)) { // Be sure to face the combatant this.m_Mobile.Direction = this.m_Mobile.GetDirectionTo(this.m_Mobile.Combatant.Location); } else { if (this.m_Mobile.Combatant != null) { if (this.m_Mobile.Debug) this.m_Mobile.DebugSay("I am still not in range of " + this.m_Mobile.Combatant.Name); if ((int)this.m_Mobile.GetDistanceToSqrt(this.m_Mobile.Combatant) > this.m_Mobile.RangePerception + 1) { if (this.m_Mobile.Debug) this.m_Mobile.DebugSay("I have lost " + this.m_Mobile.Combatant.Name); this.Action = ActionType.Guard; return true; } } } return true; } public override bool DoActionGuard() { if (this.AcquireFocusMob(this.m_Mobile.RangePerception, this.m_Mobile.FightMode, false, true, true)) { if (this.m_Mobile.Debug) this.m_Mobile.DebugSay("I have detected {0}, attacking", this.m_Mobile.FocusMob.Name); this.m_Mobile.Combatant = this.m_Mobile.FocusMob; this.Action = ActionType.Combat; } else { base.DoActionGuard(); } return true; } } }
gpl-2.0
Poppin-Tech/mitro
browser-ext/third_party/firefox-addon-sdk/lib/sdk/test/harness.js
18056
/* 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/. */ "use strict"; module.metadata = { "stability": "experimental" }; const { Cc, Ci, Cu } = require("chrome"); const { Loader } = require('./loader'); const { serializeStack, parseStack } = require("toolkit/loader"); const { setTimeout } = require('../timers'); const { PlainTextConsole } = require("../console/plain-text"); const { when: unload } = require("../system/unload"); const { format, fromException } = require("../console/traceback"); const system = require("../system"); const memory = require('../deprecated/memory'); const { gc: gcPromise } = require('./memory'); const { defer } = require('../core/promise'); // Trick manifest builder to make it think we need these modules ? const unit = require("../deprecated/unit-test"); const test = require("../../test"); const url = require("../url"); function emptyPromise() { let { promise, resolve } = defer(); resolve(); return promise; } var cService = Cc['@mozilla.org/consoleservice;1'].getService() .QueryInterface(Ci.nsIConsoleService); // The console used to log messages var testConsole; // Cuddlefish loader in which we load and execute tests. var loader; // Function to call when we're done running tests. var onDone; // Function to print text to a console, w/o CR at the end. var print; // How many more times to run all tests. var iterationsLeft; // Whether to report memory profiling information. var profileMemory; // Whether we should stop as soon as a test reports a failure. var stopOnError; // Function to call to retrieve a list of tests to execute var findAndRunTests; // Combined information from all test runs. var results = { passed: 0, failed: 0, testRuns: [] }; // A list of the compartments and windows loaded after startup var startLeaks; // JSON serialization of last memory usage stats; we keep it stringified // so we don't actually change the memory usage stats (in terms of objects) // of the JSRuntime we're profiling. var lastMemoryUsage; function analyzeRawProfilingData(data) { var graph = data.graph; var shapes = {}; // Convert keys in the graph from strings to ints. // TODO: Can we get rid of this ridiculousness? var newGraph = {}; for (id in graph) { newGraph[parseInt(id)] = graph[id]; } graph = newGraph; var modules = 0; var moduleIds = []; var moduleObjs = {UNKNOWN: 0}; for (let name in data.namedObjects) { moduleObjs[name] = 0; moduleIds[data.namedObjects[name]] = name; modules++; } var count = 0; for (id in graph) { var parent = graph[id].parent; while (parent) { if (parent in moduleIds) { var name = moduleIds[parent]; moduleObjs[name]++; break; } if (!(parent in graph)) { moduleObjs.UNKNOWN++; break; } parent = graph[parent].parent; } count++; } print("\nobject count is " + count + " in " + modules + " modules" + " (" + data.totalObjectCount + " across entire JS runtime)\n"); if (lastMemoryUsage) { var last = JSON.parse(lastMemoryUsage); var diff = { moduleObjs: dictDiff(last.moduleObjs, moduleObjs), totalObjectClasses: dictDiff(last.totalObjectClasses, data.totalObjectClasses) }; for (let name in diff.moduleObjs) print(" " + diff.moduleObjs[name] + " in " + name + "\n"); for (let name in diff.totalObjectClasses) print(" " + diff.totalObjectClasses[name] + " instances of " + name + "\n"); } lastMemoryUsage = JSON.stringify( {moduleObjs: moduleObjs, totalObjectClasses: data.totalObjectClasses} ); } function dictDiff(last, curr) { var diff = {}; for (let name in last) { var result = (curr[name] || 0) - last[name]; if (result) diff[name] = (result > 0 ? "+" : "") + result; } for (let name in curr) { var result = curr[name] - (last[name] || 0); if (result) diff[name] = (result > 0 ? "+" : "") + result; } return diff; } function reportMemoryUsage() { if (!profileMemory) { return emptyPromise(); } return gcPromise().then((function () { var mgr = Cc["@mozilla.org/memory-reporter-manager;1"] .getService(Ci.nsIMemoryReporterManager); let count = 0; function logReporter(process, path, kind, units, amount, description) { print(((++count == 1) ? "\n" : "") + description + ": " + amount + "\n"); } mgr.getReportsForThisProcess(logReporter, null); var weakrefs = [info.weakref.get() for each (info in memory.getObjects())]; weakrefs = [weakref for each (weakref in weakrefs) if (weakref)]; print("Tracked memory objects in testing sandbox: " + weakrefs.length + "\n"); })); } var gWeakrefInfo; function checkMemory() { return gcPromise().then(_ => { let leaks = getPotentialLeaks(); let compartmentURLs = Object.keys(leaks.compartments).filter(function(url) { return !(url in startLeaks.compartments); }); let windowURLs = Object.keys(leaks.windows).filter(function(url) { return !(url in startLeaks.windows); }); for (let url of compartmentURLs) console.warn("LEAKED", leaks.compartments[url]); for (let url of windowURLs) console.warn("LEAKED", leaks.windows[url]); }).then(showResults); } function showResults() { let { promise, resolve } = defer(); if (gWeakrefInfo) { gWeakrefInfo.forEach( function(info) { var ref = info.weakref.get(); if (ref !== null) { var data = ref.__url__ ? ref.__url__ : ref; var warning = data == "[object Object]" ? "[object " + data.constructor.name + "(" + [p for (p in data)].join(", ") + ")]" : data; console.warn("LEAK", warning, info.bin); } } ); } onDone(results); resolve(); return promise; } function cleanup() { let coverObject = {}; try { for (let name in loader.modules) memory.track(loader.modules[name], "module global scope: " + name); memory.track(loader, "Cuddlefish Loader"); if (profileMemory) { gWeakrefInfo = [{ weakref: info.weakref, bin: info.bin } for each (info in memory.getObjects())]; } loader.unload(); if (loader.globals.console.errorsLogged && !results.failed) { results.failed++; console.error("warnings and/or errors were logged."); } if (consoleListener.errorsLogged && !results.failed) { console.warn(consoleListener.errorsLogged + " " + "warnings or errors were logged to the " + "platform's nsIConsoleService, which could " + "be of no consequence; however, they could also " + "be indicative of aberrant behavior."); } // read the code coverage object, if it exists, from CoverJS-moz if (typeof loader.globals.global == "object") { coverObject = loader.globals.global['__$coverObject'] || {}; } consoleListener.errorsLogged = 0; loader = null; memory.gc(); } catch (e) { results.failed++; console.error("unload.send() threw an exception."); console.exception(e); }; setTimeout(require('@test/options').checkMemory ? checkMemory : showResults, 1); // dump the coverobject if (Object.keys(coverObject).length){ const self = require('sdk/self'); const {pathFor} = require("sdk/system"); let file = require('sdk/io/file'); const {env} = require('sdk/system/environment'); console.log("CWD:", env.PWD); let out = file.join(env.PWD,'coverstats-'+self.id+'.json'); console.log('coverstats:', out); let outfh = file.open(out,'w'); outfh.write(JSON.stringify(coverObject,null,2)); outfh.flush(); outfh.close(); } } function getPotentialLeaks() { memory.gc(); // Things we can assume are part of the platform and so aren't leaks let WHITELIST_BASE_URLS = [ "chrome://", "resource:///", "resource://app/", "resource://gre/", "resource://gre-resources/", "resource://pdf.js/", "resource://pdf.js.components/", "resource://services-common/", "resource://services-crypto/", "resource://services-sync/" ]; let ioService = Cc["@mozilla.org/network/io-service;1"]. getService(Ci.nsIIOService); let uri = ioService.newURI("chrome://global/content/", "UTF-8", null); let chromeReg = Cc["@mozilla.org/chrome/chrome-registry;1"]. getService(Ci.nsIChromeRegistry); uri = chromeReg.convertChromeURL(uri); let spec = uri.spec; let pos = spec.indexOf("!/"); WHITELIST_BASE_URLS.push(spec.substring(0, pos + 2)); let zoneRegExp = new RegExp("^explicit/js-non-window/zones/zone[^/]+/compartment\\((.+)\\)"); let compartmentRegexp = new RegExp("^explicit/js-non-window/compartments/non-window-global/compartment\\((.+)\\)/"); let compartmentDetails = new RegExp("^([^,]+)(?:, (.+?))?(?: \\(from: (.*)\\))?$"); let windowRegexp = new RegExp("^explicit/window-objects/top\\((.*)\\)/active"); let windowDetails = new RegExp("^(.*), id=.*$"); function isPossibleLeak(item) { if (!item.location) return false; for (let whitelist of WHITELIST_BASE_URLS) { if (item.location.substring(0, whitelist.length) == whitelist) return false; } return true; } let compartments = {}; let windows = {}; function logReporter(process, path, kind, units, amount, description) { let matches; if ((matches = compartmentRegexp.exec(path)) || (matches = zoneRegExp.exec(path))) { if (matches[1] in compartments) return; let details = compartmentDetails.exec(matches[1]); if (!details) { console.error("Unable to parse compartment detail " + matches[1]); return; } let item = { path: matches[1], principal: details[1], location: details[2] ? details[2].replace("\\", "/", "g") : undefined, source: details[3] ? details[3].split(" -> ").reverse() : undefined, toString: function() this.location }; if (!isPossibleLeak(item)) return; compartments[matches[1]] = item; return; } if (matches = windowRegexp.exec(path)) { if (matches[1] in windows) return; let details = windowDetails.exec(matches[1]); if (!details) { console.error("Unable to parse window detail " + matches[1]); return; } let item = { path: matches[1], location: details[1].replace("\\", "/", "g"), source: [details[1].replace("\\", "/", "g")], toString: function() this.location }; if (!isPossibleLeak(item)) return; windows[matches[1]] = item; } } Cc["@mozilla.org/memory-reporter-manager;1"] .getService(Ci.nsIMemoryReporterManager) .getReportsForThisProcess(logReporter, null); return { compartments: compartments, windows: windows }; } function nextIteration(tests) { if (tests) { results.passed += tests.passed; results.failed += tests.failed; reportMemoryUsage().then(_ => { let testRun = []; for each (let test in tests.testRunSummary) { let testCopy = {}; for (let info in test) { testCopy[info] = test[info]; } testRun.push(testCopy); } results.testRuns.push(testRun); iterationsLeft--; checkForEnd(); }) } else { checkForEnd(); } } function checkForEnd() { if (iterationsLeft && (!stopOnError || results.failed == 0)) { // Pass the loader which has a hooked console that doesn't dispatch // errors to the JS console and avoid firing false alarm in our // console listener findAndRunTests(loader, nextIteration); } else { setTimeout(cleanup, 0); } } var POINTLESS_ERRORS = [ 'Invalid chrome URI:', 'OpenGL LayerManager Initialized Succesfully.', '[JavaScript Error: "TelemetryStopwatch:', 'reference to undefined property', '[JavaScript Error: "The character encoding of the HTML document was ' + 'not declared.', '[Javascript Warning: "Error: Failed to preserve wrapper of wrapped ' + 'native weak map key', '[JavaScript Warning: "Duplicate resource declaration for', 'file: "chrome://browser/content/', 'file: "chrome://global/content/', '[JavaScript Warning: "The character encoding of a framed document was ' + 'not declared.' ]; var consoleListener = { errorsLogged: 0, observe: function(object) { if (!(object instanceof Ci.nsIScriptError)) return; this.errorsLogged++; var message = object.QueryInterface(Ci.nsIConsoleMessage).message; var pointless = [err for each (err in POINTLESS_ERRORS) if (message.indexOf(err) >= 0)]; if (pointless.length == 0 && message) testConsole.log(message); } }; function TestRunnerConsole(base, options) { this.__proto__ = { errorsLogged: 0, warn: function warn() { this.errorsLogged++; base.warn.apply(base, arguments); }, error: function error() { this.errorsLogged++; base.error.apply(base, arguments); }, info: function info(first) { if (options.verbose) base.info.apply(base, arguments); else if (first == "pass:") print("."); }, __proto__: base }; } function stringify(arg) { try { return String(arg); } catch(ex) { return "<toString() error>"; } } function stringifyArgs(args) { return Array.map(args, stringify).join(" "); } function TestRunnerTinderboxConsole(base, options) { this.base = base; this.print = options.print; this.verbose = options.verbose; this.errorsLogged = 0; // Binding all the public methods to an instance so that they can be used // as callback / listener functions straightaway. this.log = this.log.bind(this); this.info = this.info.bind(this); this.warn = this.warn.bind(this); this.error = this.error.bind(this); this.debug = this.debug.bind(this); this.exception = this.exception.bind(this); this.trace = this.trace.bind(this); }; TestRunnerTinderboxConsole.prototype = { testMessage: function testMessage(pass, expected, test, message) { let type = "TEST-"; if (expected) { if (pass) type += "PASS"; else type += "KNOWN-FAIL"; } else { this.errorsLogged++; if (pass) type += "UNEXPECTED-PASS"; else type += "UNEXPECTED-FAIL"; } this.print(type + " | " + test + " | " + message + "\n"); if (!expected) this.trace(); }, log: function log() { this.print("TEST-INFO | " + stringifyArgs(arguments) + "\n"); }, info: function info(first) { this.print("TEST-INFO | " + stringifyArgs(arguments) + "\n"); }, warn: function warn() { this.errorsLogged++; this.print("TEST-UNEXPECTED-FAIL | " + stringifyArgs(arguments) + "\n"); }, error: function error() { this.errorsLogged++; this.print("TEST-UNEXPECTED-FAIL | " + stringifyArgs(arguments) + "\n"); this.base.error.apply(this.base, arguments); }, debug: function debug() { this.print("TEST-INFO | " + stringifyArgs(arguments) + "\n"); }, exception: function exception(e) { this.print("An exception occurred.\n" + require("../console/traceback").format(e) + "\n" + e + "\n"); }, trace: function trace() { var traceback = require("../console/traceback"); var stack = traceback.get(); stack.splice(-1, 1); this.print("TEST-INFO | " + stringify(traceback.format(stack)) + "\n"); } }; var runTests = exports.runTests = function runTests(options) { iterationsLeft = options.iterations; profileMemory = options.profileMemory; stopOnError = options.stopOnError; onDone = options.onDone; print = options.print; findAndRunTests = options.findAndRunTests; try { cService.registerListener(consoleListener); print("Running tests on " + system.name + " " + system.version + "/Gecko " + system.platformVersion + " (" + system.id + ") under " + system.platform + "/" + system.architecture + ".\n"); if (options.parseable) testConsole = new TestRunnerTinderboxConsole(new PlainTextConsole(), options); else testConsole = new TestRunnerConsole(new PlainTextConsole(), options); loader = Loader(module, { console: testConsole, global: {} // useful for storing things like coverage testing. }); // Load these before getting initial leak stats as they will still be in // memory when we check later require("../deprecated/unit-test"); require("../deprecated/unit-test-finder"); startLeaks = getPotentialLeaks(); nextIteration(); } catch (e) { let frames = fromException(e).reverse().reduce(function(frames, frame) { if (frame.fileName.split("/").pop() === "unit-test-finder.js") frames.done = true if (!frames.done) frames.push(frame) return frames }, []) let prototype = typeof(e) === "object" ? e.constructor.prototype : Error.prototype; let stack = serializeStack(frames.reverse()); let error = Object.create(prototype, { message: { value: e.message, writable: true, configurable: true }, fileName: { value: e.fileName, writable: true, configurable: true }, lineNumber: { value: e.lineNumber, writable: true, configurable: true }, stack: { value: stack, writable: true, configurable: true }, toString: { value: function() String(e), writable: true, configurable: true }, }); print("Error: " + error + " \n " + format(error)); onDone({passed: 0, failed: 1}); } }; unload(function() { cService.unregisterListener(consoleListener); });
gpl-3.0
Poppin-Tech/mitro
browser-ext/third_party/firefox-addon-sdk/lib/sdk/test.js
4746
/* 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/. */ "use strict"; module.metadata = { "stability": "unstable" }; const { Cu } = require("chrome"); const { Task } = Cu.import("resource://gre/modules/Task.jsm", {}); const { defer } = require("sdk/core/promise"); const BaseAssert = require("sdk/test/assert").Assert; const { isFunction, isObject } = require("sdk/lang/type"); exports.Assert = BaseAssert; function extend(target) { let descriptor = {} Array.slice(arguments, 1).forEach(function(source) { Object.getOwnPropertyNames(source).forEach(function onEach(name) { descriptor[name] = Object.getOwnPropertyDescriptor(source, name); }); }); return Object.create(target, descriptor); } /** * Function takes test `suite` object in CommonJS format and defines all of the * tests from that suite and nested suites in a jetpack format on a given * `target` object. Optionally third argument `prefix` can be passed to prefix * all the test names. */ function defineTestSuite(target, suite, prefix) { prefix = prefix || ""; // If suite defines `Assert` that's what `assert` object have to be created // from and passed to a test function (This allows custom assertion functions) // See for details: http://wiki.commonjs.org/wiki/Unit_Testing/1.1 let Assert = suite.Assert || BaseAssert; // Going through each item in the test suite and wrapping it into a // Jetpack test format. Object.keys(suite).forEach(function(key) { // If name starts with test then it's a test function or suite. if (key.indexOf("test") === 0) { let test = suite[key]; // For each test function so we create a wrapper test function in a // jetpack format and copy that to a `target` exports. if (isFunction(test)) { // Since names of the test may match across suites we use full object // path as a name to avoid overriding same function. target[prefix + key] = function(options) { // Creating `assert` functions for this test. let assert = Assert(options); assert.end = () => options.done(); // If test function is a generator use a task JS to allow yield-ing // style test runs. if (test.isGenerator && test.isGenerator()) { options.waitUntilDone(); Task.spawn(test.bind(null, assert)). then(null, assert.fail). then(assert.end); } // If CommonJS test function expects more than one argument // it means that test is async and second argument is a callback // to notify that test is finished. else if (1 < test.length) { // Letting test runner know that test is executed async and // creating a callback function that CommonJS tests will call // once it's done. options.waitUntilDone(); test(assert, function() { options.done(); }); } // Otherwise CommonJS test is synchronous so we call it only with // one argument. else { test(assert); } } } // If it's an object then it's a test suite containing test function // and / or nested test suites. In that case we just extend prefix used // and call this function to copy and wrap tests from nested suite. else if (isObject(test)) { // We need to clone `tests` instead of modifying it, since it's very // likely that it is frozen (usually test suites imported modules). test = extend(Object.prototype, test, { Assert: test.Assert || Assert }); defineTestSuite(target, test, prefix + key + "."); } } }); } /** * This function is a CommonJS test runner function, but since Jetpack test * runner and test format is different from CommonJS this function shims given * `exports` with all its tests into a Jetpack test format so that the built-in * test runner will be able to run CommonJS test without manual changes. */ exports.run = function run(exports) { // We can't leave old properties on exports since those are test in a CommonJS // format that why we move everything to a new `suite` object. let suite = {}; Object.keys(exports).forEach(function(key) { suite[key] = exports[key]; delete exports[key]; }); // Now we wrap all the CommonJS tests to a Jetpack format and define // those to a given `exports` object since that where jetpack test runner // will look for them. defineTestSuite(exports, suite); };
gpl-3.0
KadekM/akka.net
src/core/Akka.TestKit/CallingThreadDispatcher.cs
1240
//----------------------------------------------------------------------- // <copyright file="CallingThreadDispatcher.cs" company="Akka.NET Project"> // Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Configuration; using Akka.Dispatch; namespace Akka.TestKit { public class CallingThreadDispatcherConfigurator : MessageDispatcherConfigurator { public CallingThreadDispatcherConfigurator(Config config, IDispatcherPrerequisites prerequisites) : base(config, prerequisites) { } public override MessageDispatcher Dispatcher() { return new CallingThreadDispatcher(this); } } public class CallingThreadDispatcher : MessageDispatcher { public static string Id = "akka.test.calling-thread-dispatcher"; public CallingThreadDispatcher(MessageDispatcherConfigurator configurator) : base(configurator) { } public override void Schedule(Action run) { run(); } } }
apache-2.0
jcouv/roslyn
src/Workspaces/Core/Portable/Rename/ConflictEngine/RelatedLocation.cs
1419
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { /// <summary> /// Gives information about an identifier span that was affected by Rename (Reference or Non reference) /// </summary> internal sealed class RelatedLocation { // The Span of the original identifier if it was in source, otherwise the span to check for implicit references public TextSpan ConflictCheckSpan { get; } public RelatedLocationType Type { get; set; } public bool IsReference { get; } public DocumentId DocumentId { get; } // If there was a conflict at ConflictCheckSpan during rename, then the next phase in rename uses ComplexifiedTargetSpan span to be expanded to resolve the conflict public TextSpan ComplexifiedTargetSpan { get; } public RelatedLocation(TextSpan location, DocumentId documentId, RelatedLocationType type, bool isReference = false, TextSpan complexifiedTargetSpan = default) { this.ConflictCheckSpan = location; this.Type = type; this.IsReference = isReference; this.DocumentId = documentId; this.ComplexifiedTargetSpan = complexifiedTargetSpan; } } }
apache-2.0
TonnyXu/Zxing
cpp/scons/scons-local-2.0.0.final.0/SCons/compat/_scons_collections.py
1869
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # 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. # __doc__ = """ collections compatibility module for older (pre-2.4) Python versions This does not not NOT (repeat, *NOT*) provide complete collections functionality. It only wraps the portions of collections functionality used by SCons, in an interface that looks enough like collections for our purposes. """ __revision__ = "src/engine/SCons/compat/_scons_collections.py 5023 2010/06/14 22:05:46 scons" # Use exec to hide old names from fixers. exec("""if True: from UserDict import UserDict from UserList import UserList from UserString import UserString""") # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
apache-2.0
prop/titanium_mobile
demos/KitchenSink/Resources/examples/coverflow_view.js
1609
var win = Titanium.UI.currentWindow; var images = []; for (var c=0;c<30;c++) { images[c]='../images/imageview/'+c+'.jpg'; } // create coverflow view with images var view = Titanium.UI.iOS.createCoverFlowView({ images:images, backgroundColor:'#000' }); // click listener - when image is clicked view.addEventListener('click',function(e) { Titanium.API.info("image clicked: "+e.index+', selected is '+view.selected); }); // change listener when active image changes view.addEventListener('change',function(e) { Titanium.API.info("image changed: "+e.index+', selected is '+view.selected); }); win.add(view); // change button to dynamically change the image var change = Titanium.UI.createButton({ title:'Change Image', style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED }); change.addEventListener('click',function() { Titanium.API.info("selected is = "+view.selected); view.setImage(view.selected,'../images/imageview/28.jpg'); }); // move scroll view left var left = Titanium.UI.createButton({ image:'../images/icon_arrow_left.png' }); left.addEventListener('click', function(e) { var i = view.selected - 1; if (i < 0) { i = 0; } view.selected = i; }); // move scroll view right var right = Titanium.UI.createButton({ image:'../images/icon_arrow_right.png' }); right.addEventListener('click', function(e) { var i = view.selected + 1; if (i >= images.length) { i = images.length - 1; } view.selected = i; }); var flexSpace = Titanium.UI.createButton({ systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE }); win.setToolbar([flexSpace,left,change,right,flexSpace]);
apache-2.0
matrix-msu/kora
vendor/composer/semver/src/Constraint/AbstractConstraint.php
1646
<?php /* * This file is part of composer/semver. * * (c) Composer <https://github.com/composer> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver\Constraint; trigger_error('The ' . __NAMESPACE__ . '\AbstractConstraint abstract class is deprecated, there is no replacement for it, it will be removed in the next major version.', E_USER_DEPRECATED); /** * Base constraint class. */ abstract class AbstractConstraint implements ConstraintInterface { /** @var string */ protected $prettyString; /** * @param ConstraintInterface $provider * * @return bool */ public function matches(ConstraintInterface $provider) { if ($provider instanceof $this) { // see note at bottom of this class declaration return $this->matchSpecific($provider); } // turn matching around to find a match return $provider->matches($this); } /** * @param string $prettyString */ public function setPrettyString($prettyString) { $this->prettyString = $prettyString; } /** * @return string */ public function getPrettyString() { if ($this->prettyString) { return $this->prettyString; } return $this->__toString(); } // implementations must implement a method of this format: // not declared abstract here because type hinting violates parameter coherence (TODO right word?) // public function matchSpecific(<SpecificConstraintType> $provider); }
gpl-2.0
BackupGGCode/propgcc
gcc/libstdc++-v3/testsuite/25_algorithms/stable_sort/moveable2.cc
1906
// { dg-options "-std=gnu++0x" } // Copyright (C) 2009, 2010 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 25.3.1.2 [lib.stable.sort] #undef _GLIBCXX_CONCEPT_CHECKS // XXX FIXME: parallel-mode should deal correctly with moveable-only types // per C++0x, at minimum smoothly fall back to serial. #undef _GLIBCXX_PARALLEL #include <algorithm> #include <testsuite_hooks.h> #include <testsuite_iterators.h> #include <testsuite_rvalref.h> using __gnu_test::test_container; using __gnu_test::random_access_iterator_wrapper; using __gnu_test::rvalstruct; typedef test_container<rvalstruct, random_access_iterator_wrapper> Container; const int A[] = { 10, 20, 1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16, 7, 17, 8, 18, 9, 19 }; const int N = sizeof(A) / sizeof(int); bool order(const rvalstruct& lhs, const rvalstruct& rhs) { return lhs < rhs; } // 25.3.1.2 stable_sort() void test01() { bool test __attribute__((unused)) = true; rvalstruct s1[N]; std::copy(A, A + N, s1); Container con(s1, s1 + N); std::stable_sort(con.begin(), con.end(), order); VERIFY( s1[0].valid ); for(int i = 1; i < N; ++i) VERIFY( s1[i].val>s1[i-1].val && s1[i].valid ); } int main() { test01(); return 0; }
gpl-3.0
SenshiSentou/SourceFight
slick_dev/tags/Slick0.3/src/org/newdawn/slick/svg/SVGMorph.java
3346
package org.newdawn.slick.svg; import java.util.ArrayList; import org.newdawn.slick.geom.MorphShape; /** * A utility to allow morphing between a set of similar SVG diagrams * * @author kevin */ public class SVGMorph extends Diagram { /** The list of figures being morphed */ private ArrayList figures = new ArrayList(); /** * Create a new morph with a first diagram base * * @param diagram The base diagram which provides the first step of the morph */ public SVGMorph(Diagram diagram) { super(diagram.getWidth(), diagram.getHeight()); for (int i=0;i<diagram.getFigureCount();i++) { Figure figure = diagram.getFigure(i); Figure copy = new Figure(figure.getType(), new MorphShape(figure.getShape()), figure.getData(), figure.getTransform()); figures.add(copy); } } /** * Add a subsquent step to the morphing * * @param diagram The diagram to add as the next step in the morph */ public void addStep(Diagram diagram) { if (diagram.getFigureCount() != figures.size()) { throw new RuntimeException("Mismatched diagrams, missing ids"); } for (int i=0;i<diagram.getFigureCount();i++) { Figure figure = diagram.getFigure(i); String id = figure.getData().getMetaData(); for (int j=0;j<figures.size();j++) { Figure existing = (Figure) figures.get(j); if (existing.getData().getMetaData().equals(id)) { MorphShape morph = (MorphShape) existing.getShape(); morph.addShape(figure.getShape()); break; } } } } /** * Set the current diagram we should morph from. This only really works with * updateMorphTime() but can be used for smooth transitions between * morphs. * * @param diagram The diagram to use as the base of the morph */ public void setExternalDiagram(Diagram diagram) { for (int i=0;i<figures.size();i++) { Figure figure = (Figure) figures.get(i); for (int j=0;j<diagram.getFigureCount();j++) { Figure newBase = diagram.getFigure(j); if (newBase.getData().getMetaData().equals(figure.getData().getMetaData())) { MorphShape shape = (MorphShape) figure.getShape(); shape.setExternalFrame(newBase.getShape()); break; } } } } /** * Update the morph time index by the amount specified * * @param delta The amount to update the morph by */ public void updateMorphTime(float delta) { for (int i=0;i<figures.size();i++) { Figure figure = (Figure) figures.get(i); MorphShape shape = (MorphShape) figure.getShape(); shape.updateMorphTime(delta); } } /** * Set the "time" index for this morph. This is given in terms of diagrams, so * 0.5f would give you the position half way between the first and second diagrams. * * @param time The time index to represent on this diagrams */ public void setMorphTime(float time) { for (int i=0;i<figures.size();i++) { Figure figure = (Figure) figures.get(i); MorphShape shape = (MorphShape) figure.getShape(); shape.setMorphTime(time); } } /** * @see Diagram#getFigureCount() */ public int getFigureCount() { return figures.size(); } /** * @see Diagram#getFigure(int) */ public Figure getFigure(int index) { return (Figure) figures.get(index); } }
bsd-2-clause
anthonygrant/panorama
vendor/zendframework/zendframework/library/Zend/Form/Element/Captcha.php
2813
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Form */ namespace Zend\Form\Element; use Traversable; use Zend\Captcha as ZendCaptcha; use Zend\Form\Element; use Zend\Form\Exception; use Zend\InputFilter\InputProviderInterface; /** * @category Zend * @package Zend_Form * @subpackage Element */ class Captcha extends Element implements InputProviderInterface { /** * @var \Zend\Captcha\AdapterInterface */ protected $captcha; /** * Accepted options for Captcha: * - captcha: a valid Zend\Captcha\AdapterInterface * * @param array|\Traversable $options * @return Captcha */ public function setOptions($options) { parent::setOptions($options); if (isset($options['captcha'])) { $this->setCaptcha($options['captcha']); } return $this; } /** * Set captcha * * @param array|ZendCaptcha\AdapterInterface $captcha * @throws Exception\InvalidArgumentException * @return Captcha */ public function setCaptcha($captcha) { if (is_array($captcha) || $captcha instanceof Traversable) { $captcha = ZendCaptcha\Factory::factory($captcha); } elseif (!$captcha instanceof ZendCaptcha\AdapterInterface) { throw new Exception\InvalidArgumentException(sprintf( '%s expects either a Zend\Captcha\AdapterInterface or specification to pass to Zend\Captcha\Factory; received "%s"', __METHOD__, (is_object($captcha) ? get_class($captcha) : gettype($captcha)) )); } $this->captcha = $captcha; return $this; } /** * Retrieve captcha (if any) * * @return null|ZendCaptcha\AdapterInterface */ public function getCaptcha() { return $this->captcha; } /** * Provide default input rules for this element * * Attaches the captcha as a validator. * * @return array */ public function getInputSpecification() { $spec = array( 'name' => $this->getName(), 'required' => true, 'filters' => array( array('name' => 'Zend\Filter\StringTrim'), ), ); // Test that we have a captcha before adding it to the spec $captcha = $this->getCaptcha(); if ($captcha instanceof ZendCaptcha\AdapterInterface) { $spec['validators'] = array($captcha); } return $spec; } }
bsd-3-clause
LeChuck42/or1k-gcc
libgo/go/time/zoneinfo_plan9.go
3226
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Parse Plan 9 timezone(2) files. package time import ( "errors" "runtime" "syscall" ) func isSpace(r rune) bool { return r == ' ' || r == '\t' || r == '\n' } // Copied from strings to avoid a dependency. func fields(s string) []string { // First count the fields. n := 0 inField := false for _, rune := range s { wasInField := inField inField = !isSpace(rune) if inField && !wasInField { n++ } } // Now create them. a := make([]string, n) na := 0 fieldStart := -1 // Set to -1 when looking for start of field. for i, rune := range s { if isSpace(rune) { if fieldStart >= 0 { a[na] = s[fieldStart:i] na++ fieldStart = -1 } } else if fieldStart == -1 { fieldStart = i } } if fieldStart >= 0 { // Last field might end at EOF. a[na] = s[fieldStart:] } return a } func loadZoneDataPlan9(s string) (l *Location, err error) { f := fields(s) if len(f) < 4 { if len(f) == 2 && f[0] == "GMT" { return UTC, nil } return nil, badData } var zones [2]zone // standard timezone offset o, err := atoi(f[1]) if err != nil { return nil, badData } zones[0] = zone{name: f[0], offset: o, isDST: false} // alternate timezone offset o, err = atoi(f[3]) if err != nil { return nil, badData } zones[1] = zone{name: f[2], offset: o, isDST: true} // transition time pairs var tx []zoneTrans f = f[4:] for i := 0; i < len(f); i++ { zi := 0 if i%2 == 0 { zi = 1 } t, err := atoi(f[i]) if err != nil { return nil, badData } t -= zones[0].offset tx = append(tx, zoneTrans{when: int64(t), index: uint8(zi)}) } // Committed to succeed. l = &Location{zone: zones[:], tx: tx} // Fill in the cache with information about right now, // since that will be the most common lookup. sec, _ := now() for i := range tx { if tx[i].when <= sec && (i+1 == len(tx) || sec < tx[i+1].when) { l.cacheStart = tx[i].when l.cacheEnd = 1<<63 - 1 if i+1 < len(tx) { l.cacheEnd = tx[i+1].when } l.cacheZone = &l.zone[tx[i].index] } } return l, nil } func loadZoneFilePlan9(name string) (*Location, error) { b, err := readFile(name) if err != nil { return nil, err } return loadZoneDataPlan9(string(b)) } func initTestingZone() { z, err := loadLocation("America/Los_Angeles") if err != nil { panic("cannot load America/Los_Angeles for testing: " + err.Error()) } z.name = "Local" localLoc = *z } func initLocal() { t, ok := syscall.Getenv("timezone") if ok { if z, err := loadZoneDataPlan9(t); err == nil { localLoc = *z return } } else { if z, err := loadZoneFilePlan9("/adm/timezone/local"); err == nil { localLoc = *z localLoc.name = "Local" return } } // Fall back to UTC. localLoc.name = "UTC" } func loadLocation(name string) (*Location, error) { if z, err := loadZoneFile(runtime.GOROOT()+"/lib/time/zoneinfo.zip", name); err == nil { z.name = name return z, nil } return nil, errors.New("unknown time zone " + name) } func forceZipFileForTesting(zipOnly bool) { // We only use the zip file anyway. }
gpl-2.0
CLAMP-IT/moodle
admin/modules.php
6839
<?php // Allows the admin to manage activity modules require_once('../config.php'); require_once('../course/lib.php'); require_once($CFG->libdir.'/adminlib.php'); require_once($CFG->libdir.'/tablelib.php'); // defines define('MODULE_TABLE','module_administration_table'); admin_externalpage_setup('managemodules'); $show = optional_param('show', '', PARAM_PLUGIN); $hide = optional_param('hide', '', PARAM_PLUGIN); /// Print headings $stractivities = get_string("activities"); $struninstall = get_string('uninstallplugin', 'core_admin'); $strversion = get_string("version"); $strhide = get_string("hide"); $strshow = get_string("show"); $strsettings = get_string("settings"); $stractivities = get_string("activities"); $stractivitymodule = get_string("activitymodule"); $strshowmodulecourse = get_string('showmodulecourse'); /// If data submitted, then process and store. if (!empty($hide) and confirm_sesskey()) { if (!$module = $DB->get_record("modules", array("name"=>$hide))) { print_error('moduledoesnotexist', 'error'); } $DB->set_field("modules", "visible", "0", array("id"=>$module->id)); // Hide main module // Remember the visibility status in visibleold // and hide... $sql = "UPDATE {course_modules} SET visibleold=visible, visible=0 WHERE module=?"; $DB->execute($sql, array($module->id)); // Increment course.cacherev for courses where we just made something invisible. // This will force cache rebuilding on the next request. increment_revision_number('course', 'cacherev', "id IN (SELECT DISTINCT course FROM {course_modules} WHERE visibleold=1 AND module=?)", array($module->id)); core_plugin_manager::reset_caches(); admin_get_root(true, false); // settings not required - only pages redirect(new moodle_url('/admin/modules.php')); } if (!empty($show) and confirm_sesskey()) { if (!$module = $DB->get_record("modules", array("name"=>$show))) { print_error('moduledoesnotexist', 'error'); } $DB->set_field("modules", "visible", "1", array("id"=>$module->id)); // Show main module $DB->set_field('course_modules', 'visible', '1', array('visibleold'=>1, 'module'=>$module->id)); // Get the previous saved visible state for the course module. // Increment course.cacherev for courses where we just made something visible. // This will force cache rebuilding on the next request. increment_revision_number('course', 'cacherev', "id IN (SELECT DISTINCT course FROM {course_modules} WHERE visible=1 AND module=?)", array($module->id)); core_plugin_manager::reset_caches(); admin_get_root(true, false); // settings not required - only pages redirect(new moodle_url('/admin/modules.php')); } echo $OUTPUT->header(); echo $OUTPUT->heading($stractivities); /// Get and sort the existing modules if (!$modules = $DB->get_records('modules', array(), 'name ASC')) { print_error('moduledoesnotexist', 'error'); } /// Print the table of all modules // construct the flexible table ready to display $table = new flexible_table(MODULE_TABLE); $table->define_columns(array('name', 'instances', 'version', 'hideshow', 'uninstall', 'settings')); $table->define_headers(array($stractivitymodule, $stractivities, $strversion, "$strhide/$strshow", $strsettings, $struninstall)); $table->define_baseurl($CFG->wwwroot.'/'.$CFG->admin.'/modules.php'); $table->set_attribute('id', 'modules'); $table->set_attribute('class', 'admintable generaltable'); $table->setup(); $pluginmanager = core_plugin_manager::instance(); foreach ($modules as $module) { $plugininfo = $pluginmanager->get_plugin_info('mod_'.$module->name); $status = $plugininfo->get_status(); if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) { $strmodulename = '<span class="notifyproblem">'.$module->name.' ('.get_string('missingfromdisk').')</span>'; $missing = true; } else { // took out hspace="\10\", because it does not validate. don't know what to replace with. $icon = "<img src=\"" . $OUTPUT->image_url('icon', $module->name) . "\" class=\"icon\" alt=\"\" />"; $strmodulename = $icon.' '.get_string('modulename', $module->name); $missing = false; } $uninstall = ''; if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('mod_'.$module->name, 'manage')) { $uninstall = html_writer::link($uninstallurl, $struninstall); } if (file_exists("$CFG->dirroot/mod/$module->name/settings.php") || file_exists("$CFG->dirroot/mod/$module->name/settingstree.php")) { $settings = "<a href=\"settings.php?section=modsetting$module->name\">$strsettings</a>"; } else { $settings = ""; } try { $count = $DB->count_records_select($module->name, "course<>0"); } catch (dml_exception $e) { $count = -1; } if ($count>0) { $countlink = $OUTPUT->action_link(new moodle_url('/course/search.php', ['modulelist' => $module->name]), $count, null, ['title' => $strshowmodulecourse]); } else if ($count < 0) { $countlink = get_string('error'); } else { $countlink = "$count"; } if ($missing) { $visible = ''; $class = ''; } else if ($module->visible) { $visible = "<a href=\"modules.php?hide=$module->name&amp;sesskey=".sesskey()."\" title=\"$strhide\">". $OUTPUT->pix_icon('t/hide', $strhide) . '</a>'; $class = ''; } else { $visible = "<a href=\"modules.php?show=$module->name&amp;sesskey=".sesskey()."\" title=\"$strshow\">". $OUTPUT->pix_icon('t/show', $strshow) . '</a>'; $class = 'dimmed_text'; } if ($module->name == "forum") { $uninstall = ""; $visible = ""; $class = ""; } $version = get_config('mod_'.$module->name, 'version'); $table->add_data(array( $strmodulename, $countlink, $version, $visible, $settings, $uninstall, ), $class); } $table->print_html(); echo $OUTPUT->footer();
gpl-3.0
tgroshon/canvas-lms
gems/rubocop-canvas/lib/rubocop_canvas/version.rb
63
module Rubocop module Canvas VERSION = "1.0.0" end end
agpl-3.0
sgallagher/origin
pkg/build/builder/source_test.go
9153
package builder import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "os/exec" "path" "path/filepath" "strings" "testing" "time" "github.com/openshift/origin/pkg/build/api" "github.com/openshift/origin/pkg/generate/git" ) func TestCheckRemoteGit(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) })) defer server.Close() gitRepo := git.NewRepositoryWithEnv([]string{"GIT_ASKPASS=true"}) var err error err = checkRemoteGit(gitRepo, server.URL, 10*time.Second) switch v := err.(type) { case gitAuthError: default: t.Errorf("expected gitAuthError, got %q", v) } err = checkRemoteGit(gitRepo, "https://github.com/openshift/origin", 10*time.Second) if err != nil { t.Errorf("unexpected error %q", err) } } type testGitRepo struct { Name string Path string Files []string Submodule *testGitRepo } func initializeTestGitRepo(name string) (*testGitRepo, error) { repo := &testGitRepo{Name: name} dir, err := ioutil.TempDir("", "test-"+repo.Name) if err != nil { return repo, err } repo.Path = dir tmpfn := filepath.Join(dir, "initial-file") if err := ioutil.WriteFile(tmpfn, []byte("test"), 0666); err != nil { return repo, fmt.Errorf("unable to create temporary file") } repo.Files = append(repo.Files, tmpfn) initCmd := exec.Command("git", "init") initCmd.Dir = dir if out, err := initCmd.CombinedOutput(); err != nil { return repo, fmt.Errorf("unable to initialize repository: %q", out) } configEmailCmd := exec.Command("git", "config", "user.email", "me@example.com") configEmailCmd.Dir = dir if out, err := configEmailCmd.CombinedOutput(); err != nil { return repo, fmt.Errorf("unable to set git email prefs: %q", out) } configNameCmd := exec.Command("git", "config", "user.name", "Me Myself") configNameCmd.Dir = dir if out, err := configNameCmd.CombinedOutput(); err != nil { return repo, fmt.Errorf("unable to set git name prefs: %q", out) } return repo, nil } func (r *testGitRepo) addSubmodule() error { subRepo, err := initializeTestGitRepo("submodule") if err != nil { return err } if err := subRepo.addCommit(); err != nil { return err } subCmd := exec.Command("git", "submodule", "add", "file://"+subRepo.Path, "sub") subCmd.Dir = r.Path if out, err := subCmd.CombinedOutput(); err != nil { return fmt.Errorf("unable to add submodule: %q", out) } r.Submodule = subRepo return nil } // getRef returns the sha256 of the commit specified by the negative offset. // The '0' is the current HEAD. func (r *testGitRepo) getRef(offset int) (string, error) { q := "" for i := offset; i != 0; i++ { q += "^" } refCmd := exec.Command("git", "rev-parse", "HEAD"+q) refCmd.Dir = r.Path if out, err := refCmd.CombinedOutput(); err != nil { return "", fmt.Errorf("unable to checkout %d offset: %q", offset, out) } else { return strings.TrimSpace(string(out)), nil } } func (r *testGitRepo) createBranch(name string) error { refCmd := exec.Command("git", "checkout", "-b", name) refCmd.Dir = r.Path if out, err := refCmd.CombinedOutput(); err != nil { return fmt.Errorf("unable to checkout new branch: %q", out) } return nil } func (r *testGitRepo) switchBranch(name string) error { refCmd := exec.Command("git", "checkout", name) refCmd.Dir = r.Path if out, err := refCmd.CombinedOutput(); err != nil { return fmt.Errorf("unable to checkout branch: %q", out) } return nil } func (r *testGitRepo) cleanup() { os.RemoveAll(r.Path) if r.Submodule != nil { os.RemoveAll(r.Submodule.Path) } } func (r *testGitRepo) addCommit() error { f, err := ioutil.TempFile(r.Path, "") if err != nil { return err } if err := ioutil.WriteFile(f.Name(), []byte("test"), 0666); err != nil { return fmt.Errorf("unable to create temporary file %q", f.Name()) } addCmd := exec.Command("git", "add", ".") addCmd.Dir = r.Path if out, err := addCmd.CombinedOutput(); err != nil { return fmt.Errorf("unable to add files to repo: %q", out) } commitCmd := exec.Command("git", "commit", "-a", "-m", "test commit") commitCmd.Dir = r.Path out, err := commitCmd.CombinedOutput() if err != nil { return fmt.Errorf("unable to commit: %q", out) } r.Files = append(r.Files, f.Name()) return nil } func TestUnqualifiedClone(t *testing.T) { repo, err := initializeTestGitRepo("unqualified") defer repo.cleanup() if err != nil { t.Errorf("%v", err) } if err := repo.addSubmodule(); err != nil { t.Errorf("%v", err) } // add two commits to check that shallow clone take account if err := repo.addCommit(); err != nil { t.Errorf("unable to add commit: %v", err) } if err := repo.addCommit(); err != nil { t.Errorf("unable to add commit: %v", err) } destDir, err := ioutil.TempDir("", "clone-dest-") defer os.RemoveAll(destDir) client := git.NewRepositoryWithEnv([]string{}) source := &api.GitBuildSource{URI: "file://" + repo.Path} revision := api.SourceRevision{Git: &api.GitSourceRevision{}} if _, err = extractGitSource(client, source, &revision, destDir, 10*time.Second); err != nil { t.Errorf("%v", err) } for _, f := range repo.Files { if _, err := os.Stat(filepath.Join(destDir, path.Base(f))); os.IsNotExist(err) { t.Errorf("unable to find repository file %q", path.Base(f)) } } if _, err := os.Stat(filepath.Join(destDir, "sub")); os.IsNotExist(err) { t.Errorf("unable to find submodule dir") } for _, f := range repo.Submodule.Files { if _, err := os.Stat(filepath.Join(destDir, "sub/"+path.Base(f))); os.IsNotExist(err) { t.Errorf("unable to find submodule repository file %q", path.Base(f)) } } } func TestCloneFromRef(t *testing.T) { repo, err := initializeTestGitRepo("commit") defer repo.cleanup() if err != nil { t.Errorf("%v", err) } if err := repo.addSubmodule(); err != nil { t.Errorf("%v", err) } // add two commits to check that shallow clone take account if err := repo.addCommit(); err != nil { t.Errorf("unable to add commit: %v", err) } if err := repo.addCommit(); err != nil { t.Errorf("unable to add commit: %v", err) } destDir, err := ioutil.TempDir("", "commit-dest-") defer os.RemoveAll(destDir) client := git.NewRepositoryWithEnv([]string{}) firstCommitRef, err := repo.getRef(-1) if err != nil { t.Errorf("%v", err) } source := &api.GitBuildSource{ URI: "file://" + repo.Path, Ref: firstCommitRef, } revision := api.SourceRevision{Git: &api.GitSourceRevision{}} if _, err = extractGitSource(client, source, &revision, destDir, 10*time.Second); err != nil { t.Errorf("%v", err) } for _, f := range repo.Files[:len(repo.Files)-1] { if _, err := os.Stat(filepath.Join(destDir, path.Base(f))); os.IsNotExist(err) { t.Errorf("unable to find repository file %q", path.Base(f)) } } if _, err := os.Stat(filepath.Join(destDir, path.Base(repo.Files[len(repo.Files)-1]))); !os.IsNotExist(err) { t.Errorf("last file should not exists in this checkout") } if _, err := os.Stat(filepath.Join(destDir, "sub")); os.IsNotExist(err) { t.Errorf("unable to find submodule dir") } for _, f := range repo.Submodule.Files { if _, err := os.Stat(filepath.Join(destDir, "sub/"+path.Base(f))); os.IsNotExist(err) { t.Errorf("unable to find submodule repository file %q", path.Base(f)) } } } func TestCloneFromBranch(t *testing.T) { repo, err := initializeTestGitRepo("branch") defer repo.cleanup() if err != nil { t.Errorf("%v", err) } if err := repo.addSubmodule(); err != nil { t.Errorf("%v", err) } // add two commits to check that shallow clone take account if err := repo.addCommit(); err != nil { t.Errorf("unable to add commit: %v", err) } if err := repo.createBranch("test"); err != nil { t.Errorf("%v", err) } if err := repo.addCommit(); err != nil { t.Errorf("unable to add commit: %v", err) } if err := repo.switchBranch("master"); err != nil { t.Errorf("%v", err) } if err := repo.addCommit(); err != nil { t.Errorf("unable to add commit: %v", err) } destDir, err := ioutil.TempDir("", "branch-dest-") defer os.RemoveAll(destDir) client := git.NewRepositoryWithEnv([]string{}) source := &api.GitBuildSource{ URI: "file://" + repo.Path, Ref: "test", } revision := api.SourceRevision{Git: &api.GitSourceRevision{}} if _, err = extractGitSource(client, source, &revision, destDir, 10*time.Second); err != nil { t.Errorf("%v", err) } for _, f := range repo.Files[:len(repo.Files)-1] { if _, err := os.Stat(filepath.Join(destDir, path.Base(f))); os.IsNotExist(err) { t.Errorf("file %q should not exists in the test branch", f) } } if _, err := os.Stat(filepath.Join(destDir, path.Base(repo.Files[len(repo.Files)-1]))); !os.IsNotExist(err) { t.Errorf("last file should not exists in the test branch") } if _, err := os.Stat(filepath.Join(destDir, "sub")); os.IsNotExist(err) { t.Errorf("unable to find submodule dir") } for _, f := range repo.Submodule.Files { if _, err := os.Stat(filepath.Join(destDir, "sub/"+path.Base(f))); os.IsNotExist(err) { t.Errorf("unable to find submodule repository file %q", path.Base(f)) } } }
apache-2.0
fouasnon/camunda-bpm-platform
distro/jbossas7/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/extension/handler/ProcessEngineRemove.java
2349
/** * Copyright (C) 2011, 2012 camunda services GmbH * * 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 org.camunda.bpm.container.impl.jboss.extension.handler; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import java.util.Locale; import org.camunda.bpm.container.impl.jboss.service.ServiceNames; import org.jboss.as.controller.AbstractRemoveStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.descriptions.DescriptionProvider; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceName; /** * Provides the description and the implementation of the process-engine#remove operation. * * @author Daniel Meyer */ public class ProcessEngineRemove extends AbstractRemoveStepHandler implements DescriptionProvider { public static final ProcessEngineRemove INSTANCE = new ProcessEngineRemove(); public ModelNode getModelDescription(Locale locale) { ModelNode node = new ModelNode(); node.get(DESCRIPTION).set("Removes a process engine"); node.get(OPERATION_NAME).set(REMOVE); return node; } protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { String suffix = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.ADDRESS)).getLastElement().getValue(); ServiceName name = ServiceNames.forManagedProcessEngine(suffix); context.removeService(name); } }
apache-2.0
Y-Less/angular
modules/angular2/src/core/forms/directives/ng_control_name.ts
3880
import {CONST_EXPR} from 'angular2/src/core/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async'; import {StringMap} from 'angular2/src/core/facade/collection'; import {OnChanges, OnDestroy} from 'angular2/lifecycle_hooks'; import {Query, Directive} from 'angular2/src/core/metadata'; import {forwardRef, Host, SkipSelf, Binding, Inject, Optional} from 'angular2/src/core/di'; import {ControlContainer} from './control_container'; import {NgControl} from './ng_control'; import {controlPath, isPropertyUpdated} from './shared'; import {Control} from '../model'; import {Validators, NG_VALIDATORS} from '../validators'; const controlNameBinding = CONST_EXPR(new Binding(NgControl, {toAlias: forwardRef(() => NgControlName)})); /** * Creates and binds a control with a specified name to a DOM element. * * This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}. * # Example * * In this example, we create the login and password controls. * We can work with each control separately: check its validity, get its value, listen to its changes. * * ``` * @Component({selector: "login-comp"}) * @View({ * directives: [FORM_DIRECTIVES], * template: ` * <form #f="form" (submit)='onLogIn(f.value)'> * Login <input type='text' ng-control='login' #l="form"> * <div *ng-if="!l.valid">Login is invalid</div> * * Password <input type='password' ng-control='password'> * <button type='submit'>Log in!</button> * </form> * `}) * class LoginComp { * onLogIn(value) { * // value === {login: 'some login', password: 'some password'} * } * } * ``` * * We can also use ng-model to bind a domain model to the form. * * ``` * @Component({selector: "login-comp"}) * @View({ * directives: [FORM_DIRECTIVES], * template: ` * <form (submit)='onLogIn()'> * Login <input type='text' ng-control='login' [(ng-model)]="credentials.login"> * Password <input type='password' ng-control='password' [(ng-model)]="credentials.password"> * <button type='submit'>Log in!</button> * </form> * `}) * class LoginComp { * credentials: {login:string, password:string}; * * onLogIn() { * // this.credentials.login === "some login" * // this.credentials.password === "some password" * } * } * ``` */ @Directive({ selector: '[ng-control]', bindings: [controlNameBinding], properties: ['name: ngControl', 'model: ngModel'], events: ['update: ngModel'], exportAs: 'form' }) export class NgControlName extends NgControl implements OnChanges, OnDestroy { _parent: ControlContainer; update = new EventEmitter(); model: any; viewModel: any; validators: Function[]; _added = false; constructor(@Host() @SkipSelf() parent: ControlContainer, @Optional() @Inject(NG_VALIDATORS) validators: Function[]) { super(); this._parent = parent; this.validators = validators; } onChanges(c: StringMap<string, any>) { if (!this._added) { this.formDirective.addControl(this); this._added = true; } if (isPropertyUpdated(c, this.viewModel)) { this.viewModel = this.model; this.formDirective.updateModel(this, this.model); } } onDestroy() { this.formDirective.removeControl(this); } viewToModelUpdate(newValue: any): void { this.viewModel = newValue; ObservableWrapper.callNext(this.update, newValue); } get path(): string[] { return controlPath(this.name, this._parent); } get formDirective(): any { return this._parent.formDirective; } get control(): Control { return this.formDirective.getControl(this); } get validator(): Function { return Validators.compose(this.validators); } }
apache-2.0