code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php /** * @author Mark van der Velden <mark@dynom.nl> */ namespace Faker\Test\Provider; use Faker; /** * Class ProviderOverrideTest * * @package Faker\Test\Provider * * This class tests a large portion of all locale specific providers. It does not test the entire stack, because each * locale specific provider (can) has specific implementations. The goal of this test is to test the common denominator * and to try to catch possible invalid multi-byte sequences. */ class ProviderOverrideTest extends \PHPUnit_Framework_TestCase { /** * Constants with regular expression patterns for testing the output. * * Regular expressions are sensitive for malformed strings (e.g.: strings with incorrect encodings) so by using * PCRE for the tests, even though they seem fairly pointless, we test for incorrect encodings also. */ const TEST_STRING_REGEX = '/.+/u'; /** * Slightly more specific for e-mail, the point isn't to properly validate e-mails. */ const TEST_EMAIL_REGEX = '/^(.+)@(.+)$/ui'; /** * @dataProvider localeDataProvider * @param string $locale */ public function testAddress($locale = null) { $faker = Faker\Factory::create($locale); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->city); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->postcode); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->address); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->country); } /** * @dataProvider localeDataProvider * @param string $locale */ public function testCompany($locale = null) { $faker = Faker\Factory::create($locale); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->company); } /** * @dataProvider localeDataProvider * @param string $locale */ public function testDateTime($locale = null) { $faker = Faker\Factory::create($locale); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->century); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->timezone); } /** * @dataProvider localeDataProvider * @param string $locale */ public function testInternet($locale = null) { $faker = Faker\Factory::create($locale); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->userName); $this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->email); $this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->safeEmail); $this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->freeEmail); $this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->companyEmail); } /** * @dataProvider localeDataProvider * @param string $locale */ public function testPerson($locale = null) { $faker = Faker\Factory::create($locale); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->name); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->title); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->firstName); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->lastName); } /** * @dataProvider localeDataProvider * @param string $locale */ public function testPhoneNumber($locale = null) { $faker = Faker\Factory::create($locale); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->phoneNumber); } /** * @dataProvider localeDataProvider * @param string $locale */ public function testUserAgent($locale = null) { $faker = Faker\Factory::create($locale); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->userAgent); } /** * @dataProvider localeDataProvider * * @param null $locale * @param string $locale */ public function testUuid($locale = null) { $faker = Faker\Factory::create($locale); $this->assertRegExp(static::TEST_STRING_REGEX, $faker->uuid); } /** * @return array */ public function localeDataProvider() { $locales = $this->getAllLocales(); $data = array(); foreach ($locales as $locale) { $data[] = array( $locale ); } return $data; } /** * Returns all locales as array values * * @return array */ private function getAllLocales() { static $locales = array(); if ( ! empty($locales)) { return $locales; } // Finding all PHP files in the xx_XX directories $providerDir = __DIR__ .'/../../../src/Faker/Provider'; foreach (glob($providerDir .'/*_*/*.php') as $file) { $localisation = basename(dirname($file)); if (isset($locales[ $localisation ])) { continue; } $locales[ $localisation ] = $localisation; } return $locales; } }
i-chengl/Student-activity-management-system
vendor/fzaninotto/faker/test/Faker/Provider/ProviderOverrideTest.php
PHP
mit
5,228
// Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var rp = require('fs.realpath') var minimatch = require('minimatch') var Minimatch = minimatch.Minimatch var inherits = require('inherits') var EE = require('events').EventEmitter var path = require('path') var assert = require('assert') var isAbsolute = require('path-is-absolute') var globSync = require('./sync.js') var common = require('./common.js') var setopts = common.setopts var ownProp = common.ownProp var inflight = require('inflight') var util = require('util') var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = require('once') function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {<filename>: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) self.fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this self.fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) self.fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) }
ealbertos/dotfiles
vscode.symlink/extensions/ms-mssql.mssql-1.11.1/node_modules/glob/glob.js
JavaScript
mit
19,362
require 'rails_helper' RSpec.describe "Stylesheets", type: :request do require "sprockets" let(:css) do assets = Rails.application.assets assets.find_asset("active_admin.css") end it "should successfully render the scss stylesheets using sprockets" do expect(css).to_not eq nil end it "should not have any syntax errors" do expect(css.to_s).to_not include("Syntax error:") end end
cmunozgar/activeadmin
spec/requests/stylesheets_spec.rb
Ruby
mit
415
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP #define BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP #include <algorithm> #include <cstddef> #include <functional> #include <boost/mpl/assert.hpp> #include <boost/range.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> #include <boost/variant/variant_fwd.hpp> #include <boost/geometry/algorithms/detail/interior_iterator.hpp> #include <boost/geometry/core/closure.hpp> #include <boost/geometry/core/cs.hpp> #include <boost/geometry/core/exterior_ring.hpp> #include <boost/geometry/core/interior_rings.hpp> #include <boost/geometry/core/mutable_range.hpp> #include <boost/geometry/core/ring_type.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include <boost/geometry/algorithms/area.hpp> #include <boost/geometry/algorithms/disjoint.hpp> #include <boost/geometry/algorithms/detail/multi_modify.hpp> #include <boost/geometry/util/order_as_direction.hpp> namespace boost { namespace geometry { // Silence warning C4127: conditional expression is constant #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4127) #endif #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace correct { template <typename Geometry> struct correct_nop { static inline void apply(Geometry& ) {} }; template <typename Box, std::size_t Dimension, std::size_t DimensionCount> struct correct_box_loop { typedef typename coordinate_type<Box>::type coordinate_type; static inline void apply(Box& box) { if (get<min_corner, Dimension>(box) > get<max_corner, Dimension>(box)) { // Swap the coordinates coordinate_type max_value = get<min_corner, Dimension>(box); coordinate_type min_value = get<max_corner, Dimension>(box); set<min_corner, Dimension>(box, min_value); set<max_corner, Dimension>(box, max_value); } correct_box_loop < Box, Dimension + 1, DimensionCount >::apply(box); } }; template <typename Box, std::size_t DimensionCount> struct correct_box_loop<Box, DimensionCount, DimensionCount> { static inline void apply(Box& ) {} }; // Correct a box: make min/max correct template <typename Box> struct correct_box { static inline void apply(Box& box) { // Currently only for Cartesian coordinates // (or spherical without crossing dateline) // Future version: adapt using strategies correct_box_loop < Box, 0, dimension<Box>::type::value >::apply(box); } }; // Close a ring, if not closed template <typename Ring, typename Predicate> struct correct_ring { typedef typename point_type<Ring>::type point_type; typedef typename coordinate_type<Ring>::type coordinate_type; typedef typename strategy::area::services::default_strategy < typename cs_tag<point_type>::type, point_type >::type strategy_type; typedef detail::area::ring_area < order_as_direction<geometry::point_order<Ring>::value>::value, geometry::closure<Ring>::value > ring_area_type; static inline void apply(Ring& r) { // Check close-ness if (boost::size(r) > 2) { // check if closed, if not, close it bool const disjoint = geometry::disjoint(*boost::begin(r), *(boost::end(r) - 1)); closure_selector const s = geometry::closure<Ring>::value; if (disjoint && (s == closed)) { geometry::append(r, *boost::begin(r)); } if (! disjoint && s != closed) { // Open it by removing last point geometry::traits::resize<Ring>::apply(r, boost::size(r) - 1); } } // Check area Predicate predicate; typedef typename default_area_result<Ring>::type area_result_type; area_result_type const zero = area_result_type(); if (predicate(ring_area_type::apply(r, strategy_type()), zero)) { std::reverse(boost::begin(r), boost::end(r)); } } }; // Correct a polygon: normalizes all rings, sets outer ring clockwise, sets all // inner rings counter clockwise (or vice versa depending on orientation) template <typename Polygon> struct correct_polygon { typedef typename ring_type<Polygon>::type ring_type; typedef typename default_area_result<Polygon>::type area_result_type; static inline void apply(Polygon& poly) { correct_ring < ring_type, std::less<area_result_type> >::apply(exterior_ring(poly)); typename interior_return_type<Polygon>::type rings = interior_rings(poly); for (typename detail::interior_iterator<Polygon>::type it = boost::begin(rings); it != boost::end(rings); ++it) { correct_ring < ring_type, std::greater<area_result_type> >::apply(*it); } } }; }} // namespace detail::correct #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template <typename Geometry, typename Tag = typename tag<Geometry>::type> struct correct: not_implemented<Tag> {}; template <typename Point> struct correct<Point, point_tag> : detail::correct::correct_nop<Point> {}; template <typename LineString> struct correct<LineString, linestring_tag> : detail::correct::correct_nop<LineString> {}; template <typename Segment> struct correct<Segment, segment_tag> : detail::correct::correct_nop<Segment> {}; template <typename Box> struct correct<Box, box_tag> : detail::correct::correct_box<Box> {}; template <typename Ring> struct correct<Ring, ring_tag> : detail::correct::correct_ring < Ring, std::less<typename default_area_result<Ring>::type> > {}; template <typename Polygon> struct correct<Polygon, polygon_tag> : detail::correct::correct_polygon<Polygon> {}; template <typename MultiPoint> struct correct<MultiPoint, multi_point_tag> : detail::correct::correct_nop<MultiPoint> {}; template <typename MultiLineString> struct correct<MultiLineString, multi_linestring_tag> : detail::correct::correct_nop<MultiLineString> {}; template <typename Geometry> struct correct<Geometry, multi_polygon_tag> : detail::multi_modify < Geometry, detail::correct::correct_polygon < typename boost::range_value<Geometry>::type > > {}; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH namespace resolve_variant { template <typename Geometry> struct correct { static inline void apply(Geometry& geometry) { concepts::check<Geometry const>(); dispatch::correct<Geometry>::apply(geometry); } }; template <BOOST_VARIANT_ENUM_PARAMS(typename T)> struct correct<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> > { struct visitor: boost::static_visitor<void> { template <typename Geometry> void operator()(Geometry& geometry) const { correct<Geometry>::apply(geometry); } }; static inline void apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>& geometry) { boost::apply_visitor(visitor(), geometry); } }; } // namespace resolve_variant /*! \brief Corrects a geometry \details Corrects a geometry: all rings which are wrongly oriented with respect to their expected orientation are reversed. To all rings which do not have a closing point and are typed as they should have one, the first point is appended. Also boxes can be corrected. \ingroup correct \tparam Geometry \tparam_geometry \param geometry \param_geometry which will be corrected if necessary \qbk{[include reference/algorithms/correct.qbk]} */ template <typename Geometry> inline void correct(Geometry& geometry) { resolve_variant::correct<Geometry>::apply(geometry); } #if defined(_MSC_VER) #pragma warning(pop) #endif }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP
nginnever/zogminer
tests/deps/boost/geometry/algorithms/correct.hpp
C++
mit
9,374
/* ======================================================================== * Bootstrap: iconset-typicon-2.0.6.js by @recktoner * https://victor-valencia.github.com/bootstrap-iconpicker * * Iconset: Typicons 2.0.6 * https://github.com/stephenhutchings/typicons.font * ======================================================================== * Copyright 2013-2014 Victor Valencia Rico. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ ;(function($){ $.iconset_typicon = { iconClass: 'typcn', iconClassFix: 'typcn-', icons: [ 'adjust-brightness', 'adjust-contrast', 'anchor-outline', 'anchor', 'archive', 'arrow-back-outline', 'arrow-back', 'arrow-down-outline', 'arrow-down-thick', 'arrow-down', 'arrow-forward-outline', 'arrow-forward', 'arrow-left-outline', 'arrow-left-thick', 'arrow-left', 'arrow-loop-outline', 'arrow-loop', 'arrow-maximise-outline', 'arrow-maximise', 'arrow-minimise-outline', 'arrow-minimise', 'arrow-move-outline', 'arrow-move', 'arrow-repeat-outline', 'arrow-repeat', 'arrow-right-outline', 'arrow-right-thick', 'arrow-right', 'arrow-shuffle', 'arrow-sorted-down', 'arrow-sorted-up', 'arrow-sync-outline', 'arrow-sync', 'arrow-unsorted', 'arrow-up-outline', 'arrow-up-thick', 'arrow-up', 'at', 'attachment-outline', 'attachment', 'backspace-outline', 'backspace', 'battery-charge', 'battery-full', 'battery-high', 'battery-low', 'battery-mid', 'beaker', 'beer', 'bell', 'book', 'bookmark', 'briefcase', 'brush', 'business-card', 'calculator', 'calendar-outline', 'calendar', 'camera-outline', 'camera', 'cancel-outline', 'cancel', 'chart-area-outline', 'chart-area', 'chart-bar-outline', 'chart-bar', 'chart-line-outline', 'chart-line', 'chart-pie-outline', 'chart-pie', 'chevron-left-outline', 'chevron-left', 'chevron-right-outline', 'chevron-right', 'clipboard', 'cloud-storage', 'cloud-storage-outline', 'code-outline', 'code', 'coffee', 'cog-outline', 'cog', 'compass', 'contacts', 'credit-card', 'css3', 'database', 'delete-outline', 'delete', 'device-desktop', 'device-laptop', 'device-phone', 'device-tablet', 'directions', 'divide-outline', 'divide', 'document-add', 'document-delete', 'document-text', 'document', 'download-outline', 'download', 'dropbox', 'edit', 'eject-outline', 'eject', 'equals-outline', 'equals', 'export-outline', 'export', 'eye-outline', 'eye', 'feather', 'film', 'filter', 'flag-outline', 'flag', 'flash-outline', 'flash', 'flow-children', 'flow-merge', 'flow-parallel', 'flow-switch', 'folder-add', 'folder-delete', 'folder-open', 'folder', 'gift', 'globe-outline', 'globe', 'group-outline', 'group', 'headphones', 'heart-full-outline', 'heart-half-outline', 'heart-outline', 'heart', 'home-outline', 'home', 'html5', 'image-outline', 'image', 'infinity-outline', 'infinity', 'info-large-outline', 'info-large', 'info-outline', 'info', 'input-checked-outline', 'input-checked', 'key-outline', 'key', 'keyboard', 'leaf', 'lightbulb', 'link-outline', 'link', 'location-arrow-outline', 'location-arrow', 'location-outline', 'location', 'lock-closed-outline', 'lock-closed', 'lock-open-outline', 'lock-open', 'mail', 'map', 'media-eject-outline', 'media-eject', 'media-fast-forward-outline', 'media-fast-forward', 'media-pause-outline', 'media-pause', 'media-play-outline', 'media-play-reverse-outline', 'media-play-reverse', 'media-play', 'media-record-outline', 'media-record', 'media-rewind-outline', 'media-rewind', 'media-stop-outline', 'media-stop', 'message-typing', 'message', 'messages', 'microphone-outline', 'microphone', 'minus-outline', 'minus', 'mortar-board', 'news', 'notes-outline', 'notes', 'pen', 'pencil', 'phone-outline', 'phone', 'pi-outline', 'pi', 'pin-outline', 'pin', 'pipette', 'plane-outline', 'plane', 'plug', 'plus-outline', 'plus', 'point-of-interest-outline', 'point-of-interest', 'power-outline', 'power', 'printer', 'puzzle-outline', 'puzzle', 'radar-outline', 'radar', 'refresh-outline', 'refresh', 'rss-outline', 'rss', 'scissors-outline', 'scissors', 'shopping-bag', 'shopping-cart', 'social-at-circular', 'social-dribbble-circular', 'social-dribbble', 'social-facebook-circular', 'social-facebook', 'social-flickr-circular', 'social-flickr', 'social-github-circular', 'social-github', 'social-google-plus-circular', 'social-google-plus', 'social-instagram-circular', 'social-instagram', 'social-last-fm-circular', 'social-last-fm', 'social-linkedin-circular', 'social-linkedin', 'social-pinterest-circular', 'social-pinterest', 'social-skype-outline', 'social-skype', 'social-tumbler-circular', 'social-tumbler', 'social-twitter-circular', 'social-twitter', 'social-vimeo-circular', 'social-vimeo', 'social-youtube-circular', 'social-youtube', 'sort-alphabetically-outline', 'sort-alphabetically', 'sort-numerically-outline', 'sort-numerically', 'spanner-outline', 'spanner', 'spiral', 'star-full-outline', 'star-half-outline', 'star-half', 'star-outline', 'star', 'starburst-outline', 'starburst', 'stopwatch', 'support', 'tabs-outline', 'tag', 'tags', 'th-large-outline', 'th-large', 'th-list-outline', 'th-list', 'th-menu-outline', 'th-menu', 'th-small-outline', 'th-small', 'thermometer', 'thumbs-down', 'thumbs-ok', 'thumbs-up', 'tick-outline', 'tick', 'ticket', 'time', 'times-outline', 'times', 'trash', 'tree', 'upload-outline', 'upload', 'user-add-outline', 'user-add', 'user-delete-outline', 'user-delete', 'user-outline', 'user', 'vendor-android', 'vendor-apple', 'vendor-microsoft', 'video-outline', 'video', 'volume-down', 'volume-mute', 'volume-up', 'volume', 'warning-outline', 'warning', 'watch', 'waves-outline', 'waves', 'weather-cloudy', 'weather-downpour', 'weather-night', 'weather-partly-sunny', 'weather-shower', 'weather-snow', 'weather-stormy', 'weather-sunny', 'weather-windy-cloudy', 'weather-windy', 'wi-fi-outline', 'wi-fi', 'wine', 'world-outline', 'world', 'zoom-in-outline', 'zoom-in', 'zoom-out-outline', 'zoom-out', 'zoom-outline', 'zoom' ]}; })(jQuery);
ahsina/StudExpo
wp-content/plugins/tiny-bootstrap-elements-light/assets/js/iconset/iconset-typicon-2.0.6.js
JavaScript
gpl-2.0
10,551
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * DNS Library for handling lookups and updates. * * PHP Version 5 * * Copyright (c) 2010, Mike Pultz <mike@mikepultz.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Mike Pultz nor the names of his contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @category Networking * @package Net_DNS2 * @author Mike Pultz <mike@mikepultz.com> * @copyright 2010 Mike Pultz <mike@mikepultz.com> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version SVN: $Id: LOC.php 127 2011-12-03 03:29:39Z mike.pultz $ * @link http://pear.php.net/package/Net_DNS2 * @since File available since Release 0.6.0 * */ /** * LOC Resource Record - RFC1876 section 2 * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | VERSION | SIZE | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | HORIZ PRE | VERT PRE | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | LATITUDE | * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | LONGITUDE | * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | ALTITUDE | * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * * @category Networking * @package Net_DNS2 * @author Mike Pultz <mike@mikepultz.com> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://pear.php.net/package/Net_DNS2 * @see Net_DNS2_RR * */ class Net_DNS2_RR_LOC extends Net_DNS2_RR { /* * the LOC version- should only ever be 0 */ public $version; /* * The diameter of a sphere enclosing the described entity */ public $size; /* * The horizontal precision of the data */ public $horiz_pre; /* * The vertical precision of the data */ public $vert_pre; /* * The latitude - stored in decimal degrees */ public $latitude; /* * The longitude - stored in decimal degrees */ public $longitude; /* * The altitude - stored in decimal */ public $altitude; /* * used for quick power-of-ten lookups */ private $_powerOfTen = array(1, 10, 100, 1000, 10000, 100000, 1000000,10000000,100000000,1000000000); /* * some conversion values */ const CONV_SEC = 1000; const CONV_MIN = 60000; const CONV_DEG = 3600000; const REFERENCE_ALT = 10000000; const REFERENCE_LATLON = 2147483648; /** * method to return the rdata portion of the packet as a string * * @return string * @access protected * */ protected function rrToString() { if ($this->version == 0) { return $this->_d2Dms($this->latitude, 'LAT') . ' ' . $this->_d2Dms($this->longitude, 'LNG') . ' ' . sprintf('%.2fm', $this->altitude) . ' ' . sprintf('%.2fm', $this->size) . ' ' . sprintf('%.2fm', $this->horiz_pre) . ' ' . sprintf('%.2fm', $this->vert_pre); } return ''; } /** * parses the rdata portion from a standard DNS config line * * @param array $rdata a string split line of values for the rdata * * @return boolean * @access protected * */ protected function rrFromString(array $rdata) { // // format as defined by RFC1876 section 3 // // d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} alt["m"] // [siz["m"] [hp["m"] [vp["m"]]]] // $res = preg_match( '/^(\d+) \s+((\d+) \s+)?(([\d.]+) \s+)?(N|S) \s+(\d+) ' . '\s+((\d+) \s+)?(([\d.]+) \s+)?(E|W) \s+(-?[\d.]+) m?(\s+ ' . '([\d.]+) m?)?(\s+ ([\d.]+) m?)?(\s+ ([\d.]+) m?)?/ix', implode(' ', $rdata), $x ); if ($res) { // // latitude // $latdeg = $x[1]; $latmin = (isset($x[3])) ? $x[3] : 0; $latsec = (isset($x[5])) ? $x[5] : 0; $lathem = strtoupper($x[6]); $this->latitude = $this->_dms2d($latdeg, $latmin, $latsec, $lathem); // // longitude // $londeg = $x[7]; $lonmin = (isset($x[9])) ? $x[9] : 0; $lonsec = (isset($x[11])) ? $x[11] : 0; $lonhem = strtoupper($x[12]); $this->longitude = $this->_dms2d($londeg, $lonmin, $lonsec, $lonhem); // // the rest of teh values // $version = 0; $this->size = (isset($x[15])) ? $x[15] : 1; $this->horiz_pre = ((isset($x[17])) ? $x[17] : 10000); $this->vert_pre = ((isset($x[19])) ? $x[19] : 10); $this->altitude = $x[13]; return true; } return false; } /** * parses the rdata of the Net_DNS2_Packet object * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * * @return boolean * @access protected * */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { // // unpack all the values // $x = unpack( 'Cver/Csize/Choriz_pre/Cvert_pre/Nlatitude/Nlongitude/Naltitude', $this->rdata ); // // version must be 0 per RFC 1876 section 2 // $this->version = $x['ver']; if ($this->version == 0) { $this->size = $this->_precsizeNtoA($x['size']); $this->horiz_pre = $this->_precsizeNtoA($x['horiz_pre']); $this->vert_pre = $this->_precsizeNtoA($x['vert_pre']); // // convert the latitude and longitude to degress in decimal // if ($x['latitude'] < 0) { $this->latitude = ($x['latitude'] + self::REFERENCE_LATLON) / self::CONV_DEG; } else { $this->latitude = ($x['latitude'] - self::REFERENCE_LATLON) / self::CONV_DEG; } if ($x['longitude'] < 0) { $this->longitude = ($x['longitude'] + self::REFERENCE_LATLON) / self::CONV_DEG; } else { $this->longitude = ($x['longitude'] - self::REFERENCE_LATLON) / self::CONV_DEG; } // // convert down the altitude // $this->altitude = ($x['altitude'] - self::REFERENCE_ALT) / 100; return true; } else { return false; } return true; } return false; } /** * returns the rdata portion of the DNS packet * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * * @return mixed either returns a binary packed * string or null on failure * @access protected * */ protected function rrGet(Net_DNS2_Packet &$packet) { if ($this->version == 0) { $lat = 0; $lng = 0; if ($this->latitude < 0) { $lat = ($this->latitude * self::CONV_DEG) - self::REFERENCE_LATLON; } else { $lat = ($this->latitude * self::CONV_DEG) + self::REFERENCE_LATLON; } if ($this->longitude < 0) { $lng = ($this->longitude * self::CONV_DEG) - self::REFERENCE_LATLON; } else { $lng = ($this->longitude * self::CONV_DEG) + self::REFERENCE_LATLON; } return pack( 'CCCCNNN', $this->version, $this->_precsizeAtoN($this->size), $this->_precsizeAtoN($this->horiz_pre), $this->_precsizeAtoN($this->vert_pre), $lat, $lng, ($this->altitude * 100) + self::REFERENCE_ALT ); } return null; } /** * takes an XeY precision/size value, returns a string representation. * shamlessly stolen from RFC1876 Appendix A * * @param integer $prec the value to convert * * @return string * @access private * */ private function _precsizeNtoA($prec) { $mantissa = (($prec >> 4) & 0x0f) % 10; $exponent = (($prec >> 0) & 0x0f) % 10; return $mantissa * $this->_powerOfTen[$exponent]; } /** * converts ascii size/precision X * 10**Y(cm) to 0xXY. * shamlessly stolen from RFC1876 Appendix A * * @param string $prec the value to convert * * @return integer * @access private * */ private function _precsizeAtoN($prec) { $exponent = 0; while ($prec >= 10) { $prec /= 10; ++$exponent; } return ($prec << 4) | ($exponent & 0x0f); } /** * convert lat/lng in deg/min/sec/hem to decimal value * * @param integer $deg the degree value * @param integer $min the minutes value * @param integer $sec the seconds value * @param string $hem the hemisphere (N/E/S/W) * * @return float the decinmal value * @access private * */ private function _dms2d($deg, $min, $sec, $hem) { $deg = $deg - 0; $min = $min - 0; $sign = ($hem == 'W' || $hem == 'S') ? -1 : 1; return ((($sec/60+$min)/60)+$deg) * $sign; } /** * convert lat/lng in decimal to deg/min/sec/hem * * @param float $data the decimal value * @param string $latlng either LAT or LNG so we can determine the HEM value * * @return string * @access private * */ private function _d2Dms($data, $latlng) { $deg = 0; $min = 0; $sec = 0; $msec = 0; $hem = ''; if ($latlng == 'LAT') { $hem = ($data > 0) ? 'N' : 'S'; } else { $hem = ($data > 0) ? 'E' : 'W'; } $data = abs($data); $deg = (int)$data; $min = (int)(($data - $deg) * 60); $sec = (int)(((($data - $deg) * 60) - $min) * 60); $msec = round((((((($data - $deg) * 60) - $min) * 60) - $sec) * 1000)); return sprintf('%d %02d %02d.%03d %s', $deg, $min, $sec, round($msec), $hem); } } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */ ?>
prdatur/soopfw
plugins/Net_DNS2-1.2.1/DNS2/RR/LOC.php
PHP
gpl-2.0
12,763
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Methods for working with cecog Copyright 2010 University of Dundee, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import os import re import sys from omero.cli import BaseControl, CLI import omero import omero.constants from omero.rtypes import rstring class CecogControl(BaseControl): """CeCog integration plugin. Provides actions for prepairing data and otherwise integrating with Cecog. See the Run_Cecog_4.1.py script. """ # [MetaMorph_PlateScanPackage] # regex_subdirectories = re.compile('(?=[^_]).*?(?P<D>\d+).*?') # regex_position = re.compile('P(?P<P>.+?)_') # continuous_frames = 1 regex_token = re.compile(r'(?P<Token>.+)\.') regex_time = re.compile(r'T(?P<T>\d+)') regex_channel = re.compile(r'_C(?P<C>.+?)(_|$)') regex_zslice = re.compile(r'_Z(?P<Z>\d+)') def _configure(self, parser): sub = parser.sub() merge = parser.add(sub, self.merge, self.merge.__doc__) merge.add_argument("path", help="Path to image files") rois = parser.add(sub, self.rois, self.rois.__doc__) rois.add_argument( "-f", "--file", required=True, help="Details file to be parsed") rois.add_argument( "-i", "--image", required=True, help="Image id which should have ids attached") for x in (merge, rois): x.add_login_arguments() # # Public methods # def merge(self, args): """Uses PIL to read multiple planes from a local folder. Planes are combined and uploaded to OMERO as new images with additional T, C, Z dimensions. It should be run as a local script (not via scripting service) in order that it has access to the local users file system. Therefore need EMAN2 or PIL installed locally. Example usage: $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/0037/ Since this dir does not contain folders, this will upload images in '0037' into a Dataset called Demo_data in a Project called 'Data'. $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/ Since this dir does contain folders, this will look for images in all subdirectories of 'Demo_data' and upload images into a Dataset called Demo_data in a Project called 'Data'. Images will be combined in Z, C and T according to the \ MetaMorph_PlateScanPackage naming convention. E.g. tubulin_P0037_T00005_Cgfp_Z1_S1.tiff is Point 37, Timepoint 5, Channel \ gfp, Z 1. S? see \ /Applications/CecogPackage/CecogAnalyzer.app/Contents/Resources/resources/\ naming_schemes.conf """ """ Processes the command args, makes project and dataset then calls uploadDirAsImages() to process and upload the images to OMERO. """ from omero.rtypes import unwrap from omero.util.script_utils import uploadDirAsImages path = args.path client = self.ctx.conn(args) queryService = client.sf.getQueryService() updateService = client.sf.getUpdateService() pixelsService = client.sf.getPixelsService() # if we don't have any folders in the 'dir' E.g. # CecogPackage/Data/Demo_data/0037/ # then 'Demo_data' becomes a dataset subDirs = [] for f in os.listdir(path): fullpath = path + f # process folders in root dir: if os.path.isdir(fullpath): subDirs.append(fullpath) # get the dataset name and project name from path if len(subDirs) == 0: p = path[:-1] # will remove the last folder p = os.path.dirname(p) else: if os.path.basename(path) == "": p = path[:-1] # remove slash datasetName = os.path.basename(p) # e.g. Demo_data p = p[:-1] p = os.path.dirname(p) projectName = os.path.basename(p) # e.g. Data self.ctx.err("Putting images in Project: %s Dataset: %s" % (projectName, datasetName)) # create dataset dataset = omero.model.DatasetI() dataset.name = rstring(datasetName) dataset = updateService.saveAndReturnObject(dataset) # create project project = omero.model.ProjectI() project.name = rstring(projectName) project = updateService.saveAndReturnObject(project) # put dataset in project link = omero.model.ProjectDatasetLinkI() link.parent = omero.model.ProjectI(project.id.val, False) link.child = omero.model.DatasetI(dataset.id.val, False) updateService.saveAndReturnObject(link) if len(subDirs) > 0: for subDir in subDirs: self.ctx.err("Processing images in %s" % subDir) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, subDir, dataset) self.ctx.out("%s" % unwrap(rv)) # if there are no sub-directories, just put all the images in the dir else: self.ctx.err("Processing images in %s" % path) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, path, dataset) self.ctx.out("%s" % unwrap(rv)) def rois(self, args): """Parses an object_details text file, as generated by CeCog Analyzer and saves the data as ROIs on an Image in OMERO. Text file is of the form: frame objID classLabel className centerX centerY mean sd 1 10 6 lateana 1119 41 76.8253796095 \ 54.9305640673 Example usage: bin/omero cecog rois -f \ Data/Demo_output/analyzed/0037/statistics/P0037__object_details.txt -i 502 """ """ Processes the command args, parses the object_details.txt file and creates ROIs on the image specified in OMERO """ from omero.util.script_utils import uploadCecogObjectDetails filePath = args.file imageId = args.image if not os.path.exists(filePath): self.ctx.die(654, "Could find the object_details file at %s" % filePath) client = self.ctx.conn(args) updateService = client.sf.getUpdateService() ids = uploadCecogObjectDetails(updateService, imageId, filePath) self.ctx.out("Rois created: %s" % len(ids)) try: register("cecog", CecogControl, CecogControl.__doc__) except NameError: if __name__ == "__main__": cli = CLI() cli.register("cecog", CecogControl, CecogControl.__doc__) cli.invoke(sys.argv[1:])
dominikl/openmicroscopy
components/tools/OmeroPy/src/omero/plugins/cecog.py
Python
gpl-2.0
6,684
<?php /** * @package JCE * @copyright Copyright © 2009-2011 Ryan Demmer. All rights reserved. * @license GNU/GPL 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * JCE 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. */ defined('_JEXEC') or die('RESTRICTED'); ?> <dl class="adminformlist"> <dt><?php echo WFText::_('WF_INSTALLER_INSTALL_DESC');?></dt> <dd> <label for="install" class="tooltip" title="<?php echo WFText::_('WF_INSTALLER_PACKAGE'); ?>::<?php echo WFText::_('WF_INSTALLER_PACKAGE_DESC'); ?>"><?php echo WFText::_('WF_INSTALLER_PACKAGE'); ?></label> <span> <input type="file" name="install" id="upload" placeholder="<?php echo $this->state->get('install.directory'); ?>" /> <button id="install_button"><?php echo WFText::_('WF_INSTALLER_UPLOAD'); ?></button> </span> </dd> </dl>
ArtificialEX/jwexport
administrator/components/com_jce/views/installer/tmpl/install_install.php
PHP
gpl-2.0
1,071
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import re from waflib import Utils,Task,TaskGen,Logs from waflib.TaskGen import feature,before_method,after_method,extension from waflib.Configure import conf INC_REGEX="""(?:^|['">]\s*;)\s*(?:|#\s*)INCLUDE\s+(?:\w+_)?[<"'](.+?)(?=["'>])""" USE_REGEX="""(?:^|;)\s*USE(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)""" MOD_REGEX="""(?:^|;)\s*MODULE(?!\s*PROCEDURE)(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)""" re_inc=re.compile(INC_REGEX,re.I) re_use=re.compile(USE_REGEX,re.I) re_mod=re.compile(MOD_REGEX,re.I) class fortran_parser(object): def __init__(self,incpaths): self.seen=[] self.nodes=[] self.names=[] self.incpaths=incpaths def find_deps(self,node): txt=node.read() incs=[] uses=[] mods=[] for line in txt.splitlines(): m=re_inc.search(line) if m: incs.append(m.group(1)) m=re_use.search(line) if m: uses.append(m.group(1)) m=re_mod.search(line) if m: mods.append(m.group(1)) return(incs,uses,mods) def start(self,node): self.waiting=[node] while self.waiting: nd=self.waiting.pop(0) self.iter(nd) def iter(self,node): path=node.abspath() incs,uses,mods=self.find_deps(node) for x in incs: if x in self.seen: continue self.seen.append(x) self.tryfind_header(x) for x in uses: name="USE@%s"%x if not name in self.names: self.names.append(name) for x in mods: name="MOD@%s"%x if not name in self.names: self.names.append(name) def tryfind_header(self,filename): found=None for n in self.incpaths: found=n.find_resource(filename) if found: self.nodes.append(found) self.waiting.append(found) break if not found: if not filename in self.names: self.names.append(filename)
asljivo1/802.11ah-ns3
ns-3/.waf-1.8.12-f00e5b53f6bbeab1384a38c9cc5d51f7/waflib/Tools/fc_scan.py
Python
gpl-2.0
1,859
<?php class AWPCP_FeeType extends AWPCP_PaymentTermType { const TYPE = 'fee'; public function __construct() { parent::__construct(_x('Fee', 'payment term type', 'AWPCP'), self::TYPE, ''); add_action('awpcp-transaction-status-updated', array($this, 'update_buys_count'), 10, 2); } public function update_buys_count($transaction, $status) { if ($transaction->is_completed() && $transaction->was_payment_successful()) { if ($transaction->get('payment-term-type', false) !== self::TYPE) return; $term = self::find_by_id($transaction->get('payment-term-id')); if (is_null($term)) return; $term->buys = $term->buys + 1; $term->save(); } } public function find_by_id($id) { if (absint($id) === 0) return $this->get_free_payment_term(); return AWPCP_Fee::find_by_id($id); } private function get_free_payment_term() { return new AWPCP_Fee(array( 'id' => 0, 'name' => __('Free Listing', 'AWPCP'), 'description' => '', 'duration_amount' => get_awpcp_option('addurationfreemode'), 'duration_interval' => AWPCP_Fee::INTERVAL_DAY, 'price' => 0, 'credits' => 0, 'categories' => array(), 'images' => get_awpcp_option('imagesallowedfree'), 'ads' => 1, 'characters' => get_awpcp_option( 'maxcharactersallowed' ), 'title_characters' => get_awpcp_option( 'characters-allowed-in-title' ), 'buys' => 0, 'featured' => 0, 'private' => 0, )); } public function get_payment_terms() { global $wpdb; if (!awpcp_payments_api()->payments_enabled()) { return array($this->get_free_payment_term()); } $order = get_awpcp_option( 'fee-order' ); $direction = get_awpcp_option( 'fee-order-direction' ); switch ($order) { case 1: $orderby = array( 'adterm_name', $direction ); break; case 2: $orderby = array( "amount $direction, adterm_name", $direction ); break; case 3: $orderby = array( "imagesallowed $direction, adterm_name", $direction ); break; case 5: $orderby = array( "_duration_interval $direction, rec_period $direction, adterm_name", $direction ); break; } if ( awpcp_current_user_is_admin() ) { $args = array( 'orderby' => $orderby[0], 'order' => $orderby[1], ); } else { $args = array( 'where' => 'private = 0', 'orderby' => $orderby[0], 'order' => $orderby[1], ); } return AWPCP_Fee::query($args); } public function get_user_payment_terms($user_id) { static $terms = null; if ( is_null( $terms ) ) { $terms = $this->get_payment_terms(); } return $terms; } }
Owchzzz/Militiatoday
wp-content/plugins/another-wordpress-classifieds-plugin/includes/payment-term-fee-type.php
PHP
gpl-2.0
3,188
/* * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * Copyright (C) 2009-2011 MaNGOSZero <https://github.com/mangos/zero> * Copyright (C) 2011-2016 Nostalrius <https://nostalrius.org> * Copyright (C) 2016-2017 Elysium Project <https://github.com/elysium-project> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "MovementGenerator.h" #include "Unit.h" MovementGenerator::~MovementGenerator() { } bool MovementGenerator::IsActive(Unit& u) { // When movement generator list modified from Update movegen object erase delayed, // so pointer still valid and be used for check return !u.GetMotionMaster()->empty() && u.GetMotionMaster()->top() == this; }
jzcxw/core
src/game/Movement/MovementGenerator.cpp
C++
gpl-2.0
1,356
<?php /** * @file * @ingroup SMWSpecialPage * @ingroup SpecialPage * * A factbox like view on an article, implemented by a special page. * * @author Denny Vrandecic */ /** * A factbox view on one specific article, showing all the Semantic data about it * * @ingroup SMWSpecialPage * @ingroup SpecialPage */ class SMWSpecialBrowse extends SpecialPage { /// int How many incoming values should be asked for static public $incomingvaluescount = 8; /// int How many incoming properties should be asked for static public $incomingpropertiescount = 21; /// SMWDataValue Topic of this page private $subject = null; /// Text to be set in the query form private $articletext = ""; /// bool To display outgoing values? private $showoutgoing = true; /// bool To display incoming values? private $showincoming = false; /// int At which incoming property are we currently? private $offset = 0; /** * Constructor */ public function __construct() { global $smwgBrowseShowAll; parent::__construct( 'Browse', '', true, false, 'default', true ); if ( $smwgBrowseShowAll ) { SMWSpecialBrowse::$incomingvaluescount = 21; SMWSpecialBrowse::$incomingpropertiescount = - 1; } } /** * Main entry point for Special Pages * * @param[in] $query string Given by MediaWiki */ public function execute( $query ) { global $wgRequest, $wgOut, $smwgBrowseShowAll; $this->setHeaders(); // get the GET parameters $this->articletext = $wgRequest->getVal( 'article' ); // no GET parameters? Then try the URL if ( is_null( $this->articletext ) ) { $params = SMWInfolink::decodeParameters( $query, false ); reset( $params ); $this->articletext = current( $params ); } $this->subject = SMWDataValueFactory::newTypeIDValue( '_wpg', $this->articletext ); $offsettext = $wgRequest->getVal( 'offset' ); $this->offset = ( is_null( $offsettext ) ) ? 0 : intval( $offsettext ); $dir = $wgRequest->getVal( 'dir' ); if ( $smwgBrowseShowAll ) { $this->showoutgoing = true; $this->showincoming = true; } if ( $dir === 'both' || $dir === 'in' ) { $this->showincoming = true; } if ( $dir === 'in' ) { $this->showoutgoing = false; } if ( $dir === 'out' ) { $this->showincoming = false; } $wgOut->addHTML( $this->displayBrowse() ); SMWOutputs::commitToOutputPage( $wgOut ); // make sure locally collected output data is pushed to the output! } /** * Create and output HTML including the complete factbox, based on the extracted * parameters in the execute comment. * * @return string A HTML string with the factbox */ private function displayBrowse() { global $wgContLang, $wgOut; $html = "\n"; $leftside = !( $wgContLang->isRTL() ); // For right to left languages, all is mirrored if ( $this->subject->isValid() ) { $html .= $this->displayHead(); if ( $this->showoutgoing ) { $data = smwfGetStore()->getSemanticData( $this->subject->getDataItem() ); $html .= $this->displayData( $data, $leftside ); $html .= $this->displayCenter(); } if ( $this->showincoming ) { list( $indata, $more ) = $this->getInData(); global $smwgBrowseShowInverse; if ( !$smwgBrowseShowInverse ) { $leftside = !$leftside; } $html .= $this->displayData( $indata, $leftside, true ); $html .= $this->displayBottom( $more ); } $this->articletext = $this->subject->getWikiValue(); // Add a bit space between the factbox and the query form if ( !$this->including() ) { $html .= "<p> &#160; </p>\n"; } } if ( !$this->including() ) { $html .= $this->queryForm(); } $wgOut->addHTML( $html ); } /** * Creates the HTML table displaying the data of one subject. * * @param[in] $data SMWSemanticData The data to be displayed * @param[in] $left bool Should properties be displayed on the left side? * @param[in] $incoming bool Is this an incoming? Or an outgoing? * * @return A string containing the HTML with the factbox */ private function displayData( SMWSemanticData $data, $left = true, $incoming = false ) { // Some of the CSS classes are different for the left or the right side. // In this case, there is an "i" after the "smwb-". This is set here. $ccsPrefix = $left ? 'smwb-' : 'smwb-i'; $html = "<table class=\"{$ccsPrefix}factbox\" cellpadding=\"0\" cellspacing=\"0\">\n"; $diProperties = $data->getProperties(); $noresult = true; foreach ( $diProperties as $key => $diProperty ) { $dvProperty = SMWDataValueFactory::newDataItemValue( $diProperty, null ); if ( $dvProperty->isVisible() ) { $dvProperty->setCaption( $this->getPropertyLabel( $dvProperty, $incoming ) ); $proptext = $dvProperty->getShortHTMLText( smwfGetLinker() ) . "\n"; } elseif ( $diProperty->getKey() == '_INST' ) { $proptext = smwfGetLinker()->specialLink( 'Categories' ); } elseif ( $diProperty->getKey() == '_REDI' ) { $proptext = smwfGetLinker()->specialLink( 'Listredirects', 'isredirect' ); } else { continue; // skip this line } $head = '<th>' . $proptext . "</th>\n"; $body = "<td>\n"; $values = $data->getPropertyValues( $diProperty ); if ( $incoming && ( count( $values ) >= SMWSpecialBrowse::$incomingvaluescount ) ) { $moreIncoming = true; array_pop( $values ); } else { $moreIncoming = false; } $first = true; foreach ( $values as /* SMWDataItem */ $di ) { if ( $first ) { $first = false; } else { $body .= ', '; } if ( $incoming ) { $dv = SMWDataValueFactory::newDataItemValue( $di, null ); } else { $dv = SMWDataValueFactory::newDataItemValue( $di, $diProperty ); } $body .= "<span class=\"{$ccsPrefix}value\">" . $this->displayValue( $dvProperty, $dv, $incoming ) . "</span>\n"; } if ( $moreIncoming ) { // link to the remaining incoming pages: $body .= Html::element( 'a', array( 'href' => SpecialPage::getSafeTitleFor( 'SearchByProperty' )->getLocalURL( array( 'property' => $dvProperty->getWikiValue(), 'value' => $this->subject->getWikiValue() ) ) ), wfMessage( 'smw_browse_more' )->text() ); } $body .= "</td>\n"; // display row $html .= "<tr class=\"{$ccsPrefix}propvalue\">\n" . ( $left ? ( $head . $body ):( $body . $head ) ) . "</tr>\n"; $noresult = false; } // end foreach properties if ( $noresult ) { $html .= "<tr class=\"smwb-propvalue\"><th> &#160; </th><td><em>" . wfMessage( $incoming ? 'smw_browse_no_incoming':'smw_browse_no_outgoing' )->text() . "</em></td></tr>\n"; } $html .= "</table>\n"; return $html; } /** * Displays a value, including all relevant links (browse and search by property) * * @param[in] $property SMWPropertyValue The property this value is linked to the subject with * @param[in] $value SMWDataValue The actual value * @param[in] $incoming bool If this is an incoming or outgoing link * * @return string HTML with the link to the article, browse, and search pages */ private function displayValue( SMWPropertyValue $property, SMWDataValue $dataValue, $incoming ) { $linker = smwfGetLinker(); $html = $dataValue->getLongHTMLText( $linker ); if ( $dataValue->getTypeID() == '_wpg' ) { $html .= "&#160;" . SMWInfolink::newBrowsingLink( '+', $dataValue->getLongWikiText() )->getHTML( $linker ); } elseif ( $incoming && $property->isVisible() ) { $html .= "&#160;" . SMWInfolink::newInversePropertySearchLink( '+', $dataValue->getTitle(), $property->getDataItem()->getLabel(), 'smwsearch' )->getHTML( $linker ); } else { $html .= $dataValue->getInfolinkText( SMW_OUTPUT_HTML, $linker ); } return $html; } /** * Displays the subject that is currently being browsed to. * * @return A string containing the HTML with the subject line */ private function displayHead() { global $wgOut; $wgOut->setHTMLTitle( $this->subject->getTitle() ); $html = "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" . "<tr class=\"smwb-title\"><td colspan=\"2\">\n" . $this->subject->getLongHTMLText( smwfGetLinker() ) . "\n" . "</td></tr>\n</table>\n"; return $html; } /** * Creates the HTML for the center bar including the links with further navigation options. * * @return string HTMl with the center bar */ private function displayCenter() { return "<a name=\"smw_browse_incoming\"></a>\n" . "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" . "<tr class=\"smwb-center\"><td colspan=\"2\">\n" . ( $this->showincoming ? $this->linkHere( wfMessage( 'smw_browse_hide_incoming' )->text(), true, false, 0 ): $this->linkHere( wfMessage( 'smw_browse_show_incoming' )->text(), true, true, $this->offset ) ) . "&#160;\n" . "</td></tr>\n" . "</table>\n"; } /** * Creates the HTML for the bottom bar including the links with further navigation options. * * @param[in] $more bool Are there more inproperties to be displayed? * @return string HTMl with the bottom bar */ private function displayBottom( $more ) { $html = "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" . "<tr class=\"smwb-center\"><td colspan=\"2\">\n"; global $smwgBrowseShowAll; if ( !$smwgBrowseShowAll ) { if ( ( $this->offset > 0 ) || $more ) { $offset = max( $this->offset - SMWSpecialBrowse::$incomingpropertiescount + 1, 0 ); $html .= ( $this->offset == 0 ) ? wfMessage( 'smw_result_prev' )->text(): $this->linkHere( wfMessage( 'smw_result_prev' )->text(), $this->showoutgoing, true, $offset ); $offset = $this->offset + SMWSpecialBrowse::$incomingpropertiescount - 1; // @todo FIXME: i18n patchwork. $html .= " &#160;&#160;&#160; <strong>" . wfMessage( 'smw_result_results' )->text() . " " . ( $this->offset + 1 ) . " – " . ( $offset ) . "</strong> &#160;&#160;&#160; "; $html .= $more ? $this->linkHere( wfMessage( 'smw_result_next' )->text(), $this->showoutgoing, true, $offset ):wfMessage( 'smw_result_next' )->text(); } } $html .= "&#160;\n" . "</td></tr>\n" . "</table>\n"; return $html; } /** * Creates the HTML for a link to this page, with some parameters set. * * @param[in] $text string The anchor text for the link * @param[in] $out bool Should the linked to page include outgoing properties? * @param[in] $in bool Should the linked to page include incoming properties? * @param[in] $offset int What is the offset for the incoming properties? * * @return string HTML with the link to this page */ private function linkHere( $text, $out, $in, $offset ) { $frag = ( $text == wfMessage( 'smw_browse_show_incoming' )->text() ) ? '#smw_browse_incoming' : ''; return Html::element( 'a', array( 'href' => SpecialPage::getSafeTitleFor( 'Browse' )->getLocalURL( array( 'offset' => $offset, 'dir' => $out ? ( $in ? 'both' : 'out' ) : 'in', 'article' => $this->subject->getLongWikiText() ) ) . $frag ), $text ); } /** * Creates a Semantic Data object with the incoming properties instead of the * usual outproperties. * * @return array(SMWSemanticData, bool) The semantic data including all inproperties, and if there are more inproperties left */ private function getInData() { $indata = new SMWSemanticData( $this->subject->getDataItem() ); $options = new SMWRequestOptions(); $options->sort = true; $options->limit = SMWSpecialBrowse::$incomingpropertiescount; if ( $this->offset > 0 ) $options->offset = $this->offset; $inproperties = smwfGetStore()->getInProperties( $this->subject->getDataItem(), $options ); if ( count( $inproperties ) == SMWSpecialBrowse::$incomingpropertiescount ) { $more = true; array_pop( $inproperties ); // drop the last one } else { $more = false; } $valoptions = new SMWRequestOptions(); $valoptions->sort = true; $valoptions->limit = SMWSpecialBrowse::$incomingvaluescount; foreach ( $inproperties as $property ) { $values = smwfGetStore()->getPropertySubjects( $property, $this->subject->getDataItem(), $valoptions ); foreach ( $values as $value ) { $indata->addPropertyObjectValue( $property, $value ); } } return array( $indata, $more ); } /** * Figures out the label of the property to be used. For outgoing ones it is just * the text, for incoming ones we try to figure out the inverse one if needed, * either by looking for an explicitly stated one or by creating a default one. * * @param[in] $property SMWPropertyValue The property of interest * @param[in] $incoming bool If it is an incoming property * * @return string The label of the property */ private function getPropertyLabel( SMWPropertyValue $property, $incoming = false ) { global $smwgBrowseShowInverse; if ( $incoming && $smwgBrowseShowInverse ) { $oppositeprop = SMWPropertyValue::makeUserProperty( wfMessage( 'smw_inverse_label_property' )->text() ); $labelarray = &smwfGetStore()->getPropertyValues( $property->getDataItem()->getDiWikiPage(), $oppositeprop->getDataItem() ); $rv = ( count( $labelarray ) > 0 ) ? $labelarray[0]->getLongWikiText(): wfMessage( 'smw_inverse_label_default', $property->getWikiValue() )->text(); } else { $rv = $property->getWikiValue(); } return $this->unbreak( $rv ); } /** * Creates the query form in order to quickly switch to a specific article. * * @return A string containing the HTML for the form */ private function queryForm() { SMWOutputs::requireResource( 'ext.smw.browse' ); $title = SpecialPage::getTitleFor( 'Browse' ); return ' <form name="smwbrowse" action="' . htmlspecialchars( $title->getLocalURL() ) . '" method="get">' . "\n" . ' <input type="hidden" name="title" value="' . $title->getPrefixedText() . '"/>' . wfMessage( 'smw_browse_article' )->text() . "<br />\n" . ' <input type="text" name="article" id="page_input_box" value="' . htmlspecialchars( $this->articletext ) . '" />' . "\n" . ' <input type="submit" value="' . wfMessage( 'smw_browse_go' )->text() . "\"/>\n" . " </form>\n"; } /** * Replace the last two space characters with unbreakable spaces for beautification. * * @param[in] $text string Text to be transformed. Does not need to have spaces * @return string Transformed text */ private function unbreak( $text ) { $nonBreakingSpace = html_entity_decode( '&#160;', ENT_NOQUOTES, 'UTF-8' ); $text = preg_replace( '/[\s]/u', $nonBreakingSpace, $text, - 1, $count ); return $count > 2 ? preg_replace( '/($nonBreakingSpace)/u', ' ', $text, max( 0, $count - 2 ) ):$text; } }
JeroenDeDauw/SemanticMediaWiki
includes/specials/SMW_SpecialBrowse.php
PHP
gpl-2.0
14,800
<?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\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; /** * Validates that a card number belongs to a specified scheme. * * @author Tim Nagel <t.nagel@infinite.net.au> * @author Bernhard Schussek <bschussek@gmail.com> * * @see http://en.wikipedia.org/wiki/Bank_card_number * @see http://www.regular-expressions.info/creditcard.html * @see http://www.barclaycard.co.uk/business/files/Ranges_and_Rules_September_2014.pdf */ class CardSchemeValidator extends ConstraintValidator { protected $schemes = [ // American Express card numbers start with 34 or 37 and have 15 digits. 'AMEX' => [ '/^3[47][0-9]{13}$/', ], // China UnionPay cards start with 62 and have between 16 and 19 digits. // Please note that these cards do not follow Luhn Algorithm as a checksum. 'CHINA_UNIONPAY' => [ '/^62[0-9]{14,17}$/', ], // Diners Club card numbers begin with 300 through 305, 36 or 38. All have 14 digits. // There are Diners Club cards that begin with 5 and have 16 digits. // These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard. 'DINERS' => [ '/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/', ], // Discover card numbers begin with 6011, 622126 through 622925, 644 through 649 or 65. // All have 16 digits. 'DISCOVER' => [ '/^6011[0-9]{12}$/', '/^64[4-9][0-9]{13}$/', '/^65[0-9]{14}$/', '/^622(12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|91[0-9]|92[0-5])[0-9]{10}$/', ], // InstaPayment cards begin with 637 through 639 and have 16 digits. 'INSTAPAYMENT' => [ '/^63[7-9][0-9]{13}$/', ], // JCB cards beginning with 2131 or 1800 have 15 digits. // JCB cards beginning with 35 have 16 digits. 'JCB' => [ '/^(?:2131|1800|35[0-9]{3})[0-9]{11}$/', ], // Laser cards begin with either 6304, 6706, 6709 or 6771 and have between 16 and 19 digits. 'LASER' => [ '/^(6304|670[69]|6771)[0-9]{12,15}$/', ], // Maestro international cards begin with 675900..675999 and have between 12 and 19 digits. // Maestro UK cards begin with either 500000..509999 or 560000..699999 and have between 12 and 19 digits. 'MAESTRO' => [ '/^(6759[0-9]{2})[0-9]{6,13}$/', '/^(50[0-9]{4})[0-9]{6,13}$/', '/^5[6-9][0-9]{10,17}$/', '/^6[0-9]{11,18}$/', ], // All MasterCard numbers start with the numbers 51 through 55. All have 16 digits. // October 2016 MasterCard numbers can also start with 222100 through 272099. 'MASTERCARD' => [ '/^5[1-5][0-9]{14}$/', '/^2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12})$/', ], // All Visa card numbers start with a 4 and have a length of 13, 16, or 19 digits. 'VISA' => [ '/^4([0-9]{12}|[0-9]{15}|[0-9]{18})$/', ], ]; /** * Validates a creditcard belongs to a specified scheme. * * @param mixed $value * @param Constraint $constraint */ public function validate($value, Constraint $constraint) { if (!$constraint instanceof CardScheme) { throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\CardScheme'); } if (null === $value || '' === $value) { return; } if (!is_numeric($value)) { $this->context->buildViolation($constraint->message) ->setParameter('{{ value }}', $this->formatValue($value)) ->setCode(CardScheme::NOT_NUMERIC_ERROR) ->addViolation(); return; } $schemes = array_flip((array) $constraint->schemes); $schemeRegexes = array_intersect_key($this->schemes, $schemes); foreach ($schemeRegexes as $regexes) { foreach ($regexes as $regex) { if (preg_match($regex, $value)) { return; } } } $this->context->buildViolation($constraint->message) ->setParameter('{{ value }}', $this->formatValue($value)) ->setCode(CardScheme::INVALID_FORMAT_ERROR) ->addViolation(); } }
enslyon/ensl
vendor/symfony/validator/Constraints/CardSchemeValidator.php
PHP
gpl-2.0
4,811
<?php Class AddThis_addjs_extender extends AddThis_addjs{ var $jsAfterAdd; function getAtPluginPromoText(){ if (! did_action('admin_init') && ! current_filter('admin_init')) { _doing_it_wrong('getAtPluginPromoText', 'This function should only be called on an admin page load and no earlier the admin_init', 1); return null; } if (apply_filters('addthis_crosspromote', '__return_true')) { $plugins = get_plugins(); if (empty($this->_atInstalled)) { foreach($plugins as $plugin) { if (substr($plugin['Name'], 0, 7) === 'AddThis') array_push($this->_atInstalled, $plugin['Name']); } } $keys = array_keys($this->_atPlugins); $uninstalled = array_diff( $keys, $this->_atInstalled); if (empty($uninstalled)) return false; // Get rid of our keys, we just want the names which are the keys elsewhere $uninstalled = array_values($uninstalled); $string = __('Want to increase your site traffic? AddThis also has '); $count = count($uninstalled); if ($count == 1){ $string .= __('a plugin for ', 'addthis'); $string .= __( sprintf('<a href="%s" target="_blank">' .$this->_atPlugins[$uninstalled[0]][1] .'</a>', $this->_atPlugins[$uninstalled[0]][0]), 'addthis'); } else { $string . __('plugins for '); for ($i = 0; $i < $count; $i++) { $string .= __( sprintf('<strong><a href="%s" target="_blank" >' .$this->_atPlugins[$uninstalled[$i]][1] .'</a></strong>', $this->_atPlugins[$uninstalled[$i]][0]), 'addthis'); if ($i < ($count - 2)) $string .= ', '; else if ($i == ($count -2)) $string .= ' and '; else if ($i == ($count -1)) $string .= ' plugins available.'; } } return '<p class="addthis_more_promo">' .$string . '</p>'; } } function addAfterScript($newData){ $this->jsAfterAdd .= $newData; } function addAfterToJs(){ if (! empty($this->jsAfterAdd)); $this->jsToAdd .= '<script type="text/javascript">' . $this->jsAfterAdd . '</script>'; } function output_script(){ if ($this->_js_added != true) { $this->wrapJs(); $this->addWidgetToJs(); $this->addAfterToJs(); echo $this->jsToAdd; $this->_js_added = true; } } function output_script_filter($content){ if ($this->_js_added != true && ! is_admin() && ! is_feed() ) { $this->wrapJs(); $this->addWidgetToJs(); $this->addAfterToJs(); $content = $content . $this->jsToAdd; $this->_js_added = true; } return $content; } }
cw196/tiwal
zh/wp-content/plugins/addthis-smart-layers/views/includes/addthis_addjs_extender.php
PHP
gpl-2.0
3,170
<?php /** * File containing the LocaleConverterInterface interface. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Publish\Core\MVC\Symfony\Locale; /** * Interface for locale converters. * eZ Publish uses <ISO639-2/B>-<ISO3166-Alpha2> locale format (mostly, some supported locales being out of this format, e.g. cro-HR). * Symfony uses the standard POSIX locale format (<ISO639-1>_<ISO3166-Alpha2>), which is supported by Intl PHP extension. * * Locale converters are meant to convert in those 2 formats back and forth. */ interface LocaleConverterInterface { /** * Converts a locale in eZ Publish internal format to POSIX format. * Returns null if conversion cannot be made. * * @param string $ezpLocale * * @return string|null */ public function convertToPOSIX($ezpLocale); /** * Converts a locale in POSIX format to eZ Publish internal format. * Returns null if conversion cannot be made. * * @param string $posixLocale * * @return string|null */ public function convertToEz($posixLocale); }
alongosz/ezpublish-kernel
eZ/Publish/Core/MVC/Symfony/Locale/LocaleConverterInterface.php
PHP
gpl-2.0
1,236
<?php defined('_JEXEC') or die; ?> <?php if ( $this->params->def( 'show_page_title', 1 ) ) : ?> <div class="componentheading<?php echo $this->params->get( 'pageclass_sfx' ); ?>"> <?php echo $this->escape($this->params->get('page_title')); ?> </div> <?php endif; ?> <form action="index.php?option=com_user&amp;task=remindusername" method="post" class="josForm form-validate"> <table cellpadding="0" cellspacing="0" border="0" width="100%" class="contentpane"> <tr> <td colspan="2" height="40"> <p><?php echo JText::_('REMIND_USERNAME_DESCRIPTION'); ?></p> </td> </tr> <tr> <td height="40"> <label for="email" class="hasTip" title="<?php echo JText::_('REMIND_USERNAME_EMAIL_TIP_TITLE'); ?>::<?php echo JText::_('REMIND_USERNAME_EMAIL_TIP_TEXT'); ?>"><?php echo JText::_('Email Address'); ?>:</label> </td> <td> <input id="email" name="email" type="text" class="required validate-email" /> </td> </tr> </table> <button type="submit" class="validate"><?php echo JText::_('Submit'); ?></button> <?php echo JHTML::_( 'form.token' ); ?> </form>
intelogen/organica
components/com_user_0/views/remind/tmpl/default.php
PHP
gpl-2.0
1,088
# # Copyright (C) 2000-2005 by Yasushi Saito (yasushi.saito@gmail.com) # # Jockey 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. # # Jockey 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. # import tick_mark import line_style import pychart_util import error_bar import chart_object import legend import object_set import line_plot_doc import theme from pychart_types import * from types import * default_width = 1.2 line_style_itr = None _keys = { 'data' : (AnyType, None, pychart_util.data_desc), 'label': (StringType, '???', pychart_util.label_desc), 'data_label_offset': (CoordType, (0, 5), """The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""), 'data_label_format': (FormatType, None, """The format string for the label printed beside a sample point. It can be a `printf' style format string, or a two-parameter function that takes the (x, y) values and returns a string. """ + pychart_util.string_desc), 'xcol' : (IntType, 0, pychart_util.xcol_desc), 'ycol': (IntType, 1, pychart_util.ycol_desc), 'y_error_minus_col': (IntType, 2, """The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""), 'y_error_plus_col': (IntType, -1, """The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""), 'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'), 'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'), 'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc, "By default, a style is picked from standard styles round-robin. <<line_style>>"), 'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc), 'error_bar': (error_bar.T, None, 'The style of the error bar. <<error_bar>>'), } class T(chart_object.T): __doc__ = line_plot_doc.doc keys = _keys def check_integrity(self): assert chart_object.T.check_integrity(self) ##AUTOMATICALLY GENERATED ##END AUTOMATICALLY GENERATED def get_data_range(self, which): if which == 'X': return pychart_util.get_data_range(self.data, self.xcol) else: return pychart_util.get_data_range(self.data, self.ycol) def get_legend_entry(self): if self.label: line_style = self.line_style if not line_style and self.error_bar: line_style = getattr(self.error_bar, 'line_style', None) or \ getattr(self.error_bar, 'hline_style', None) or \ getattr(self.error_bar, 'vline_style', None) if not line_style: raise Exception, 'Line plot has label, but an empty line style and error bar.' return legend.Entry(line_style=line_style, tick_mark=self.tick_mark, fill_style=None, label=self.label) return None def draw(self, ar, can): # Draw the line clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1], ar.loc[0] + ar.size[0], ar.loc[1] + ar.size[1]]); can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3]) if self.line_style: points = [] for pair in self.data: yval = pychart_util.get_sample_val(pair, self.ycol) xval = pair[self.xcol] if None not in (xval, yval): points.append((ar.x_pos(xval), ar.y_pos(yval))) can.lines(self.line_style, points) can.endclip() # Draw tick marks and error bars can.clip(ar.loc[0] - 10, ar.loc[1] - 10, ar.loc[0] + ar.size[0] + 10, ar.loc[1] + ar.size[1] + 10) for pair in self.data: x = pair[self.xcol] y = pychart_util.get_sample_val(pair, self.ycol) if None in (x, y): continue x_pos = ar.x_pos(x) y_pos = ar.y_pos(y) if self.error_bar: plus = pair[self.y_error_plus_col or self.y_error_minus_col] minus = pair[self.y_error_minus_col or self.y_error_plus_col] if self.y_qerror_minus_col or self.y_qerror_plus_col: q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col] q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col] if None not in (minus,plus,q_minus,q_plus): self.error_bar.draw(can, (x_pos, y_pos), ar.y_pos(y - minus), ar.y_pos(y + plus), ar.y_pos(y - q_minus), ar.y_pos(y + q_plus)) else: if None not in (minus,plus): #PDS self.error_bar.draw(can, (x_pos, y_pos), ar.y_pos(y - minus), ar.y_pos(y + plus)) if self.tick_mark: self.tick_mark.draw(can, x_pos, y_pos) if self.data_label_format: can.show(x_pos + self.data_label_offset[0], y_pos + self.data_label_offset[1], '/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1)) can.endclip() def init(): global line_style_itr line_styles = object_set.T() for org_style in line_style.standards.list(): style = line_style.T(width = default_width, color = org_style.color, dash = org_style.dash) line_styles.add(style) line_style_itr = line_styles.iterate() theme.add_reinitialization_hook(init)
ShaolongHu/lpts
site-packages/pychart/line_plot.py
Python
gpl-2.0
6,684
<?php /** * FTP Exception Class * * @author Andreas Skodzek <webmaster@phpbuddy.eu> * @link http://www.phpbuddy.eu/ * @copyright 2008 Andreas Skodzek * @license GNU Public License <http://www.gnu.org/licenses/gpl.html> * @package phpBuddy.FTP.Exception.Class * @version 1.0 released 01.09.2008 */ class FTPException extends Exception { /** * Error Message if no native FTP support is available */ const FTP_SUPPORT_ERROR = 'Die FTP-Funktionen sind auf diesem System nicht verfuegbar!'; /** * Error Message if the given Host does not respond */ const CONNECT_FAILED_BADHOST = 'Der angegebene Host konnte nicht kontaktiert werden!'; /** * Error Message if no SSL-FTP is available and no fallback is used */ const CONNECT_FAILED_NOSSL = 'Die Verbindung via SSL konnte nicht hergestellt werden!'; /** * Error Message if the given login information is not valid */ const CONNECT_FAILED_BADLOGIN = 'Die Zugangsdaten für die FTP Verbindung sind inkorrekt!'; /** * Error Message if the FTP server OS could not be determined. */ const CONNECT_UNKNOWN_OS = 'Das Betriebssystem des FTP Server konnte nicht identifiziert werden!'; /** * Constructor */ public function __construct( $meldung, $code = 0 ) { parent::__construct( $meldung, $code ); } } ?>
meetai/2Moons
src/includes/libs/ftp/ftpexception.class.php
PHP
gpl-3.0
1,339
using SmartStore.Web.Framework.Modelling; namespace SmartStore.PayPal.Models { public class PayPalExpressPaymentInfoModel : ModelBase { public PayPalExpressPaymentInfoModel() { } public bool CurrentPageIsBasket { get; set; } public string SubmitButtonImageUrl { get; set; } } }
chunlizh/SmartStoreNET
src/Plugins/SmartStore.PayPal/Models/PayPalExpressPaymentInfoModel.cs
C#
gpl-3.0
349
<?php namespace app\models; use app\properties\HasProperties; use devgroup\TagDependencyHelper\ActiveRecordHelper; use Yii; use yii\behaviors\AttributeBehavior; use yii\caching\TagDependency; use yii\data\ActiveDataProvider; use yii\db\ActiveRecord; /** * This is the model class for table "property_group". * * @property integer $id * @property integer $object_id * @property string $name * @property integer $sort_order * @property integer $is_internal * @property integer $hidden_group_title */ class PropertyGroup extends ActiveRecord { private static $identity_map = []; private static $groups_by_object_id = []; /** * @inheritdoc */ public function behaviors() { return [ [ 'class' => AttributeBehavior::className(), 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => 'sort_order', ], 'value' => 0, ], [ 'class' => ActiveRecordHelper::className(), ], ]; } /** * @inheritdoc */ public static function tableName() { return '{{%property_group}}'; } /** * @inheritdoc */ public function rules() { return [ [['object_id', 'name'], 'required'], [['object_id', 'sort_order', 'is_internal', 'hidden_group_title'], 'integer'], [['name'], 'string'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'object_id' => Yii::t('app', 'Object ID'), 'name' => Yii::t('app', 'Name'), 'sort_order' => Yii::t('app', 'Sort Order'), 'is_internal' => Yii::t('app', 'Is Internal'), 'hidden_group_title' => Yii::t('app', 'Hidden Group Title'), ]; } /** * Relation to \app\models\Object * @return \yii\db\ActiveQuery */ public function getObject() { return $this->hasOne(Object::className(), ['id' => 'object_id']); } /** * Search tasks * @param $params * @return ActiveDataProvider */ public function search($params) { /* @var $query \yii\db\ActiveQuery */ $query = self::find(); $dataProvider = new ActiveDataProvider( [ 'query' => $query, 'pagination' => [ 'pageSize' => 10, ], ] ); if (!($this->load($params))) { return $dataProvider; } $query->andFilterWhere(['id' => $this->id]); $query->andFilterWhere(['like', 'name', $this->name]); $query->andFilterWhere(['object_id' => $this->object_id]); $query->andFilterWhere(['is_internal' => $this->is_internal]); $query->andFilterWhere(['hidden_group_title' => $this->hidden_group_title]); return $dataProvider; } /** * Возвращает модель по ID с использованием IdentityMap * * @param int $id * @return null|PropertyGroup */ public static function findById($id) { if (!isset(static::$identity_map[$id])) { $cacheKey = "PropertyGroup:$id"; if (false === $group = Yii::$app->cache->get($cacheKey)) { if (null !== $group = static::findOne($id)) { Yii::$app->cache->set( $cacheKey, $group, 0, new TagDependency( [ 'tags' => [ ActiveRecordHelper::getObjectTag(static::className(), $id), ], ] ) ); } } static::$identity_map[$id] = $group; } return static::$identity_map[$id]; } /** * Relation to properties * @return \yii\db\ActiveQuery */ public function getProperties() { return $this->hasMany(Property::className(), ['property_group_id' => 'id'])->orderBy('sort_order'); } /** * @param $object_id * @param bool $withProperties * @return PropertyGroup[] */ public static function getForObjectId($object_id, $withProperties = false) { if (null === $object_id) { return []; } if (!isset(static::$groups_by_object_id[$object_id])) { $cacheKey = 'PropertyGroup:objectId:'.$object_id; static::$groups_by_object_id[$object_id] = Yii::$app->cache->get($cacheKey); if (!is_array(static::$groups_by_object_id[$object_id])) { $query = static::find() ->where(['object_id'=>$object_id]) ->orderBy('sort_order'); if ($withProperties === true) { $query = $query->with('properties'); } static::$groups_by_object_id[$object_id] = $query->all(); if (null !== $object = Object::findById($object_id)) { $tags = [ ActiveRecordHelper::getObjectTag($object, $object_id) ]; foreach (static::$groups_by_object_id[$object_id] as $propertyGroup){ $tags[] = ActiveRecordHelper::getObjectTag($propertyGroup, $propertyGroup->id); if ($withProperties === true) { foreach ($propertyGroup->properties as $prop) { if (isset(Property::$group_id_to_property_ids[$propertyGroup->id]) === false) { Property::$group_id_to_property_ids[$propertyGroup->id]=[]; } Property::$group_id_to_property_ids[$propertyGroup->id][] = $prop->id; Property::$identity_map[$prop->id] = $prop; } } } Yii::$app->cache->set( $cacheKey, static::$groups_by_object_id[$object_id], 0, new TagDependency( [ 'tags' => $tags, ] ) ); } } } return static::$groups_by_object_id[$object_id]; } /** * @param int $object_id * @param int $object_model_id * @return null|\yii\db\ActiveRecord[] */ public static function getForModel($object_id, $object_model_id) { $cacheKey = "PropertyGroupBy:$object_id:$object_model_id"; if (false === $groups = Yii::$app->cache->get($cacheKey)) { $group_ids = ObjectPropertyGroup::find() ->select('property_group_id') ->where([ 'object_id' => $object_id, 'object_model_id' => $object_model_id, ])->column(); if (null === $group_ids) { return null; } if (null === $groups = static::find()->where(['in', 'id', $group_ids])->all()) { return null; } if (null !== $object = Object::findById($object_id)) { Yii::$app->cache->set( $cacheKey, $groups, 0, new TagDependency( [ 'tags' => [ ActiveRecordHelper::getObjectTag($object, $object_id), ActiveRecordHelper::getObjectTag($object->object_class, $object_model_id), ], ] ) ); } } return $groups; } public function beforeDelete() { if (!parent::beforeDelete()) { return false; } $properties = Property::findAll(['property_group_id' => $this->id]); foreach ($properties as $prop) { $prop->delete(); } return true; } public function afterDelete() { ObjectPropertyGroup::deleteAll(['property_group_id' => $this->id]); parent::afterDelete(); } /** * @param ActiveRecord|HasProperties $model * @param string $idAttribute * @return bool */ public function appendToObjectModel(ActiveRecord $model, $idAttribute = 'id') { $object = Object::getForClass($model::className()); if (null === $object || !$model->hasAttribute($idAttribute)) { return false; } $link = new ObjectPropertyGroup(); $link->object_id = $object->id; $link->object_model_id = $model->$idAttribute; $link->property_group_id = $this->id; $result = $link->save(); $model->updatePropertyGroupsInformation(); return $result; } } ?>
rinodung/yii2-shop-cms
models/PropertyGroup.php
PHP
gpl-3.0
9,292
package org.jnbt; /* * JNBT License * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * The <code>TAG_Float</code> tag. * @author Graham Edgecombe * */ public final class FloatTag extends Tag { /** * The value. */ private final float value; /** * Creates the tag. * @param name The name. * @param value The value. */ public FloatTag(String name, float value) { super(name); this.value = value; } @Override public Float getValue() { return value; } @Override public String toString() { String name = getName(); String append = ""; if(name != null && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } return "TAG_Float" + append + ": " + value; } }
ferrybig/Enderstone
src/org/jnbt/FloatTag.java
Java
gpl-3.0
2,294
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ /* * Date: 2001-07-12 * * SUMMARY: Regression test for bug 89443 * See http://bugzilla.mozilla.org/show_bug.cgi?id=89443 * * Just seeing if this script will compile without stack overflow. */ //----------------------------------------------------------------------------- var gTestfile = 'regress-89443.js'; var BUGNUMBER = 89443; var summary = 'Testing this script will compile without stack overflow'; printBugNumber(BUGNUMBER); printStatus (summary); // I don't know what these functions are supposed to be; use dummies - function isPlainHostName() { } function dnsDomainIs() { } // Here's the big function - function FindProxyForURL(url, host) { if (isPlainHostName(host) || dnsDomainIs(host, ".hennepin.lib.mn.us") || dnsDomainIs(host, ".hclib.org") ) return "DIRECT"; else if (isPlainHostName(host) // subscription database access || dnsDomainIs(host, ".asahi.com") || dnsDomainIs(host, ".2facts.com") || dnsDomainIs(host, ".oclc.org") || dnsDomainIs(host, ".collegesource.com") || dnsDomainIs(host, ".cq.com") || dnsDomainIs(host, ".grolier.com") || dnsDomainIs(host, ".groveart.com") || dnsDomainIs(host, ".groveopera.com") || dnsDomainIs(host, ".fsonline.com") || dnsDomainIs(host, ".carl.org") || dnsDomainIs(host, ".newslibrary.com") || dnsDomainIs(host, ".pioneerplanet.com") || dnsDomainIs(host, ".startribune.com") || dnsDomainIs(host, ".poemfinder.com") || dnsDomainIs(host, ".umi.com") || dnsDomainIs(host, ".referenceusa.com") || dnsDomainIs(host, ".sirs.com") || dnsDomainIs(host, ".krmediastream.com") || dnsDomainIs(host, ".gale.com") || dnsDomainIs(host, ".galenet.com") || dnsDomainIs(host, ".galegroup.com") || dnsDomainIs(host, ".facts.com") || dnsDomainIs(host, ".eb.com") || dnsDomainIs(host, ".worldbookonline.com") || dnsDomainIs(host, ".galegroup.com") || dnsDomainIs(host, ".accessscience.com") || dnsDomainIs(host, ".booksinprint.com") || dnsDomainIs(host, ".infolearning.com") || dnsDomainIs(host, ".standardpoor.com") // image servers || dnsDomainIs(host, ".akamaitech.net") || dnsDomainIs(host, ".akamai.net") || dnsDomainIs(host, ".yimg.com") || dnsDomainIs(host, ".imgis.com") || dnsDomainIs(host, ".ibsys.com") // KidsClick-linked kids search engines || dnsDomainIs(host, ".edview.com") || dnsDomainIs(host, ".searchopolis.com") || dnsDomainIs(host, ".onekey.com") || dnsDomainIs(host, ".askjeeves.com") // Non-subscription Reference Tools URLs from the RecWebSites DBData table || dnsDomainIs(host, "www.cnn.com") || dnsDomainIs(host, "www.emulateme.com") || dnsDomainIs(host, "terraserver.microsoft.com") || dnsDomainIs(host, "www.theodora.com") || dnsDomainIs(host, "www.3datlas.com") || dnsDomainIs(host, "www.infoplease.com") || dnsDomainIs(host, "www.switchboard.com") || dnsDomainIs(host, "www.bartleby.com") || dnsDomainIs(host, "www.mn-politics.com") || dnsDomainIs(host, "www.thesaurus.com") || dnsDomainIs(host, "www.usnews.com") || dnsDomainIs(host, "www.petersons.com") || dnsDomainIs(host, "www.collegenet.com") || dnsDomainIs(host, "www.m-w.com") || dnsDomainIs(host, "clever.net") || dnsDomainIs(host, "maps.expedia.com") || dnsDomainIs(host, "www.CollegeEdge.com") || dnsDomainIs(host, "www.homeworkcentral.com") || dnsDomainIs(host, "www.studyweb.com") || dnsDomainIs(host, "www.mnpro.com") // custom URLs for local and other access || dnsDomainIs(host, ".dsdukes.com") || dnsDomainIs(host, ".spsaints.com") || dnsDomainIs(host, ".mnzoo.com") || dnsDomainIs(host, ".realaudio.com") || dnsDomainIs(host, ".co.hennepin.mn.us") || dnsDomainIs(host, ".gov") || dnsDomainIs(host, ".org") || dnsDomainIs(host, ".edu") || dnsDomainIs(host, ".fox29.com") || dnsDomainIs(host, ".wcco.com") || dnsDomainIs(host, ".kstp.com") || dnsDomainIs(host, ".kmsp.com") || dnsDomainIs(host, ".kare11.com") || dnsDomainIs(host, ".macromedia.com") || dnsDomainIs(host, ".shockwave.com") || dnsDomainIs(host, ".wwf.com") || dnsDomainIs(host, ".wwfsuperstars.com") || dnsDomainIs(host, ".summerslam.com") || dnsDomainIs(host, ".yahooligans.com") || dnsDomainIs(host, ".mhoob.com") || dnsDomainIs(host, "www.hmonginternet.com") || dnsDomainIs(host, "www.hmongonline.com") || dnsDomainIs(host, ".yahoo.com") || dnsDomainIs(host, ".pokemon.com") || dnsDomainIs(host, ".bet.com") || dnsDomainIs(host, ".smallworld.com") || dnsDomainIs(host, ".cartoonnetwork.com") || dnsDomainIs(host, ".carmensandiego.com") || dnsDomainIs(host, ".disney.com") || dnsDomainIs(host, ".powerpuffgirls.com") || dnsDomainIs(host, ".aol.com") // Smithsonian || dnsDomainIs(host, "160.111.100.190") // Hotmail || dnsDomainIs(host, ".passport.com") || dnsDomainIs(host, ".hotmail.com") || dnsDomainIs(host, "216.33.236.24") || dnsDomainIs(host, "216.32.182.251") || dnsDomainIs(host, ".hotmail.msn.com") // K12 schools || dnsDomainIs(host, ".k12.al.us") || dnsDomainIs(host, ".k12.ak.us") || dnsDomainIs(host, ".k12.ar.us") || dnsDomainIs(host, ".k12.az.us") || dnsDomainIs(host, ".k12.ca.us") || dnsDomainIs(host, ".k12.co.us") || dnsDomainIs(host, ".k12.ct.us") || dnsDomainIs(host, ".k12.dc.us") || dnsDomainIs(host, ".k12.de.us") || dnsDomainIs(host, ".k12.fl.us") || dnsDomainIs(host, ".k12.ga.us") || dnsDomainIs(host, ".k12.hi.us") || dnsDomainIs(host, ".k12.id.us") || dnsDomainIs(host, ".k12.il.us") || dnsDomainIs(host, ".k12.in.us") || dnsDomainIs(host, ".k12.ia.us") || dnsDomainIs(host, ".k12.ks.us") || dnsDomainIs(host, ".k12.ky.us") || dnsDomainIs(host, ".k12.la.us") || dnsDomainIs(host, ".k12.me.us") || dnsDomainIs(host, ".k12.md.us") || dnsDomainIs(host, ".k12.ma.us") || dnsDomainIs(host, ".k12.mi.us") || dnsDomainIs(host, ".k12.mn.us") || dnsDomainIs(host, ".k12.ms.us") || dnsDomainIs(host, ".k12.mo.us") || dnsDomainIs(host, ".k12.mt.us") || dnsDomainIs(host, ".k12.ne.us") || dnsDomainIs(host, ".k12.nv.us") || dnsDomainIs(host, ".k12.nh.us") || dnsDomainIs(host, ".k12.nj.us") || dnsDomainIs(host, ".k12.nm.us") || dnsDomainIs(host, ".k12.ny.us") || dnsDomainIs(host, ".k12.nc.us") || dnsDomainIs(host, ".k12.nd.us") || dnsDomainIs(host, ".k12.oh.us") || dnsDomainIs(host, ".k12.ok.us") || dnsDomainIs(host, ".k12.or.us") || dnsDomainIs(host, ".k12.pa.us") || dnsDomainIs(host, ".k12.ri.us") || dnsDomainIs(host, ".k12.sc.us") || dnsDomainIs(host, ".k12.sd.us") || dnsDomainIs(host, ".k12.tn.us") || dnsDomainIs(host, ".k12.tx.us") || dnsDomainIs(host, ".k12.ut.us") || dnsDomainIs(host, ".k12.vt.us") || dnsDomainIs(host, ".k12.va.us") || dnsDomainIs(host, ".k12.wa.us") || dnsDomainIs(host, ".k12.wv.us") || dnsDomainIs(host, ".k12.wi.us") || dnsDomainIs(host, ".k12.wy.us") // U.S. Libraries || dnsDomainIs(host, ".lib.al.us") || dnsDomainIs(host, ".lib.ak.us") || dnsDomainIs(host, ".lib.ar.us") || dnsDomainIs(host, ".lib.az.us") || dnsDomainIs(host, ".lib.ca.us") || dnsDomainIs(host, ".lib.co.us") || dnsDomainIs(host, ".lib.ct.us") || dnsDomainIs(host, ".lib.dc.us") || dnsDomainIs(host, ".lib.de.us") || dnsDomainIs(host, ".lib.fl.us") || dnsDomainIs(host, ".lib.ga.us") || dnsDomainIs(host, ".lib.hi.us") || dnsDomainIs(host, ".lib.id.us") || dnsDomainIs(host, ".lib.il.us") || dnsDomainIs(host, ".lib.in.us") || dnsDomainIs(host, ".lib.ia.us") || dnsDomainIs(host, ".lib.ks.us") || dnsDomainIs(host, ".lib.ky.us") || dnsDomainIs(host, ".lib.la.us") || dnsDomainIs(host, ".lib.me.us") || dnsDomainIs(host, ".lib.md.us") || dnsDomainIs(host, ".lib.ma.us") || dnsDomainIs(host, ".lib.mi.us") || dnsDomainIs(host, ".lib.mn.us") || dnsDomainIs(host, ".lib.ms.us") || dnsDomainIs(host, ".lib.mo.us") || dnsDomainIs(host, ".lib.mt.us") || dnsDomainIs(host, ".lib.ne.us") || dnsDomainIs(host, ".lib.nv.us") || dnsDomainIs(host, ".lib.nh.us") || dnsDomainIs(host, ".lib.nj.us") || dnsDomainIs(host, ".lib.nm.us") || dnsDomainIs(host, ".lib.ny.us") || dnsDomainIs(host, ".lib.nc.us") || dnsDomainIs(host, ".lib.nd.us") || dnsDomainIs(host, ".lib.oh.us") || dnsDomainIs(host, ".lib.ok.us") || dnsDomainIs(host, ".lib.or.us") || dnsDomainIs(host, ".lib.pa.us") || dnsDomainIs(host, ".lib.ri.us") || dnsDomainIs(host, ".lib.sc.us") || dnsDomainIs(host, ".lib.sd.us") || dnsDomainIs(host, ".lib.tn.us") || dnsDomainIs(host, ".lib.tx.us") || dnsDomainIs(host, ".lib.ut.us") || dnsDomainIs(host, ".lib.vt.us") || dnsDomainIs(host, ".lib.va.us") || dnsDomainIs(host, ".lib.wa.us") || dnsDomainIs(host, ".lib.wv.us") || dnsDomainIs(host, ".lib.wi.us") || dnsDomainIs(host, ".lib.wy.us") // U.S. Cities || dnsDomainIs(host, ".ci.al.us") || dnsDomainIs(host, ".ci.ak.us") || dnsDomainIs(host, ".ci.ar.us") || dnsDomainIs(host, ".ci.az.us") || dnsDomainIs(host, ".ci.ca.us") || dnsDomainIs(host, ".ci.co.us") || dnsDomainIs(host, ".ci.ct.us") || dnsDomainIs(host, ".ci.dc.us") || dnsDomainIs(host, ".ci.de.us") || dnsDomainIs(host, ".ci.fl.us") || dnsDomainIs(host, ".ci.ga.us") || dnsDomainIs(host, ".ci.hi.us") || dnsDomainIs(host, ".ci.id.us") || dnsDomainIs(host, ".ci.il.us") || dnsDomainIs(host, ".ci.in.us") || dnsDomainIs(host, ".ci.ia.us") || dnsDomainIs(host, ".ci.ks.us") || dnsDomainIs(host, ".ci.ky.us") || dnsDomainIs(host, ".ci.la.us") || dnsDomainIs(host, ".ci.me.us") || dnsDomainIs(host, ".ci.md.us") || dnsDomainIs(host, ".ci.ma.us") || dnsDomainIs(host, ".ci.mi.us") || dnsDomainIs(host, ".ci.mn.us") || dnsDomainIs(host, ".ci.ms.us") || dnsDomainIs(host, ".ci.mo.us") || dnsDomainIs(host, ".ci.mt.us") || dnsDomainIs(host, ".ci.ne.us") || dnsDomainIs(host, ".ci.nv.us") || dnsDomainIs(host, ".ci.nh.us") || dnsDomainIs(host, ".ci.nj.us") || dnsDomainIs(host, ".ci.nm.us") || dnsDomainIs(host, ".ci.ny.us") || dnsDomainIs(host, ".ci.nc.us") || dnsDomainIs(host, ".ci.nd.us") || dnsDomainIs(host, ".ci.oh.us") || dnsDomainIs(host, ".ci.ok.us") || dnsDomainIs(host, ".ci.or.us") || dnsDomainIs(host, ".ci.pa.us") || dnsDomainIs(host, ".ci.ri.us") || dnsDomainIs(host, ".ci.sc.us") || dnsDomainIs(host, ".ci.sd.us") || dnsDomainIs(host, ".ci.tn.us") || dnsDomainIs(host, ".ci.tx.us") || dnsDomainIs(host, ".ci.ut.us") || dnsDomainIs(host, ".ci.vt.us") || dnsDomainIs(host, ".ci.va.us") || dnsDomainIs(host, ".ci.wa.us") || dnsDomainIs(host, ".ci.wv.us") || dnsDomainIs(host, ".ci.wi.us") || dnsDomainIs(host, ".ci.wy.us") // U.S. Counties || dnsDomainIs(host, ".co.al.us") || dnsDomainIs(host, ".co.ak.us") || dnsDomainIs(host, ".co.ar.us") || dnsDomainIs(host, ".co.az.us") || dnsDomainIs(host, ".co.ca.us") || dnsDomainIs(host, ".co.co.us") || dnsDomainIs(host, ".co.ct.us") || dnsDomainIs(host, ".co.dc.us") || dnsDomainIs(host, ".co.de.us") || dnsDomainIs(host, ".co.fl.us") || dnsDomainIs(host, ".co.ga.us") || dnsDomainIs(host, ".co.hi.us") || dnsDomainIs(host, ".co.id.us") || dnsDomainIs(host, ".co.il.us") || dnsDomainIs(host, ".co.in.us") || dnsDomainIs(host, ".co.ia.us") || dnsDomainIs(host, ".co.ks.us") || dnsDomainIs(host, ".co.ky.us") || dnsDomainIs(host, ".co.la.us") || dnsDomainIs(host, ".co.me.us") || dnsDomainIs(host, ".co.md.us") || dnsDomainIs(host, ".co.ma.us") || dnsDomainIs(host, ".co.mi.us") || dnsDomainIs(host, ".co.mn.us") || dnsDomainIs(host, ".co.ms.us") || dnsDomainIs(host, ".co.mo.us") || dnsDomainIs(host, ".co.mt.us") || dnsDomainIs(host, ".co.ne.us") || dnsDomainIs(host, ".co.nv.us") || dnsDomainIs(host, ".co.nh.us") || dnsDomainIs(host, ".co.nj.us") || dnsDomainIs(host, ".co.nm.us") || dnsDomainIs(host, ".co.ny.us") || dnsDomainIs(host, ".co.nc.us") || dnsDomainIs(host, ".co.nd.us") || dnsDomainIs(host, ".co.oh.us") || dnsDomainIs(host, ".co.ok.us") || dnsDomainIs(host, ".co.or.us") || dnsDomainIs(host, ".co.pa.us") || dnsDomainIs(host, ".co.ri.us") || dnsDomainIs(host, ".co.sc.us") || dnsDomainIs(host, ".co.sd.us") || dnsDomainIs(host, ".co.tn.us") || dnsDomainIs(host, ".co.tx.us") || dnsDomainIs(host, ".co.ut.us") || dnsDomainIs(host, ".co.vt.us") || dnsDomainIs(host, ".co.va.us") || dnsDomainIs(host, ".co.wa.us") || dnsDomainIs(host, ".co.wv.us") || dnsDomainIs(host, ".co.wi.us") || dnsDomainIs(host, ".co.wy.us") // U.S. States || dnsDomainIs(host, ".state.al.us") || dnsDomainIs(host, ".state.ak.us") || dnsDomainIs(host, ".state.ar.us") || dnsDomainIs(host, ".state.az.us") || dnsDomainIs(host, ".state.ca.us") || dnsDomainIs(host, ".state.co.us") || dnsDomainIs(host, ".state.ct.us") || dnsDomainIs(host, ".state.dc.us") || dnsDomainIs(host, ".state.de.us") || dnsDomainIs(host, ".state.fl.us") || dnsDomainIs(host, ".state.ga.us") || dnsDomainIs(host, ".state.hi.us") || dnsDomainIs(host, ".state.id.us") || dnsDomainIs(host, ".state.il.us") || dnsDomainIs(host, ".state.in.us") || dnsDomainIs(host, ".state.ia.us") || dnsDomainIs(host, ".state.ks.us") || dnsDomainIs(host, ".state.ky.us") || dnsDomainIs(host, ".state.la.us") || dnsDomainIs(host, ".state.me.us") || dnsDomainIs(host, ".state.md.us") || dnsDomainIs(host, ".state.ma.us") || dnsDomainIs(host, ".state.mi.us") || dnsDomainIs(host, ".state.mn.us") || dnsDomainIs(host, ".state.ms.us") || dnsDomainIs(host, ".state.mo.us") || dnsDomainIs(host, ".state.mt.us") || dnsDomainIs(host, ".state.ne.us") || dnsDomainIs(host, ".state.nv.us") || dnsDomainIs(host, ".state.nh.us") || dnsDomainIs(host, ".state.nj.us") || dnsDomainIs(host, ".state.nm.us") || dnsDomainIs(host, ".state.ny.us") || dnsDomainIs(host, ".state.nc.us") || dnsDomainIs(host, ".state.nd.us") || dnsDomainIs(host, ".state.oh.us") || dnsDomainIs(host, ".state.ok.us") || dnsDomainIs(host, ".state.or.us") || dnsDomainIs(host, ".state.pa.us") || dnsDomainIs(host, ".state.ri.us") || dnsDomainIs(host, ".state.sc.us") || dnsDomainIs(host, ".state.sd.us") || dnsDomainIs(host, ".state.tn.us") || dnsDomainIs(host, ".state.tx.us") || dnsDomainIs(host, ".state.ut.us") || dnsDomainIs(host, ".state.vt.us") || dnsDomainIs(host, ".state.va.us") || dnsDomainIs(host, ".state.wa.us") || dnsDomainIs(host, ".state.wv.us") || dnsDomainIs(host, ".state.wi.us") || dnsDomainIs(host, ".state.wy.us") // KidsClick URLs || dnsDomainIs(host, "12.16.163.163") || dnsDomainIs(host, "128.59.173.136") || dnsDomainIs(host, "165.112.78.61") || dnsDomainIs(host, "216.55.23.140") || dnsDomainIs(host, "63.111.53.150") || dnsDomainIs(host, "64.94.206.8") || dnsDomainIs(host, "abc.go.com") || dnsDomainIs(host, "acmepet.petsmart.com") || dnsDomainIs(host, "adver-net.com") || dnsDomainIs(host, "aint-it-cool-news.com") || dnsDomainIs(host, "akidsheart.com") || dnsDomainIs(host, "alabanza.com") || dnsDomainIs(host, "allerdays.com") || dnsDomainIs(host, "allgame.com") || dnsDomainIs(host, "allowancenet.com") || dnsDomainIs(host, "amish-heartland.com") || dnsDomainIs(host, "ancienthistory.about.com") || dnsDomainIs(host, "animals.about.com") || dnsDomainIs(host, "antenna.nl") || dnsDomainIs(host, "arcweb.sos.state.or.us") || dnsDomainIs(host, "artistmummer.homestead.com") || dnsDomainIs(host, "artists.vh1.com") || dnsDomainIs(host, "arts.lausd.k12.ca.us") || dnsDomainIs(host, "asiatravel.com") || dnsDomainIs(host, "asterius.com") || dnsDomainIs(host, "atlas.gc.ca") || dnsDomainIs(host, "atschool.eduweb.co.uk") || dnsDomainIs(host, "ayya.pd.net") || dnsDomainIs(host, "babelfish.altavista.com") || dnsDomainIs(host, "babylon5.warnerbros.com") || dnsDomainIs(host, "banzai.neosoft.com") || dnsDomainIs(host, "barneyonline.com") || dnsDomainIs(host, "baroque-music.com") || dnsDomainIs(host, "barsoom.msss.com") || dnsDomainIs(host, "baseball-almanac.com") || dnsDomainIs(host, "bcadventure.com") || dnsDomainIs(host, "beadiecritters.hosting4less.com") || dnsDomainIs(host, "beverlyscrafts.com") || dnsDomainIs(host, "biology.about.com") || dnsDomainIs(host, "birding.about.com") || dnsDomainIs(host, "boatsafe.com") || dnsDomainIs(host, "bombpop.com") || dnsDomainIs(host, "boulter.com") || dnsDomainIs(host, "bright-ideas-software.com") || dnsDomainIs(host, "buckman.pps.k12.or.us") || dnsDomainIs(host, "buffalobills.com") || dnsDomainIs(host, "bvsd.k12.co.us") || dnsDomainIs(host, "cagle.slate.msn.com") || dnsDomainIs(host, "calc.entisoft.com") || dnsDomainIs(host, "canada.gc.ca") || dnsDomainIs(host, "candleandsoap.about.com") || dnsDomainIs(host, "caselaw.lp.findlaw.com") || dnsDomainIs(host, "catalog.com") || dnsDomainIs(host, "catalog.socialstudies.com") || dnsDomainIs(host, "cavern.com") || dnsDomainIs(host, "cbs.sportsline.com") || dnsDomainIs(host, "cc.matsuyama-u.ac.jp") || dnsDomainIs(host, "celt.net") || dnsDomainIs(host, "cgfa.kelloggcreek.com") || dnsDomainIs(host, "channel4000.com") || dnsDomainIs(host, "chess.delorie.com") || dnsDomainIs(host, "chess.liveonthenet.com") || dnsDomainIs(host, "childfun.com") || dnsDomainIs(host, "christmas.com") || dnsDomainIs(host, "citystar.com") || dnsDomainIs(host, "claim.goldrush.com") || dnsDomainIs(host, "clairerosemaryjane.com") || dnsDomainIs(host, "clevermedia.com") || dnsDomainIs(host, "cobblestonepub.com") || dnsDomainIs(host, "codebrkr.infopages.net") || dnsDomainIs(host, "colitz.com") || dnsDomainIs(host, "collections.ic.gc.ca") || dnsDomainIs(host, "coloquio.com") || dnsDomainIs(host, "come.to") || dnsDomainIs(host, "coombs.anu.edu.au") || dnsDomainIs(host, "crafterscommunity.com") || dnsDomainIs(host, "craftsforkids.about.com") || dnsDomainIs(host, "creativity.net") || dnsDomainIs(host, "cslewis.drzeus.net") || dnsDomainIs(host, "cust.idl.com.au") || dnsDomainIs(host, "cvs.anu.edu.au") || dnsDomainIs(host, "cybersleuth-kids.com") || dnsDomainIs(host, "cybertown.com") || dnsDomainIs(host, "darkfish.com") || dnsDomainIs(host, "datadragon.com") || dnsDomainIs(host, "davesite.com") || dnsDomainIs(host, "dbertens.www.cistron.nl") || dnsDomainIs(host, "detnews.com") || dnsDomainIs(host, "dhr.dos.state.fl.us") || dnsDomainIs(host, "dialspace.dial.pipex.com") || dnsDomainIs(host, "dictionaries.travlang.com") || dnsDomainIs(host, "disney.go.com") || dnsDomainIs(host, "disneyland.disney.go.com") || dnsDomainIs(host, "district.gresham.k12.or.us") || dnsDomainIs(host, "dmarie.com") || dnsDomainIs(host, "dreamwater.com") || dnsDomainIs(host, "duke.fuse.net") || dnsDomainIs(host, "earlyamerica.com") || dnsDomainIs(host, "earthsky.com") || dnsDomainIs(host, "easyweb.easynet.co.uk") || dnsDomainIs(host, "ecards1.bansheeweb.com") || dnsDomainIs(host, "edugreen.teri.res.in") || dnsDomainIs(host, "edwardlear.tripod.com") || dnsDomainIs(host, "eelink.net") || dnsDomainIs(host, "elizabethsings.com") || dnsDomainIs(host, "enature.com") || dnsDomainIs(host, "encarta.msn.com") || dnsDomainIs(host, "endangeredspecie.com") || dnsDomainIs(host, "enterprise.america.com") || dnsDomainIs(host, "ericae.net") || dnsDomainIs(host, "esl.about.com") || dnsDomainIs(host, "eveander.com") || dnsDomainIs(host, "exn.ca") || dnsDomainIs(host, "fallscam.niagara.com") || dnsDomainIs(host, "family.go.com") || dnsDomainIs(host, "family2.go.com") || dnsDomainIs(host, "familyeducation.com") || dnsDomainIs(host, "finditquick.com") || dnsDomainIs(host, "fln-bma.yazigi.com.br") || dnsDomainIs(host, "fln-con.yazigi.com.br") || dnsDomainIs(host, "food.epicurious.com") || dnsDomainIs(host, "forums.sympatico.ca") || dnsDomainIs(host, "fotw.vexillum.com") || dnsDomainIs(host, "fox.nstn.ca") || dnsDomainIs(host, "framingham.com") || dnsDomainIs(host, "freevote.com") || dnsDomainIs(host, "freeweb.pdq.net") || dnsDomainIs(host, "games.yahoo.com") || dnsDomainIs(host, "gardening.sierrahome.com") || dnsDomainIs(host, "gardenofpraise.com") || dnsDomainIs(host, "gcclearn.gcc.cc.va.us") || dnsDomainIs(host, "genealogytoday.com") || dnsDomainIs(host, "genesis.ne.mediaone.net") || dnsDomainIs(host, "geniefind.com") || dnsDomainIs(host, "geography.about.com") || dnsDomainIs(host, "gf.state.wy.us") || dnsDomainIs(host, "gi.grolier.com") || dnsDomainIs(host, "golf.com") || dnsDomainIs(host, "greatseal.com") || dnsDomainIs(host, "guardians.net") || dnsDomainIs(host, "hamlet.hypermart.net") || dnsDomainIs(host, "happypuppy.com") || dnsDomainIs(host, "harcourt.fsc.follett.com") || dnsDomainIs(host, "haringkids.com") || dnsDomainIs(host, "harrietmaysavitz.com") || dnsDomainIs(host, "harrypotter.warnerbros.com") || dnsDomainIs(host, "hca.gilead.org.il") || dnsDomainIs(host, "header.future.easyspace.com") || dnsDomainIs(host, "historymedren.about.com") || dnsDomainIs(host, "home.att.net") || dnsDomainIs(host, "home.austin.rr.com") || dnsDomainIs(host, "home.capu.net") || dnsDomainIs(host, "home.cfl.rr.com") || dnsDomainIs(host, "home.clara.net") || dnsDomainIs(host, "home.clear.net.nz") || dnsDomainIs(host, "home.earthlink.net") || dnsDomainIs(host, "home.eznet.net") || dnsDomainIs(host, "home.flash.net") || dnsDomainIs(host, "home.hiwaay.net") || dnsDomainIs(host, "home.hkstar.com") || dnsDomainIs(host, "home.ici.net") || dnsDomainIs(host, "home.inreach.com") || dnsDomainIs(host, "home.interlynx.net") || dnsDomainIs(host, "home.istar.ca") || dnsDomainIs(host, "home.mira.net") || dnsDomainIs(host, "home.nycap.rr.com") || dnsDomainIs(host, "home.online.no") || dnsDomainIs(host, "home.pb.net") || dnsDomainIs(host, "home2.pacific.net.sg") || dnsDomainIs(host, "homearts.com") || dnsDomainIs(host, "homepage.mac.com") || dnsDomainIs(host, "hometown.aol.com") || dnsDomainIs(host, "homiliesbyemail.com") || dnsDomainIs(host, "hotei.fix.co.jp") || dnsDomainIs(host, "hotwired.lycos.com") || dnsDomainIs(host, "hp.vector.co.jp") || dnsDomainIs(host, "hum.amu.edu.pl") || dnsDomainIs(host, "i-cias.com") || dnsDomainIs(host, "icatapults.freeservers.com") || dnsDomainIs(host, "ind.cioe.com") || dnsDomainIs(host, "info.ex.ac.uk") || dnsDomainIs(host, "infocan.gc.ca") || dnsDomainIs(host, "infoservice.gc.ca") || dnsDomainIs(host, "interoz.com") || dnsDomainIs(host, "ireland.iol.ie") || dnsDomainIs(host, "is.dal.ca") || dnsDomainIs(host, "itss.raytheon.com") || dnsDomainIs(host, "iul.com") || dnsDomainIs(host, "jameswhitcombriley.com") || dnsDomainIs(host, "jellieszone.com") || dnsDomainIs(host, "jordan.sportsline.com") || dnsDomainIs(host, "judyanddavid.com") || dnsDomainIs(host, "jurai.murdoch.edu.au") || dnsDomainIs(host, "just.about.com") || dnsDomainIs(host, "kayleigh.tierranet.com") || dnsDomainIs(host, "kcwingwalker.tripod.com") || dnsDomainIs(host, "kidexchange.about.com") || dnsDomainIs(host, "kids-world.colgatepalmolive.com") || dnsDomainIs(host, "kids.mysterynet.com") || dnsDomainIs(host, "kids.ot.com") || dnsDomainIs(host, "kidsartscrafts.about.com") || dnsDomainIs(host, "kidsastronomy.about.com") || dnsDomainIs(host, "kidscience.about.com") || dnsDomainIs(host, "kidscience.miningco.com") || dnsDomainIs(host, "kidscollecting.about.com") || dnsDomainIs(host, "kidsfun.co.uk") || dnsDomainIs(host, "kidsinternet.about.com") || dnsDomainIs(host, "kidslangarts.about.com") || dnsDomainIs(host, "kidspenpals.about.com") || dnsDomainIs(host, "kitecast.com") || dnsDomainIs(host, "knight.city.ba.k12.md.us") || dnsDomainIs(host, "kodak.com") || dnsDomainIs(host, "kwanzaa4kids.homestead.com") || dnsDomainIs(host, "lagos.africaonline.com") || dnsDomainIs(host, "lancearmstrong.com") || dnsDomainIs(host, "landru.i-link-2.net") || dnsDomainIs(host, "lang.nagoya-u.ac.jp") || dnsDomainIs(host, "lascala.milano.it") || dnsDomainIs(host, "latinoculture.about.com") || dnsDomainIs(host, "litcal.yasuda-u.ac.jp") || dnsDomainIs(host, "littlebit.com") || dnsDomainIs(host, "live.edventures.com") || dnsDomainIs(host, "look.net") || dnsDomainIs(host, "lycoskids.infoplease.com") || dnsDomainIs(host, "lynx.uio.no") || dnsDomainIs(host, "macdict.dict.mq.edu.au") || dnsDomainIs(host, "maori.culture.co.nz") || dnsDomainIs(host, "marktwain.about.com") || dnsDomainIs(host, "marktwain.miningco.com") || dnsDomainIs(host, "mars2030.net") || dnsDomainIs(host, "martin.parasitology.mcgill.ca") || dnsDomainIs(host, "martinlutherking.8m.com") || dnsDomainIs(host, "mastercollector.com") || dnsDomainIs(host, "mathcentral.uregina.ca") || dnsDomainIs(host, "members.aol.com") || dnsDomainIs(host, "members.carol.net") || dnsDomainIs(host, "members.cland.net") || dnsDomainIs(host, "members.cruzio.com") || dnsDomainIs(host, "members.easyspace.com") || dnsDomainIs(host, "members.eisa.net.au") || dnsDomainIs(host, "members.home.net") || dnsDomainIs(host, "members.iinet.net.au") || dnsDomainIs(host, "members.nbci.com") || dnsDomainIs(host, "members.ozemail.com.au") || dnsDomainIs(host, "members.surfsouth.com") || dnsDomainIs(host, "members.theglobe.com") || dnsDomainIs(host, "members.tripod.com") || dnsDomainIs(host, "mexplaza.udg.mx") || dnsDomainIs(host, "mgfx.com") || dnsDomainIs(host, "microimg.com") || dnsDomainIs(host, "midusa.net") || dnsDomainIs(host, "mildan.com") || dnsDomainIs(host, "millennianet.com") || dnsDomainIs(host, "mindbreakers.e-fun.nu") || dnsDomainIs(host, "missjanet.xs4all.nl") || dnsDomainIs(host, "mistral.culture.fr") || dnsDomainIs(host, "mobileation.com") || dnsDomainIs(host, "mrshowbiz.go.com") || dnsDomainIs(host, "ms.simplenet.com") || dnsDomainIs(host, "museum.gov.ns.ca") || dnsDomainIs(host, "music.excite.com") || dnsDomainIs(host, "musicfinder.yahoo.com") || dnsDomainIs(host, "my.freeway.net") || dnsDomainIs(host, "mytrains.com") || dnsDomainIs(host, "nativeauthors.com") || dnsDomainIs(host, "nba.com") || dnsDomainIs(host, "nch.ari.net") || dnsDomainIs(host, "neonpeach.tripod.com") || dnsDomainIs(host, "net.indra.com") || dnsDomainIs(host, "ngeorgia.com") || dnsDomainIs(host, "ngp.ngpc.state.ne.us") || dnsDomainIs(host, "nhd.heinle.com") || dnsDomainIs(host, "nick.com") || dnsDomainIs(host, "normandy.eb.com") || dnsDomainIs(host, "northshore.shore.net") || dnsDomainIs(host, "now2000.com") || dnsDomainIs(host, "npc.nunavut.ca") || dnsDomainIs(host, "ns2.carib-link.net") || dnsDomainIs(host, "ntl.sympatico.ca") || dnsDomainIs(host, "oceanographer.navy.mil") || dnsDomainIs(host, "oddens.geog.uu.nl") || dnsDomainIs(host, "officialcitysites.com") || dnsDomainIs(host, "oneida-nation.net") || dnsDomainIs(host, "onlinegeorgia.com") || dnsDomainIs(host, "originator_2.tripod.com") || dnsDomainIs(host, "ortech-engr.com") || dnsDomainIs(host, "osage.voorhees.k12.nj.us") || dnsDomainIs(host, "osiris.sund.ac.uk") || dnsDomainIs(host, "ourworld.compuserve.com") || dnsDomainIs(host, "outdoorphoto.com") || dnsDomainIs(host, "pages.map.com") || dnsDomainIs(host, "pages.prodigy.com") || dnsDomainIs(host, "pages.prodigy.net") || dnsDomainIs(host, "pages.tca.net") || dnsDomainIs(host, "parcsafari.qc.ca") || dnsDomainIs(host, "parenthoodweb.com") || dnsDomainIs(host, "pathfinder.com") || dnsDomainIs(host, "people.clarityconnect.com") || dnsDomainIs(host, "people.enternet.com.au") || dnsDomainIs(host, "people.ne.mediaone.net") || dnsDomainIs(host, "phonics.jazzles.com") || dnsDomainIs(host, "pibburns.com") || dnsDomainIs(host, "pilgrims.net") || dnsDomainIs(host, "pinenet.com") || dnsDomainIs(host, "place.scholastic.com") || dnsDomainIs(host, "playground.kodak.com") || dnsDomainIs(host, "politicalgraveyard.com") || dnsDomainIs(host, "polk.ga.net") || dnsDomainIs(host, "pompstory.home.mindspring.com") || dnsDomainIs(host, "popularmechanics.com") || dnsDomainIs(host, "projects.edtech.sandi.net") || dnsDomainIs(host, "psyche.usno.navy.mil") || dnsDomainIs(host, "pubweb.parc.xerox.com") || dnsDomainIs(host, "puzzlemaker.school.discovery.com") || dnsDomainIs(host, "quest.classroom.com") || dnsDomainIs(host, "quilting.about.com") || dnsDomainIs(host, "rabbitmoon.home.mindspring.com") || dnsDomainIs(host, "radio.cbc.ca") || dnsDomainIs(host, "rats2u.com") || dnsDomainIs(host, "rbcm1.rbcm.gov.bc.ca") || dnsDomainIs(host, "readplay.com") || dnsDomainIs(host, "recipes4children.homestead.com") || dnsDomainIs(host, "redsox.com") || dnsDomainIs(host, "renaissance.district96.k12.il.us") || dnsDomainIs(host, "rhyme.lycos.com") || dnsDomainIs(host, "rhythmweb.com") || dnsDomainIs(host, "riverresource.com") || dnsDomainIs(host, "rockhoundingar.com") || dnsDomainIs(host, "rockies.mlb.com") || dnsDomainIs(host, "rosecity.net") || dnsDomainIs(host, "rr-vs.informatik.uni-ulm.de") || dnsDomainIs(host, "rubens.anu.edu.au") || dnsDomainIs(host, "rummelplatz.uni-mannheim.de") || dnsDomainIs(host, "sandbox.xerox.com") || dnsDomainIs(host, "sarah.fredart.com") || dnsDomainIs(host, "schmidel.com") || dnsDomainIs(host, "scholastic.com") || dnsDomainIs(host, "school.discovery.com") || dnsDomainIs(host, "schoolcentral.com") || dnsDomainIs(host, "seattletimes.nwsource.com") || dnsDomainIs(host, "sericulum.com") || dnsDomainIs(host, "sf.airforce.com") || dnsDomainIs(host, "shop.usps.com") || dnsDomainIs(host, "showcase.netins.net") || dnsDomainIs(host, "sikids.com") || dnsDomainIs(host, "sites.huji.ac.il") || dnsDomainIs(host, "sjliving.com") || dnsDomainIs(host, "skullduggery.com") || dnsDomainIs(host, "skyways.lib.ks.us") || dnsDomainIs(host, "snowdaymovie.nick.com") || dnsDomainIs(host, "sosa21.hypermart.net") || dnsDomainIs(host, "soundamerica.com") || dnsDomainIs(host, "spaceboy.nasda.go.jp") || dnsDomainIs(host, "sports.nfl.com") || dnsDomainIs(host, "sportsillustrated.cnn.com") || dnsDomainIs(host, "starwars.hasbro.com") || dnsDomainIs(host, "statelibrary.dcr.state.nc.us") || dnsDomainIs(host, "streetplay.com") || dnsDomainIs(host, "sts.gsc.nrcan.gc.ca") || dnsDomainIs(host, "sunniebunniezz.com") || dnsDomainIs(host, "sunsite.nus.edu.sg") || dnsDomainIs(host, "sunsite.sut.ac.jp") || dnsDomainIs(host, "superm.bart.nl") || dnsDomainIs(host, "surf.to") || dnsDomainIs(host, "svinet2.fs.fed.us") || dnsDomainIs(host, "swiminfo.com") || dnsDomainIs(host, "tabletennis.about.com") || dnsDomainIs(host, "teacher.scholastic.com") || dnsDomainIs(host, "theforce.net") || dnsDomainIs(host, "thejessicas.homestead.com") || dnsDomainIs(host, "themes.editthispage.com") || dnsDomainIs(host, "theory.uwinnipeg.ca") || dnsDomainIs(host, "theshadowlands.net") || dnsDomainIs(host, "thinks.com") || dnsDomainIs(host, "thryomanes.tripod.com") || dnsDomainIs(host, "time_zone.tripod.com") || dnsDomainIs(host, "titania.cobuild.collins.co.uk") || dnsDomainIs(host, "torre.duomo.pisa.it") || dnsDomainIs(host, "touregypt.net") || dnsDomainIs(host, "toycollecting.about.com") || dnsDomainIs(host, "trace.ntu.ac.uk") || dnsDomainIs(host, "travelwithkids.about.com") || dnsDomainIs(host, "tukids.tucows.com") || dnsDomainIs(host, "tv.yahoo.com") || dnsDomainIs(host, "tycho.usno.navy.mil") || dnsDomainIs(host, "ubl.artistdirect.com") || dnsDomainIs(host, "uk-pages.net") || dnsDomainIs(host, "ukraine.uazone.net") || dnsDomainIs(host, "unmuseum.mus.pa.us") || dnsDomainIs(host, "us.imdb.com") || dnsDomainIs(host, "userpage.chemie.fu-berlin.de") || dnsDomainIs(host, "userpage.fu-berlin.de") || dnsDomainIs(host, "userpages.aug.com") || dnsDomainIs(host, "users.aol.com") || dnsDomainIs(host, "users.bigpond.net.au") || dnsDomainIs(host, "users.breathemail.net") || dnsDomainIs(host, "users.erols.com") || dnsDomainIs(host, "users.imag.net") || dnsDomainIs(host, "users.inetw.net") || dnsDomainIs(host, "users.massed.net") || dnsDomainIs(host, "users.skynet.be") || dnsDomainIs(host, "users.uniserve.com") || dnsDomainIs(host, "venus.spaceports.com") || dnsDomainIs(host, "vgstrategies.about.com") || dnsDomainIs(host, "victorian.fortunecity.com") || dnsDomainIs(host, "vilenski.com") || dnsDomainIs(host, "village.infoweb.ne.jp") || dnsDomainIs(host, "virtual.finland.fi") || dnsDomainIs(host, "vrml.fornax.hu") || dnsDomainIs(host, "vvv.com") || dnsDomainIs(host, "w1.xrefer.com") || dnsDomainIs(host, "w3.one.net") || dnsDomainIs(host, "w3.rz-berlin.mpg.de") || dnsDomainIs(host, "w3.trib.com") || dnsDomainIs(host, "wallofsound.go.com") || dnsDomainIs(host, "web.aimnet.com") || dnsDomainIs(host, "web.ccsd.k12.wy.us") || dnsDomainIs(host, "web.cs.ualberta.ca") || dnsDomainIs(host, "web.idirect.com") || dnsDomainIs(host, "web.kyoto-inet.or.jp") || dnsDomainIs(host, "web.macam98.ac.il") || dnsDomainIs(host, "web.massvacation.com") || dnsDomainIs(host, "web.one.net.au") || dnsDomainIs(host, "web.qx.net") || dnsDomainIs(host, "web.uvic.ca") || dnsDomainIs(host, "web2.airmail.net") || dnsDomainIs(host, "webcoast.com") || dnsDomainIs(host, "webgames.kalisto.com") || dnsDomainIs(host, "webhome.idirect.com") || dnsDomainIs(host, "webpages.homestead.com") || dnsDomainIs(host, "webrum.uni-mannheim.de") || dnsDomainIs(host, "webusers.anet-stl.com") || dnsDomainIs(host, "welcome.to") || dnsDomainIs(host, "wgntv.com") || dnsDomainIs(host, "whales.magna.com.au") || dnsDomainIs(host, "wildheart.com") || dnsDomainIs(host, "wilstar.net") || dnsDomainIs(host, "winter-wonderland.com") || dnsDomainIs(host, "women.com") || dnsDomainIs(host, "woodrow.mpls.frb.fed.us") || dnsDomainIs(host, "wordzap.com") || dnsDomainIs(host, "worldkids.net") || dnsDomainIs(host, "worldwideguide.net") || dnsDomainIs(host, "ww3.bay.k12.fl.us") || dnsDomainIs(host, "ww3.sportsline.com") || dnsDomainIs(host, "www-groups.dcs.st-and.ac.uk") || dnsDomainIs(host, "www-public.rz.uni-duesseldorf.de") || dnsDomainIs(host, "www.1stkids.com") || dnsDomainIs(host, "www.2020tech.com") || dnsDomainIs(host, "www.21stcenturytoys.com") || dnsDomainIs(host, "www.4adventure.com") || dnsDomainIs(host, "www.50states.com") || dnsDomainIs(host, "www.800padutch.com") || dnsDomainIs(host, "www.88.com") || dnsDomainIs(host, "www.a-better.com") || dnsDomainIs(host, "www.aaa.com.au") || dnsDomainIs(host, "www.aacca.com") || dnsDomainIs(host, "www.aalbc.com") || dnsDomainIs(host, "www.aardman.com") || dnsDomainIs(host, "www.aardvarkelectric.com") || dnsDomainIs(host, "www.aawc.com") || dnsDomainIs(host, "www.ababmx.com") || dnsDomainIs(host, "www.abbeville.com") || dnsDomainIs(host, "www.abc.net.au") || dnsDomainIs(host, "www.abcb.com") || dnsDomainIs(host, "www.abctooncenter.com") || dnsDomainIs(host, "www.about.ch") || dnsDomainIs(host, "www.accessart.org.uk") || dnsDomainIs(host, "www.accu.or.jp") || dnsDomainIs(host, "www.accuweather.com") || dnsDomainIs(host, "www.achuka.co.uk") || dnsDomainIs(host, "www.acmecity.com") || dnsDomainIs(host, "www.acorn-group.com") || dnsDomainIs(host, "www.acs.ucalgary.ca") || dnsDomainIs(host, "www.actden.com") || dnsDomainIs(host, "www.actionplanet.com") || dnsDomainIs(host, "www.activityvillage.co.uk") || dnsDomainIs(host, "www.actwin.com") || dnsDomainIs(host, "www.adequate.com") || dnsDomainIs(host, "www.adidas.com") || dnsDomainIs(host, "www.advent-calendars.com") || dnsDomainIs(host, "www.aegis.com") || dnsDomainIs(host, "www.af.mil") || dnsDomainIs(host, "www.africaindex.africainfo.no") || dnsDomainIs(host, "www.africam.com") || dnsDomainIs(host, "www.africancrafts.com") || dnsDomainIs(host, "www.aggressive.com") || dnsDomainIs(host, "www.aghines.com") || dnsDomainIs(host, "www.agirlsworld.com") || dnsDomainIs(host, "www.agora.stm.it") || dnsDomainIs(host, "www.agriculture.com") || dnsDomainIs(host, "www.aikidofaq.com") || dnsDomainIs(host, "www.ajkids.com") || dnsDomainIs(host, "www.akfkoala.gil.com.au") || dnsDomainIs(host, "www.akhlah.com") || dnsDomainIs(host, "www.alabamainfo.com") || dnsDomainIs(host, "www.aland.fi") || dnsDomainIs(host, "www.albion.com") || dnsDomainIs(host, "www.alcoholismhelp.com") || dnsDomainIs(host, "www.alcottweb.com") || dnsDomainIs(host, "www.alfanet.it") || dnsDomainIs(host, "www.alfy.com") || dnsDomainIs(host, "www.algebra-online.com") || dnsDomainIs(host, "www.alienexplorer.com") || dnsDomainIs(host, "www.aliensatschool.com") || dnsDomainIs(host, "www.all-links.com") || dnsDomainIs(host, "www.alldetroit.com") || dnsDomainIs(host, "www.allexperts.com") || dnsDomainIs(host, "www.allmixedup.com") || dnsDomainIs(host, "www.allmusic.com") || dnsDomainIs(host, "www.almanac.com") || dnsDomainIs(host, "www.almaz.com") || dnsDomainIs(host, "www.almondseed.com") || dnsDomainIs(host, "www.aloha.com") || dnsDomainIs(host, "www.aloha.net") || dnsDomainIs(host, "www.altonweb.com") || dnsDomainIs(host, "www.alyeska-pipe.com") || dnsDomainIs(host, "www.am-wood.com") || dnsDomainIs(host, "www.amazingadventure.com") || dnsDomainIs(host, "www.amazon.com") || dnsDomainIs(host, "www.americancheerleader.com") || dnsDomainIs(host, "www.americancowboy.com") || dnsDomainIs(host, "www.americangirl.com") || dnsDomainIs(host, "www.americanparknetwork.com") || dnsDomainIs(host, "www.americansouthwest.net") || dnsDomainIs(host, "www.americanwest.com") || dnsDomainIs(host, "www.ameritech.net") || dnsDomainIs(host, "www.amtexpo.com") || dnsDomainIs(host, "www.anbg.gov.au") || dnsDomainIs(host, "www.anc.org.za") || dnsDomainIs(host, "www.ancientegypt.co.uk") || dnsDomainIs(host, "www.angelfire.com") || dnsDomainIs(host, "www.angelsbaseball.com") || dnsDomainIs(host, "www.anholt.co.uk") || dnsDomainIs(host, "www.animabets.com") || dnsDomainIs(host, "www.animalnetwork.com") || dnsDomainIs(host, "www.animalpicturesarchive.com") || dnsDomainIs(host, "www.anime-genesis.com") || dnsDomainIs(host, "www.annefrank.com") || dnsDomainIs(host, "www.annefrank.nl") || dnsDomainIs(host, "www.annie75.com") || dnsDomainIs(host, "www.antbee.com") || dnsDomainIs(host, "www.antiquetools.com") || dnsDomainIs(host, "www.antiquetoy.com") || dnsDomainIs(host, "www.anzsbeg.org.au") || dnsDomainIs(host, "www.aol.com") || dnsDomainIs(host, "www.aone.com") || dnsDomainIs(host, "www.aphids.com") || dnsDomainIs(host, "www.apl.com") || dnsDomainIs(host, "www.aplusmath.com") || dnsDomainIs(host, "www.applebookshop.co.uk") || dnsDomainIs(host, "www.appropriatesoftware.com") || dnsDomainIs(host, "www.appukids.com") || dnsDomainIs(host, "www.april-joy.com") || dnsDomainIs(host, "www.arab.net") || dnsDomainIs(host, "www.aracnet.com") || dnsDomainIs(host, "www.arborday.com") || dnsDomainIs(host, "www.arcadevillage.com") || dnsDomainIs(host, "www.archiecomics.com") || dnsDomainIs(host, "www.archives.state.al.us") || dnsDomainIs(host, "www.arctic.ca") || dnsDomainIs(host, "www.ardenjohnson.com") || dnsDomainIs(host, "www.aristotle.net") || dnsDomainIs(host, "www.arizhwys.com") || dnsDomainIs(host, "www.arizonaguide.com") || dnsDomainIs(host, "www.arlingtoncemetery.com") || dnsDomainIs(host, "www.armory.com") || dnsDomainIs(host, "www.armwrestling.com") || dnsDomainIs(host, "www.arnprior.com") || dnsDomainIs(host, "www.artabunga.com") || dnsDomainIs(host, "www.artcarte.com") || dnsDomainIs(host, "www.artchive.com") || dnsDomainIs(host, "www.artcontest.com") || dnsDomainIs(host, "www.artcyclopedia.com") || dnsDomainIs(host, "www.artisandevelopers.com") || dnsDomainIs(host, "www.artlex.com") || dnsDomainIs(host, "www.artsandkids.com") || dnsDomainIs(host, "www.artyastro.com") || dnsDomainIs(host, "www.arwhead.com") || dnsDomainIs(host, "www.asahi-net.or.jp") || dnsDomainIs(host, "www.asap.unimelb.edu.au") || dnsDomainIs(host, "www.ascpl.lib.oh.us") || dnsDomainIs(host, "www.asia-art.net") || dnsDomainIs(host, "www.asiabigtime.com") || dnsDomainIs(host, "www.asianart.com") || dnsDomainIs(host, "www.asiatour.com") || dnsDomainIs(host, "www.asiaweek.com") || dnsDomainIs(host, "www.askanexpert.com") || dnsDomainIs(host, "www.askbasil.com") || dnsDomainIs(host, "www.assa.org.au") || dnsDomainIs(host, "www.ast.cam.ac.uk") || dnsDomainIs(host, "www.astronomy.com") || dnsDomainIs(host, "www.astros.com") || dnsDomainIs(host, "www.atek.com") || dnsDomainIs(host, "www.athlete.com") || dnsDomainIs(host, "www.athropolis.com") || dnsDomainIs(host, "www.atkielski.com") || dnsDomainIs(host, "www.atlantabraves.com") || dnsDomainIs(host, "www.atlantafalcons.com") || dnsDomainIs(host, "www.atlantathrashers.com") || dnsDomainIs(host, "www.atlanticus.com") || dnsDomainIs(host, "www.atm.ch.cam.ac.uk") || dnsDomainIs(host, "www.atom.co.jp") || dnsDomainIs(host, "www.atomicarchive.com") || dnsDomainIs(host, "www.att.com") || dnsDomainIs(host, "www.audreywood.com") || dnsDomainIs(host, "www.auntannie.com") || dnsDomainIs(host, "www.auntie.com") || dnsDomainIs(host, "www.avi-writer.com") || dnsDomainIs(host, "www.awesomeclipartforkids.com") || dnsDomainIs(host, "www.awhitehorse.com") || dnsDomainIs(host, "www.axess.com") || dnsDomainIs(host, "www.ayles.com") || dnsDomainIs(host, "www.ayn.ca") || dnsDomainIs(host, "www.azcardinals.com") || dnsDomainIs(host, "www.azdiamondbacks.com") || dnsDomainIs(host, "www.azsolarcenter.com") || dnsDomainIs(host, "www.azstarnet.com") || dnsDomainIs(host, "www.aztecafoods.com") || dnsDomainIs(host, "www.b-witched.com") || dnsDomainIs(host, "www.baberuthmuseum.com") || dnsDomainIs(host, "www.backstreetboys.com") || dnsDomainIs(host, "www.bagheera.com") || dnsDomainIs(host, "www.bahamas.com") || dnsDomainIs(host, "www.baileykids.com") || dnsDomainIs(host, "www.baldeagleinfo.com") || dnsDomainIs(host, "www.balloonhq.com") || dnsDomainIs(host, "www.balloonzone.com") || dnsDomainIs(host, "www.ballparks.com") || dnsDomainIs(host, "www.balmoralsoftware.com") || dnsDomainIs(host, "www.banja.com") || dnsDomainIs(host, "www.banph.com") || dnsDomainIs(host, "www.barbie.com") || dnsDomainIs(host, "www.barkingbuddies.com") || dnsDomainIs(host, "www.barnsdle.demon.co.uk") || dnsDomainIs(host, "www.barrysclipart.com") || dnsDomainIs(host, "www.bartleby.com") || dnsDomainIs(host, "www.baseplate.com") || dnsDomainIs(host, "www.batman-superman.com") || dnsDomainIs(host, "www.batmanbeyond.com") || dnsDomainIs(host, "www.bbc.co.uk") || dnsDomainIs(host, "www.bbhighway.com") || dnsDomainIs(host, "www.bboy.com") || dnsDomainIs(host, "www.bcit.tec.nj.us") || dnsDomainIs(host, "www.bconnex.net") || dnsDomainIs(host, "www.bcpl.net") || dnsDomainIs(host, "www.beach-net.com") || dnsDomainIs(host, "www.beachboys.com") || dnsDomainIs(host, "www.beakman.com") || dnsDomainIs(host, "www.beano.co.uk") || dnsDomainIs(host, "www.beans.demon.co.uk") || dnsDomainIs(host, "www.beartime.com") || dnsDomainIs(host, "www.bearyspecial.co.uk") || dnsDomainIs(host, "www.bedtime.com") || dnsDomainIs(host, "www.beingme.com") || dnsDomainIs(host, "www.belizeexplorer.com") || dnsDomainIs(host, "www.bell-labs.com") || dnsDomainIs(host, "www.bemorecreative.com") || dnsDomainIs(host, "www.bengals.com") || dnsDomainIs(host, "www.benjerry.com") || dnsDomainIs(host, "www.bennygoodsport.com") || dnsDomainIs(host, "www.berenstainbears.com") || dnsDomainIs(host, "www.beringia.com") || dnsDomainIs(host, "www.beritsbest.com") || dnsDomainIs(host, "www.berksweb.com") || dnsDomainIs(host, "www.best.com") || dnsDomainIs(host, "www.betsybyars.com") || dnsDomainIs(host, "www.bfro.net") || dnsDomainIs(host, "www.bgmm.com") || dnsDomainIs(host, "www.bibliography.com") || dnsDomainIs(host, "www.bigblue.com.au") || dnsDomainIs(host, "www.bigchalk.com") || dnsDomainIs(host, "www.bigidea.com") || dnsDomainIs(host, "www.bigtop.com") || dnsDomainIs(host, "www.bikecrawler.com") || dnsDomainIs(host, "www.billboard.com") || dnsDomainIs(host, "www.billybear4kids.com") || dnsDomainIs(host, "www.biography.com") || dnsDomainIs(host, "www.birdnature.com") || dnsDomainIs(host, "www.birdsnways.com") || dnsDomainIs(host, "www.birdtimes.com") || dnsDomainIs(host, "www.birminghamzoo.com") || dnsDomainIs(host, "www.birthdaypartyideas.com") || dnsDomainIs(host, "www.bis.arachsys.com") || dnsDomainIs(host, "www.bkgm.com") || dnsDomainIs(host, "www.blackbaseball.com") || dnsDomainIs(host, "www.blackbeardthepirate.com") || dnsDomainIs(host, "www.blackbeltmag.com") || dnsDomainIs(host, "www.blackfacts.com") || dnsDomainIs(host, "www.blackfeetnation.com") || dnsDomainIs(host, "www.blackhills-info.com") || dnsDomainIs(host, "www.blackholegang.com") || dnsDomainIs(host, "www.blaque.net") || dnsDomainIs(host, "www.blarg.net") || dnsDomainIs(host, "www.blasternaut.com") || dnsDomainIs(host, "www.blizzard.com") || dnsDomainIs(host, "www.blocksite.com") || dnsDomainIs(host, "www.bluejackets.com") || dnsDomainIs(host, "www.bluejays.ca") || dnsDomainIs(host, "www.bluemountain.com") || dnsDomainIs(host, "www.blupete.com") || dnsDomainIs(host, "www.blyton.co.uk") || dnsDomainIs(host, "www.boatnerd.com") || dnsDomainIs(host, "www.boatsafe.com") || dnsDomainIs(host, "www.bonus.com") || dnsDomainIs(host, "www.boowakwala.com") || dnsDomainIs(host, "www.bostonbruins.com") || dnsDomainIs(host, "www.braceface.com") || dnsDomainIs(host, "www.bracesinfo.com") || dnsDomainIs(host, "www.bradkent.com") || dnsDomainIs(host, "www.brainium.com") || dnsDomainIs(host, "www.brainmania.com") || dnsDomainIs(host, "www.brainpop.com") || dnsDomainIs(host, "www.bridalcave.com") || dnsDomainIs(host, "www.brightmoments.com") || dnsDomainIs(host, "www.britannia.com") || dnsDomainIs(host, "www.britannica.com") || dnsDomainIs(host, "www.british-museum.ac.uk") || dnsDomainIs(host, "www.brookes.ac.uk") || dnsDomainIs(host, "www.brookfieldreader.com") || dnsDomainIs(host, "www.btinternet.com") || dnsDomainIs(host, "www.bubbledome.co.nz") || dnsDomainIs(host, "www.buccaneers.com") || dnsDomainIs(host, "www.buffy.com") || dnsDomainIs(host, "www.bullying.co.uk") || dnsDomainIs(host, "www.bumply.com") || dnsDomainIs(host, "www.bungi.com") || dnsDomainIs(host, "www.burlco.lib.nj.us") || dnsDomainIs(host, "www.burlingamepezmuseum.com") || dnsDomainIs(host, "www.bus.ualberta.ca") || dnsDomainIs(host, "www.busprod.com") || dnsDomainIs(host, "www.butlerart.com") || dnsDomainIs(host, "www.butterflies.com") || dnsDomainIs(host, "www.butterflyfarm.co.cr") || dnsDomainIs(host, "www.bway.net") || dnsDomainIs(host, "www.bydonovan.com") || dnsDomainIs(host, "www.ca-mall.com") || dnsDomainIs(host, "www.cabinessence.com") || dnsDomainIs(host, "www.cablecarmuseum.com") || dnsDomainIs(host, "www.cadbury.co.uk") || dnsDomainIs(host, "www.calendarzone.com") || dnsDomainIs(host, "www.calgaryflames.com") || dnsDomainIs(host, "www.californiamissions.com") || dnsDomainIs(host, "www.camalott.com") || dnsDomainIs(host, "www.camelotintl.com") || dnsDomainIs(host, "www.campbellsoup.com") || dnsDomainIs(host, "www.camvista.com") || dnsDomainIs(host, "www.canadiens.com") || dnsDomainIs(host, "www.canals.state.ny.us") || dnsDomainIs(host, "www.candlelightstories.com") || dnsDomainIs(host, "www.candles-museum.com") || dnsDomainIs(host, "www.candystand.com") || dnsDomainIs(host, "www.caneshockey.com") || dnsDomainIs(host, "www.canismajor.com") || dnsDomainIs(host, "www.canucks.com") || dnsDomainIs(host, "www.capecod.net") || dnsDomainIs(host, "www.capital.net") || dnsDomainIs(host, "www.capstonestudio.com") || dnsDomainIs(host, "www.cardblvd.com") || dnsDomainIs(host, "www.caro.net") || dnsDomainIs(host, "www.carolhurst.com") || dnsDomainIs(host, "www.carr.lib.md.us") || dnsDomainIs(host, "www.cartooncorner.com") || dnsDomainIs(host, "www.cartooncritters.com") || dnsDomainIs(host, "www.cartoonnetwork.com") || dnsDomainIs(host, "www.carvingpatterns.com") || dnsDomainIs(host, "www.cashuniversity.com") || dnsDomainIs(host, "www.castles-of-britain.com") || dnsDomainIs(host, "www.castlewales.com") || dnsDomainIs(host, "www.catholic-forum.com") || dnsDomainIs(host, "www.catholic.net") || dnsDomainIs(host, "www.cattle.guelph.on.ca") || dnsDomainIs(host, "www.cavedive.com") || dnsDomainIs(host, "www.caveofthewinds.com") || dnsDomainIs(host, "www.cbc4kids.ca") || dnsDomainIs(host, "www.ccer.ggl.ruu.nl") || dnsDomainIs(host, "www.ccnet.com") || dnsDomainIs(host, "www.celineonline.com") || dnsDomainIs(host, "www.cellsalive.com") || dnsDomainIs(host, "www.centuryinshoes.com") || dnsDomainIs(host, "www.cfl.ca") || dnsDomainIs(host, "www.channel4.com") || dnsDomainIs(host, "www.channel8.net") || dnsDomainIs(host, "www.chanukah99.com") || dnsDomainIs(host, "www.charged.com") || dnsDomainIs(host, "www.chargers.com") || dnsDomainIs(host, "www.charlotte.com") || dnsDomainIs(host, "www.chaseday.com") || dnsDomainIs(host, "www.chateauversailles.fr") || dnsDomainIs(host, "www.cheatcc.com") || dnsDomainIs(host, "www.cheerleading.net") || dnsDomainIs(host, "www.cheese.com") || dnsDomainIs(host, "www.chem4kids.com") || dnsDomainIs(host, "www.chemicool.com") || dnsDomainIs(host, "www.cherbearsden.com") || dnsDomainIs(host, "www.chesskids.com") || dnsDomainIs(host, "www.chessvariants.com") || dnsDomainIs(host, "www.cheungswingchun.com") || dnsDomainIs(host, "www.chevroncars.com") || dnsDomainIs(host, "www.chibi.simplenet.com") || dnsDomainIs(host, "www.chicagobears.com") || dnsDomainIs(host, "www.chicagoblackhawks.com") || dnsDomainIs(host, "www.chickasaw.net") || dnsDomainIs(host, "www.childrensmusic.co.uk") || dnsDomainIs(host, "www.childrenssoftware.com") || dnsDomainIs(host, "www.childrenstory.com") || dnsDomainIs(host, "www.childrenwithdiabetes.com") || dnsDomainIs(host, "www.chinapage.com") || dnsDomainIs(host, "www.chinatoday.com") || dnsDomainIs(host, "www.chinavista.com") || dnsDomainIs(host, "www.chinnet.net") || dnsDomainIs(host, "www.chiquita.com") || dnsDomainIs(host, "www.chisox.com") || dnsDomainIs(host, "www.chivalry.com") || dnsDomainIs(host, "www.christiananswers.net") || dnsDomainIs(host, "www.christianity.com") || dnsDomainIs(host, "www.christmas.com") || dnsDomainIs(host, "www.christmas98.com") || dnsDomainIs(host, "www.chron.com") || dnsDomainIs(host, "www.chronique.com") || dnsDomainIs(host, "www.chuckecheese.com") || dnsDomainIs(host, "www.chucklebait.com") || dnsDomainIs(host, "www.chunkymonkey.com") || dnsDomainIs(host, "www.ci.chi.il.us") || dnsDomainIs(host, "www.ci.nyc.ny.us") || dnsDomainIs(host, "www.ci.phoenix.az.us") || dnsDomainIs(host, "www.ci.san-diego.ca.us") || dnsDomainIs(host, "www.cibc.com") || dnsDomainIs(host, "www.ciderpresspottery.com") || dnsDomainIs(host, "www.cincinnatireds.com") || dnsDomainIs(host, "www.circusparade.com") || dnsDomainIs(host, "www.circusweb.com") || dnsDomainIs(host, "www.cirquedusoleil.com") || dnsDomainIs(host, "www.cit.state.vt.us") || dnsDomainIs(host, "www.citycastles.com") || dnsDomainIs(host, "www.cityu.edu.hk") || dnsDomainIs(host, "www.civicmind.com") || dnsDomainIs(host, "www.civil-war.net") || dnsDomainIs(host, "www.civilization.ca") || dnsDomainIs(host, "www.cl.cam.ac.uk") || dnsDomainIs(host, "www.clantongang.com") || dnsDomainIs(host, "www.clark.net") || dnsDomainIs(host, "www.classicgaming.com") || dnsDomainIs(host, "www.claus.com") || dnsDomainIs(host, "www.clayz.com") || dnsDomainIs(host, "www.clearcf.uvic.ca") || dnsDomainIs(host, "www.clearlight.com") || dnsDomainIs(host, "www.clemusart.com") || dnsDomainIs(host, "www.clevelandbrowns.com") || dnsDomainIs(host, "www.clipartcastle.com") || dnsDomainIs(host, "www.clubi.ie") || dnsDomainIs(host, "www.cnn.com") || dnsDomainIs(host, "www.co.henrico.va.us") || dnsDomainIs(host, "www.coax.net") || dnsDomainIs(host, "www.cocacola.com") || dnsDomainIs(host, "www.cocori.com") || dnsDomainIs(host, "www.codesmiths.com") || dnsDomainIs(host, "www.codetalk.fed.us") || dnsDomainIs(host, "www.coin-gallery.com") || dnsDomainIs(host, "www.colinthompson.com") || dnsDomainIs(host, "www.collectoronline.com") || dnsDomainIs(host, "www.colonialhall.com") || dnsDomainIs(host, "www.coloradoavalanche.com") || dnsDomainIs(host, "www.coloradorockies.com") || dnsDomainIs(host, "www.colormathpink.com") || dnsDomainIs(host, "www.colts.com") || dnsDomainIs(host, "www.comet.net") || dnsDomainIs(host, "www.cometsystems.com") || dnsDomainIs(host, "www.comicbookresources.com") || dnsDomainIs(host, "www.comicspage.com") || dnsDomainIs(host, "www.compassnet.com") || dnsDomainIs(host, "www.compleatbellairs.com") || dnsDomainIs(host, "www.comptons.com") || dnsDomainIs(host, "www.concentric.net") || dnsDomainIs(host, "www.congogorillaforest.com") || dnsDomainIs(host, "www.conjuror.com") || dnsDomainIs(host, "www.conk.com") || dnsDomainIs(host, "www.conservation.state.mo.us") || dnsDomainIs(host, "www.contracostatimes.com") || dnsDomainIs(host, "www.control.chalmers.se") || dnsDomainIs(host, "www.cookierecipe.com") || dnsDomainIs(host, "www.cooljapanesetoys.com") || dnsDomainIs(host, "www.cooper.com") || dnsDomainIs(host, "www.corpcomm.net") || dnsDomainIs(host, "www.corrietenboom.com") || dnsDomainIs(host, "www.corynet.com") || dnsDomainIs(host, "www.corypaints.com") || dnsDomainIs(host, "www.cosmosmith.com") || dnsDomainIs(host, "www.countdown2000.com") || dnsDomainIs(host, "www.cowboy.net") || dnsDomainIs(host, "www.cowboypal.com") || dnsDomainIs(host, "www.cowcreek.com") || dnsDomainIs(host, "www.cowgirl.net") || dnsDomainIs(host, "www.cowgirls.com") || dnsDomainIs(host, "www.cp.duluth.mn.us") || dnsDomainIs(host, "www.cpsweb.com") || dnsDomainIs(host, "www.craftideas.com") || dnsDomainIs(host, "www.craniamania.com") || dnsDomainIs(host, "www.crater.lake.national-park.com") || dnsDomainIs(host, "www.crayoncrawler.com") || dnsDomainIs(host, "www.crazybone.com") || dnsDomainIs(host, "www.crazybones.com") || dnsDomainIs(host, "www.crd.ge.com") || dnsDomainIs(host, "www.create4kids.com") || dnsDomainIs(host, "www.creativemusic.com") || dnsDomainIs(host, "www.crocodilian.com") || dnsDomainIs(host, "www.crop.cri.nz") || dnsDomainIs(host, "www.cruzio.com") || dnsDomainIs(host, "www.crwflags.com") || dnsDomainIs(host, "www.cryptograph.com") || dnsDomainIs(host, "www.cryst.bbk.ac.uk") || dnsDomainIs(host, "www.cs.bilkent.edu.tr") || dnsDomainIs(host, "www.cs.man.ac.uk") || dnsDomainIs(host, "www.cs.sfu.ca") || dnsDomainIs(host, "www.cs.ubc.ca") || dnsDomainIs(host, "www.csd.uu.se") || dnsDomainIs(host, "www.csmonitor.com") || dnsDomainIs(host, "www.csse.monash.edu.au") || dnsDomainIs(host, "www.cstone.net") || dnsDomainIs(host, "www.csu.edu.au") || dnsDomainIs(host, "www.cubs.com") || dnsDomainIs(host, "www.culture.fr") || dnsDomainIs(host, "www.cultures.com") || dnsDomainIs(host, "www.curtis-collection.com") || dnsDomainIs(host, "www.cut-the-knot.com") || dnsDomainIs(host, "www.cws-scf.ec.gc.ca") || dnsDomainIs(host, "www.cyber-dyne.com") || dnsDomainIs(host, "www.cyberbee.com") || dnsDomainIs(host, "www.cyberbee.net") || dnsDomainIs(host, "www.cybercom.net") || dnsDomainIs(host, "www.cybercomm.net") || dnsDomainIs(host, "www.cybercomm.nl") || dnsDomainIs(host, "www.cybercorp.co.nz") || dnsDomainIs(host, "www.cybercs.com") || dnsDomainIs(host, "www.cybergoal.com") || dnsDomainIs(host, "www.cyberkids.com") || dnsDomainIs(host, "www.cyberspaceag.com") || dnsDomainIs(host, "www.cyberteens.com") || dnsDomainIs(host, "www.cybertours.com") || dnsDomainIs(host, "www.cybiko.com") || dnsDomainIs(host, "www.czweb.com") || dnsDomainIs(host, "www.d91.k12.id.us") || dnsDomainIs(host, "www.dailygrammar.com") || dnsDomainIs(host, "www.dakidz.com") || dnsDomainIs(host, "www.dalejarrettonline.com") || dnsDomainIs(host, "www.dallascowboys.com") || dnsDomainIs(host, "www.dallasdogndisc.com") || dnsDomainIs(host, "www.dallasstars.com") || dnsDomainIs(host, "www.damnyankees.com") || dnsDomainIs(host, "www.danceart.com") || dnsDomainIs(host, "www.daniellesplace.com") || dnsDomainIs(host, "www.dare-america.com") || dnsDomainIs(host, "www.darkfish.com") || dnsDomainIs(host, "www.darsbydesign.com") || dnsDomainIs(host, "www.datadragon.com") || dnsDomainIs(host, "www.davidreilly.com") || dnsDomainIs(host, "www.dccomics.com") || dnsDomainIs(host, "www.dcn.davis.ca.us") || dnsDomainIs(host, "www.deepseaworld.com") || dnsDomainIs(host, "www.delawaretribeofindians.nsn.us") || dnsDomainIs(host, "www.demon.co.uk") || dnsDomainIs(host, "www.denverbroncos.com") || dnsDomainIs(host, "www.denverpost.com") || dnsDomainIs(host, "www.dep.state.pa.us") || dnsDomainIs(host, "www.desert-fairy.com") || dnsDomainIs(host, "www.desert-storm.com") || dnsDomainIs(host, "www.desertusa.com") || dnsDomainIs(host, "www.designltd.com") || dnsDomainIs(host, "www.designsbykat.com") || dnsDomainIs(host, "www.detnews.com") || dnsDomainIs(host, "www.detroitlions.com") || dnsDomainIs(host, "www.detroitredwings.com") || dnsDomainIs(host, "www.detroittigers.com") || dnsDomainIs(host, "www.deutsches-museum.de") || dnsDomainIs(host, "www.devilray.com") || dnsDomainIs(host, "www.dhorse.com") || dnsDomainIs(host, "www.diana-ross.co.uk") || dnsDomainIs(host, "www.dianarossandthesupremes.net") || dnsDomainIs(host, "www.diaryproject.com") || dnsDomainIs(host, "www.dickbutkus.com") || dnsDomainIs(host, "www.dickshovel.com") || dnsDomainIs(host, "www.dictionary.com") || dnsDomainIs(host, "www.didyouknow.com") || dnsDomainIs(host, "www.diegorivera.com") || dnsDomainIs(host, "www.digitalcentury.com") || dnsDomainIs(host, "www.digitaldog.com") || dnsDomainIs(host, "www.digiweb.com") || dnsDomainIs(host, "www.dimdima.com") || dnsDomainIs(host, "www.dinodon.com") || dnsDomainIs(host, "www.dinosauria.com") || dnsDomainIs(host, "www.discovereso.com") || dnsDomainIs(host, "www.discovergalapagos.com") || dnsDomainIs(host, "www.discovergames.com") || dnsDomainIs(host, "www.discoveringarchaeology.com") || dnsDomainIs(host, "www.discoveringmontana.com") || dnsDomainIs(host, "www.discoverlearning.com") || dnsDomainIs(host, "www.discovery.com") || dnsDomainIs(host, "www.disknet.com") || dnsDomainIs(host, "www.disney.go.com") || dnsDomainIs(host, "www.distinguishedwomen.com") || dnsDomainIs(host, "www.dkonline.com") || dnsDomainIs(host, "www.dltk-kids.com") || dnsDomainIs(host, "www.dmgi.com") || dnsDomainIs(host, "www.dnr.state.md.us") || dnsDomainIs(host, "www.dnr.state.mi.us") || dnsDomainIs(host, "www.dnr.state.wi.us") || dnsDomainIs(host, "www.dodgers.com") || dnsDomainIs(host, "www.dodoland.com") || dnsDomainIs(host, "www.dog-play.com") || dnsDomainIs(host, "www.dogbreedinfo.com") || dnsDomainIs(host, "www.doginfomat.com") || dnsDomainIs(host, "www.dole5aday.com") || dnsDomainIs(host, "www.dollart.com") || dnsDomainIs(host, "www.dolliedish.com") || dnsDomainIs(host, "www.dome2000.co.uk") || dnsDomainIs(host, "www.domtar.com") || dnsDomainIs(host, "www.donegal.k12.pa.us") || dnsDomainIs(host, "www.dorneypark.com") || dnsDomainIs(host, "www.dorothyhinshawpatent.com") || dnsDomainIs(host, "www.dougweb.com") || dnsDomainIs(host, "www.dps.state.ak.us") || dnsDomainIs(host, "www.draw3d.com") || dnsDomainIs(host, "www.dreamgate.com") || dnsDomainIs(host, "www.dreamkitty.com") || dnsDomainIs(host, "www.dreamscape.com") || dnsDomainIs(host, "www.dreamtime.net.au") || dnsDomainIs(host, "www.drpeppermuseum.com") || dnsDomainIs(host, "www.drscience.com") || dnsDomainIs(host, "www.drseward.com") || dnsDomainIs(host, "www.drtoy.com") || dnsDomainIs(host, "www.dse.nl") || dnsDomainIs(host, "www.dtic.mil") || dnsDomainIs(host, "www.duracell.com") || dnsDomainIs(host, "www.dustbunny.com") || dnsDomainIs(host, "www.dynanet.com") || dnsDomainIs(host, "www.eagerreaders.com") || dnsDomainIs(host, "www.eaglekids.com") || dnsDomainIs(host, "www.earthcalendar.net") || dnsDomainIs(host, "www.earthday.net") || dnsDomainIs(host, "www.earthdog.com") || dnsDomainIs(host, "www.earthwatch.com") || dnsDomainIs(host, "www.ease.com") || dnsDomainIs(host, "www.eastasia.ws") || dnsDomainIs(host, "www.easytype.com") || dnsDomainIs(host, "www.eblewis.com") || dnsDomainIs(host, "www.ebs.hw.ac.uk") || dnsDomainIs(host, "www.eclipse.net") || dnsDomainIs(host, "www.eco-pros.com") || dnsDomainIs(host, "www.edbydesign.com") || dnsDomainIs(host, "www.eddytheeco-dog.com") || dnsDomainIs(host, "www.edgate.com") || dnsDomainIs(host, "www.edmontonoilers.com") || dnsDomainIs(host, "www.edu-source.com") || dnsDomainIs(host, "www.edu.gov.on.ca") || dnsDomainIs(host, "www.edu4kids.com") || dnsDomainIs(host, "www.educ.uvic.ca") || dnsDomainIs(host, "www.educate.org.uk") || dnsDomainIs(host, "www.education-world.com") || dnsDomainIs(host, "www.edunet.com") || dnsDomainIs(host, "www.eduplace.com") || dnsDomainIs(host, "www.edupuppy.com") || dnsDomainIs(host, "www.eduweb.com") || dnsDomainIs(host, "www.ee.ryerson.ca") || dnsDomainIs(host, "www.ee.surrey.ac.uk") || dnsDomainIs(host, "www.eeggs.com") || dnsDomainIs(host, "www.efes.com") || dnsDomainIs(host, "www.egalvao.com") || dnsDomainIs(host, "www.egypt.com") || dnsDomainIs(host, "www.egyptology.com") || dnsDomainIs(host, "www.ehobbies.com") || dnsDomainIs(host, "www.ehow.com") || dnsDomainIs(host, "www.eia.brad.ac.uk") || dnsDomainIs(host, "www.elbalero.gob.mx") || dnsDomainIs(host, "www.eliki.com") || dnsDomainIs(host, "www.elnino.com") || dnsDomainIs(host, "www.elok.com") || dnsDomainIs(host, "www.emf.net") || dnsDomainIs(host, "www.emsphone.com") || dnsDomainIs(host, "www.emulateme.com") || dnsDomainIs(host, "www.en.com") || dnsDomainIs(host, "www.enature.com") || dnsDomainIs(host, "www.enchantedlearning.com") || dnsDomainIs(host, "www.encyclopedia.com") || dnsDomainIs(host, "www.endex.com") || dnsDomainIs(host, "www.enjoyillinois.com") || dnsDomainIs(host, "www.enn.com") || dnsDomainIs(host, "www.enriqueig.com") || dnsDomainIs(host, "www.enteract.com") || dnsDomainIs(host, "www.epals.com") || dnsDomainIs(host, "www.equine-world.co.uk") || dnsDomainIs(host, "www.eric-carle.com") || dnsDomainIs(host, "www.ericlindros.net") || dnsDomainIs(host, "www.escape.com") || dnsDomainIs(host, "www.eskimo.com") || dnsDomainIs(host, "www.essentialsofmusic.com") || dnsDomainIs(host, "www.etch-a-sketch.com") || dnsDomainIs(host, "www.ethanallen.together.com") || dnsDomainIs(host, "www.etoys.com") || dnsDomainIs(host, "www.eurekascience.com") || dnsDomainIs(host, "www.euronet.nl") || dnsDomainIs(host, "www.everyrule.com") || dnsDomainIs(host, "www.ex.ac.uk") || dnsDomainIs(host, "www.excite.com") || dnsDomainIs(host, "www.execpc.com") || dnsDomainIs(host, "www.execulink.com") || dnsDomainIs(host, "www.exn.net") || dnsDomainIs(host, "www.expa.hvu.nl") || dnsDomainIs(host, "www.expage.com") || dnsDomainIs(host, "www.explode.to") || dnsDomainIs(host, "www.explorescience.com") || dnsDomainIs(host, "www.explorezone.com") || dnsDomainIs(host, "www.extremescience.com") || dnsDomainIs(host, "www.eyelid.co.uk") || dnsDomainIs(host, "www.eyeneer.com") || dnsDomainIs(host, "www.eyesofachild.com") || dnsDomainIs(host, "www.eyesofglory.com") || dnsDomainIs(host, "www.ezschool.com") || dnsDomainIs(host, "www.f1-live.com") || dnsDomainIs(host, "www.fables.co.uk") || dnsDomainIs(host, "www.factmonster.com") || dnsDomainIs(host, "www.fairygodmother.com") || dnsDomainIs(host, "www.familybuzz.com") || dnsDomainIs(host, "www.familygames.com") || dnsDomainIs(host, "www.familygardening.com") || dnsDomainIs(host, "www.familyinternet.com") || dnsDomainIs(host, "www.familymoney.com") || dnsDomainIs(host, "www.familyplay.com") || dnsDomainIs(host, "www.famousbirthdays.com") || dnsDomainIs(host, "www.fandom.com") || dnsDomainIs(host, "www.fansites.com") || dnsDomainIs(host, "www.faoschwarz.com") || dnsDomainIs(host, "www.fbe.unsw.edu.au") || dnsDomainIs(host, "www.fcps.k12.va.us") || dnsDomainIs(host, "www.fellersartsfactory.com") || dnsDomainIs(host, "www.ferrari.it") || dnsDomainIs(host, "www.fertnel.com") || dnsDomainIs(host, "www.fh-konstanz.de") || dnsDomainIs(host, "www.fhw.gr") || dnsDomainIs(host, "www.fibblesnork.com") || dnsDomainIs(host, "www.fidnet.com") || dnsDomainIs(host, "www.fieldhockey.com") || dnsDomainIs(host, "www.fieldhockeytraining.com") || dnsDomainIs(host, "www.fieler.com") || dnsDomainIs(host, "www.finalfour.net") || dnsDomainIs(host, "www.finifter.com") || dnsDomainIs(host, "www.fireworks-safety.com") || dnsDomainIs(host, "www.firstcut.com") || dnsDomainIs(host, "www.firstnations.com") || dnsDomainIs(host, "www.fishbc.com") || dnsDomainIs(host, "www.fisher-price.com") || dnsDomainIs(host, "www.fisheyeview.com") || dnsDomainIs(host, "www.fishgeeks.com") || dnsDomainIs(host, "www.fishindex.com") || dnsDomainIs(host, "www.fitzgeraldstudio.com") || dnsDomainIs(host, "www.flags.net") || dnsDomainIs(host, "www.flail.com") || dnsDomainIs(host, "www.flamarlins.com") || dnsDomainIs(host, "www.flausa.com") || dnsDomainIs(host, "www.floodlight-findings.com") || dnsDomainIs(host, "www.floridahistory.com") || dnsDomainIs(host, "www.floridapanthers.com") || dnsDomainIs(host, "www.fng.fi") || dnsDomainIs(host, "www.foodsci.uoguelph.ca") || dnsDomainIs(host, "www.foremost.com") || dnsDomainIs(host, "www.fortress.am") || dnsDomainIs(host, "www.fortunecity.com") || dnsDomainIs(host, "www.fosterclub.com") || dnsDomainIs(host, "www.foundus.com") || dnsDomainIs(host, "www.fourmilab.ch") || dnsDomainIs(host, "www.fox.com") || dnsDomainIs(host, "www.foxfamilychannel.com") || dnsDomainIs(host, "www.foxhome.com") || dnsDomainIs(host, "www.foxkids.com") || dnsDomainIs(host, "www.franceway.com") || dnsDomainIs(host, "www.fred.net") || dnsDomainIs(host, "www.fredpenner.com") || dnsDomainIs(host, "www.freedomknot.com") || dnsDomainIs(host, "www.freejigsawpuzzles.com") || dnsDomainIs(host, "www.freenet.edmonton.ab.ca") || dnsDomainIs(host, "www.frii.com") || dnsDomainIs(host, "www.frisbee.com") || dnsDomainIs(host, "www.fritolay.com") || dnsDomainIs(host, "www.frogsonice.com") || dnsDomainIs(host, "www.frontiernet.net") || dnsDomainIs(host, "www.fs.fed.us") || dnsDomainIs(host, "www.funattic.com") || dnsDomainIs(host, ".funbrain.com") || dnsDomainIs(host, "www.fundango.com") || dnsDomainIs(host, "www.funisland.com") || dnsDomainIs(host, "www.funkandwagnalls.com") || dnsDomainIs(host, "www.funorama.com") || dnsDomainIs(host, "www.funschool.com") || dnsDomainIs(host, "www.funster.com") || dnsDomainIs(host, "www.furby.com") || dnsDomainIs(host, "www.fusion.org.uk") || dnsDomainIs(host, "www.futcher.com") || dnsDomainIs(host, "www.futurescan.com") || dnsDomainIs(host, "www.fyi.net") || dnsDomainIs(host, "www.gailgibbons.com") || dnsDomainIs(host, "www.galegroup.com") || dnsDomainIs(host, "www.gambia.com") || dnsDomainIs(host, "www.gamecabinet.com") || dnsDomainIs(host, "www.gamecenter.com") || dnsDomainIs(host, "www.gamefaqs.com") || dnsDomainIs(host, "www.garfield.com") || dnsDomainIs(host, "www.garyharbo.com") || dnsDomainIs(host, "www.gatefish.com") || dnsDomainIs(host, "www.gateway-va.com") || dnsDomainIs(host, "www.gazillionaire.com") || dnsDomainIs(host, "www.gearhead.com") || dnsDomainIs(host, "www.genesplicing.com") || dnsDomainIs(host, "www.genhomepage.com") || dnsDomainIs(host, "www.geobop.com") || dnsDomainIs(host, "www.geocities.com") || dnsDomainIs(host, "www.geographia.com") || dnsDomainIs(host, "www.georgeworld.com") || dnsDomainIs(host, "www.georgian.net") || dnsDomainIs(host, "www.german-way.com") || dnsDomainIs(host, "www.germanfortravellers.com") || dnsDomainIs(host, "www.germantown.k12.il.us") || dnsDomainIs(host, "www.germany-tourism.de") || dnsDomainIs(host, "www.getmusic.com") || dnsDomainIs(host, "www.gettysburg.com") || dnsDomainIs(host, "www.ghirardellisq.com") || dnsDomainIs(host, "www.ghosttowngallery.com") || dnsDomainIs(host, "www.ghosttownsusa.com") || dnsDomainIs(host, "www.giants.com") || dnsDomainIs(host, "www.gibraltar.gi") || dnsDomainIs(host, "www.gigglepoetry.com") || dnsDomainIs(host, "www.gilchriststudios.com") || dnsDomainIs(host, "www.gillslap.freeserve.co.uk") || dnsDomainIs(host, "www.gilmer.net") || dnsDomainIs(host, "www.gio.gov.tw") || dnsDomainIs(host, "www.girltech.com") || dnsDomainIs(host, "www.girlzone.com") || dnsDomainIs(host, "www.globalgang.org.uk") || dnsDomainIs(host, "www.globalindex.com") || dnsDomainIs(host, "www.globalinfo.com") || dnsDomainIs(host, "www.gloriafan.com") || dnsDomainIs(host, "www.gms.ocps.k12.fl.us") || dnsDomainIs(host, "www.go-go-diggity.com") || dnsDomainIs(host, "www.goals.com") || dnsDomainIs(host, "www.godiva.com") || dnsDomainIs(host, "www.golden-retriever.com") || dnsDomainIs(host, "www.goldenbooks.com") || dnsDomainIs(host, "www.goldeneggs.com.au") || dnsDomainIs(host, "www.golfonline.com") || dnsDomainIs(host, "www.goobo.com") || dnsDomainIs(host, "www.goodearthgraphics.com") || dnsDomainIs(host, "www.goodyear.com") || dnsDomainIs(host, "www.gopbi.com") || dnsDomainIs(host, "www.gorge.net") || dnsDomainIs(host, "www.gorp.com") || dnsDomainIs(host, "www.got-milk.com") || dnsDomainIs(host, "www.gov.ab.ca") || dnsDomainIs(host, "www.gov.nb.ca") || dnsDomainIs(host, "www.grammarbook.com") || dnsDomainIs(host, "www.grammarlady.com") || dnsDomainIs(host, "www.grandparents-day.com") || dnsDomainIs(host, "www.granthill.com") || dnsDomainIs(host, "www.grayweb.com") || dnsDomainIs(host, "www.greatbuildings.com") || dnsDomainIs(host, "www.greatkids.com") || dnsDomainIs(host, "www.greatscience.com") || dnsDomainIs(host, "www.greeceny.com") || dnsDomainIs(host, "www.greenkeepers.com") || dnsDomainIs(host, "www.greylabyrinth.com") || dnsDomainIs(host, "www.grimmy.com") || dnsDomainIs(host, "www.gsrg.nmh.ac.uk") || dnsDomainIs(host, "www.gti.net") || dnsDomainIs(host, "www.guinnessworldrecords.com") || dnsDomainIs(host, "www.guitar.net") || dnsDomainIs(host, "www.guitarplaying.com") || dnsDomainIs(host, "www.gumbyworld.com") || dnsDomainIs(host, "www.gurlwurld.com") || dnsDomainIs(host, "www.gwi.net") || dnsDomainIs(host, "www.gymn-forum.com") || dnsDomainIs(host, "www.gzkidzone.com") || dnsDomainIs(host, "www.haemibalgassi.com") || dnsDomainIs(host, "www.hairstylist.com") || dnsDomainIs(host, "www.halcyon.com") || dnsDomainIs(host, "www.halifax.cbc.ca") || dnsDomainIs(host, "www.halloween-online.com") || dnsDomainIs(host, "www.halloweenkids.com") || dnsDomainIs(host, "www.halloweenmagazine.com") || dnsDomainIs(host, "www.hamill.co.uk") || dnsDomainIs(host, "www.hamsterdance2.com") || dnsDomainIs(host, "www.hamsters.co.uk") || dnsDomainIs(host, "www.hamstertours.com") || dnsDomainIs(host, "www.handsonmath.com") || dnsDomainIs(host, "www.handspeak.com") || dnsDomainIs(host, "www.hansonline.com") || dnsDomainIs(host, "www.happychild.org.uk") || dnsDomainIs(host, "www.happyfamilies.com") || dnsDomainIs(host, "www.happytoy.com") || dnsDomainIs(host, "www.harley-davidson.com") || dnsDomainIs(host, "www.harmonicalessons.com") || dnsDomainIs(host, "www.harperchildrens.com") || dnsDomainIs(host, "www.harvey.com") || dnsDomainIs(host, "www.hasbro-interactive.com") || dnsDomainIs(host, "www.haynet.net") || dnsDomainIs(host, "www.hbc.com") || dnsDomainIs(host, "www.hblewis.com") || dnsDomainIs(host, "www.hbook.com") || dnsDomainIs(host, "www.he.net") || dnsDomainIs(host, "www.headbone.com") || dnsDomainIs(host, "www.healthatoz.com") || dnsDomainIs(host, "www.healthypet.com") || dnsDomainIs(host, "www.heartfoundation.com.au") || dnsDomainIs(host, "www.heatersworld.com") || dnsDomainIs(host, "www.her-online.com") || dnsDomainIs(host, "www.heroesofhistory.com") || dnsDomainIs(host, "www.hersheypa.com") || dnsDomainIs(host, "www.hersheys.com") || dnsDomainIs(host, "www.hevanet.com") || dnsDomainIs(host, "www.heynetwork.com") || dnsDomainIs(host, "www.hgo.com") || dnsDomainIs(host, "www.hhof.com") || dnsDomainIs(host, "www.hideandseekpuppies.com") || dnsDomainIs(host, "www.hifusion.com") || dnsDomainIs(host, "www.highbridgepress.com") || dnsDomainIs(host, "www.his.com") || dnsDomainIs(host, "www.history.navy.mil") || dnsDomainIs(host, "www.historychannel.com") || dnsDomainIs(host, "www.historyhouse.com") || dnsDomainIs(host, "www.historyplace.com") || dnsDomainIs(host, "www.hisurf.com") || dnsDomainIs(host, "www.hiyah.com") || dnsDomainIs(host, "www.hmnet.com") || dnsDomainIs(host, "www.hoboes.com") || dnsDomainIs(host, "www.hockeydb.com") || dnsDomainIs(host, "www.hohnerusa.com") || dnsDomainIs(host, "www.holidaychannel.com") || dnsDomainIs(host, "www.holidayfestival.com") || dnsDomainIs(host, "www.holidays.net") || dnsDomainIs(host, "www.hollywood.com") || dnsDomainIs(host, "www.holoworld.com") || dnsDomainIs(host, "www.homepagers.com") || dnsDomainIs(host, "www.homeschoolzone.com") || dnsDomainIs(host, "www.homestead.com") || dnsDomainIs(host, "www.homeworkspot.com") || dnsDomainIs(host, "www.hompro.com") || dnsDomainIs(host, "www.honey.com") || dnsDomainIs(host, "www.hooked.net") || dnsDomainIs(host, "www.hoophall.com") || dnsDomainIs(host, "www.hooverdam.com") || dnsDomainIs(host, "www.hopepaul.com") || dnsDomainIs(host, "www.horse-country.com") || dnsDomainIs(host, "www.horsechat.com") || dnsDomainIs(host, "www.horsefun.com") || dnsDomainIs(host, "www.horus.ics.org.eg") || dnsDomainIs(host, "www.hotbraille.com") || dnsDomainIs(host, "www.hotwheels.com") || dnsDomainIs(host, "www.howstuffworks.com") || dnsDomainIs(host, "www.hpdigitalbookclub.com") || dnsDomainIs(host, "www.hpj.com") || dnsDomainIs(host, "www.hpl.hp.com") || dnsDomainIs(host, "www.hpl.lib.tx.us") || dnsDomainIs(host, "www.hpnetwork.f2s.com") || dnsDomainIs(host, "www.hsswp.com") || dnsDomainIs(host, "www.hsx.com") || dnsDomainIs(host, "www.humboldt1.com") || dnsDomainIs(host, "www.humongous.com") || dnsDomainIs(host, "www.humph3.freeserve.co.uk") || dnsDomainIs(host, "www.humphreybear.com ") || dnsDomainIs(host, "www.hurricanehunters.com") || dnsDomainIs(host, "www.hyperhistory.com") || dnsDomainIs(host, "www.i2k.com") || dnsDomainIs(host, "www.ibhof.com") || dnsDomainIs(host, "www.ibiscom.com") || dnsDomainIs(host, "www.ibm.com") || dnsDomainIs(host, "www.icangarden.com") || dnsDomainIs(host, "www.icecreamusa.com") || dnsDomainIs(host, "www.icn.co.uk") || dnsDomainIs(host, "www.icomm.ca") || dnsDomainIs(host, "www.idfishnhunt.com") || dnsDomainIs(host, "www.iditarod.com") || dnsDomainIs(host, "www.iei.net") || dnsDomainIs(host, "www.iemily.com") || dnsDomainIs(host, "www.iir.com") || dnsDomainIs(host, "www.ika.com") || dnsDomainIs(host, "www.ikoala.com") || dnsDomainIs(host, "www.iln.net") || dnsDomainIs(host, "www.imagine5.com") || dnsDomainIs(host, "www.imes.boj.or.jp") || dnsDomainIs(host, "www.inch.com") || dnsDomainIs(host, "www.incwell.com") || dnsDomainIs(host, "www.indian-river.fl.us") || dnsDomainIs(host, "www.indians.com") || dnsDomainIs(host, "www.indo.com") || dnsDomainIs(host, "www.indyracingleague.com") || dnsDomainIs(host, "www.indyzoo.com") || dnsDomainIs(host, "www.info-canada.com") || dnsDomainIs(host, "www.infomagic.net") || dnsDomainIs(host, "www.infoplease.com") || dnsDomainIs(host, "www.infoporium.com") || dnsDomainIs(host, "www.infostuff.com") || dnsDomainIs(host, "www.inhandmuseum.com") || dnsDomainIs(host, "www.inil.com") || dnsDomainIs(host, "www.inkspot.com") || dnsDomainIs(host, "www.inkyfingers.com") || dnsDomainIs(host, "www.innerauto.com") || dnsDomainIs(host, "www.innerbody.com") || dnsDomainIs(host, "www.inqpub.com") || dnsDomainIs(host, "www.insecta-inspecta.com") || dnsDomainIs(host, "www.insectclopedia.com") || dnsDomainIs(host, "www.inside-mexico.com") || dnsDomainIs(host, "www.insiders.com") || dnsDomainIs(host, "www.insteam.com") || dnsDomainIs(host, "www.intel.com") || dnsDomainIs(host, "www.intellicast.com") || dnsDomainIs(host, "www.interads.co.uk") || dnsDomainIs(host, "www.intercot.com") || dnsDomainIs(host, "www.intergraffix.com") || dnsDomainIs(host, "www.interknowledge.com") || dnsDomainIs(host, "www.interlog.com") || dnsDomainIs(host, "www.internet4kids.com") || dnsDomainIs(host, "www.intersurf.com") || dnsDomainIs(host, "www.inthe80s.com") || dnsDomainIs(host, "www.inventorsmuseum.com") || dnsDomainIs(host, "www.inwap.com") || dnsDomainIs(host, "www.ioa.com") || dnsDomainIs(host, "www.ionet.net") || dnsDomainIs(host, "www.iowacity.com") || dnsDomainIs(host, "www.ireland-now.com") || dnsDomainIs(host, "www.ireland.com") || dnsDomainIs(host, "www.irelandseye.com") || dnsDomainIs(host, "www.irlgov.ie") || dnsDomainIs(host, "www.isd.net") || dnsDomainIs(host, "www.islandnet.com") || dnsDomainIs(host, "www.isomedia.com") || dnsDomainIs(host, "www.itftennis.com") || dnsDomainIs(host, "www.itpi.dpi.state.nc.us") || dnsDomainIs(host, "www.itskwanzaatime.com") || dnsDomainIs(host, "www.itss.raytheon.com") || dnsDomainIs(host, "www.iuma.com") || dnsDomainIs(host, "www.iwaynet.net") || dnsDomainIs(host, "www.iwc.com") || dnsDomainIs(host, "www.iwight.gov.uk") || dnsDomainIs(host, "www.ixpres.com") || dnsDomainIs(host, "www.j.b.allen.btinternet.co.uk") || dnsDomainIs(host, "www.jabuti.com") || dnsDomainIs(host, "www.jackinthebox.com") || dnsDomainIs(host, "www.jaffebros.com") || dnsDomainIs(host, "www.jaguars.com") || dnsDomainIs(host, "www.jamaica-gleaner.com") || dnsDomainIs(host, "www.jamm.com") || dnsDomainIs(host, "www.janbrett.com") || dnsDomainIs(host, "www.janetstevens.com") || dnsDomainIs(host, "www.japan-guide.com") || dnsDomainIs(host, "www.jargon.net") || dnsDomainIs(host, "www.javelinamx.com") || dnsDomainIs(host, "www.jayjay.com") || dnsDomainIs(host, "www.jazclass.aust.com") || dnsDomainIs(host, "www.jedinet.com") || dnsDomainIs(host, "www.jenniferlopez.com") || dnsDomainIs(host, "www.jlpanagopoulos.com") || dnsDomainIs(host, "www.jmarshall.com") || dnsDomainIs(host, "www.jmccall.demon.co.uk") || dnsDomainIs(host, "www.jmts.com") || dnsDomainIs(host, "www.joesherlock.com") || dnsDomainIs(host, "www.jorvik-viking-centre.co.uk") || dnsDomainIs(host, "www.joycecarolthomas.com") || dnsDomainIs(host, "www.joycone.com") || dnsDomainIs(host, "www.joyrides.com") || dnsDomainIs(host, "www.jps.net") || dnsDomainIs(host, "www.jspub.com") || dnsDomainIs(host, "www.judaica.com") || dnsDomainIs(host, "www.judyblume.com") || dnsDomainIs(host, "www.julen.net") || dnsDomainIs(host, "www.june29.com") || dnsDomainIs(host, "www.juneteenth.com") || dnsDomainIs(host, "www.justuskidz.com") || dnsDomainIs(host, "www.justwomen.com") || dnsDomainIs(host, "www.jwindow.net") || dnsDomainIs(host, "www.k9web.com") || dnsDomainIs(host, "www.kaercher.de") || dnsDomainIs(host, "www.kaleidoscapes.com") || dnsDomainIs(host, "www.kapili.com") || dnsDomainIs(host, "www.kcchiefs.com") || dnsDomainIs(host, "www.kcpl.lib.mo.us") || dnsDomainIs(host, "www.kcroyals.com") || dnsDomainIs(host, "www.kcsd.k12.pa.us") || dnsDomainIs(host, "www.kdu.com") || dnsDomainIs(host, "www.kelloggs.com") || dnsDomainIs(host, "www.kentuckyfriedchicken.com") || dnsDomainIs(host, "www.kenyaweb.com") || dnsDomainIs(host, "www.keypals.com") || dnsDomainIs(host, "www.kfn.com") || dnsDomainIs(host, "www.kid-at-art.com") || dnsDomainIs(host, "www.kid-channel.com") || dnsDomainIs(host, "www.kidallergy.com") || dnsDomainIs(host, "www.kidbibs.com") || dnsDomainIs(host, "www.kidcomics.com") || dnsDomainIs(host, "www.kiddesafety.com") || dnsDomainIs(host, "www.kiddiecampus.com") || dnsDomainIs(host, "www.kididdles.com") || dnsDomainIs(host, "www.kidnews.com") || dnsDomainIs(host, "www.kidocracy.com") || dnsDomainIs(host, "www.kidport.com") || dnsDomainIs(host, "www.kids-channel.co.uk") || dnsDomainIs(host, "www.kids-drawings.com") || dnsDomainIs(host, "www.kids-in-mind.com") || dnsDomainIs(host, "www.kids4peace.com") || dnsDomainIs(host, "www.kidsandcomputers.com") || dnsDomainIs(host, "www.kidsart.co.uk") || dnsDomainIs(host, "www.kidsastronomy.com") || dnsDomainIs(host, "www.kidsbank.com") || dnsDomainIs(host, "www.kidsbookshelf.com") || dnsDomainIs(host, "www.kidsclick.com") || dnsDomainIs(host, "www.kidscom.com") || dnsDomainIs(host, "www.kidscook.com") || dnsDomainIs(host, "www.kidsdoctor.com") || dnsDomainIs(host, "www.kidsdomain.com") || dnsDomainIs(host, "www.kidsfarm.com") || dnsDomainIs(host, "www.kidsfreeware.com") || dnsDomainIs(host, "www.kidsfun.tv") || dnsDomainIs(host, "www.kidsgolf.com") || dnsDomainIs(host, "www.kidsgowild.com") || dnsDomainIs(host, "www.kidsjokes.com") || dnsDomainIs(host, "www.kidsloveamystery.com") || dnsDomainIs(host, "www.kidsmoneycents.com") || dnsDomainIs(host, "www.kidsnewsroom.com") || dnsDomainIs(host, "www.kidsource.com") || dnsDomainIs(host, "www.kidsparties.com") || dnsDomainIs(host, "www.kidsplaytown.com") || dnsDomainIs(host, "www.kidsreads.com") || dnsDomainIs(host, "www.kidsreport.com") || dnsDomainIs(host, "www.kidsrunning.com") || dnsDomainIs(host, "www.kidstamps.com") || dnsDomainIs(host, "www.kidsvideogames.com") || dnsDomainIs(host, "www.kidsway.com") || dnsDomainIs(host, "www.kidswithcancer.com") || dnsDomainIs(host, "www.kidszone.ourfamily.com") || dnsDomainIs(host, "www.kidzup.com") || dnsDomainIs(host, "www.kinderart.com") || dnsDomainIs(host, "www.kineticcity.com") || dnsDomainIs(host, "www.kings.k12.ca.us") || dnsDomainIs(host, "www.kiplinger.com") || dnsDomainIs(host, "www.kiwirecovery.org.nz") || dnsDomainIs(host, "www.klipsan.com") || dnsDomainIs(host, "www.klutz.com") || dnsDomainIs(host, "www.kn.pacbell.com") || dnsDomainIs(host, "www.knex.com") || dnsDomainIs(host, "www.knowledgeadventure.com") || dnsDomainIs(host, "www.knto.or.kr") || dnsDomainIs(host, "www.kodak.com") || dnsDomainIs(host, "www.konica.co.jp") || dnsDomainIs(host, "www.kraftfoods.com") || dnsDomainIs(host, "www.kudzukids.com") || dnsDomainIs(host, "www.kulichki.com") || dnsDomainIs(host, "www.kuttu.com") || dnsDomainIs(host, "www.kv5.com") || dnsDomainIs(host, "www.kyes-world.com") || dnsDomainIs(host, "www.kyohaku.go.jp") || dnsDomainIs(host, "www.kyrene.k12.az.us") || dnsDomainIs(host, "www.kz") || dnsDomainIs(host, "www.la-hq.org.uk") || dnsDomainIs(host, "www.labs.net") || dnsDomainIs(host, "www.labyrinth.net.au") || dnsDomainIs(host, "www.laffinthedark.com") || dnsDomainIs(host, "www.lakhota.com") || dnsDomainIs(host, "www.lakings.com") || dnsDomainIs(host, "www.lam.mus.ca.us") || dnsDomainIs(host, "www.lampstras.k12.pa.us") || dnsDomainIs(host, "www.lams.losalamos.k12.nm.us") || dnsDomainIs(host, "www.landofcadbury.ca") || dnsDomainIs(host, "www.larry-boy.com") || dnsDomainIs(host, "www.lasersite.com") || dnsDomainIs(host, "www.last-word.com") || dnsDomainIs(host, "www.latimes.com") || dnsDomainIs(host, "www.laughon.com") || dnsDomainIs(host, "www.laurasmidiheaven.com") || dnsDomainIs(host, "www.lausd.k12.ca.us") || dnsDomainIs(host, "www.learn2.com") || dnsDomainIs(host, "www.learn2type.com") || dnsDomainIs(host, "www.learnfree-hobbies.com") || dnsDomainIs(host, "www.learningkingdom.com") || dnsDomainIs(host, "www.learningplanet.com") || dnsDomainIs(host, "www.leftjustified.com") || dnsDomainIs(host, "www.legalpadjr.com") || dnsDomainIs(host, "www.legendarysurfers.com") || dnsDomainIs(host, "www.legends.dm.net") || dnsDomainIs(host, "www.legis.state.wi.us") || dnsDomainIs(host, "www.legis.state.wv.us") || dnsDomainIs(host, "www.lego.com") || dnsDomainIs(host, "www.leje.com") || dnsDomainIs(host, "www.leonardodicaprio.com") || dnsDomainIs(host, "www.lessonplanspage.com") || dnsDomainIs(host, "www.letour.fr") || dnsDomainIs(host, "www.levins.com") || dnsDomainIs(host, "www.levistrauss.com") || dnsDomainIs(host, "www.libertystatepark.com") || dnsDomainIs(host, "www.libraryspot.com") || dnsDomainIs(host, "www.lifelong.com") || dnsDomainIs(host, "www.lighthouse.cc") || dnsDomainIs(host, "www.lightlink.com") || dnsDomainIs(host, "www.lightspan.com") || dnsDomainIs(host, "www.lil-fingers.com") || dnsDomainIs(host, "www.linc.or.jp") || dnsDomainIs(host, "www.lindsaysbackyard.com") || dnsDomainIs(host, "www.lindtchocolate.com") || dnsDomainIs(host, "www.lineone.net") || dnsDomainIs(host, "www.lionel.com") || dnsDomainIs(host, "www.lisafrank.com") || dnsDomainIs(host, "www.lissaexplains.com") || dnsDomainIs(host, "www.literacycenter.net") || dnsDomainIs(host, "www.littleartist.com") || dnsDomainIs(host, "www.littlechiles.com") || dnsDomainIs(host, "www.littlecritter.com") || dnsDomainIs(host, "www.littlecrowtoys.com") || dnsDomainIs(host, "www.littlehousebooks.com") || dnsDomainIs(host, "www.littlejason.com") || dnsDomainIs(host, "www.littleplanettimes.com") || dnsDomainIs(host, "www.liveandlearn.com") || dnsDomainIs(host, "www.loadstar.prometeus.net") || dnsDomainIs(host, "www.localaccess.com") || dnsDomainIs(host, "www.lochness.co.uk") || dnsDomainIs(host, "www.lochness.scotland.net") || dnsDomainIs(host, "www.logos.it") || dnsDomainIs(host, "www.lonelyplanet.com") || dnsDomainIs(host, "www.looklearnanddo.com") || dnsDomainIs(host, "www.loosejocks.com") || dnsDomainIs(host, "www.lost-worlds.com") || dnsDomainIs(host, "www.love-story.com") || dnsDomainIs(host, "www.lpga.com") || dnsDomainIs(host, "www.lsjunction.com") || dnsDomainIs(host, "www.lucasarts.com") || dnsDomainIs(host, "www.lucent.com") || dnsDomainIs(host, "www.lucie.com") || dnsDomainIs(host, "www.lunaland.co.za") || dnsDomainIs(host, "www.luth.se") || dnsDomainIs(host, "www.lyricalworks.com") || dnsDomainIs(host, "www.infoporium.com") || dnsDomainIs(host, "www.infostuff.com") || dnsDomainIs(host, "www.inhandmuseum.com") || dnsDomainIs(host, "www.inil.com") || dnsDomainIs(host, "www.inkspot.com") || dnsDomainIs(host, "www.inkyfingers.com") || dnsDomainIs(host, "www.innerauto.com") || dnsDomainIs(host, "www.innerbody.com") || dnsDomainIs(host, "www.inqpub.com") || dnsDomainIs(host, "www.insecta-inspecta.com") || dnsDomainIs(host, "www.insectclopedia.com") || dnsDomainIs(host, "www.inside-mexico.com") || dnsDomainIs(host, "www.insiders.com") || dnsDomainIs(host, "www.insteam.com") || dnsDomainIs(host, "www.intel.com") || dnsDomainIs(host, "www.intellicast.com") || dnsDomainIs(host, "www.interads.co.uk") || dnsDomainIs(host, "www.intercot.com") || dnsDomainIs(host, "www.intergraffix.com") || dnsDomainIs(host, "www.interknowledge.com") || dnsDomainIs(host, "www.interlog.com") || dnsDomainIs(host, "www.internet4kids.com") || dnsDomainIs(host, "www.intersurf.com") || dnsDomainIs(host, "www.inthe80s.com") || dnsDomainIs(host, "www.inventorsmuseum.com") || dnsDomainIs(host, "www.inwap.com") || dnsDomainIs(host, "www.ioa.com") || dnsDomainIs(host, "www.ionet.net") || dnsDomainIs(host, "www.iowacity.com") || dnsDomainIs(host, "www.ireland-now.com") || dnsDomainIs(host, "www.ireland.com") || dnsDomainIs(host, "www.irelandseye.com") || dnsDomainIs(host, "www.irlgov.ie") || dnsDomainIs(host, "www.isd.net") || dnsDomainIs(host, "www.islandnet.com") || dnsDomainIs(host, "www.isomedia.com") || dnsDomainIs(host, "www.itftennis.com") || dnsDomainIs(host, "www.itpi.dpi.state.nc.us") || dnsDomainIs(host, "www.itskwanzaatime.com") || dnsDomainIs(host, "www.itss.raytheon.com") || dnsDomainIs(host, "www.iuma.com") || dnsDomainIs(host, "www.iwaynet.net") || dnsDomainIs(host, "www.iwc.com") || dnsDomainIs(host, "www.iwight.gov.uk") || dnsDomainIs(host, "www.ixpres.com") || dnsDomainIs(host, "www.j.b.allen.btinternet.co.uk") || dnsDomainIs(host, "www.jabuti.com") || dnsDomainIs(host, "www.jackinthebox.com") || dnsDomainIs(host, "www.jaffebros.com") || dnsDomainIs(host, "www.jaguars.com") || dnsDomainIs(host, "www.jamaica-gleaner.com") || dnsDomainIs(host, "www.jamm.com") || dnsDomainIs(host, "www.janbrett.com") || dnsDomainIs(host, "www.janetstevens.com") || dnsDomainIs(host, "www.japan-guide.com") || dnsDomainIs(host, "www.jargon.net") || dnsDomainIs(host, "www.javelinamx.com") || dnsDomainIs(host, "www.jayjay.com") || dnsDomainIs(host, "www.jazclass.aust.com") ) return "PROXY proxy.hclib.org:80"; else return "PROXY 172.16.100.20:8080"; } reportCompare('No Crash', 'No Crash', '');
sam/htmlunit-rhino-fork
testsrc/tests/js1_5/Regress/regress-89443.js
JavaScript
mpl-2.0
94,445
package aws import ( "errors" "fmt" "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" ) func dataSourceAwsNetworkAcls() *schema.Resource { return &schema.Resource{ Read: dataSourceAwsNetworkAclsRead, Schema: map[string]*schema.Schema{ "filter": ec2CustomFiltersSchema(), "tags": tagsSchemaComputed(), "vpc_id": { Type: schema.TypeString, Optional: true, }, "ids": { Type: schema.TypeSet, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, Set: schema.HashString, }, }, } } func dataSourceAwsNetworkAclsRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn req := &ec2.DescribeNetworkAclsInput{} if v, ok := d.GetOk("vpc_id"); ok { req.Filters = buildEC2AttributeFilterList( map[string]string{ "vpc-id": v.(string), }, ) } filters, filtersOk := d.GetOk("filter") tags, tagsOk := d.GetOk("tags") if tagsOk { req.Filters = append(req.Filters, buildEC2TagFilterList( tagsFromMap(tags.(map[string]interface{})), )...) } if filtersOk { req.Filters = append(req.Filters, buildEC2CustomFilterList( filters.(*schema.Set), )...) } if len(req.Filters) == 0 { // Don't send an empty filters list; the EC2 API won't accept it. req.Filters = nil } log.Printf("[DEBUG] DescribeNetworkAcls %s\n", req) resp, err := conn.DescribeNetworkAcls(req) if err != nil { return err } if resp == nil || len(resp.NetworkAcls) == 0 { return errors.New("no matching network ACLs found") } networkAcls := make([]string, 0) for _, networkAcl := range resp.NetworkAcls { networkAcls = append(networkAcls, aws.StringValue(networkAcl.NetworkAclId)) } d.SetId(resource.UniqueId()) if err := d.Set("ids", networkAcls); err != nil { return fmt.Errorf("Error setting network ACL ids: %s", err) } return nil }
tpounds/terraform
vendor/github.com/terraform-providers/terraform-provider-aws/aws/data_source_aws_network_acls.go
GO
mpl-2.0
1,999
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "ExampleApp.h" #include "Moose.h" #include "AppFactory.h" #include "MooseSyntax.h" // Example 13 Includes #include "ExampleFunction.h" template<> InputParameters validParams<ExampleApp>() { InputParameters params = validParams<MooseApp>(); params.set<bool>("use_legacy_uo_initialization") = false; params.set<bool>("use_legacy_uo_aux_computation") = false; return params; } ExampleApp::ExampleApp(InputParameters parameters) : MooseApp(parameters) { srand(processor_id()); Moose::registerObjects(_factory); ExampleApp::registerObjects(_factory); Moose::associateSyntax(_syntax, _action_factory); ExampleApp::associateSyntax(_syntax, _action_factory); } ExampleApp::~ExampleApp() { } void ExampleApp::registerApps() { registerApp(ExampleApp); } void ExampleApp::registerObjects(Factory & factory) { registerFunction(ExampleFunction); } void ExampleApp::associateSyntax(Syntax & /*syntax*/, ActionFactory & /*action_factory*/) { }
katyhuff/moose
examples/ex13_functions/src/base/ExampleApp.C
C++
lgpl-2.1
1,845
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.doclava; import java.util.ArrayList; public class ParsedTagInfo extends TagInfo { private ContainerInfo mContainer; private String mCommentText; private Comment mComment; ParsedTagInfo(String name, String kind, String text, ContainerInfo base, SourcePositionInfo sp) { super(name, kind, text, SourcePositionInfo.findBeginning(sp, text)); mContainer = base; mCommentText = text; } public TagInfo[] commentTags() { if (mComment == null) { mComment = new Comment(mCommentText, mContainer, position()); } return mComment.tags(); } protected void setCommentText(String comment) { mCommentText = comment; } public static <T extends ParsedTagInfo> TagInfo[] joinTags(T[] tags) { ArrayList<TagInfo> list = new ArrayList<TagInfo>(); final int N = tags.length; for (int i = 0; i < N; i++) { TagInfo[] t = tags[i].commentTags(); final int M = t.length; for (int j = 0; j < M; j++) { list.add(t[j]); } } return list.toArray(new TagInfo[list.size()]); } }
kwf2030/doclava
src/main/java/com/google/doclava/ParsedTagInfo.java
Java
apache-2.0
1,692
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WingtipToys { public partial class About : Page { protected void Page_Load(object sender, EventArgs e) { } } }
sorenhl/Glimpse
source/Glimpse.WebForms.WingTip.Sample/About.aspx.cs
C#
apache-2.0
300
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import,line-too-long,wildcard-import from tensorflow.contrib.kfac.python.ops.utils import * from tensorflow.python.util.all_util import remove_undocumented # pylint: enable=unused-import,line-too-long,wildcard-import _allowed_symbols = [ "SequenceDict", "setdefault", "tensors_to_column", "column_to_tensors", "kronecker_product", "layer_params_to_mat2d", "mat2d_to_layer_params", "compute_pi", "posdef_inv", "posdef_inv_matrix_inverse", "posdef_inv_cholesky", "posdef_inv_funcs", "SubGraph", "generate_random_signs", "fwd_gradients", ] remove_undocumented(__name__, allowed_exception_list=_allowed_symbols)
benoitsteiner/tensorflow-opencl
tensorflow/contrib/kfac/python/ops/utils_lib.py
Python
apache-2.0
1,520
/* * 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. */ (function() { 'use strict'; var ALERT_FETCH_LIMIT = 1000 * 60 * 60 * 12; var ALERT_REFRESH_INTERVAL = 1000 * 10; var ALERT_TEMPLATE = '#/site/${siteId}/alert/detail/${alertId}?timestamp=${timestamp}'; var serviceModule = angular.module('eagle.service'); serviceModule.service('Alert', function ($notification, Time, CompatibleEntity) { var Alert = { list: null, }; $notification.getPromise().then(function () { function queryAlerts() { var endTime = new Time(); var list = CompatibleEntity.query("LIST", { query: "AlertService", startTime: endTime.clone().subtract(ALERT_FETCH_LIMIT, 'ms'), endTime: endTime }); list._then(function () { if (!Alert.list) { Alert.list = list; return; } var subList = common.array.minus(list, Alert.list, ['encodedRowkey'], ['encodedRowkey']); Alert.list = list; $.each(subList, function (i, alert) { $notification(alert.alertSubject, common.template(ALERT_TEMPLATE, { siteId: alert.tags.siteId, alertId: alert.tags.alertId, timestamp: alert.timestamp, })); }); }); } queryAlerts(); setInterval(queryAlerts, ALERT_REFRESH_INTERVAL); }); return Alert; }); })();
qingwen220/eagle
eagle-server/src/main/webapp/app/dev/public/js/services/alertSrv.js
JavaScript
apache-2.0
2,048
/* * 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.ignite.spi.checkpoint.jdbc; import org.apache.ignite.spi.checkpoint.*; import org.apache.ignite.testframework.junits.spi.*; import org.hsqldb.jdbc.*; /** * Grid jdbc checkpoint SPI custom config self test. */ @GridSpiTest(spi = JdbcCheckpointSpi.class, group = "Checkpoint SPI") public class JdbcCheckpointSpiCustomConfigSelfTest extends GridCheckpointSpiAbstractTest<JdbcCheckpointSpi> { /** {@inheritDoc} */ @Override protected void spiConfigure(JdbcCheckpointSpi spi) throws Exception { jdbcDataSource ds = new jdbcDataSource(); ds.setDatabase("jdbc:hsqldb:mem:gg_test_" + getClass().getSimpleName()); ds.setUser("sa"); ds.setPassword(""); spi.setDataSource(ds); spi.setCheckpointTableName("custom_config_checkpoints"); spi.setKeyFieldName("key"); spi.setValueFieldName("value"); spi.setValueFieldType("longvarbinary"); spi.setExpireDateFieldName("expire_date"); super.spiConfigure(spi); } }
akuznetsov-gridgain/ignite
modules/core/src/test/java/org/apache/ignite/spi/checkpoint/jdbc/JdbcCheckpointSpiCustomConfigSelfTest.java
Java
apache-2.0
1,829
/* * 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.jackrabbit.oak.plugins.document.blob.ds; import java.util.Date; import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreBlobStore; import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreUtils; import org.apache.jackrabbit.oak.plugins.document.DocumentMK; import org.apache.jackrabbit.oak.plugins.document.MongoBlobGCTest; import org.apache.jackrabbit.oak.plugins.document.MongoUtils; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; /** * Test for MongoMK GC with {@link DataStoreBlobStore} * */ public class MongoDataStoreBlobGCTest extends MongoBlobGCTest { protected Date startDate; protected DataStoreBlobStore blobStore; @BeforeClass public static void setUpBeforeClass() throws Exception { try { Assume.assumeNotNull(DataStoreUtils.getBlobStore()); } catch (Exception e) { Assume.assumeNoException(e); } } @Override protected DocumentMK.Builder addToBuilder(DocumentMK.Builder mk) { return super.addToBuilder(mk).setBlobStore(blobStore); } @Before @Override public void setUpConnection() throws Exception { startDate = new Date(); blobStore = DataStoreUtils.getBlobStore(folder.newFolder()); super.setUpConnection(); } }
trekawek/jackrabbit-oak
oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/blob/ds/MongoDataStoreBlobGCTest.java
Java
apache-2.0
2,161
/* * 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.drill.exec.physical.impl.validate; import java.util.List; import org.apache.drill.common.exceptions.ExecutionSetupException; import org.apache.drill.exec.ExecConstants; import org.apache.drill.exec.ops.ExecutorFragmentContext; import org.apache.drill.exec.physical.config.IteratorValidator; import org.apache.drill.exec.physical.impl.BatchCreator; import org.apache.drill.exec.record.RecordBatch; import org.apache.drill.shaded.guava.com.google.common.base.Preconditions; public class IteratorValidatorCreator implements BatchCreator<IteratorValidator>{ static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(IteratorValidatorCreator.class); @Override public IteratorValidatorBatchIterator getBatch(ExecutorFragmentContext context, IteratorValidator config, List<RecordBatch> children) throws ExecutionSetupException { Preconditions.checkArgument(children.size() == 1); RecordBatch child = children.iterator().next(); IteratorValidatorBatchIterator iter = new IteratorValidatorBatchIterator(child, config.isRepeatable); boolean validateBatches = context.getOptions().getOption(ExecConstants.ENABLE_VECTOR_VALIDATOR) || context.getConfig().getBoolean(ExecConstants.ENABLE_VECTOR_VALIDATION); iter.enableBatchValidation(validateBatches); logger.trace("Iterator validation enabled for " + child.getClass().getSimpleName() + (validateBatches ? " with vector validation" : "")); return iter; } }
apache/drill
exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/validate/IteratorValidatorCreator.java
Java
apache-2.0
2,373
<?php require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php'); /** * OAuth Store * * Updated version, works with consumer-callbacks, certificates and 1.0-RevA protocol * behaviour (requestToken-callbacks and verifiers) * * @author Andreas Åkre Solberg, <andreas.solberg@uninett.no>, UNINETT AS. * @author Mark Dobrinic, <mdobrinic@cozmanova.com>, Cozmanova bv * @package SimpleSAMLphp */ class sspmod_oauth_OAuthStore extends OAuthDataStore { private $store; private $config; private $defaultversion = '1.0'; protected $_store_tables = array( 'consumers' => 'consumer = array with consumer attributes', 'nonce' => 'nonce+consumer_key = -boolean-', 'requesttorequest' => 'requestToken.key = array(version,callback,consumerKey,)', 'authorized' => 'requestToken.key, verifier = array(authenticated-user-attributes)', 'access' => 'accessToken.key+consumerKey = accestoken', 'request' => 'requestToken.key+consumerKey = requesttoken', ); function __construct() { $this->store = new sspmod_core_Storage_SQLPermanentStorage('oauth'); $this->config = SimpleSAML_Configuration::getOptionalConfig('module_oauth.php'); } /** * Attach the data to the token, and establish the Callback URL and verifier * @param $requestTokenKey RequestToken that was authorized * @param $data Data that is authorized and to be attached to the requestToken * @return array(string:url, string:verifier) ; empty verifier for 1.0-response */ public function authorize($requestTokenKey, $data) { $url = null; $verifier = ''; $version = $this->defaultversion; // See whether to remember values from the original requestToken request: $request_attributes = $this->store->get('requesttorequest', $requestTokenKey, ''); // must be there .. if ($request_attributes['value']) { // establish version to work with $v = $request_attributes['value']['version']; if ($v) $version = $v; // establish callback to use if ($request_attributes['value']['callback']) { $url = $request_attributes['value']['callback']; } } // Is there a callback registered? This is leading, even over a supplied oauth_callback-parameter $oConsumer = $this->lookup_consumer($request_attributes['value']['consumerKey']); if ($oConsumer && ($oConsumer->callback_url)) $url = $oConsumer->callback_url; $verifier = SimpleSAML\Utils\Random::generateID(); $url = \SimpleSAML\Utils\HTTP::addURLParameters($url, array("oauth_verifier"=>$verifier)); $this->store->set('authorized', $requestTokenKey, $verifier, $data, $this->config->getValue('requestTokenDuration', 60*30) ); return array($url, $verifier); } /** * Perform lookup whether a given token exists in the list of authorized tokens; if a verifier is * passed as well, the verifier *must* match the verifier that was registered with the token<br/> * Note that an accessToken should never be stored with a verifier * @param $requestToken * @param $verifier * @return unknown_type */ public function isAuthorized($requestToken, $verifier='') { SimpleSAML_Logger::info('OAuth isAuthorized(' . $requestToken . ')'); return $this->store->exists('authorized', $requestToken, $verifier); } public function getAuthorizedData($token, $verifier = '') { SimpleSAML_Logger::info('OAuth getAuthorizedData(' . $token . ')'); $data = $this->store->get('authorized', $token, $verifier); return $data['value']; } public function moveAuthorizedData($requestToken, $verifier, $accessTokenKey) { SimpleSAML_Logger::info('OAuth moveAuthorizedData(' . $requestToken . ', ' . $accessTokenKey . ')'); // Retrieve authorizedData from authorized.requestToken (with provider verifier) $authorizedData = $this->getAuthorizedData($requestToken, $verifier); // Remove the requesttoken+verifier from authorized store $this->store->remove('authorized', $requestToken, $verifier); // Add accesstoken with authorizedData to authorized store (with empty verifier) // accessTokenKey+consumer => accessToken is already registered in 'access'-table $this->store->set('authorized', $accessTokenKey, '', $authorizedData, $this->config->getValue('accessTokenDuration', 60*60*24)); } public function lookup_consumer($consumer_key) { SimpleSAML_Logger::info('OAuth lookup_consumer(' . $consumer_key . ')'); if (! $this->store->exists('consumers', $consumer_key, '')) return NULL; $consumer = $this->store->get('consumers', $consumer_key, ''); $callback = NULL; if ($consumer['value']['callback_url']) $callback = $consumer['value']['callback_url']; if ($consumer['value']['RSAcertificate']) { return new OAuthConsumer($consumer['value']['key'], $consumer['value']['RSAcertificate'], $callback); } else { return new OAuthConsumer($consumer['value']['key'], $consumer['value']['secret'], $callback); } } function lookup_token($consumer, $tokenType = 'default', $token) { SimpleSAML_Logger::info('OAuth lookup_token(' . $consumer->key . ', ' . $tokenType. ',' . $token . ')'); $data = $this->store->get($tokenType, $token, $consumer->key); if ($data == NULL) throw new Exception('Could not find token'); return $data['value']; } function lookup_nonce($consumer, $token, $nonce, $timestamp) { SimpleSAML_Logger::info('OAuth lookup_nonce(' . $consumer . ', ' . $token. ',' . $nonce . ')'); if ($this->store->exists('nonce', $nonce, $consumer->key)) return TRUE; $this->store->set('nonce', $nonce, $consumer->key, TRUE, $this->config->getValue('nonceCache', 60*60*24*14)); return FALSE; } function new_request_token($consumer, $callback = null, $version = null) { SimpleSAML_Logger::info('OAuth new_request_token(' . $consumer . ')'); $lifetime = $this->config->getValue('requestTokenDuration', 60*30); $token = new OAuthToken(SimpleSAML\Utils\Random::generateID(), SimpleSAML\Utils\Random::generateID()); $token->callback = $callback; // OAuth1.0-RevA $this->store->set('request', $token->key, $consumer->key, $token, $lifetime); // also store in requestToken->key => array('callback'=>CallbackURL, 'version'=>oauth_version $request_attributes = array( 'callback' => $callback, 'version' => ($version?$version:$this->defaultversion), 'consumerKey' => $consumer->key, ); $this->store->set('requesttorequest', $token->key, '', $request_attributes, $lifetime); // also store in requestToken->key => Consumer->key (enables consumer-lookup during reqToken-authorization stage) $this->store->set('requesttoconsumer', $token->key, '', $consumer->key, $lifetime); return $token; } function new_access_token($requestToken, $consumer, $verifier = null) { SimpleSAML_Logger::info('OAuth new_access_token(' . $requestToken . ',' . $consumer . ')'); $accestoken = new OAuthToken(SimpleSAML\Utils\Random::generateID(), SimpleSAML\Utils\Random::generateID()); $this->store->set('access', $accestoken->key, $consumer->key, $accestoken, $this->config->getValue('accessTokenDuration', 60*60*24) ); return $accestoken; } /** * Return OAuthConsumer-instance that a given requestToken was issued to * @param $requestTokenKey * @return unknown_type */ public function lookup_consumer_by_requestToken($requestTokenKey) { SimpleSAML_Logger::info('OAuth lookup_consumer_by_requestToken(' . $requestTokenKey . ')'); if (! $this->store->exists('requesttorequest', $requestTokenKey, '')) return NULL; $request = $this->store->get('requesttorequest', $requestTokenKey, ''); $consumerKey = $request['value']['consumerKey']; if (! $consumerKey) { return NULL; } $consumer = $this->store->get('consumers', $consumerKey['value'], ''); return $consumer['value']; } }
RKathees/is-connectors
tiqr/tiqr-client/modules/oauth/lib/OAuthStore.php
PHP
apache-2.0
7,852
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.predicate; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import io.undertow.server.HttpServerExchange; import io.undertow.util.HttpString; import io.undertow.util.Methods; /** * A predicate that returns true if the request is idempotent * according to the HTTP RFC. * * @author Stuart Douglas */ public class IdempotentPredicate implements Predicate { public static final IdempotentPredicate INSTANCE = new IdempotentPredicate(); private static final Set<HttpString> METHODS; static { Set<HttpString> methods = new HashSet<>(); methods.add(Methods.GET); methods.add(Methods.DELETE); methods.add(Methods.PUT); methods.add(Methods.HEAD); methods.add(Methods.OPTIONS); METHODS = Collections.unmodifiableSet(methods); } @Override public boolean resolve(HttpServerExchange value) { return METHODS.contains(value.getRequestMethod()); } public static class Builder implements PredicateBuilder { @Override public String name() { return "idempotent"; } @Override public Map<String, Class<?>> parameters() { return Collections.emptyMap(); } @Override public Set<String> requiredParameters() { return Collections.emptySet(); } @Override public String defaultParameter() { return null; } @Override public Predicate build(Map<String, Object> config) { return INSTANCE; } } }
stuartwdouglas/undertow
core/src/main/java/io/undertow/predicate/IdempotentPredicate.java
Java
apache-2.0
2,348
/* 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 github import ( "sync" "k8s.io/kubernetes/pkg/util/sets" ) // StatusChange keeps track of issue/commit for status changes type StatusChange struct { heads map[int]string // Pull-Request ID -> head-sha pullRequests map[string]sets.Int // head-sha -> Pull-Request IDs changed sets.String // SHA of commits whose status changed mutex sync.Mutex } // NewStatusChange creates a new status change tracker func NewStatusChange() *StatusChange { return &StatusChange{ heads: map[int]string{}, pullRequests: map[string]sets.Int{}, changed: sets.NewString(), } } // UpdatePullRequestHead updates the head commit for a pull-request func (s *StatusChange) UpdatePullRequestHead(pullRequestID int, newHead string) { s.mutex.Lock() defer s.mutex.Unlock() if oldHead, has := s.heads[pullRequestID]; has { delete(s.pullRequests, oldHead) } s.heads[pullRequestID] = newHead if _, has := s.pullRequests[newHead]; !has { s.pullRequests[newHead] = sets.NewInt() } s.pullRequests[newHead].Insert(pullRequestID) } // CommitStatusChanged must be called when the status for this commit has changed func (s *StatusChange) CommitStatusChanged(commit string) { s.mutex.Lock() defer s.mutex.Unlock() s.changed.Insert(commit) } // PopChangedPullRequests returns the list of issues changed since last call func (s *StatusChange) PopChangedPullRequests() []int { s.mutex.Lock() defer s.mutex.Unlock() changedPullRequests := sets.NewInt() for _, commit := range s.changed.List() { if pullRequests, has := s.pullRequests[commit]; has { changedPullRequests = changedPullRequests.Union(pullRequests) } } s.changed = sets.NewString() return changedPullRequests.List() }
piosz/test-infra
mungegithub/github/status_change.go
GO
apache-2.0
2,311
package terraform import ( "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/dag" ) // ResourceCountTransformer is a GraphTransformer that expands the count // out for a specific resource. // // This assumes that the count is already interpolated. type ResourceCountTransformer struct { Concrete ConcreteResourceInstanceNodeFunc Schema *configschema.Block // Count is either the number of indexed instances to create, or -1 to // indicate that count is not set at all and thus a no-key instance should // be created. Count int Addr addrs.AbsResource } func (t *ResourceCountTransformer) Transform(g *Graph) error { if t.Count < 0 { // Negative count indicates that count is not set at all. addr := t.Addr.Instance(addrs.NoKey) abstract := NewNodeAbstractResourceInstance(addr) abstract.Schema = t.Schema var node dag.Vertex = abstract if f := t.Concrete; f != nil { node = f(abstract) } g.Add(node) return nil } // For each count, build and add the node for i := 0; i < t.Count; i++ { key := addrs.IntKey(i) addr := t.Addr.Instance(key) abstract := NewNodeAbstractResourceInstance(addr) abstract.Schema = t.Schema var node dag.Vertex = abstract if f := t.Concrete; f != nil { node = f(abstract) } g.Add(node) } return nil }
xanzy/terraform-provider-cosmic
vendor/github.com/hashicorp/terraform/terraform/transform_resource_count.go
GO
apache-2.0
1,368
/* * 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.camel.component.cxf.converter; import javax.xml.transform.TransformerException; import org.w3c.dom.Element; import org.apache.camel.Converter; import org.apache.camel.component.cxf.CxfPayload; import org.apache.camel.converter.jaxp.DomConverter; // This converter is used to show how to override the CxfPayload default toString converter @Converter public final class MyCxfCustomerConverter { private MyCxfCustomerConverter() { //Helper class } @Converter public static String cxfPayloadToString(final CxfPayload<?> payload) { DomConverter converter = new DomConverter(); StringBuilder buf = new StringBuilder(); for (Object element : payload.getBody()) { String elementString = ""; try { elementString = converter.toString((Element) element, null); } catch (TransformerException e) { elementString = element.toString(); } buf.append(elementString); } return buf.toString(); } }
nikhilvibhav/camel
components/camel-cxf/src/test/java/org/apache/camel/component/cxf/converter/MyCxfCustomerConverter.java
Java
apache-2.0
1,868
package builds import ( "fmt" "path/filepath" "strings" "time" g "github.com/onsi/ginkgo" o "github.com/onsi/gomega" "k8s.io/kubernetes/test/e2e" exutil "github.com/openshift/origin/test/extended/util" ) var _ = g.Describe("default: S2I incremental build with push and pull to authenticated registry", func() { defer g.GinkgoRecover() var ( templateFixture = exutil.FixturePath("fixtures", "incremental-auth-build.json") oc = exutil.NewCLI("build-sti-env", exutil.KubeConfigPath()) ) g.JustBeforeEach(func() { g.By("waiting for builder service account") err := exutil.WaitForBuilderAccount(oc.KubeREST().ServiceAccounts(oc.Namespace())) o.Expect(err).NotTo(o.HaveOccurred()) }) g.Describe("Building from a template", func() { g.It(fmt.Sprintf("should create a build from %q template and run it", templateFixture), func() { oc.SetOutputDir(exutil.TestContext.OutputDir) g.By(fmt.Sprintf("calling oc new-app -f %q", templateFixture)) err := oc.Run("new-app").Args("-f", templateFixture).Execute() o.Expect(err).NotTo(o.HaveOccurred()) g.By("starting a test build") buildName, err := oc.Run("start-build").Args("initial-build").Output() o.Expect(err).NotTo(o.HaveOccurred()) g.By("expecting the build is in Complete phase") err = exutil.WaitForABuild(oc.REST().Builds(oc.Namespace()), buildName, exutil.CheckBuildSuccessFunc, exutil.CheckBuildFailedFunc) o.Expect(err).NotTo(o.HaveOccurred()) g.By("starting a test build using the image produced by the last build") buildName, err = oc.Run("start-build").Args("internal-build").Output() o.Expect(err).NotTo(o.HaveOccurred()) g.By("expecting the build is in Complete phase") err = exutil.WaitForABuild(oc.REST().Builds(oc.Namespace()), buildName, exutil.CheckBuildSuccessFunc, exutil.CheckBuildFailedFunc) o.Expect(err).NotTo(o.HaveOccurred()) g.By("getting the Docker image reference from ImageStream") imageName, err := exutil.GetDockerImageReference(oc.REST().ImageStreams(oc.Namespace()), "internal-image", "latest") o.Expect(err).NotTo(o.HaveOccurred()) g.By("writing the pod definition to a file") outputPath := filepath.Join(exutil.TestContext.OutputDir, oc.Namespace()+"-sample-pod.json") pod := exutil.CreatePodForImage(imageName) err = exutil.WriteObjectToFile(pod, outputPath) o.Expect(err).NotTo(o.HaveOccurred()) g.By(fmt.Sprintf("calling oc create -f %q", outputPath)) err = oc.Run("create").Args("-f", outputPath).Execute() o.Expect(err).NotTo(o.HaveOccurred()) g.By("expecting the pod to be running") err = oc.KubeFramework().WaitForPodRunning(pod.Name) o.Expect(err).NotTo(o.HaveOccurred()) // even though the pod is running, the app isn't always started // so wait until webrick output is complete before curling. logs := "" count := 0 for strings.Contains(logs, "8080") && count < 10 { logs, _ = oc.Run("logs").Args(pod.Name).Output() time.Sleep(time.Second) count++ } g.By("expecting the pod container has saved artifacts") out, err := oc.Run("exec").Args("-p", pod.Name, "--", "curl", "http://0.0.0.0:8080").Output() o.Expect(err).NotTo(o.HaveOccurred()) if !strings.Contains(out, "artifacts exist") { logs, _ = oc.Run("logs").Args(pod.Name).Output() e2e.Failf("Pod %q does not contain expected artifacts: %q\n%q", pod.Name, out, logs) } }) }) })
pkdevbox/origin
test/extended/builds/sti_incremental.go
GO
apache-2.0
3,417
//===--- SILDebugInfoGenerator.cpp - Writes a SIL file for debugging ------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "gsil-gen" #include "swift/AST/SILOptions.h" #include "swift/SIL/SILPrintContext.h" #include "swift/SIL/SILModule.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" using namespace swift; namespace { /// A pass for generating debug info on SIL level. /// /// This pass is only enabled if SILOptions::SILOutputFileNameForDebugging is /// set (i.e. if the -gsil command line option is specified). /// The pass writes all SIL functions into one or multiple output files, /// depending on the size of the SIL. The names of the output files are derived /// from the main output file. /// /// output file name = <main-output-filename>.gsil_<n>.sil /// /// Where <n> is a consecutive number. The files are stored in the same /// same directory as the main output file. /// The debug locations and scopes of all functions and instructions are changed /// to point to the generated SIL output files. /// This enables debugging and profiling on SIL level. class SILDebugInfoGenerator : public SILModuleTransform { enum { /// To prevent extra large output files, e.g. when compiling the stdlib. LineLimitPerFile = 10000 }; /// A stream for counting line numbers. struct LineCountStream : public llvm::raw_ostream { llvm::raw_ostream &Underlying; int LineNum = 1; uint64_t Pos = 0; void write_impl(const char *Ptr, size_t Size) override { for (size_t Idx = 0; Idx < Size; Idx++) { char c = Ptr[Idx]; if (c == '\n') ++LineNum; } Underlying.write(Ptr, Size); Pos += Size; } uint64_t current_pos() const override { return Pos; } LineCountStream(llvm::raw_ostream &Underlying) : llvm::raw_ostream(/* unbuffered = */ true), Underlying(Underlying) { } ~LineCountStream() { flush(); } }; /// A print context which records the line numbers where instructions are /// printed. struct PrintContext : public SILPrintContext { LineCountStream LCS; llvm::DenseMap<const SILInstruction *, int> LineNums; void printInstructionCallBack(const SILInstruction *I) override { // Record the current line number of the instruction. LineNums[I] = LCS.LineNum; } PrintContext(llvm::raw_ostream &OS) : SILPrintContext(LCS), LCS(OS) { } virtual ~PrintContext() { } }; void run() override { SILModule *M = getModule(); StringRef FileBaseName = M->getOptions().SILOutputFileNameForDebugging; if (FileBaseName.empty()) return; DEBUG(llvm::dbgs() << "** SILDebugInfoGenerator **\n"); std::vector<SILFunction *> PrintedFuncs; int FileIdx = 0; auto FIter = M->begin(); while (FIter != M->end()) { std::string FileName; llvm::raw_string_ostream NameOS(FileName); NameOS << FileBaseName << ".gsil_" << FileIdx++ << ".sil"; NameOS.flush(); char *FileNameBuf = (char *)M->allocate(FileName.size() + 1, 1); strcpy(FileNameBuf, FileName.c_str()); DEBUG(llvm::dbgs() << "Write debug SIL file " << FileName << '\n'); std::error_code EC; llvm::raw_fd_ostream OutFile(FileName, EC, llvm::sys::fs::OpenFlags::F_None); assert(!OutFile.has_error() && !EC && "Can't write SIL debug file"); PrintContext Ctx(OutFile); // Write functions until we reach the LineLimitPerFile. do { SILFunction *F = &*FIter++; PrintedFuncs.push_back(F); // Set the debug scope for the function. SILLocation::DebugLoc DL(Ctx.LCS.LineNum, 1, FileNameBuf); RegularLocation Loc(DL); SILDebugScope *Scope = new (*M) SILDebugScope(Loc, F); F->setDebugScope(Scope); // Ensure that the function is visible for debugging. F->setBare(IsNotBare); // Print it to the output file. F->print(Ctx); } while (FIter != M->end() && Ctx.LCS.LineNum < LineLimitPerFile); // Set the debug locations of all instructions. for (SILFunction *F : PrintedFuncs) { const SILDebugScope *Scope = F->getDebugScope(); for (SILBasicBlock &BB : *F) { for (SILInstruction &I : BB) { SILLocation Loc = I.getLoc(); SILLocation::DebugLoc DL(Ctx.LineNums[&I], 1, FileNameBuf); assert(DL.Line && "no line set for instruction"); if (Loc.is<ReturnLocation>() || Loc.is<ImplicitReturnLocation>()) { Loc.setDebugInfoLoc(DL); I.setDebugLocation(SILDebugLocation(Loc, Scope)); } else { RegularLocation RLoc(DL); I.setDebugLocation(SILDebugLocation(RLoc, Scope)); } } } } PrintedFuncs.clear(); } } StringRef getName() override { return "SILDebugInfoGenerator"; } }; } // end anonymous namespace SILTransform *swift::createSILDebugInfoGenerator() { return new SILDebugInfoGenerator(); }
russbishop/swift
lib/SILOptimizer/UtilityPasses/SILDebugInfoGenerator.cpp
C++
apache-2.0
5,535
// ---------------------------------------------------------------------------------- // // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation { using Common.ArgumentCompleters; using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels; using System.Collections; using System.Collections.Generic; using System.Management.Automation; /// <summary> /// Filters resource groups. /// </summary> [Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "ResourceGroup", SupportsShouldProcess = true), OutputType(typeof(PSResourceGroup))] public class NewAzureResourceGroupCmdlet : ResourceManagerCmdletBase { [Alias("ResourceGroupName")] [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group location.")] [LocationCompleter("Microsoft.Resources/resourceGroups")] [ValidateNotNullOrEmpty] public string Location { get; set; } [Alias("Tags")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable which represents resource tags.")] public Hashtable Tag { get; set; } [Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")] public SwitchParameter Force { get; set; } public override void ExecuteCmdlet() { PSCreateResourceGroupParameters parameters = new PSCreateResourceGroupParameters { ResourceGroupName = Name, Location = Location, Force = Force.IsPresent, Tag = Tag, ConfirmAction = ConfirmAction }; WriteObject(ResourceManagerSdkClient.CreatePSResourceGroup(parameters)); } } }
AzureAutomationTeam/azure-powershell
src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/ResourceGroups/NewAzureResourceGroupCmdlet.cs
C#
apache-2.0
2,741
/** * Copyright 2005-2015 The Kuali 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/ecl2.php * * 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.kuali.rice.krad.util; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.comparators.ComparableComparator; import org.kuali.rice.core.api.exception.KualiException; import org.kuali.rice.core.api.util.type.TypeUtils; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * BeanPropertyComparator compares the two beans using multiple property names * * */ public class BeanPropertyComparator implements Comparator, Serializable { private static final long serialVersionUID = -2675700473766186018L; boolean ignoreCase; private List propertyNames; private Comparator stringComparator; private Comparator booleanComparator; private Comparator genericComparator; /** * Constructs a PropertyComparator for comparing beans using the properties named in the given List * * <p>if the List is null, the beans will be compared directly * by Properties will be compared in the order in which they are listed. Case will be ignored * in String comparisons.</p> * * @param propertyNames List of property names (as Strings) used to compare beans */ public BeanPropertyComparator(List propertyNames) { this(propertyNames, true); } /** * Constructs a PropertyComparator for comparing beans using the properties named in the given List. * * <p>Properties will be compared * in the order in which they are listed. Case will be ignored if ignoreCase is true.</p> * * @param propertyNames List of property names (as Strings) used to compare beans * @param ignoreCase if true, case will be ignored during String comparisons */ public BeanPropertyComparator(List propertyNames, boolean ignoreCase) { if (propertyNames == null) { throw new IllegalArgumentException("invalid (null) propertyNames list"); } if (propertyNames.size() == 0) { throw new IllegalArgumentException("invalid (empty) propertyNames list"); } this.propertyNames = Collections.unmodifiableList(propertyNames); this.ignoreCase = ignoreCase; if (ignoreCase) { this.stringComparator = String.CASE_INSENSITIVE_ORDER; } else { this.stringComparator = ComparableComparator.getInstance(); } this.booleanComparator = new Comparator() { public int compare(Object o1, Object o2) { int compared = 0; Boolean b1 = (Boolean) o1; Boolean b2 = (Boolean) o2; if (!b1.equals(b2)) { if (b1.equals(Boolean.FALSE)) { compared = -1; } else { compared = 1; } } return compared; } }; this.genericComparator = ComparableComparator.getInstance(); } /** * Compare two JavaBeans by the properties given to the constructor. * * @param o1 Object The first bean to get data from to compare against * @param o2 Object The second bean to get data from to compare * @return int negative or positive based on order */ public int compare(Object o1, Object o2) { int compared = 0; try { for (Iterator i = propertyNames.iterator(); (compared == 0) && i.hasNext();) { String currentProperty = i.next().toString(); // choose appropriate comparator Comparator currentComparator = null; try { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(o1, currentProperty); Class propertyClass = propertyDescriptor.getPropertyType(); if (propertyClass.equals(String.class)) { currentComparator = this.stringComparator; } else if (TypeUtils.isBooleanClass(propertyClass)) { currentComparator = this.booleanComparator; } else { currentComparator = this.genericComparator; } } catch (NullPointerException e) { throw new BeanComparisonException("unable to find property '" + o1.getClass().getName() + "." + currentProperty + "'", e); } // compare the values Object value1 = PropertyUtils.getProperty(o1, currentProperty); Object value2 = PropertyUtils.getProperty(o2, currentProperty); /* Fix for KULRICE-5170 : BeanPropertyComparator throws exception when a null value is found in sortable non-string data type column */ if ( value1 == null && value2 == null) return 0; else if ( value1 == null) return -1; else if ( value2 == null ) return 1; /* End KULRICE-5170 Fix*/ compared = currentComparator.compare(value1, value2); } } catch (IllegalAccessException e) { throw new BeanComparisonException("unable to compare property values", e); } catch (NoSuchMethodException e) { throw new BeanComparisonException("unable to compare property values", e); } catch (InvocationTargetException e) { throw new BeanComparisonException("unable to compare property values", e); } return compared; } public static class BeanComparisonException extends KualiException { private static final long serialVersionUID = 2622379680100640029L; /** * @param message * @param t */ public BeanComparisonException(String message, Throwable t) { super(message, t); } } }
jruchcolo/rice-cd
rice-framework/krad-app-framework/src/main/java/org/kuali/rice/krad/util/BeanPropertyComparator.java
Java
apache-2.0
6,807
/** * * 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.openejb.core.mdb; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Session; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.TreeMap; public class MdbInvoker implements MessageListener { private final Map<String, Method> signatures = new TreeMap<String, Method>(); private final Object target; private Connection connection; private Session session; private ConnectionFactory connectionFactory; public MdbInvoker(ConnectionFactory connectionFactory, Object target) throws JMSException { this.target = target; this.connectionFactory = connectionFactory; for (Method method : target.getClass().getMethods()) { String signature = MdbUtil.getSignature(method); signatures.put(signature, method); } } public synchronized void destroy() { MdbUtil.close(session); session = null; MdbUtil.close(connection); connection = null; } private synchronized Session getSession() throws JMSException { connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); return session; } public void onMessage(Message message) { if (!(message instanceof ObjectMessage)) return; try { Session session = getSession(); if (session == null) throw new IllegalStateException("Invoker has been destroyed"); if (message == null) throw new NullPointerException("request message is null"); if (!(message instanceof ObjectMessage)) throw new IllegalArgumentException("Expected a ObjectMessage request but got a " + message.getClass().getName()); ObjectMessage objectMessage = (ObjectMessage) message; Serializable object = objectMessage.getObject(); if (object == null) throw new NullPointerException("object in ObjectMessage is null"); if (!(object instanceof Map)) { if (message instanceof ObjectMessage) throw new IllegalArgumentException("Expected a Map contained in the ObjectMessage request but got a " + object.getClass().getName()); } Map request = (Map) object; String signature = (String) request.get("method"); Method method = signatures.get(signature); Object[] args = (Object[]) request.get("args"); boolean exception = false; Object result = null; try { result = method.invoke(target, args); } catch (IllegalAccessException e) { result = e; exception = true; } catch (InvocationTargetException e) { result = e.getCause(); if (result == null) result = e; exception = true; } MessageProducer producer = null; try { // create response Map<String, Object> response = new TreeMap<String, Object>(); if (exception) { response.put("exception", "true"); } response.put("return", result); // create response message ObjectMessage resMessage = session.createObjectMessage(); resMessage.setJMSCorrelationID(objectMessage.getJMSCorrelationID()); resMessage.setObject((Serializable) response); // send response message producer = session.createProducer(objectMessage.getJMSReplyTo()); producer.send(resMessage); } catch (Exception e) { e.printStackTrace(); } finally { MdbUtil.close(producer); destroy(); } } catch (Throwable e) { e.printStackTrace(); } } }
apache/openejb
container/openejb-core/src/test/java/org/apache/openejb/core/mdb/MdbInvoker.java
Java
apache-2.0
5,024
/* * Copyright 2014 NAVER Corp. * * 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.navercorp.pinpoint.collector.cluster.route; import com.navercorp.pinpoint.collector.cluster.ClusterPointLocator; import com.navercorp.pinpoint.collector.cluster.TargetClusterPoint; import com.navercorp.pinpoint.collector.cluster.route.filter.RouteFilter; import com.navercorp.pinpoint.rpc.Future; import com.navercorp.pinpoint.rpc.ResponseMessage; import com.navercorp.pinpoint.thrift.dto.command.TCommandTransferResponse; import com.navercorp.pinpoint.thrift.dto.command.TRouteResult; import com.navercorp.pinpoint.thrift.io.TCommandTypeVersion; import org.apache.thrift.TBase; /** * @author koo.taejin * @author HyunGil Jeong */ public class DefaultRouteHandler extends AbstractRouteHandler<RequestEvent> { private final RouteFilterChain<RequestEvent> requestFilterChain; private final RouteFilterChain<ResponseEvent> responseFilterChain; public DefaultRouteHandler(ClusterPointLocator<TargetClusterPoint> targetClusterPointLocator, RouteFilterChain<RequestEvent> requestFilterChain, RouteFilterChain<ResponseEvent> responseFilterChain) { super(targetClusterPointLocator); this.requestFilterChain = requestFilterChain; this.responseFilterChain = responseFilterChain; } @Override public void addRequestFilter(RouteFilter<RequestEvent> filter) { this.requestFilterChain.addLast(filter); } @Override public void addResponseFilter(RouteFilter<ResponseEvent> filter) { this.responseFilterChain.addLast(filter); } @Override public TCommandTransferResponse onRoute(RequestEvent event) { requestFilterChain.doEvent(event); TCommandTransferResponse routeResult = onRoute0(event); responseFilterChain.doEvent(new ResponseEvent(event, event.getRequestId(), routeResult)); return routeResult; } private TCommandTransferResponse onRoute0(RequestEvent event) { TBase<?,?> requestObject = event.getRequestObject(); if (requestObject == null) { return createResponse(TRouteResult.EMPTY_REQUEST); } TargetClusterPoint clusterPoint = findClusterPoint(event.getDeliveryCommand()); if (clusterPoint == null) { return createResponse(TRouteResult.NOT_FOUND); } TCommandTypeVersion commandVersion = TCommandTypeVersion.getVersion(clusterPoint.gerVersion()); if (!commandVersion.isSupportCommand(requestObject)) { return createResponse(TRouteResult.NOT_SUPPORTED_REQUEST); } Future<ResponseMessage> future = clusterPoint.request(event.getDeliveryCommand().getPayload()); boolean isCompleted = future.await(); if (!isCompleted) { return createResponse(TRouteResult.TIMEOUT); } ResponseMessage responseMessage = future.getResult(); if (responseMessage == null) { return createResponse(TRouteResult.EMPTY_RESPONSE); } byte[] responsePayload = responseMessage.getMessage(); if (responsePayload == null || responsePayload.length == 0) { return createResponse(TRouteResult.EMPTY_RESPONSE, new byte[0]); } return createResponse(TRouteResult.OK, responsePayload); } private TCommandTransferResponse createResponse(TRouteResult result) { return createResponse(result, new byte[0]); } private TCommandTransferResponse createResponse(TRouteResult result, byte[] payload) { TCommandTransferResponse response = new TCommandTransferResponse(); response.setRouteResult(result); response.setPayload(payload); return response; } }
dawidmalina/pinpoint
collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteHandler.java
Java
apache-2.0
4,382
/* * 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.camel.component.twitter.search; import java.util.Collections; import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.component.twitter.TwitterEndpoint; import org.apache.camel.component.twitter.consumer.AbstractTwitterConsumerHandler; import org.apache.camel.component.twitter.consumer.TwitterEventType; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.GeoLocation; import twitter4j.Query; import twitter4j.Query.Unit; import twitter4j.QueryResult; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; /** * Consumes search requests */ public class SearchConsumerHandler extends AbstractTwitterConsumerHandler { private static final Logger LOG = LoggerFactory.getLogger(SearchConsumerHandler.class); private String keywords; public SearchConsumerHandler(TwitterEndpoint te, String keywords) { super(te); this.keywords = keywords; } @Override public List<Exchange> pollConsume() throws TwitterException { String keywords = this.keywords; Query query; if (keywords != null && keywords.trim().length() > 0) { query = new Query(keywords); LOG.debug("Searching twitter with keywords: {}", keywords); } else { query = new Query(); LOG.debug("Searching twitter without keywords."); } if (endpoint.getProperties().isFilterOld()) { query.setSinceId(getLastId()); } return search(query); } @Override public List<Exchange> directConsume() throws TwitterException { String keywords = this.keywords; if (keywords == null || keywords.trim().length() == 0) { return Collections.emptyList(); } Query query = new Query(keywords); LOG.debug("Searching twitter with keywords: {}", keywords); return search(query); } private List<Exchange> search(Query query) throws TwitterException { Integer numberOfPages = 1; if (ObjectHelper.isNotEmpty(endpoint.getProperties().getLang())) { query.setLang(endpoint.getProperties().getLang()); } if (ObjectHelper.isNotEmpty(endpoint.getProperties().getCount())) { query.setCount(endpoint.getProperties().getCount()); } if (ObjectHelper.isNotEmpty(endpoint.getProperties().getNumberOfPages())) { numberOfPages = endpoint.getProperties().getNumberOfPages(); } if (ObjectHelper.isNotEmpty(endpoint.getProperties().getLatitude()) && ObjectHelper.isNotEmpty(endpoint.getProperties().getLongitude()) && ObjectHelper.isNotEmpty(endpoint.getProperties().getRadius())) { GeoLocation location = new GeoLocation(endpoint.getProperties().getLatitude(), endpoint.getProperties().getLongitude()); query.setGeoCode(location, endpoint.getProperties().getRadius(), Unit.valueOf(endpoint.getProperties().getDistanceMetric())); LOG.debug("Searching with additional geolocation parameters."); } LOG.debug("Searching with {} pages.", numberOfPages); Twitter twitter = getTwitter(); QueryResult qr = twitter.search(query); List<Status> tweets = qr.getTweets(); for (int i = 1; i < numberOfPages; i++) { if (!qr.hasNext()) { break; } qr = twitter.search(qr.nextQuery()); tweets.addAll(qr.getTweets()); } if (endpoint.getProperties().isFilterOld()) { for (Status status : tweets) { setLastIdIfGreater(status.getId()); } } return TwitterEventType.STATUS.createExchangeList(endpoint, tweets); } }
nikhilvibhav/camel
components/camel-twitter/src/main/java/org/apache/camel/component/twitter/search/SearchConsumerHandler.java
Java
apache-2.0
4,705
/* * * Copyright 2015 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 springfox.documentation.spring.web.dummy; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.Authorization; import io.swagger.annotations.AuthorizationScope; import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.multipart.MultipartFile; import springfox.documentation.annotations.ApiIgnore; import springfox.documentation.spring.web.dummy.DummyModels.Ignorable; import springfox.documentation.spring.web.dummy.models.EnumType; import springfox.documentation.spring.web.dummy.models.Example; import springfox.documentation.spring.web.dummy.models.FoobarDto; import springfox.documentation.spring.web.dummy.models.Treeish; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import java.util.List; import java.util.Map; @RequestMapping(produces = {"application/json"}, consumes = {"application/json", "application/xml"}) public class DummyClass { @ApiParam public void annotatedWithApiParam() { } public void dummyMethod() { } public void methodWithOneArgs(int a) { } public void methodWithTwoArgs(int a, String b) { } public void methodWithNoArgs() { } @ApiOperation(value = "description", httpMethod = "GET") public void methodWithHttpGETMethod() { } @ApiOperation(value = "description", nickname = "unique") public void methodWithNickName() { } @ApiOperation(value = "description", httpMethod = "GET", hidden = true) public void methodThatIsHidden() { } @ApiOperation(value = "description", httpMethod = "RUBBISH") public void methodWithInvalidHttpMethod() { } @ApiOperation(value = "summary", httpMethod = "RUBBISH") public void methodWithSummary() { } @ApiOperation(value = "", notes = "some notes") public void methodWithNotes() { } @ApiOperation(value = "", nickname = "a nickname") public void methodWithNickname() { } @ApiOperation(value = "", position = 5) public void methodWithPosition() { } @ApiOperation(value = "", consumes = "application/xml") public void methodWithXmlConsumes() { } @ApiOperation(value = "", produces = "application/xml") public void methodWithXmlProduces() { } @ApiOperation(value = "", produces = "application/xml, application/json", consumes = "application/xml, " + "application/json") public void methodWithMultipleMediaTypes() { } @ApiOperation(value = "", produces = "application/xml", consumes = "application/xml") public void methodWithBothXmlMediaTypes() { } @ApiOperation(value = "", produces = "application/json", consumes = "application/xml") public void methodWithMediaTypeAndFile(MultipartFile multipartFile) { } @ApiOperation(value = "", response = DummyModels.FunkyBusiness.class) public void methodApiResponseClass() { } @ApiResponses({ @ApiResponse(code = 201, response = Void.class, message = "Rule Scheduled successfuly"), @ApiResponse(code = 500, response = RestError.class, message = "Internal Server Error"), @ApiResponse(code = 406, response = RestError.class, message = "Not acceptable")}) public void methodAnnotatedWithApiResponse() { } @ApiOperation(value = "methodWithExtensions", extensions = { @Extension(properties = @ExtensionProperty(name="x-test1", value="value1")), @Extension(name="test2", properties = @ExtensionProperty(name="name2", value="value2")) } ) public void methodWithExtensions() { } @ApiOperation(value = "SomeVal", authorizations = @Authorization(value = "oauth2", scopes = {@AuthorizationScope(scope = "scope", description = "scope description") })) public void methodWithAuth() { } @ApiOperation(value = "") public DummyModels.FunkyBusiness methodWithAPiAnnotationButWithoutResponseClass() { return null; } @ApiOperation(value = "") public DummyModels.Paginated<BusinessType> methodWithGenericType() { return null; } public ResponseEntity<byte[]> methodWithGenericPrimitiveArray() { return null; } public ResponseEntity<DummyClass[]> methodWithGenericComplexArray() { return null; } public ResponseEntity<EnumType> methodWithEnumResponse() { return null; } @Deprecated public void methodWithDeprecated() { } public void methodWithServletRequest(ServletRequest req) { } public void methodWithBindingResult(BindingResult res) { } public void methodWithInteger(Integer integer) { } public void methodWithAnnotatedInteger(@Ignorable Integer integer) { } public void methodWithModelAttribute(@ModelAttribute Example example) { } public void methodWithoutModelAttribute(Example example) { } public void methodWithTreeishModelAttribute(@ModelAttribute Treeish example) { } @RequestMapping("/businesses/{businessId}") public void methodWithSinglePathVariable(@PathVariable String businessId) { } @RequestMapping("/businesses/{businessId}") public void methodWithSingleEnum(BusinessType businessType) { } @RequestMapping("/businesses/{businessId}") public void methodWithSingleEnumArray(BusinessType[] businessTypes) { } @RequestMapping("/businesses/{businessId}/employees/{employeeId}/salary") public void methodWithRatherLongRequestPath() { } @RequestMapping(value = "/parameter-conditions", params = "test=testValue") public void methodWithParameterRequestCondition() { } @ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header", value = "Authentication token") public void methodWithApiImplicitParam() { } @ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header", value = "Authentication token") public void methodWithApiImplicitParamAndInteger(Integer integer) { } @ApiImplicitParams({ @ApiImplicitParam(name = "lang", dataType = "string", required = true, paramType = "query", value = "Language", defaultValue = "EN", allowableValues = "EN,FR"), @ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header", value = "Authentication token") }) public void methodWithApiImplicitParams(Integer integer) { } public interface ApiImplicitParamsInterface { @ApiImplicitParams({ @ApiImplicitParam(name = "lang", dataType = "string", required = true, paramType = "query", value = "Language", defaultValue = "EN", allowableValues = "EN,FR") }) @ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header", value = "Authentication token") void methodWithApiImplicitParam(); } public static class ApiImplicitParamsClass implements ApiImplicitParamsInterface { @Override public void methodWithApiImplicitParam() { } } @ResponseBody public DummyModels.BusinessModel methodWithConcreteResponseBody() { return null; } @ResponseBody public Map<String, DummyModels.BusinessModel> methodWithMapReturn() { return null; } @ResponseBody @ResponseStatus(value = HttpStatus.ACCEPTED, reason = "Accepted request") public DummyModels.BusinessModel methodWithResponseStatusAnnotation() { return null; } @ResponseBody @ResponseStatus(value = HttpStatus.NO_CONTENT) public void methodWithResponseStatusAnnotationAndEmptyReason() { } @ResponseBody public DummyModels.AnnotatedBusinessModel methodWithModelPropertyAnnotations() { return null; } @ResponseBody public DummyModels.NamedBusinessModel methodWithModelAnnotations() { return null; } @ResponseBody public List<DummyModels.BusinessModel> methodWithListOfBusinesses() { return null; } @ResponseBody public DummyModels.CorporationModel methodWithConcreteCorporationModel() { return null; } @ResponseBody public Date methodWithDateResponseBody() { return null; } public void methodParameterWithRequestBodyAnnotation( @RequestBody DummyModels.BusinessModel model, HttpServletResponse response, DummyModels.AnnotatedBusinessModel annotatedBusinessModel) { } public void methodParameterWithRequestPartAnnotation( @RequestPart DummyModels.BusinessModel model, HttpServletResponse response, DummyModels.AnnotatedBusinessModel annotatedBusinessModel) { } public void methodParameterWithRequestPartAnnotationOnSimpleType( @RequestPart String model, HttpServletResponse response, DummyModels.AnnotatedBusinessModel annotatedBusinessModel) { } @ResponseBody public DummyModels.AnnotatedBusinessModel methodWithSameAnnotatedModelInReturnAndRequestBodyParam( @RequestBody DummyModels.AnnotatedBusinessModel model) { return null; } @ApiResponses({@ApiResponse(code = 413, message = "a message")}) public void methodWithApiResponses() { } @ApiIgnore public static class ApiIgnorableClass { @ApiIgnore public void dummyMethod() { } } @ResponseBody public DummyModels.ModelWithSerializeOnlyProperty methodWithSerializeOnlyPropInReturnAndRequestBodyParam( @RequestBody DummyModels.ModelWithSerializeOnlyProperty model) { return null; } @ResponseBody public FoobarDto methodToTestFoobarDto(@RequestBody FoobarDto model) { return null; } public enum BusinessType { PRODUCT(1), SERVICE(2); private int value; private BusinessType(int value) { this.value = value; } public int getValue() { return value; } } public class CustomClass { } public class MethodsWithSameName { public ResponseEntity methodToTest(Integer integer, Parent child) { return null; } public void methodToTest(Integer integer, Child child) { } } class Parent { } class Child extends Parent { } }
zhiqinghuang/springfox
springfox-spring-web/src/test/java/springfox/documentation/spring/web/dummy/DummyClass.java
Java
apache-2.0
11,454
from Child import Child from Node import Node # noqa: I201 AVAILABILITY_NODES = [ # availability-spec-list -> availability-entry availability-spec-list? Node('AvailabilitySpecList', kind='SyntaxCollection', element='AvailabilityArgument'), # Wrapper for all the different entries that may occur inside @available # availability-entry -> '*' ','? # | identifier ','? # | availability-version-restriction ','? # | availability-versioned-argument ','? Node('AvailabilityArgument', kind='Syntax', description=''' A single argument to an `@available` argument like `*`, `iOS 10.1`, \ or `message: "This has been deprecated"`. ''', children=[ Child('Entry', kind='Syntax', description='The actual argument', node_choices=[ Child('Star', kind='SpacedBinaryOperatorToken', text_choices=['*']), Child('IdentifierRestriction', kind='IdentifierToken'), Child('AvailabilityVersionRestriction', kind='AvailabilityVersionRestriction'), Child('AvailabilityLabeledArgument', kind='AvailabilityLabeledArgument'), ]), Child('TrailingComma', kind='CommaToken', is_optional=True, description=''' A trailing comma if the argument is followed by another \ argument '''), ]), # Representation of 'deprecated: 2.3', 'message: "Hello world"' etc. # availability-versioned-argument -> identifier ':' version-tuple Node('AvailabilityLabeledArgument', kind='Syntax', description=''' A argument to an `@available` attribute that consists of a label and \ a value, e.g. `message: "This has been deprecated"`. ''', children=[ Child('Label', kind='IdentifierToken', description='The label of the argument'), Child('Colon', kind='ColonToken', description='The colon separating label and value'), Child('Value', kind='Syntax', node_choices=[ Child('String', 'StringLiteralToken'), Child('Version', 'VersionTuple'), ], description='The value of this labeled argument',), ]), # Representation for 'iOS 10', 'swift 3.4' etc. # availability-version-restriction -> identifier version-tuple Node('AvailabilityVersionRestriction', kind='Syntax', description=''' An argument to `@available` that restricts the availability on a \ certain platform to a version, e.g. `iOS 10` or `swift 3.4`. ''', children=[ Child('Platform', kind='IdentifierToken', classification='Keyword', description=''' The name of the OS on which the availability should be \ restricted or 'swift' if the availability should be \ restricted based on a Swift version. '''), Child('Version', kind='VersionTuple'), ]), # version-tuple -> integer-literal # | float-literal # | float-literal '.' integer-literal Node('VersionTuple', kind='Syntax', description=''' A version number of the form major.minor.patch in which the minor \ and patch part may be ommited. ''', children=[ Child('MajorMinor', kind='Syntax', node_choices=[ Child('Major', kind='IntegerLiteralToken'), Child('MajorMinor', kind='FloatingLiteralToken') ], description=''' In case the version consists only of the major version, an \ integer literal that specifies the major version. In case \ the version consists of major and minor version number, a \ floating literal in which the decimal part is interpreted \ as the minor version. '''), Child('PatchPeriod', kind='PeriodToken', is_optional=True, description=''' If the version contains a patch number, the period \ separating the minor from the patch number. '''), Child('PatchVersion', kind='IntegerLiteralToken', is_optional=True, description=''' The patch version if specified. '''), ]), ]
austinzheng/swift
utils/gyb_syntax_support/AvailabilityNodes.py
Python
apache-2.0
4,872
class Multimarkdown < Formula desc "Turn marked-up plain text into well-formatted documents" homepage "http://fletcherpenney.net/multimarkdown/" # Use git tag instead of the tarball to get submodules url "https://github.com/fletcher/MultiMarkdown-5.git", :tag => "5.4.0", :revision => "193c09a5362eb8a6c6433cd5d5f1d7db3efe986a" head "https://github.com/fletcher/MultiMarkdown-5.git" bottle do cellar :any_skip_relocation sha256 "cc9f163eaa9eb53def1e66cd2e3871ea9f8274028a3d399d01e2944d8cf2ac6f" => :sierra sha256 "72571c5521bda002ce2b140bc7e8fd224c0545e9f21b6268ad5a2ecedfe4e025" => :el_capitan sha256 "7c5370be42b0e15b19da90d8ead5aec745e24c842aea2cf2c210f399d84b67d8" => :yosemite sha256 "475aed59ab53d010d8238fb8d0646c43de994c46893baecabcbcfc33c99b15fc" => :mavericks end depends_on "cmake" => :build conflicts_with "mtools", :because => "both install `mmd` binaries" conflicts_with "markdown", :because => "both install `markdown` binaries" conflicts_with "discount", :because => "both install `markdown` binaries" def install system "sh", "link_git_modules" system "sh", "update_git_modules" system "make" cd "build" do system "make" bin.install "multimarkdown" end bin.install Dir["scripts/*"].reject { |f| f =~ /\.bat$/ } end test do assert_equal "<p>foo <em>bar</em></p>\n", pipe_output(bin/"multimarkdown", "foo *bar*\n") assert_equal "<p>foo <em>bar</em></p>\n", pipe_output(bin/"mmd", "foo *bar*\n") end end
kunickiaj/homebrew-core
Formula/multimarkdown.rb
Ruby
bsd-2-clause
1,528
cask 'fontexplorer-x-pro' do version '6.0.2' sha256 'f842e373d6126218dcd34bd116ceab29a7abb5c6ea22afec04ad86652f19a290' url "http://fast.fontexplorerx.com/FontExplorerXPro#{version.no_dots}.dmg" name 'FontExplorer X Pro' homepage 'https://www.fontexplorerx.com/' depends_on macos: '>= :mountain_lion' app 'FontExplorer X Pro.app' zap delete: [ '/Library/PrivilegedHelperTools/com.linotype.FontExplorerX.securityhelper', '/Library/LaunchDaemons/com.linotype.FontExplorerX.securityhelper.plist', '~/Library/Application Support/Linotype/FontExplorer X', '~/Library/Application\ Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.linotype.fontexplorerx.sfl', '~/Library/Caches/com.linotype.FontExplorerX', '~/Library/Cookies/com.linotype.FontExplorerX.binarycookies', '~/Library/LaunchAgents/com.linotype.FontFolderProtector.plist', '~/Library/Preferences/com.linotype.FontExplorerX.plist', '~/Library/Saved\ Application\ State/com.linotype.FontExplorerX.savedState', ] end
malford/homebrew-cask
Casks/fontexplorer-x-pro.rb
Ruby
bsd-2-clause
1,187
<?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_Service * @subpackage DeveloperGarden * @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$ */ /** * @see Zend_Service_DeveloperGarden_Request_RequestAbstract */ // require_once 'Zend/Service/DeveloperGarden/Request/RequestAbstract.php'; /** * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @author Marco Kaiser * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest extends Zend_Service_DeveloperGarden_Request_RequestAbstract { /** * unique owner id * * @var string */ public $ownerId = null; /** * object with details for this conference * * @var Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail */ public $detail = null; /** * array with Zend_Service_DeveloperGarden_ConferenceCall_ParticipantDetail elements * * @var array */ public $participants = null; /** * constructor * * @param integer $environment * @param string $ownerId * @param Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $conferenceDetails * @param array $conferenceParticipants */ public function __construct($environment, $ownerId, Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $conferenceDetails, array $conferenceParticipants = null ) { parent::__construct($environment); $this->setOwnerId($ownerId) ->setDetail($conferenceDetails) ->setParticipants($conferenceParticipants); } /** * sets $participants * * @param array $participants * @return Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest */ public function setParticipants(array $participants = null) { $this->participants = $participants; return $this; } /** * sets $detail * * @param Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $detail * @return Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest */ public function setDetail(Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $detail) { $this->detail = $detail; return $this; } /** * sets $ownerId * * @param string $ownerId * @return Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest */ public function setOwnerId($ownerId) { $this->ownerId = $ownerId; return $this; } }
kanevbg/pimcore
pimcore/lib/Zend/Service/DeveloperGarden/Request/ConferenceCall/CreateConferenceTemplateRequest.php
PHP
bsd-3-clause
3,379
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /** * Implements custom element observation and attached/detached callbacks * @module observe */ window.CustomElements.addModule(function(scope){ // imports var flags = scope.flags; var forSubtree = scope.forSubtree; var forDocumentTree = scope.forDocumentTree; /* Manage nodes attached to document trees */ // manage lifecycle on added node and it's subtree; upgrade the node and // entire subtree if necessary and process attached for the node and entire // subtree function addedNode(node, isAttached) { return added(node, isAttached) || addedSubtree(node, isAttached); } // manage lifecycle on added node; upgrade if necessary and process attached function added(node, isAttached) { if (scope.upgrade(node, isAttached)) { // Return true to indicate return true; } if (isAttached) { attached(node); } } // manage lifecycle on added node's subtree only; allows the entire subtree // to upgrade if necessary and process attached function addedSubtree(node, isAttached) { forSubtree(node, function(e) { if (added(e, isAttached)) { return true; } }); } // On platforms without MutationObserver, mutations may not be // reliable and therefore attached/detached are not reliable. // To make these callbacks less likely to fail, we defer all inserts and removes // to give a chance for elements to be attached into dom. // This ensures attachedCallback fires for elements that are created and // immediately added to dom. var hasPolyfillMutations = (!window.MutationObserver || (window.MutationObserver === window.JsMutationObserver)); scope.hasPolyfillMutations = hasPolyfillMutations; var isPendingMutations = false; var pendingMutations = []; function deferMutation(fn) { pendingMutations.push(fn); if (!isPendingMutations) { isPendingMutations = true; setTimeout(takeMutations); } } function takeMutations() { isPendingMutations = false; var $p = pendingMutations; for (var i=0, l=$p.length, p; (i<l) && (p=$p[i]); i++) { p(); } pendingMutations = []; } function attached(element) { if (hasPolyfillMutations) { deferMutation(function() { _attached(element); }); } else { _attached(element); } } // NOTE: due to how MO works (see comments below), an element may be attached // multiple times so we protect against extra processing here. function _attached(element) { // track element for insertion if it's upgraded and cares about insertion // bail if the element is already marked as attached if (element.__upgraded__ && !element.__attached) { element.__attached = true; if (element.attachedCallback) { element.attachedCallback(); } } } /* Manage nodes detached from document trees */ // manage lifecycle on detached node and it's subtree; process detached // for the node and entire subtree function detachedNode(node) { detached(node); forSubtree(node, function(e) { detached(e); }); } function detached(element) { if (hasPolyfillMutations) { deferMutation(function() { _detached(element); }); } else { _detached(element); } } // NOTE: due to how MO works (see comments below), an element may be detached // multiple times so we protect against extra processing here. function _detached(element) { // track element for removal if it's upgraded and cares about removal // bail if the element is already marked as not attached if (element.__upgraded__ && element.__attached) { element.__attached = false; if (element.detachedCallback) { element.detachedCallback(); } } } // recurse up the tree to check if an element is actually in the main document. function inDocument(element) { var p = element; var doc = window.wrap(document); while (p) { if (p == doc) { return true; } p = p.parentNode || ((p.nodeType === Node.DOCUMENT_FRAGMENT_NODE) && p.host); } } // Install an element observer on all shadowRoots owned by node. function watchShadow(node) { if (node.shadowRoot && !node.shadowRoot.__watched) { flags.dom && console.log('watching shadow-root for: ', node.localName); // watch all unwatched roots... var root = node.shadowRoot; while (root) { observe(root); root = root.olderShadowRoot; } } } /* NOTE: In order to process all mutations, it's necessary to recurse into any added nodes. However, it's not possible to determine a priori if a node will get its own mutation record. This means *nodes can be seen multiple times*. Here's an example: (1) In this case, recursion is required to see `child`: node.innerHTML = '<div><child></child></div>' (2) In this case, child will get its own mutation record: node.appendChild(div).appendChild(child); We cannot know ahead of time if we need to walk into the node in (1) so we do and see child; however, if it was added via case (2) then it will have its own record and therefore be seen 2x. */ function handler(root, mutations) { // for logging only if (flags.dom) { var mx = mutations[0]; if (mx && mx.type === 'childList' && mx.addedNodes) { if (mx.addedNodes) { var d = mx.addedNodes[0]; while (d && d !== document && !d.host) { d = d.parentNode; } var u = d && (d.URL || d._URL || (d.host && d.host.localName)) || ''; u = u.split('/?').shift().split('/').pop(); } } console.group('mutations (%d) [%s]', mutations.length, u || ''); } // handle mutations // NOTE: do an `inDocument` check dynamically here. It's possible that `root` // is a document in which case the answer here can never change; however // `root` may be an element like a shadowRoot that can be added/removed // from the main document. var isAttached = inDocument(root); mutations.forEach(function(mx) { if (mx.type === 'childList') { forEach(mx.addedNodes, function(n) { if (!n.localName) { return; } addedNode(n, isAttached); }); forEach(mx.removedNodes, function(n) { if (!n.localName) { return; } detachedNode(n); }); } }); flags.dom && console.groupEnd(); }; /* When elements are added to the dom, upgrade and attached/detached may be asynchronous. `CustomElements.takeRecords` can be called to process any pending upgrades and attached/detached callbacks synchronously. */ function takeRecords(node) { node = window.wrap(node); // If the optional node is not supplied, assume we mean the whole document. if (!node) { node = window.wrap(document); } // Find the root of the tree, which will be an Document or ShadowRoot. while (node.parentNode) { node = node.parentNode; } var observer = node.__observer; if (observer) { handler(node, observer.takeRecords()); takeMutations(); } } var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); // observe a node tree; bail if it's already being observed. function observe(inRoot) { if (inRoot.__observer) { return; } // For each ShadowRoot, we create a new MutationObserver, so the root can be // garbage collected once all references to the `inRoot` node are gone. // Give the handler access to the root so that an 'in document' check can // be done. var observer = new MutationObserver(handler.bind(this, inRoot)); observer.observe(inRoot, {childList: true, subtree: true}); inRoot.__observer = observer; } // upgrade an entire document and observe it for elements changes. function upgradeDocument(doc) { doc = window.wrap(doc); flags.dom && console.group('upgradeDocument: ', (doc.baseURI).split('/').pop()); var isMainDocument = (doc === window.wrap(document)); addedNode(doc, isMainDocument); observe(doc); flags.dom && console.groupEnd(); } /* This method is intended to be called when the document tree (including imports) has pending custom elements to upgrade. It can be called multiple times and should do nothing if no elements are in need of upgrade. */ function upgradeDocumentTree(doc) { forDocumentTree(doc, upgradeDocument); } // Patch `createShadowRoot()` if Shadow DOM is available, otherwise leave // undefined to aid feature detection of Shadow DOM. var originalCreateShadowRoot = Element.prototype.createShadowRoot; if (originalCreateShadowRoot) { Element.prototype.createShadowRoot = function() { var root = originalCreateShadowRoot.call(this); window.CustomElements.watchShadow(this); return root; }; } // exports scope.watchShadow = watchShadow; scope.upgradeDocumentTree = upgradeDocumentTree; scope.upgradeDocument = upgradeDocument; scope.upgradeSubtree = addedSubtree; scope.upgradeAll = addedNode; scope.attached = attached; scope.takeRecords = takeRecords; });
tachyon1337/webcomponentsjs
src/CustomElements/observe.js
JavaScript
bsd-3-clause
9,347
<?php /** * Squiz_Sniffs_Formatting_OperationBracketSniff. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @author Marc McIntyre <mmcintyre@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 */ /** * Squiz_Sniffs_Formatting_OperationBracketSniff. * * Tests that all arithmetic operations are bracketed. * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @author Marc McIntyre <mmcintyre@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: 1.4.3 * @link http://pear.php.net/package/PHP_CodeSniffer */ class Squiz_Sniffs_Formatting_OperatorBracketSniff implements PHP_CodeSniffer_Sniff { /** * A list of tokenizers this sniff supports. * * @var array */ public $supportedTokenizers = array( 'PHP', 'JS', ); /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return PHP_CodeSniffer_Tokens::$operators; }//end register() /** * Processes this test, when one of its tokens is encountered. * * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token in the * stack passed in $tokens. * * @return void */ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if ($phpcsFile->tokenizerType === 'JS' && $tokens[$stackPtr]['code'] === T_PLUS) { // JavaScript uses the plus operator for string concatenation as well // so we cannot accurately determine if it is a string concat or addition. // So just ignore it. return; } // If the & is a reference, then we don't want to check for brackets. if ($tokens[$stackPtr]['code'] === T_BITWISE_AND && $phpcsFile->isReference($stackPtr) === true) { return; } // There is one instance where brackets aren't needed, which involves // the minus sign being used to assign a negative number to a variable. if ($tokens[$stackPtr]['code'] === T_MINUS) { // Check to see if we are trying to return -n. $prev = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true); if ($tokens[$prev]['code'] === T_RETURN) { return; } $number = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); if ($tokens[$number]['code'] === T_LNUMBER || $tokens[$number]['code'] === T_DNUMBER) { $previous = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); if ($previous !== false) { $isAssignment = in_array($tokens[$previous]['code'], PHP_CodeSniffer_Tokens::$assignmentTokens); $isEquality = in_array($tokens[$previous]['code'], PHP_CodeSniffer_Tokens::$equalityTokens); $isComparison = in_array($tokens[$previous]['code'], PHP_CodeSniffer_Tokens::$comparisonTokens); if ($isAssignment === true || $isEquality === true || $isComparison === true) { // This is a negative assignment or comparion. // We need to check that the minus and the number are // adjacent. if (($number - $stackPtr) !== 1) { $error = 'No space allowed between minus sign and number'; $phpcsFile->addError($error, $stackPtr, 'SpacingAfterMinus'); } return; } } } }//end if $lastBracket = false; if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { $parenthesis = array_reverse($tokens[$stackPtr]['nested_parenthesis'], true); foreach ($parenthesis as $bracket => $endBracket) { $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($bracket - 1), null, true); $prevCode = $tokens[$prevToken]['code']; if ($prevCode === T_ISSET) { // This operation is inside an isset() call, but has // no bracket of it's own. break; } if ($prevCode === T_STRING || $prevCode === T_SWITCH) { // We allow very simple operations to not be bracketed. // For example, ceil($one / $two). $allowed = array( T_VARIABLE, T_LNUMBER, T_DNUMBER, T_STRING, T_WHITESPACE, T_THIS, T_OBJECT_OPERATOR, T_OPEN_SQUARE_BRACKET, T_CLOSE_SQUARE_BRACKET, T_MODULUS, ); for ($prev = ($stackPtr - 1); $prev > $bracket; $prev--) { if (in_array($tokens[$prev]['code'], $allowed) === true) { continue; } if ($tokens[$prev]['code'] === T_CLOSE_PARENTHESIS) { $prev = $tokens[$prev]['parenthesis_opener']; } else { break; } } if ($prev !== $bracket) { break; } for ($next = ($stackPtr + 1); $next < $endBracket; $next++) { if (in_array($tokens[$next]['code'], $allowed) === true) { continue; } if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) { $next = $tokens[$next]['parenthesis_closer']; } else { break; } } if ($next !== $endBracket) { break; } }//end if if (in_array($prevCode, PHP_CodeSniffer_Tokens::$scopeOpeners) === true) { // This operation is inside a control structure like FOREACH // or IF, but has no bracket of it's own. // The only control structure allowed to do this is SWITCH. if ($prevCode !== T_SWITCH) { break; } } if ($prevCode === T_OPEN_PARENTHESIS) { // These are two open parenthesis in a row. If the current // one doesn't enclose the operator, go to the previous one. if ($endBracket < $stackPtr) { continue; } } $lastBracket = $bracket; break; }//end foreach }//end if if ($lastBracket === false) { // It is not in a bracketed statement at all. $previousToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true, null, true); if ($previousToken !== false) { // A list of tokens that indicate that the token is not // part of an arithmetic operation. $invalidTokens = array( T_COMMA, T_COLON, T_OPEN_PARENTHESIS, T_OPEN_SQUARE_BRACKET, T_CASE, ); if (in_array($tokens[$previousToken]['code'], $invalidTokens) === false) { $error = 'Arithmetic operation must be bracketed'; $phpcsFile->addError($error, $stackPtr, 'MissingBrackets'); } return; } } else if ($tokens[$lastBracket]['parenthesis_closer'] < $stackPtr) { // There are a set of brackets in front of it that don't include it. $error = 'Arithmetic operation must be bracketed'; $phpcsFile->addError($error, $stackPtr, 'MissingBrackets'); return; } else { // We are enclosed in a set of bracket, so the last thing to // check is that we are not also enclosed in square brackets // like this: ($array[$index + 1]), which is invalid. $brackets = array( T_OPEN_SQUARE_BRACKET, T_CLOSE_SQUARE_BRACKET, ); $squareBracket = $phpcsFile->findPrevious($brackets, ($stackPtr - 1), $lastBracket); if ($squareBracket !== false && $tokens[$squareBracket]['code'] === T_OPEN_SQUARE_BRACKET) { $closeSquareBracket = $phpcsFile->findNext($brackets, ($stackPtr + 1)); if ($closeSquareBracket !== false && $tokens[$closeSquareBracket]['code'] === T_CLOSE_SQUARE_BRACKET) { $error = 'Arithmetic operation must be bracketed'; $phpcsFile->addError($error, $stackPtr, 'MissingBrackets'); } } return; }//end if $lastAssignment = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$assignmentTokens, $stackPtr, null, false, null, true); if ($lastAssignment !== false && $lastAssignment > $lastBracket) { $error = 'Arithmetic operation must be bracketed'; $phpcsFile->addError($error, $stackPtr, 'MissingBrackets'); } }//end process() }//end class ?>
theghostbel/pimcore
tests/lib/PHP/CodeSniffer/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php
PHP
bsd-3-clause
10,520
/* * Copyright (C) 2010 Google Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "config.h" #include "core/workers/WorkerEventQueue.h" #include "core/dom/ExecutionContext.h" #include "core/dom/ExecutionContextTask.h" #include "core/events/Event.h" #include "core/inspector/InspectorInstrumentation.h" namespace blink { PassOwnPtrWillBeRawPtr<WorkerEventQueue> WorkerEventQueue::create(ExecutionContext* context) { return adoptPtrWillBeNoop(new WorkerEventQueue(context)); } WorkerEventQueue::WorkerEventQueue(ExecutionContext* context) : m_executionContext(context) , m_isClosed(false) { } WorkerEventQueue::~WorkerEventQueue() { ASSERT(m_eventTaskMap.isEmpty()); } void WorkerEventQueue::trace(Visitor* visitor) { #if ENABLE(OILPAN) visitor->trace(m_executionContext); visitor->trace(m_eventTaskMap); #endif EventQueue::trace(visitor); } class WorkerEventQueue::EventDispatcherTask : public ExecutionContextTask { public: static PassOwnPtr<EventDispatcherTask> create(PassRefPtrWillBeRawPtr<Event> event, WorkerEventQueue* eventQueue) { return adoptPtr(new EventDispatcherTask(event, eventQueue)); } virtual ~EventDispatcherTask() { if (m_event) m_eventQueue->removeEvent(m_event.get()); } void dispatchEvent(ExecutionContext*, PassRefPtrWillBeRawPtr<Event> event) { event->target()->dispatchEvent(event); } virtual void performTask(ExecutionContext* context) { if (m_isCancelled) return; m_eventQueue->removeEvent(m_event.get()); dispatchEvent(context, m_event); m_event.clear(); } void cancel() { m_isCancelled = true; m_event.clear(); } private: EventDispatcherTask(PassRefPtrWillBeRawPtr<Event> event, WorkerEventQueue* eventQueue) : m_event(event) , m_eventQueue(eventQueue) , m_isCancelled(false) { } RefPtrWillBePersistent<Event> m_event; WorkerEventQueue* m_eventQueue; bool m_isCancelled; }; void WorkerEventQueue::removeEvent(Event* event) { InspectorInstrumentation::didRemoveEvent(event->target(), event); m_eventTaskMap.remove(event); } bool WorkerEventQueue::enqueueEvent(PassRefPtrWillBeRawPtr<Event> prpEvent) { if (m_isClosed) return false; RefPtrWillBeRawPtr<Event> event = prpEvent; InspectorInstrumentation::didEnqueueEvent(event->target(), event.get()); OwnPtr<EventDispatcherTask> task = EventDispatcherTask::create(event, this); m_eventTaskMap.add(event.release(), task.get()); m_executionContext->postTask(task.release()); return true; } bool WorkerEventQueue::cancelEvent(Event* event) { EventDispatcherTask* task = m_eventTaskMap.get(event); if (!task) return false; task->cancel(); removeEvent(event); return true; } void WorkerEventQueue::close() { m_isClosed = true; for (EventTaskMap::iterator it = m_eventTaskMap.begin(); it != m_eventTaskMap.end(); ++it) { Event* event = it->key.get(); EventDispatcherTask* task = it->value; InspectorInstrumentation::didRemoveEvent(event->target(), event); task->cancel(); } m_eventTaskMap.clear(); } }
xin3liang/platform_external_chromium_org_third_party_WebKit
Source/core/workers/WorkerEventQueue.cpp
C++
bsd-3-clause
4,525
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Generator for C++ structs from api json files. The purpose of this tool is to remove the need for hand-written code that converts to and from base::Value types when receiving javascript api calls. Originally written for generating code for extension apis. Reference schemas are in chrome/common/extensions/api. Usage example: compiler.py --root /home/Work/src --namespace extensions windows.json tabs.json compiler.py --destdir gen --root /home/Work/src --namespace extensions windows.json tabs.json """ import optparse import os import shlex import sys from cpp_bundle_generator import CppBundleGenerator from cpp_generator import CppGenerator from cpp_type_generator import CppTypeGenerator from js_externs_generator import JsExternsGenerator from js_interface_generator import JsInterfaceGenerator import json_schema from cpp_namespace_environment import CppNamespaceEnvironment from model import Model from schema_loader import SchemaLoader # Names of supported code generators, as specified on the command-line. # First is default. GENERATORS = [ 'cpp', 'cpp-bundle-registration', 'cpp-bundle-schema', 'externs', 'interface' ] def GenerateSchema(generator_name, file_paths, root, destdir, cpp_namespace_pattern, bundle_name, impl_dir, include_rules): # Merge the source files into a single list of schemas. api_defs = [] for file_path in file_paths: schema = os.path.relpath(file_path, root) schema_loader = SchemaLoader( root, os.path.dirname(schema), include_rules, cpp_namespace_pattern) api_def = schema_loader.LoadSchema(schema) # If compiling the C++ model code, delete 'nocompile' nodes. if generator_name == 'cpp': api_def = json_schema.DeleteNodes(api_def, 'nocompile') # Delete all 'nodefine' nodes. They are only for documentation. api_def = json_schema.DeleteNodes(api_def, 'nodefine') api_defs.extend(api_def) api_model = Model(allow_inline_enums=False) # For single-schema compilation make sure that the first (i.e. only) schema # is the default one. default_namespace = None # If we have files from multiple source paths, we'll use the common parent # path as the source directory. src_path = None # Load the actual namespaces into the model. for target_namespace, file_path in zip(api_defs, file_paths): relpath = os.path.relpath(os.path.normpath(file_path), root) namespace = api_model.AddNamespace(target_namespace, relpath, include_compiler_options=True, environment=CppNamespaceEnvironment( cpp_namespace_pattern)) if default_namespace is None: default_namespace = namespace if src_path is None: src_path = namespace.source_file_dir else: src_path = os.path.commonprefix((src_path, namespace.source_file_dir)) _, filename = os.path.split(file_path) filename_base, _ = os.path.splitext(filename) # Construct the type generator with all the namespaces in this model. type_generator = CppTypeGenerator(api_model, schema_loader, default_namespace) if generator_name in ('cpp-bundle-registration', 'cpp-bundle-schema'): cpp_bundle_generator = CppBundleGenerator(root, api_model, api_defs, type_generator, cpp_namespace_pattern, bundle_name, src_path, impl_dir) if generator_name == 'cpp-bundle-registration': generators = [ ('generated_api_registration.cc', cpp_bundle_generator.api_cc_generator), ('generated_api_registration.h', cpp_bundle_generator.api_h_generator), ] elif generator_name == 'cpp-bundle-schema': generators = [ ('generated_schemas.cc', cpp_bundle_generator.schemas_cc_generator), ('generated_schemas.h', cpp_bundle_generator.schemas_h_generator) ] elif generator_name == 'cpp': cpp_generator = CppGenerator(type_generator) generators = [ ('%s.h' % filename_base, cpp_generator.h_generator), ('%s.cc' % filename_base, cpp_generator.cc_generator) ] elif generator_name == 'externs': generators = [ ('%s_externs.js' % namespace.unix_name, JsExternsGenerator()) ] elif generator_name == 'interface': generators = [ ('%s_interface.js' % namespace.unix_name, JsInterfaceGenerator()) ] else: raise Exception('Unrecognised generator %s' % generator_name) output_code = [] for filename, generator in generators: code = generator.Generate(namespace).Render() if destdir: if generator_name == 'cpp-bundle-registration': # Function registrations must be output to impl_dir, since they link in # API implementations. output_dir = os.path.join(destdir, impl_dir) else: output_dir = os.path.join(destdir, src_path) if not os.path.exists(output_dir): os.makedirs(output_dir) with open(os.path.join(output_dir, filename), 'w') as f: f.write(code) # If multiple files are being output, add the filename for each file. if len(generators) > 1: output_code += [filename, '', code, ''] else: output_code += [code] return '\n'.join(output_code) if __name__ == '__main__': parser = optparse.OptionParser( description='Generates a C++ model of an API from JSON schema', usage='usage: %prog [option]... schema') parser.add_option('-r', '--root', default='.', help='logical include root directory. Path to schema files from specified' ' dir will be the include path.') parser.add_option('-d', '--destdir', help='root directory to output generated files.') parser.add_option('-n', '--namespace', default='generated_api_schemas', help='C++ namespace for generated files. e.g extensions::api.') parser.add_option('-b', '--bundle-name', default='', help='A string to prepend to generated bundle class names, so that ' 'multiple bundle rules can be used without conflicting. ' 'Only used with one of the cpp-bundle generators.') parser.add_option('-g', '--generator', default=GENERATORS[0], choices=GENERATORS, help='The generator to use to build the output code. Supported values are' ' %s' % GENERATORS) parser.add_option('-i', '--impl-dir', dest='impl_dir', help='The root path of all API implementations') parser.add_option('-I', '--include-rules', help='A list of paths to include when searching for referenced objects,' ' with the namespace separated by a \':\'. Example: ' '/foo/bar:Foo::Bar::%(namespace)s') (opts, file_paths) = parser.parse_args() if not file_paths: sys.exit(0) # This is OK as a no-op # Unless in bundle mode, only one file should be specified. if (opts.generator not in ('cpp-bundle-registration', 'cpp-bundle-schema') and len(file_paths) > 1): # TODO(sashab): Could also just use file_paths[0] here and not complain. raise Exception( "Unless in bundle mode, only one file can be specified at a time.") def split_path_and_namespace(path_and_namespace): if ':' not in path_and_namespace: raise ValueError('Invalid include rule "%s". Rules must be of ' 'the form path:namespace' % path_and_namespace) return path_and_namespace.split(':', 1) include_rules = [] if opts.include_rules: include_rules = map(split_path_and_namespace, shlex.split(opts.include_rules)) result = GenerateSchema(opts.generator, file_paths, opts.root, opts.destdir, opts.namespace, opts.bundle_name, opts.impl_dir, include_rules) if not opts.destdir: print result
heke123/chromium-crosswalk
tools/json_schema_compiler/compiler.py
Python
bsd-3-clause
8,474
// Any copyright is dedicated to the Public Domain. // http://creativecommons.org/licenses/publicdomain/ //----------------------------------------------------------------------------- var BUGNUMBER = 565604; var summary = "Typed-array properties don't work when accessed from an object whose " + "prototype (or further-descended prototype) is a typed array"; print(BUGNUMBER + ": " + summary); /************** * BEGIN TEST * **************/ var o = Object.create(new Uint8Array(1)); assertEq(o.length, 1); var o2 = Object.create(o); assertEq(o2.length, 1); var VARIABLE_OBJECT = {}; var props = [ { property: "length", value: 1 }, { property: "byteLength", value: 1 }, { property: "byteOffset", value: 0 }, { property: "buffer", value: VARIABLE_OBJECT }, ]; for (var i = 0, sz = props.length; i < sz; i++) { var p = props[i]; var o = Object.create(new Uint8Array(1)); var v = o[p.property]; if (p.value !== VARIABLE_OBJECT) assertEq(o[p.property], p.value, "bad " + p.property + " (proto)"); var o2 = Object.create(o); if (p.value !== VARIABLE_OBJECT) assertEq(o2[p.property], p.value, "bad " + p.property + " (grand-proto)"); assertEq(o2[p.property], v, p.property + " mismatch"); } reportCompare(true, true);
darkrsw/safe
tests/browser_extensions/js1_8_5/extensions/typedarray-prototype.js
JavaScript
bsd-3-clause
1,266
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/rendering/RenderThemeChromiumFontProvider.h" #include "core/CSSValueKeywords.h" #include "platform/fonts/FontDescription.h" #include "wtf/StdLibExtras.h" #include "wtf/text/WTFString.h" namespace blink { // static void RenderThemeChromiumFontProvider::setDefaultFontSize(int fontSize) { s_defaultFontSize = static_cast<float>(fontSize); } // static void RenderThemeChromiumFontProvider::systemFont(CSSValueID valueID, FontDescription& fontDescription) { float fontSize = s_defaultFontSize; switch (valueID) { case CSSValueWebkitMiniControl: case CSSValueWebkitSmallControl: case CSSValueWebkitControl: // Why 2 points smaller? Because that's what Gecko does. Note that we // are assuming a 96dpi screen, which is the default that we use on // Windows. static const float pointsPerInch = 72.0f; static const float pixelsPerInch = 96.0f; fontSize -= (2.0f / pointsPerInch) * pixelsPerInch; break; default: break; } fontDescription.firstFamily().setFamily(defaultGUIFont()); fontDescription.setSpecifiedSize(fontSize); fontDescription.setIsAbsoluteSize(true); fontDescription.setGenericFamily(FontDescription::NoFamily); fontDescription.setWeight(FontWeightNormal); fontDescription.setStyle(FontStyleNormal); } } // namespace blink
temasek/android_external_chromium_org_third_party_WebKit
Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp
C++
bsd-3-clause
2,746
import AuthenticatedRoute from 'ghost/routes/authenticated'; import CurrentUserSettings from 'ghost/mixins/current-user-settings'; import styleBody from 'ghost/mixins/style-body'; var AppsRoute = AuthenticatedRoute.extend(styleBody, CurrentUserSettings, { titleToken: 'Apps', classNames: ['settings-view-apps'], beforeModel: function () { if (!this.get('config.apps')) { return this.transitionTo('settings.general'); } return this.get('session.user') .then(this.transitionAuthor()) .then(this.transitionEditor()); }, model: function () { return this.store.find('app'); } }); export default AppsRoute;
PepijnSenders/whatsontheotherside
core/client/app/routes/settings/apps.js
JavaScript
mit
699
<?php /** * @file * Contains \Drupal\Core\Entity\Query\Sql\Query. */ namespace Drupal\Core\Entity\Query\Sql; use Drupal\Core\Database\Connection; use Drupal\Core\Database\Query\SelectInterface; use Drupal\Core\Entity\EntityTypeInterface; use Drupal\Core\Entity\Query\QueryBase; use Drupal\Core\Entity\Query\QueryException; use Drupal\Core\Entity\Query\QueryInterface; /** * The SQL storage entity query class. */ class Query extends QueryBase implements QueryInterface { /** * The build sql select query. * * @var \Drupal\Core\Database\Query\SelectInterface */ protected $sqlQuery; /** * An array of fields keyed by the field alias. * * Each entry correlates to the arguments of * \Drupal\Core\Database\Query\SelectInterface::addField(), so the first one * is the table alias, the second one the field and the last one optional the * field alias. * * @var array */ protected $sqlFields = array(); /** * An array of strings added as to the group by, keyed by the string to avoid * duplicates. * * @var array */ protected $sqlGroupBy = array(); /** * @var \Drupal\Core\Database\Connection */ protected $connection; /** * Stores the entity manager used by the query. * * @var \Drupal\Core\Entity\EntityManagerInterface */ protected $entityManager; /** * Constructs a query object. * * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type * The entity type definition. * @param string $conjunction * - AND: all of the conditions on the query need to match. * - OR: at least one of the conditions on the query need to match. * @param \Drupal\Core\Database\Connection $connection * The database connection to run the query against. * @param array $namespaces * List of potential namespaces of the classes belonging to this query. */ public function __construct(EntityTypeInterface $entity_type, $conjunction, Connection $connection, array $namespaces) { parent::__construct($entity_type, $conjunction, $namespaces); $this->connection = $connection; } /** * Implements \Drupal\Core\Entity\Query\QueryInterface::execute(). */ public function execute() { return $this ->prepare() ->compile() ->addSort() ->finish() ->result(); } /** * Prepares the basic query with proper metadata/tags and base fields. * * @throws \Drupal\Core\Entity\Query\QueryException * Thrown if the base table does not exists. * * @return \Drupal\Core\Entity\Query\Sql\Query * Returns the called object. */ protected function prepare() { if ($this->allRevisions) { if (!$base_table = $this->entityType->getRevisionTable()) { throw new QueryException("No revision table for " . $this->entityTypeId . ", invalid query."); } } else { if (!$base_table = $this->entityType->getBaseTable()) { throw new QueryException("No base table for " . $this->entityTypeId . ", invalid query."); } } $simple_query = TRUE; if ($this->entityType->getDataTable()) { $simple_query = FALSE; } $this->sqlQuery = $this->connection->select($base_table, 'base_table', array('conjunction' => $this->conjunction)); $this->sqlQuery->addMetaData('entity_type', $this->entityTypeId); $id_field = $this->entityType->getKey('id'); // Add the key field for fetchAllKeyed(). if (!$revision_field = $this->entityType->getKey('revision')) { // When there is no revision support, the key field is the entity key. $this->sqlFields["base_table.$id_field"] = array('base_table', $id_field); // Now add the value column for fetchAllKeyed(). This is always the // entity id. $this->sqlFields["base_table.$id_field" . '_1'] = array('base_table', $id_field); } else { // When there is revision support, the key field is the revision key. $this->sqlFields["base_table.$revision_field"] = array('base_table', $revision_field); // Now add the value column for fetchAllKeyed(). This is always the // entity id. $this->sqlFields["base_table.$id_field"] = array('base_table', $id_field); } if ($this->accessCheck) { $this->sqlQuery->addTag($this->entityTypeId . '_access'); } $this->sqlQuery->addTag('entity_query'); $this->sqlQuery->addTag('entity_query_' . $this->entityTypeId); // Add further tags added. if (isset($this->alterTags)) { foreach ($this->alterTags as $tag => $value) { $this->sqlQuery->addTag($tag); } } // Add further metadata added. if (isset($this->alterMetaData)) { foreach ($this->alterMetaData as $key => $value) { $this->sqlQuery->addMetaData($key, $value); } } // This now contains first the table containing entity properties and // last the entity base table. They might be the same. $this->sqlQuery->addMetaData('all_revisions', $this->allRevisions); $this->sqlQuery->addMetaData('simple_query', $simple_query); return $this; } /** * Compiles the conditions. * * @return \Drupal\Core\Entity\Query\Sql\Query * Returns the called object. */ protected function compile() { $this->condition->compile($this->sqlQuery); return $this; } /** * Adds the sort to the build query. * * @return \Drupal\Core\Entity\Query\Sql\Query * Returns the called object. */ protected function addSort() { if ($this->count) { $this->sort = array(); } // Gather the SQL field aliases first to make sure every field table // necessary is added. This might change whether the query is simple or // not. See below for more on simple queries. $sort = array(); if ($this->sort) { foreach ($this->sort as $key => $data) { $sort[$key] = $this->getSqlField($data['field'], $data['langcode']); } } $simple_query = $this->isSimpleQuery(); // If the query is set up for paging either via pager or by range or a // count is requested, then the correct amount of rows returned is // important. If the entity has a data table or multiple value fields are // involved then each revision might appear in several rows and this needs // a significantly more complex query. if (!$simple_query) { // First, GROUP BY revision id (if it has been added) and entity id. // Now each group contains a single revision of an entity. foreach ($this->sqlFields as $field) { $group_by = "$field[0].$field[1]"; $this->sqlGroupBy[$group_by] = $group_by; } } // Now we know whether this is a simple query or not, actually do the // sorting. foreach ($sort as $key => $sql_alias) { $direction = $this->sort[$key]['direction']; if ($simple_query || isset($this->sqlGroupBy[$sql_alias])) { // Simple queries, and the grouped columns of complicated queries // can be ordered normally, without the aggregation function. $this->sqlQuery->orderBy($sql_alias, $direction); if (!isset($this->sqlFields[$sql_alias])) { $this->sqlFields[$sql_alias] = explode('.', $sql_alias); } } else { // Order based on the smallest element of each group if the // direction is ascending, or on the largest element of each group // if the direction is descending. $function = $direction == 'ASC' ? 'min' : 'max'; $expression = "$function($sql_alias)"; $expression_alias = $this->sqlQuery->addExpression($expression); $this->sqlQuery->orderBy($expression_alias, $direction); } } return $this; } /** * Finish the query by adding fields, GROUP BY and range. * * @return \Drupal\Core\Entity\Query\Sql\Query * Returns the called object. */ protected function finish() { $this->initializePager(); if ($this->range) { $this->sqlQuery->range($this->range['start'], $this->range['length']); } foreach ($this->sqlGroupBy as $field) { $this->sqlQuery->groupBy($field); } foreach ($this->sqlFields as $field) { $this->sqlQuery->addField($field[0], $field[1], isset($field[2]) ? $field[2] : NULL); } return $this; } /** * Executes the query and returns the result. * * @return int|array * Returns the query result as entity IDs. */ protected function result() { if ($this->count) { return $this->sqlQuery->countQuery()->execute()->fetchField(); } // Return a keyed array of results. The key is either the revision_id or // the entity_id depending on whether the entity type supports revisions. // The value is always the entity id. return $this->sqlQuery->execute()->fetchAllKeyed(); } /** * Constructs a select expression for a given field and language. * * @param string $field * The name of the field being queried. * @param string $langcode * The language code of the field. * * @return string * An expression that will select the given field for the given language in * a SELECT query, such as 'base_table.id'. */ protected function getSqlField($field, $langcode) { if (!isset($this->tables)) { $this->tables = $this->getTables($this->sqlQuery); } $base_property = "base_table.$field"; if (isset($this->sqlFields[$base_property])) { return $base_property; } else { return $this->tables->addField($field, 'LEFT', $langcode); } } /** * Returns whether the query requires GROUP BY and ORDER BY MIN/MAX. * * @return bool */ protected function isSimpleQuery() { return (!$this->pager && !$this->range && !$this->count) || $this->sqlQuery->getMetaData('simple_query'); } /** * Implements the magic __clone method. * * Reset fields and GROUP BY when cloning. */ public function __clone() { parent::__clone(); $this->sqlFields = array(); $this->sqlGroupBy = array(); } /** * Gets the Tables object for this query. * * @param \Drupal\Core\Database\Query\SelectInterface $sql_query * The SQL query object being built. * * @return \Drupal\Core\Entity\Query\Sql\TablesInterface * The object that adds tables and fields to the SQL query object. */ public function getTables(SelectInterface $sql_query) { $class = static::getClass($this->namespaces, 'Tables'); return new $class($sql_query); } }
casivaagustin/drupalcon-mentoring
src/core/lib/Drupal/Core/Entity/Query/Sql/Query.php
PHP
mit
10,521
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-hours', templateUrl: 'hours.html', }) export class HoursPage { started: boolean = false; stopped: boolean = true; constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { } startstop() { this.started = !this.started; this.stopped = !this.stopped; var date = new Date(); var month = date.getMonth() + 1; var year = date.getFullYear(); var day = date.getUTCDate(); var hour = date.getHours(); var mins = date.getMinutes(); var time = `${month}/${day}/${year} ${hour}:${mins}`; var msg = `Time ${this.started ? 'in' : 'out'} ${time}`; document.getElementById('startstops').innerHTML = "<div class='time'>" + msg + "</div>" + document.getElementById('startstops').innerHTML; } }
HamidMosalla/allReady
AllReadyApp/Mobile-App/src/pages/hours/hours.ts
TypeScript
mit
944
//--------------------------------------------------------------------- // <copyright file="QueryReferenceValue.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.Test.Taupo.Query.Contracts { using System; using System.Linq; using Microsoft.Test.Taupo.Common; /// <summary> /// Result of a query evaluation which is a reference of entity /// </summary> public class QueryReferenceValue : QueryValue { internal QueryReferenceValue(QueryReferenceType type, QueryError evaluationError, IQueryEvaluationStrategy evaluationStrategy) : base(evaluationError, evaluationStrategy) { ExceptionUtilities.CheckArgumentNotNull(type, "type"); this.Type = type; } /// <summary> /// Gets the reference type. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "Must be the same as the base class.")] public new QueryReferenceType Type { get; private set; } /// <summary> /// Gets a value indicating whether this instance is null. /// </summary> public override bool IsNull { get { return this.KeyValue == null; } } /// <summary> /// Gets the entity value (for dereference) /// </summary> /// <remarks>For dangling reference, this should be null value</remarks> public QueryStructuralValue EntityValue { get; private set; } /// <summary> /// Gets the entity set full name /// </summary> public string EntitySetFullName { get; private set; } /// <summary> /// Gets the key value /// </summary> public QueryRecordValue KeyValue { get; private set; } /// <summary> /// Casts a <see cref="QueryValue"/> to a <see cref="QueryType"/>. The cast will return the value type cast to the new type. /// </summary> /// <param name="type">The type for the cast operation.</param> /// <returns><see cref="QueryValue"/> which is cast to the appropriate type</returns> public override QueryValue Cast(QueryType type) { return type.CreateErrorValue(new QueryError("Cannot perform Cast on a reference value")); } /// <summary> /// Checks if a <see cref="QueryValue"/> is of a particular <see cref="QueryType"/>. This operation will return a true if the value is of the specified type. /// </summary> /// <param name="type">The type for the IsOf operation.</param> /// <param name="performExactMatch">Determines if an exact match needs to be performed.</param> /// <returns>A <see cref="QueryValue"/> containing true or false depending on whether the value is of the specified type or not.</returns> public override QueryValue IsOf(QueryType type, bool performExactMatch) { return type.CreateErrorValue(new QueryError("Cannot perform IsOf on a reference value")); } /// <summary> /// Converts the <see cref="QueryValue"/> to a particular <see cref="QueryType"/>. /// </summary> /// <param name="type">The type for the As operation.</param> /// <returns>The <see cref="QueryValue"/> converted to the specified type if successful. Returns null if this operation fails.</returns> public override QueryValue TreatAs(QueryType type) { return type.CreateErrorValue(new QueryError("Cannot perform TreatAs on a reference value")); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { if (this.EvaluationError != null) { return "Reference Value Error=" + this.EvaluationError + ", Type=" + this.Type.StringRepresentation; } else if (this.IsNull) { return "Null Reference, Type=" + this.Type.StringRepresentation; } else { return "Reference Value=" + this.EntitySetFullName + ", keyValue[" + this.KeyValue + "], Type=" + this.Type.StringRepresentation; } } /// <summary> /// The Accept method used to support the double-dispatch visitor pattern with a visitor that returns a result. /// </summary> /// <typeparam name="TResult">The result type returned by the visitor.</typeparam> /// <param name="visitor">The visitor that is visiting this query value.</param> /// <returns>The result of visiting this query value.</returns> public override TResult Accept<TResult>(IQueryValueVisitor<TResult> visitor) { return visitor.Visit(this); } /// <summary> /// Gets a <see cref="QueryReferenceValue"/> value indicating whether two values are equal. /// </summary> /// <param name="otherValue">The second value.</param> /// <returns> /// Instance of <see cref="QueryScalarValue"/> which represents the result of comparison. /// </returns> public QueryScalarValue EqualTo(QueryReferenceValue otherValue) { if ((this.IsNull && otherValue.IsNull) || object.ReferenceEquals(this.EntityValue, otherValue.EntityValue)) { return new QueryScalarValue(EvaluationStrategy.BooleanType, true, this.EvaluationError, this.EvaluationStrategy); } else { return new QueryScalarValue(EvaluationStrategy.BooleanType, false, this.EvaluationError, this.EvaluationStrategy); } } /// <summary> /// Gets a <see cref="QueryReferenceValue"/> value indicating whether two values are not equal. /// </summary> /// <param name="otherValue">The second value.</param> /// <returns> /// Instance of <see cref="QueryScalarValue"/> which represents the result of comparison. /// </returns> public QueryScalarValue NotEqualTo(QueryReferenceValue otherValue) { bool areEqual = (bool)this.EqualTo(otherValue).Value; return new QueryScalarValue(EvaluationStrategy.BooleanType, !areEqual, this.EvaluationError, this.EvaluationStrategy); } internal void SetReferenceValue(QueryStructuralValue entityValue) { ExceptionUtilities.CheckArgumentNotNull(entityValue, "entityValue"); this.EntityValue = entityValue; // compute key value QueryEntityType entityType = this.Type.QueryEntityType; var keyType = new QueryRecordType(this.EvaluationStrategy); keyType.AddProperties(entityType.Properties.Where(m => m.IsPrimaryKey)); this.KeyValue = keyType.CreateNewInstance(); for (int i = 0; i < keyType.Properties.Count; i++) { this.KeyValue.SetMemberValue(i, entityValue.GetValue(keyType.Properties[i].Name)); } var set = entityType.EntitySet; this.EntitySetFullName = set.Container.Name + "." + set.Name; } // this is only heppening when reading from product or creating dangling reference internal void SetReferenceValue(string entitySetFullName, QueryRecordValue keyValue) { ExceptionUtilities.CheckStringArgumentIsNotNullOrEmpty(entitySetFullName, "entitySetFullName"); ExceptionUtilities.CheckArgumentNotNull(keyValue, "keyValue"); this.EntitySetFullName = entitySetFullName; this.KeyValue = keyValue; this.EntityValue = this.Type.QueryEntityType.NullValue; } /// <summary> /// Gets the type of the value. /// </summary> /// <returns>Type of the value.</returns> protected override QueryType GetTypeInternal() { return this.Type; } } }
abkmr/odata.net
test/FunctionalTests/Taupo/Source/Taupo.Query/Contracts/QueryReferenceValue.cs
C#
mit
8,618
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.IO.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.IO { public enum HandleInheritability { None = 0, Inheritable = 1, } }
ndykman/CodeContracts
Microsoft.Research/Contracts/System.Core/Sources/System.IO.cs
C#
mit
2,061
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.WebParts.TransformerTypeCollection.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls.WebParts { sealed public partial class TransformerTypeCollection : System.Collections.ReadOnlyCollectionBase { #region Methods and constructors public bool Contains(Type value) { return default(bool); } public void CopyTo(Type[] array, int index) { } public int IndexOf(Type value) { return default(int); } public TransformerTypeCollection() { } public TransformerTypeCollection(System.Web.UI.WebControls.WebParts.TransformerTypeCollection existingTransformerTypes, System.Collections.ICollection transformerTypes) { } public TransformerTypeCollection(System.Collections.ICollection transformerTypes) { } #endregion #region Properties and indexers public Type this [int index] { get { return default(Type); } } #endregion #region Fields public readonly static System.Web.UI.WebControls.WebParts.TransformerTypeCollection Empty; #endregion } }
ndykman/CodeContracts
Microsoft.Research/Contracts/System.Web/Sources/System.Web.UI.WebControls.WebParts.TransformerTypeCollection.cs
C#
mit
3,050
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Umbraco.Core.Xml.XPath { /// <summary> /// Represents the type of a content that can be navigated via XPath. /// </summary> interface INavigableContentType { /// <summary> /// Gets the name of the content type. /// </summary> string Name { get; } /// <summary> /// Gets the field types of the content type. /// </summary> /// <remarks>This includes the attributes and the properties.</remarks> INavigableFieldType[] FieldTypes { get; } } }
lars-erik/Umbraco-CMS
src/Umbraco.Core/Xml/XPath/INavigableContentType.cs
C#
mit
637
package com.mozu.api.utils; public class Endpoints { public static final String AUTH_URL = "api/platform/applications/authtickets"; public static final String AUTH_REFRESH_URL = "api/platform/applications/authtickets/refresh-ticket/%s"; public static final String TENANT_END_POINT = "api/platform/tenants"; public static final String SITES_END_POINT = "api/platform/tenants/%s/sites"; public static final String ATTRIBUTE_END_POINT = "api/commerce/catalog/admin/attributedefinition/attributes"; public static final String VOCABULARY_END_POINT = "api/commerce/catalog/admin/attributedefinition/attributes/%s/VocabularyValues"; public static final String PRODUCTTYPE_END_POINT = "api/commerce/catalog/admin/attributedefinition/producttypes"; public static final String ORDER_END_POINT = "api/commerce/orders"; public static final String APPLICATIONSTATUS_END_POINT = "api/commerce/settings/applicationstatus"; public static final String MZDB_APP_DATA_ENDPOINT = "api/platform/appdata"; public static final String MZDB_SITE_DATA_ENDPOINT = "api/platform/sitedata"; public static final String MZDB_TENANT_DATA_ENDPOINT = "api/platform/tenantdata"; }
carsonreinke/mozu-java-sdk
src/main/java/com/mozu/api/utils/Endpoints.java
Java
mit
1,200
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman 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 BOOST_PP_IS_ITERATING #if !defined(FUSION_MAKE_TUPLE_10032005_0843) #define FUSION_MAKE_TUPLE_10032005_0843 #include <boost/preprocessor/iterate.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/fusion/tuple/detail/tuple.hpp> #include <boost/fusion/support/detail/as_fusion_element.hpp> namespace boost { namespace fusion { BOOST_FUSION_GPU_ENABLED inline tuple<> make_tuple() { return tuple<>(); } }} #if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES) #include <boost/fusion/tuple/detail/preprocessed/make_tuple.hpp> #else #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 2, line: 0, output: "preprocessed/make_tuple" FUSION_MAX_VECTOR_SIZE_STR ".hpp") #endif /*============================================================================= Copyright (c) 2001-2011 Joel de Guzman 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) This is an auto-generated file. Do not edit! ==============================================================================*/ #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 1) #endif namespace boost { namespace fusion { #define BOOST_FUSION_AS_FUSION_ELEMENT(z, n, data) \ typename detail::as_fusion_element<BOOST_PP_CAT(T, n)>::type #define BOOST_PP_FILENAME_1 <boost/fusion/tuple/detail/make_tuple.hpp> #define BOOST_PP_ITERATION_LIMITS (1, FUSION_MAX_VECTOR_SIZE) #include BOOST_PP_ITERATE() #undef BOOST_FUSION_AS_FUSION_ELEMENT }} #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES #endif #else // defined(BOOST_PP_IS_ITERATING) /////////////////////////////////////////////////////////////////////////////// // // Preprocessor vertical repetition code // /////////////////////////////////////////////////////////////////////////////// #define N BOOST_PP_ITERATION() template <BOOST_PP_ENUM_PARAMS(N, typename T)> BOOST_FUSION_GPU_ENABLED inline tuple<BOOST_PP_ENUM(N, BOOST_FUSION_AS_FUSION_ELEMENT, _)> make_tuple(BOOST_PP_ENUM_BINARY_PARAMS(N, T, const& arg)) { return tuple<BOOST_PP_ENUM(N, BOOST_FUSION_AS_FUSION_ELEMENT, _)>( BOOST_PP_ENUM_PARAMS(N, arg)); } #undef N #endif // defined(BOOST_PP_IS_ITERATING)
nginnever/zogminer
tests/deps/boost/fusion/tuple/detail/make_tuple.hpp
C++
mit
3,058
<?php namespace Bolt\Helpers; use Cocur\Slugify\Slugify; class Str { /** * Returns a "safe" version of the given string - basically only US-ASCII and * numbers. Needed because filenames and titles and such, can't use all characters. * * @param string $str * @param boolean $strict * @param string $extrachars * * @return string */ public static function makeSafe($str, $strict = false, $extrachars = '') { $str = str_replace('&amp;', '', $str); $delim = '/'; if ($extrachars != '') { $extrachars = preg_quote($extrachars, $delim); } if ($strict) { $slugify = Slugify::create('/[^a-z0-9_' . $extrachars . ' -]+/'); $str = $slugify->slugify($str, ''); $str = str_replace(' ', '-', $str); } else { // Allow Uppercase and don't convert spaces to dashes $slugify = Slugify::create('/[^a-zA-Z0-9_.,' . $extrachars . ' -]+/', ['lowercase' => false]); $str = $slugify->slugify($str, ''); } return $str; } /** * Replace the first occurence of a string only. Behaves like str_replace, but * replaces _only_ the _first_ occurence. * * @see http://stackoverflow.com/a/2606638 * * @param string $search * @param string $replace * @param string $subject * * @return string */ public static function replaceFirst($search, $replace, $subject) { $pos = strpos($subject, $search); if ($pos !== false) { $subject = substr_replace($subject, $replace, $pos, strlen($search)); } return $subject; } /** * Add 'soft hyphens' &shy; to a string, so that it won't break layout in HTML when * using strings without spaces or dashes. Only breaks in long (> 19 chars) words. * * @param string $str * * @return string */ public static function shyphenate($str) { $res = preg_match_all('/([a-z0-9]{19,})/i', $str, $matches); if ($res) { foreach ($matches[1] as $key => $match) { $str = str_replace($match, wordwrap($match, 10, '&shy;', true), $str); } } return $str; } }
CarsonF/bolt
src/Helpers/Str.php
PHP
mit
2,298
import Ember from 'ember-metal'; // Ember as namespace import { A as emberA, typeOf, String as StringUtils, Namespace, Object as EmberObject } from 'ember-runtime'; /** @module ember @submodule ember-extension-support */ /** The `ContainerDebugAdapter` helps the container and resolver interface with tools that debug Ember such as the [Ember Extension](https://github.com/tildeio/ember-extension) for Chrome and Firefox. This class can be extended by a custom resolver implementer to override some of the methods with library-specific code. The methods likely to be overridden are: * `canCatalogEntriesByType` * `catalogEntriesByType` The adapter will need to be registered in the application's container as `container-debug-adapter:main`. Example: ```javascript Application.initializer({ name: "containerDebugAdapter", initialize(application) { application.register('container-debug-adapter:main', require('app/container-debug-adapter')); } }); ``` @class ContainerDebugAdapter @namespace Ember @extends Ember.Object @since 1.5.0 @public */ export default EmberObject.extend({ /** The resolver instance of the application being debugged. This property will be injected on creation. @property resolver @default null @public */ resolver: null, /** Returns true if it is possible to catalog a list of available classes in the resolver for a given type. @method canCatalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route". @return {boolean} whether a list is available for this type. @public */ canCatalogEntriesByType(type) { if (type === 'model' || type === 'template') { return false; } return true; }, /** Returns the available classes a given type. @method catalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route". @return {Array} An array of strings. @public */ catalogEntriesByType(type) { let namespaces = emberA(Namespace.NAMESPACES); let types = emberA(); let typeSuffixRegex = new RegExp(`${StringUtils.classify(type)}$`); namespaces.forEach(namespace => { if (namespace !== Ember) { for (let key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } if (typeSuffixRegex.test(key)) { let klass = namespace[key]; if (typeOf(klass) === 'class') { types.push(StringUtils.dasherize(key.replace(typeSuffixRegex, ''))); } } } } }); return types; } });
duggiefresh/ember.js
packages/ember-extension-support/lib/container_debug_adapter.js
JavaScript
mit
2,656
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model common\models\User */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="user-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'status')->textInput() ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
wedigitalApps/foundation
themes/wedigital/backend/user/_form.php
PHP
mit
555
<?php /** * WPSEO plugin file. * * @package WPSEO\Internals\Options */ /** * Option: wpseo_taxonomy_meta. */ class WPSEO_Taxonomy_Meta extends WPSEO_Option { /** * @var string Option name. */ public $option_name = 'wpseo_taxonomy_meta'; /** * @var bool Whether to include the option in the return for WPSEO_Options::get_all(). */ public $include_in_all = false; /** * @var array Array of defaults for the option. * Shouldn't be requested directly, use $this->get_defaults(); * * {@internal Important: in contrast to most defaults, the below array format is * very bare. The real option is in the format [taxonomy_name][term_id][...] * where [...] is any of the $defaults_per_term options shown below. * This is of course taken into account in the below methods.}} */ protected $defaults = array(); /** * @var string Option name - same as $option_name property, but now also available to static methods. * @static */ public static $name; /** * @var array Array of defaults for individual taxonomy meta entries. * @static */ public static $defaults_per_term = array( 'wpseo_title' => '', 'wpseo_desc' => '', 'wpseo_canonical' => '', 'wpseo_bctitle' => '', 'wpseo_noindex' => 'default', 'wpseo_focuskw' => '', 'wpseo_linkdex' => '', 'wpseo_content_score' => '', // Social fields. 'wpseo_opengraph-title' => '', 'wpseo_opengraph-description' => '', 'wpseo_opengraph-image' => '', 'wpseo_twitter-title' => '', 'wpseo_twitter-description' => '', 'wpseo_twitter-image' => '', ); /** * @var array Available index options. * Used for form generation and input validation. * * @static * * {@internal Labels (translation) added on admin_init via WPSEO_Taxonomy::translate_meta_options().}} */ public static $no_index_options = array( 'default' => '', 'index' => '', 'noindex' => '', ); /** * Add the actions and filters for the option. * * @todo [JRF => testers] Check if the extra actions below would run into problems if an option * is updated early on and if so, change the call to schedule these for a later action on add/update * instead of running them straight away. * * @return \WPSEO_Taxonomy_Meta */ protected function __construct() { parent::__construct(); self::$name = $this->option_name; /* On succesfull update/add of the option, flush the W3TC cache. */ add_action( 'add_option_' . $this->option_name, array( 'WPSEO_Utils', 'flush_w3tc_cache' ) ); add_action( 'update_option_' . $this->option_name, array( 'WPSEO_Utils', 'flush_w3tc_cache' ) ); } /** * Get the singleton instance of this class. * * @return object */ public static function get_instance() { if ( ! ( self::$instance instanceof self ) ) { self::$instance = new self(); self::$name = self::$instance->option_name; } return self::$instance; } /** * Add extra default options received from a filter. */ public function enrich_defaults() { $extra_defaults_per_term = apply_filters( 'wpseo_add_extra_taxmeta_term_defaults', array() ); if ( is_array( $extra_defaults_per_term ) ) { self::$defaults_per_term = array_merge( $extra_defaults_per_term, self::$defaults_per_term ); } } /** * Helper method - Combines a fixed array of default values with an options array * while filtering out any keys which are not in the defaults array. * * @static * * @param string $option_key Option name of the option we're doing the merge for. * @param array $options Optional. Current options. If not set, the option defaults for the $option_key will be returned. * * @return array Combined and filtered options array. */ /* Public function array_filter_merge( $option_key, $options = null ) { $defaults = $this->get_defaults( $option_key ); if ( ! isset( $options ) || $options === false ) { return $defaults; } / * {@internal Adding the defaults to all taxonomy terms each time the option is retrieved will be quite inefficient if there are a lot of taxonomy terms. As long as taxonomy_meta is only retrieved via methods in this class, we shouldn't need this.}} $options = (array) $options; $filtered = array(); if ( $options !== array() ) { foreach ( $options as $taxonomy => $terms ) { if ( is_array( $terms ) && $terms !== array() ) { foreach ( $terms as $id => $term_meta ) { foreach ( self::$defaults_per_term as $name => $default ) { if ( isset( $options[ $taxonomy ][ $id ][ $name ] ) ) { $filtered[ $taxonomy ][ $id ][ $name ] = $options[ $taxonomy ][ $id ][ $name ]; } else { $filtered[ $name ] = $default; } } } } } unset( $taxonomy, $terms, $id, $term_meta, $name, $default ); } // end of may be remove. return $filtered; * / return (array) $options; } */ /** * Validate the option. * * @param array $dirty New value for the option. * @param array $clean Clean value for the option, normally the defaults. * @param array $old Old value of the option. * * @return array Validated clean value for the option to be saved to the database. */ protected function validate_option( $dirty, $clean, $old ) { /* * Prevent complete validation (which can be expensive when there are lots of terms) * if only one item has changed and has already been validated. */ if ( isset( $dirty['wpseo_already_validated'] ) && $dirty['wpseo_already_validated'] === true ) { unset( $dirty['wpseo_already_validated'] ); return $dirty; } foreach ( $dirty as $taxonomy => $terms ) { /* Don't validate taxonomy - may not be registered yet and we don't want to remove valid ones. */ if ( is_array( $terms ) && $terms !== array() ) { foreach ( $terms as $term_id => $meta_data ) { /* Only validate term if the taxonomy exists. */ if ( taxonomy_exists( $taxonomy ) && get_term_by( 'id', $term_id, $taxonomy ) === false ) { /* Is this term id a special case ? */ if ( has_filter( 'wpseo_tax_meta_special_term_id_validation_' . $term_id ) !== false ) { $clean[ $taxonomy ][ $term_id ] = apply_filters( 'wpseo_tax_meta_special_term_id_validation_' . $term_id, $meta_data, $taxonomy, $term_id ); } continue; } if ( is_array( $meta_data ) && $meta_data !== array() ) { /* Validate meta data. */ $old_meta = self::get_term_meta( $term_id, $taxonomy ); $meta_data = self::validate_term_meta_data( $meta_data, $old_meta ); if ( $meta_data !== array() ) { $clean[ $taxonomy ][ $term_id ] = $meta_data; } } // Deal with special cases (for when taxonomy doesn't exist yet). if ( ! isset( $clean[ $taxonomy ][ $term_id ] ) && has_filter( 'wpseo_tax_meta_special_term_id_validation_' . $term_id ) !== false ) { $clean[ $taxonomy ][ $term_id ] = apply_filters( 'wpseo_tax_meta_special_term_id_validation_' . $term_id, $meta_data, $taxonomy, $term_id ); } } } } return $clean; } /** * Validate the meta data for one individual term and removes default values (no need to save those). * * @static * * @param array $meta_data New values. * @param array $old_meta The original values. * * @return array Validated and filtered value. */ public static function validate_term_meta_data( $meta_data, $old_meta ) { $clean = self::$defaults_per_term; $meta_data = array_map( array( 'WPSEO_Utils', 'trim_recursive' ), $meta_data ); if ( ! is_array( $meta_data ) || $meta_data === array() ) { return $clean; } foreach ( $clean as $key => $value ) { switch ( $key ) { case 'wpseo_noindex': if ( isset( $meta_data[ $key ] ) ) { if ( isset( self::$no_index_options[ $meta_data[ $key ] ] ) ) { $clean[ $key ] = $meta_data[ $key ]; } } elseif ( isset( $old_meta[ $key ] ) ) { // Retain old value if field currently not in use. $clean[ $key ] = $old_meta[ $key ]; } break; case 'wpseo_canonical': if ( isset( $meta_data[ $key ] ) && $meta_data[ $key ] !== '' ) { $url = WPSEO_Utils::sanitize_url( $meta_data[ $key ] ); if ( $url !== '' ) { $clean[ $key ] = $url; } unset( $url ); } break; case 'wpseo_bctitle': if ( isset( $meta_data[ $key ] ) ) { $clean[ $key ] = WPSEO_Utils::sanitize_text_field( stripslashes( $meta_data[ $key ] ) ); } elseif ( isset( $old_meta[ $key ] ) ) { // Retain old value if field currently not in use. $clean[ $key ] = $old_meta[ $key ]; } break; case 'wpseo_focuskw': case 'wpseo_title': case 'wpseo_desc': case 'wpseo_linkdex': default: if ( isset( $meta_data[ $key ] ) && is_string( $meta_data[ $key ] ) ) { $clean[ $key ] = WPSEO_Utils::sanitize_text_field( stripslashes( $meta_data[ $key ] ) ); } if ( 'wpseo_focuskw' === $key ) { $clean[ $key ] = str_replace( array( '&lt;', '&gt;', '&quot', '&#96', '<', '>', '"', '`', ), '', $clean[ $key ] ); } break; } $clean[ $key ] = apply_filters( 'wpseo_sanitize_tax_meta_' . $key, $clean[ $key ], ( isset( $meta_data[ $key ] ) ? $meta_data[ $key ] : null ), ( isset( $old_meta[ $key ] ) ? $old_meta[ $key ] : null ) ); } // Only save the non-default values. return array_diff_assoc( $clean, self::$defaults_per_term ); } /** * Clean a given option value. * - Convert old option values to new * - Fixes strings which were escaped (should have been sanitized - escaping is for output) * * @param array $option_value Old (not merged with defaults or filtered) option value to * clean according to the rules for this option. * @param string $current_version Optional. Version from which to upgrade, if not set, * version specific upgrades will be disregarded. * @param array $all_old_option_values Optional. Only used when importing old options to have * access to the real old values, in contrast to the saved ones. * * @return array Cleaned option. */ protected function clean_option( $option_value, $current_version = null, $all_old_option_values = null ) { /* Clean up old values and remove empty arrays. */ if ( is_array( $option_value ) && $option_value !== array() ) { foreach ( $option_value as $taxonomy => $terms ) { if ( is_array( $terms ) && $terms !== array() ) { foreach ( $terms as $term_id => $meta_data ) { if ( ! is_array( $meta_data ) || $meta_data === array() ) { // Remove empty term arrays. unset( $option_value[ $taxonomy ][ $term_id ] ); } else { foreach ( $meta_data as $key => $value ) { switch ( $key ) { case 'noindex': if ( $value === 'on' ) { // Convert 'on' to 'noindex'. $option_value[ $taxonomy ][ $term_id ][ $key ] = 'noindex'; } break; case 'canonical': case 'wpseo_bctitle': case 'wpseo_title': case 'wpseo_desc': case 'wpseo_linkdex': // @todo [JRF => whomever] needs checking, I don't have example data [JRF]. if ( $value !== '' ) { // Fix incorrectly saved (encoded) canonical urls and texts. $option_value[ $taxonomy ][ $term_id ][ $key ] = wp_specialchars_decode( stripslashes( $value ), ENT_QUOTES ); } break; default: // @todo [JRF => whomever] needs checking, I don't have example data [JRF]. if ( $value !== '' ) { // Fix incorrectly saved (escaped) text strings. $option_value[ $taxonomy ][ $term_id ][ $key ] = wp_specialchars_decode( $value, ENT_QUOTES ); } break; } } } } } else { // Remove empty taxonomy arrays. unset( $option_value[ $taxonomy ] ); } } } return $option_value; } /** * Retrieve a taxonomy term's meta value(s). * * @static * * @param mixed $term Term to get the meta value for * either (string) term name, (int) term id or (object) term. * @param string $taxonomy Name of the taxonomy to which the term is attached. * @param string $meta Optional. Meta value to get (without prefix). * * @return mixed|bool Value for the $meta if one is given, might be the default. * If no meta is given, an array of all the meta data for the term. * False if the term does not exist or the $meta provided is invalid. */ public static function get_term_meta( $term, $taxonomy, $meta = null ) { /* Figure out the term id. */ if ( is_int( $term ) ) { $term = get_term_by( 'id', $term, $taxonomy ); } elseif ( is_string( $term ) ) { $term = get_term_by( 'slug', $term, $taxonomy ); } if ( is_object( $term ) && isset( $term->term_id ) ) { $term_id = $term->term_id; } else { return false; } $tax_meta = self::get_term_tax_meta( $term_id, $taxonomy ); /* * Either return the complete array or a single value from it or false if the value does not exist * (shouldn't happen after merge with defaults, indicates typo in request). */ if ( ! isset( $meta ) ) { return $tax_meta; } if ( isset( $tax_meta[ 'wpseo_' . $meta ] ) ) { return $tax_meta[ 'wpseo_' . $meta ]; } return false; } /** * Get the current queried object and return the meta value. * * @param string $meta The meta field that is needed. * * @return bool|mixed */ public static function get_meta_without_term( $meta ) { $term = $GLOBALS['wp_query']->get_queried_object(); return self::get_term_meta( $term, $term->taxonomy, $meta ); } /** * Saving the values for the given term_id. * * @param int $term_id ID of the term to save data for. * @param string $taxonomy The taxonomy the term belongs to. * @param array $meta_values The values that will be saved. */ public static function set_values( $term_id, $taxonomy, array $meta_values ) { /* Validate the post values */ $old = self::get_term_meta( $term_id, $taxonomy ); $clean = self::validate_term_meta_data( $meta_values, $old ); self::save_clean_values( $term_id, $taxonomy, $clean ); } /** * Setting a single value to the term meta. * * @param int $term_id ID of the term to save data for. * @param string $taxonomy The taxonomy the term belongs to. * @param string $meta_key The target meta key to store the value in. * @param string $meta_value The value of the target meta key. */ public static function set_value( $term_id, $taxonomy, $meta_key, $meta_value ) { if ( substr( strtolower( $meta_key ), 0, 6 ) !== 'wpseo_' ) { $meta_key = 'wpseo_' . $meta_key; } self::set_values( $term_id, $taxonomy, array( $meta_key => $meta_value ) ); } /** * Find the keyword usages in the metas for the taxonomies/terms. * * @param string $keyword The keyword to look for. * @param string $current_term_id The current term id. * @param string $current_taxonomy The current taxonomy name. * * @return array */ public static function get_keyword_usage( $keyword, $current_term_id, $current_taxonomy ) { $tax_meta = self::get_tax_meta(); $found = array(); // @todo Check for terms of all taxonomies, not only the current taxonomy. foreach ( $tax_meta as $taxonomy_name => $terms ) { foreach ( $terms as $term_id => $meta_values ) { $is_current = ( $current_taxonomy === $taxonomy_name && (string) $current_term_id === (string) $term_id ); if ( ! $is_current && ! empty( $meta_values['wpseo_focuskw'] ) && $meta_values['wpseo_focuskw'] === $keyword ) { $found[] = $term_id; } } } return array( $keyword => $found ); } /** * Saving the values for the given term_id. * * @param int $term_id ID of the term to save data for. * @param string $taxonomy The taxonomy the term belongs to. * @param array $clean Array with clean values. */ private static function save_clean_values( $term_id, $taxonomy, array $clean ) { $tax_meta = self::get_tax_meta(); /* Add/remove the result to/from the original option value. */ if ( $clean !== array() ) { $tax_meta[ $taxonomy ][ $term_id ] = $clean; } else { unset( $tax_meta[ $taxonomy ][ $term_id ] ); if ( isset( $tax_meta[ $taxonomy ] ) && $tax_meta[ $taxonomy ] === array() ) { unset( $tax_meta[ $taxonomy ] ); } } // Prevent complete array validation. $tax_meta['wpseo_already_validated'] = true; self::save_tax_meta( $tax_meta ); } /** * Getting the meta from the options. * * @return void|array */ private static function get_tax_meta() { return get_option( self::$name ); } /** * Saving the tax meta values to the database. * * @param array $tax_meta Array with the meta values for taxonomy. */ private static function save_tax_meta( $tax_meta ) { update_option( self::$name, $tax_meta ); } /** * Getting the taxonomy meta for the given term_id and taxonomy. * * @param int $term_id The id of the term. * @param string $taxonomy Name of the taxonomy to which the term is attached. * * @return array */ private static function get_term_tax_meta( $term_id, $taxonomy ) { $tax_meta = self::get_tax_meta(); /* If we have data for the term, merge with defaults for complete array, otherwise set defaults. */ if ( isset( $tax_meta[ $taxonomy ][ $term_id ] ) ) { return array_merge( self::$defaults_per_term, $tax_meta[ $taxonomy ][ $term_id ] ); } return self::$defaults_per_term; } }
smpetrey/leahconstantine.com
web/app/plugins/wordpress-seo/inc/options/class-wpseo-taxonomy-meta.php
PHP
mit
18,076
<?php namespace Sonata\AdminBundle\Tests\Fixtures\Admin; use Sonata\AdminBundle\Admin\Admin; class PostAdmin extends Admin { protected $metadataClass = null; public function setParentAssociationMapping($associationMapping) { $this->parentAssociationMapping = $associationMapping; } public function setClassMetaData($classMetaData) { $this->classMetaData = $classMetaData; } public function getClassMetaData() { if ($this->classMetaData) { return $this->classMetaData; } return parent::getClassMetaData(); } }
evgenikozlov/test-task
vendor/sonata-project/admin-bundle/Tests/Fixtures/Admin/PostAdmin.php
PHP
mit
607
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections; using System.Reflection; using System.Diagnostics.Contracts; //using System.Runtime.CompilerServices; namespace System.Collections.Generic { // Summary: // Represents a collection of objects that can be individually accessed by index. // // Type parameters: // T: // The type of elements in the list. [ContractClass(typeof(IListContract<>))] public interface IList<T> : ICollection<T> { // Summary: // Gets or sets the element at the specified index. // // Parameters: // index: // The zero-based index of the element to get or set. // // Returns: // The element at the specified index. // // Exceptions: // System.ArgumentOutOfRangeException: // index is not a valid index in the System.Collections.Generic.IList<T>. // // System.NotSupportedException: // The property is set and the System.Collections.Generic.IList<T> is read-only. T this[int index] { get; set; } // Summary: // Determines the index of a specific item in the System.Collections.Generic.IList<T>. // // Parameters: // item: // The object to locate in the System.Collections.Generic.IList<T>. // // Returns: // The index of item if found in the list; otherwise, -1. [Pure] int IndexOf(T item); // // Summary: // Inserts an item to the System.Collections.Generic.IList<T> at the specified // index. // // Parameters: // index: // The zero-based index at which item should be inserted. // // item: // The object to insert into the System.Collections.Generic.IList<T>. // // Exceptions: // System.ArgumentOutOfRangeException: // index is not a valid index in the System.Collections.Generic.IList<T>. // // System.NotSupportedException: // The System.Collections.Generic.IList<T> is read-only. void Insert(int index, T item); // // Summary: // Removes the System.Collections.Generic.IList<T> item at the specified index. // // Parameters: // index: // The zero-based index of the item to remove. // // Exceptions: // System.ArgumentOutOfRangeException: // index is not a valid index in the System.Collections.Generic.IList<T>. // // System.NotSupportedException: // The System.Collections.Generic.IList<T> is read-only. void RemoveAt(int index); } [ContractClassFor(typeof(IList<>))] abstract class IListContract<T> : IList<T> { #region IList<T> Members T IList<T>.this[int index] { get { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); return default(T); } set { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); } } [Pure] int IList<T>.IndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < this.Count); throw new NotImplementedException(); } void IList<T>.Insert(int index, T item) { Contract.Requires(index >= 0); Contract.Requires(index <= this.Count); } void IList<T>.RemoveAt(int index) { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); Contract.Ensures(this.Count == Contract.OldValue(this.Count) - 1); } #endregion #region ICollection<T> Members public int Count { get { throw new NotImplementedException(); } } bool ICollection<T>.IsReadOnly { get { throw new NotImplementedException(); } } void ICollection<T>.Add(T item) { // Contract.Ensures(Count == Contract.OldValue(Count) + 1); // cannot be seen by our tools as there is no IList<T>.Add throw new NotImplementedException(); } void ICollection<T>.Clear() { throw new NotImplementedException(); } bool ICollection<T>.Contains(T item) { throw new NotImplementedException(); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); } bool ICollection<T>.Remove(T item) { throw new NotImplementedException(); } #endregion #region IEnumerable<T> Members IEnumerator<T> IEnumerable<T>.GetEnumerator() { throw new NotImplementedException(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } #endregion #region IEnumerable Members public object[] Model { get { throw new NotImplementedException(); } } #endregion } }
ndykman/CodeContracts
Microsoft.Research/Contracts/MsCorlib/System.Collections.Generic.IList.cs
C#
mit
5,963
namespace Merchello.Web.Models.ContentEditing { using System; using System.Collections.Generic; using Merchello.Core; using Merchello.Core.Models.TypeFields; using Newtonsoft.Json; using Newtonsoft.Json.Converters; /// <summary> /// The line item display base. /// </summary> public abstract class LineItemDisplayBase { /// <summary> /// Gets or sets the key. /// </summary> public Guid Key { get; set; } /// <summary> /// Gets or sets the container key. /// </summary> public Guid ContainerKey { get; set; } /// <summary> /// Gets or sets the line item type field key. /// </summary> public Guid LineItemTfKey { get; set; } /// <summary> /// Gets or sets the SKU. /// </summary> public string Sku { get; set; } /// <summary> /// Gets or sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the quantity. /// </summary> public int Quantity { get; set; } /// <summary> /// Gets or sets the price. /// </summary> public decimal Price { get; set; } /// <summary> /// Gets or sets a value indicating whether exported. /// </summary> public bool Exported { get; set; } /// <summary> /// Gets or sets the line item type. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public LineItemType LineItemType { get; set; } /// <summary> /// Gets or sets the line item type field. /// </summary> public TypeField LineItemTypeField { get; set; } /// <summary> /// Gets or sets the extended data. /// </summary> public IEnumerable<KeyValuePair<string, string>> ExtendedData { get; set; } } }
MindfireTechnology/Merchello
src/Merchello.Web/Models/ContentEditing/LineItemDisplayBase.cs
C#
mit
1,952
(function ($) { 'use strict'; $.extend(true, $.trumbowyg, { langs: { // jshint camelcase:false en: { fontFamily: 'Font' }, es: { fontFamily: 'Fuente' }, da: { fontFamily: 'Skrifttype' }, fr: { fontFamily: 'Police' }, de: { fontFamily: 'Schriftart' }, nl: { fontFamily: 'Lettertype' }, tr: { fontFamily: 'Yazı Tipi' }, zh_tw: { fontFamily: '字體', }, pt_br: { fontFamily: 'Fonte', } } }); // jshint camelcase:true var defaultOptions = { fontList: [ {name: 'Arial', family: 'Arial, Helvetica, sans-serif'}, {name: 'Arial Black', family: '\'Arial Black\', Gadget, sans-serif'}, {name: 'Comic Sans', family: '\'Comic Sans MS\', Textile, cursive, sans-serif'}, {name: 'Courier New', family: '\'Courier New\', Courier, monospace'}, {name: 'Georgia', family: 'Georgia, serif'}, {name: 'Impact', family: 'Impact, Charcoal, sans-serif'}, {name: 'Lucida Console', family: '\'Lucida Console\', Monaco, monospace'}, {name: 'Lucida Sans', family: '\'Lucida Sans Uncide\', \'Lucida Grande\', sans-serif'}, {name: 'Palatino', family: '\'Palatino Linotype\', \'Book Antiqua\', Palatino, serif'}, {name: 'Tahoma', family: 'Tahoma, Geneva, sans-serif'}, {name: 'Times New Roman', family: '\'Times New Roman\', Times, serif'}, {name: 'Trebuchet', family: '\'Trebuchet MS\', Helvetica, sans-serif'}, {name: 'Verdana', family: 'Verdana, Geneva, sans-serif'} ] }; // Add dropdown with web safe fonts $.extend(true, $.trumbowyg, { plugins: { fontfamily: { init: function (trumbowyg) { trumbowyg.o.plugins.fontfamily = $.extend(true, {}, defaultOptions, trumbowyg.o.plugins.fontfamily || {} ); trumbowyg.addBtnDef('fontfamily', { dropdown: buildDropdown(trumbowyg), hasIcon: false, text: trumbowyg.lang.fontFamily }); } } } }); function buildDropdown(trumbowyg) { var dropdown = []; $.each(trumbowyg.o.plugins.fontfamily.fontList, function (index, font) { trumbowyg.addBtnDef('fontfamily_' + index, { title: '<span style="font-family: ' + font.family + ';">' + font.name + '</span>', hasIcon: false, fn: function () { trumbowyg.execCmd('fontName', font.family, true); } }); dropdown.push('fontfamily_' + index); }); return dropdown; } })(jQuery);
extend1994/cdnjs
ajax/libs/Trumbowyg/2.16.2/plugins/fontfamily/trumbowyg.fontfamily.js
JavaScript
mit
3,157
<?php global $qode_options_proya; $blog_hide_comments = ""; if (isset($qode_options_proya['blog_hide_comments'])) { $blog_hide_comments = $qode_options_proya['blog_hide_comments']; } $blog_hide_author = ""; if (isset($qode_options_proya['blog_hide_author'])) { $blog_hide_author = $qode_options_proya['blog_hide_author']; } $qode_like = "on"; if (isset($qode_options_proya['qode_like'])) { $qode_like = $qode_options_proya['qode_like']; } ?> <?php $_post_format = get_post_format(); ?> <?php switch ($_post_format) { case "video": ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <div class="post_image"> <?php $_video_type = get_post_meta(get_the_ID(), "video_format_choose", true);?> <?php if($_video_type == "youtube") { ?> <iframe src="//www.youtube.com/embed/<?php echo get_post_meta(get_the_ID(), "video_format_link", true); ?>?wmode=transparent" wmode="Opaque" frameborder="0" allowfullscreen></iframe> <?php } elseif ($_video_type == "vimeo"){ ?> <iframe src="//player.vimeo.com/video/<?php echo get_post_meta(get_the_ID(), "video_format_link", true); ?>?title=0&amp;byline=0&amp;portrait=0" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe> <?php } elseif ($_video_type == "self"){ ?> <div class="video"> <div class="mobile-video-image" style="background-image: url(<?php echo get_post_meta(get_the_ID(), "video_format_image", true); ?>);"></div> <div class="video-wrap" > <video class="video" poster="<?php echo get_post_meta(get_the_ID(), "video_format_image", true); ?>" preload="auto"> <?php if(get_post_meta(get_the_ID(), "video_format_webm", true) != "") { ?> <source type="video/webm" src="<?php echo get_post_meta(get_the_ID(), "video_format_webm", true); ?>"> <?php } ?> <?php if(get_post_meta(get_the_ID(), "video_format_mp4", true) != "") { ?> <source type="video/mp4" src="<?php echo get_post_meta(get_the_ID(), "video_format_mp4", true); ?>"> <?php } ?> <?php if(get_post_meta(get_the_ID(), "video_format_ogv", true) != "") { ?> <source type="video/ogg" src="<?php echo get_post_meta(get_the_ID(), "video_format_ogv", true); ?>"> <?php } ?> <object width="320" height="240" type="application/x-shockwave-flash" data="<?php echo get_template_directory_uri(); ?>/js/flashmediaelement.swf"> <param name="movie" value="<?php echo get_template_directory_uri(); ?>/js/flashmediaelement.swf" /> <param name="flashvars" value="controls=true&file=<?php echo get_post_meta(get_the_ID(), "video_format_mp4", true); ?>" /> <img src="<?php echo get_post_meta(get_the_ID(), "video_format_image", true); ?>" width="1920" height="800" title="No video playback capabilities" alt="Video thumb" /> </object> </video> </div></div> <?php } ?> </div> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <div class="separator small center"></div> <?php qode_excerpt(); ?> </div> </div> </div> </article> <?php break; case "audio": ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <div class="post_image"> <audio class="blog_audio" src="<?php echo get_post_meta(get_the_ID(), "audio_link", true) ?>" controls="controls"> <?php _e("Your browser don't support audio player","qode"); ?> </audio> </div> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <div class="separator small center"></div> <?php qode_excerpt(); ?> </div> </div> </div> </article> <?php break; case "gallery": ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <div class="post_image"> <div class="flexslider"> <ul class="slides"> <?php $post_content = get_the_content(); preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids); $array_id = explode(",", $ids[1]); foreach($array_id as $img_id){ ?> <li><a href="<?php the_permalink(); ?>"><?php echo wp_get_attachment_image( $img_id, 'full' ); ?></a></li> <?php } ?> </ul> </div> </div> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <div class="separator small center"></div> <?php qode_excerpt(); ?> </div> </div> </div> </article> <?php break; case "link": ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <i class="link_mark fa fa-link pull-left"></i> <div class="post_title"> <p><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></p> </div> </div> </div> </div> </article> <?php break; case "quote": ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <i class="qoute_mark fa fa-quote-right pull-left"></i> <div class="post_title"> <p><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php echo get_post_meta(get_the_ID(), "quote_format", true); ?></a></p> <span class="quote_author">&mdash; <?php the_title(); ?></span> </div> </div> </div> </div> </article> <?php break; default: ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <?php if ( has_post_thumbnail() ) { ?> <div class="post_image"> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"> <?php the_post_thumbnail('full'); ?> </a> </div> <?php } ?> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <div class="separator small center"></div> <?php qode_excerpt(); ?> </div> </div> </div> </article> <?php } ?>
comc49/a2f_bridge_theme
wp-content/themes_bak/bridge/templates/blog_large_image_simple-loop.php
PHP
gpl-2.0
7,098
<?php namespace Drupal\Tests\rest\Functional\EntityResource\Media; @trigger_error('The ' . __NAMESPACE__ . '\MediaResourceTestBase is deprecated in Drupal 8.6.x and will be removed before Drupal 9.0.0. Instead, use Drupal\Tests\media\Functional\Rest\MediaResourceTestBase. See https://www.drupal.org/node/2971931.', E_USER_DEPRECATED); use Drupal\Tests\media\Functional\Rest\MediaResourceTestBase as MediaResourceTestBaseReal; /** * @deprecated in drupal:8.6.0 and is removed from drupal:9.0.0. Use * Drupal\Tests\media\Functional\Rest\MediaResourceTestBase instead. * * @see https://www.drupal.org/node/2971931 */ abstract class MediaResourceTestBase extends MediaResourceTestBaseReal { }
maskedjellybean/tee-prop
web/core/modules/rest/tests/src/Functional/EntityResource/Media/MediaResourceTestBase.php
PHP
gpl-2.0
701
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Moorabi SD%Complete: 20% SDComment: SDCategory: Gundrak EndScriptData */ #include "precompiled.h" #include "gundrak.h" enum { SAY_AGGRO = -1604011, SAY_QUAKE = -1604012, SAY_TRANSFORM = -1604013, SAY_SLAY_1 = -1604014, SAY_SLAY_2 = -1604015, SAY_SLAY_3 = -1604016, SAY_DEATH = -1604017, EMOTE_TRANSFORM = -1604018, EMOTE_TRANSFORMED = -1604029, // Troll form SPELL_DETERMINED_STAB = 55104, SPELL_MOJO_FRENZY = 55163, SPELL_GROUND_TREMOR = 55142, SPELL_NUMBING_SHOUT = 55106, SPELL_TRANSFORMATION = 55098, // Mammoth SPELL_DETERMINED_GORE = 55102, SPELL_DETERMINED_GORE_H = 59444, SPELL_QUAKE = 55101, SPELL_NUMBING_ROAR = 55100, }; /*###### ## boss_moorabi ######*/ struct boss_moorabiAI : public ScriptedAI { boss_moorabiAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_gundrak*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } instance_gundrak* m_pInstance; bool m_bIsRegularMode; uint32 m_uiStabTimer; // used for stab and gore uint32 m_uiQuakeTimer; // used for quake and ground tremor uint32 m_uiRoarTimer; // both roars on it uint32 m_uiTransformationTimer; uint32 m_uiPreviousTimer; bool m_bMammothPhase; void Reset() override { m_bMammothPhase = false; m_uiStabTimer = 8000; m_uiQuakeTimer = 1000; m_uiRoarTimer = 7000; m_uiTransformationTimer = 10000; m_uiPreviousTimer = 10000; } void Aggro(Unit* /*pWho*/) override { DoScriptText(SAY_AGGRO, m_creature); DoCastSpellIfCan(m_creature, SPELL_MOJO_FRENZY); if (m_pInstance) m_pInstance->SetData(TYPE_MOORABI, IN_PROGRESS); } void KilledUnit(Unit* /*pVictim*/) override { switch (urand(0, 2)) { case 0: DoScriptText(SAY_SLAY_1, m_creature); break; case 1: DoScriptText(SAY_SLAY_2, m_creature); break; case 2: DoScriptText(SAY_SLAY_3, m_creature); break; } } void JustDied(Unit* /*pKiller*/) override { DoScriptText(SAY_DEATH, m_creature); if (m_pInstance) m_pInstance->SetData(TYPE_MOORABI, DONE); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_creature->HasAura(SPELL_TRANSFORMATION) && !m_bMammothPhase) { DoScriptText(EMOTE_TRANSFORMED, m_creature); m_bMammothPhase = true; // Set the achievement to failed if (m_pInstance) m_pInstance->SetLessRabiAchievementCriteria(false); } if (m_uiRoarTimer < uiDiff) { DoCastSpellIfCan(m_creature->getVictim(), m_bMammothPhase ? SPELL_NUMBING_ROAR : SPELL_NUMBING_SHOUT); m_uiRoarTimer = 20000; } else m_uiRoarTimer -= uiDiff; if (m_uiQuakeTimer < uiDiff) { DoScriptText(SAY_QUAKE, m_creature); DoCastSpellIfCan(m_creature->getVictim(), m_bMammothPhase ? SPELL_QUAKE : SPELL_GROUND_TREMOR); m_uiQuakeTimer = m_bMammothPhase ? 13000 : 18000; } else m_uiQuakeTimer -= uiDiff; if (m_uiStabTimer < uiDiff) { if (m_bMammothPhase) DoCastSpellIfCan(m_creature->getVictim(), m_bIsRegularMode ? SPELL_DETERMINED_GORE : SPELL_DETERMINED_GORE_H); else DoCastSpellIfCan(m_creature->getVictim(), SPELL_DETERMINED_STAB); m_uiStabTimer = 7000; } else m_uiStabTimer -= uiDiff; // check only in troll phase if (!m_bMammothPhase) { if (m_uiTransformationTimer < uiDiff) { DoScriptText(SAY_TRANSFORM, m_creature); DoScriptText(EMOTE_TRANSFORM, m_creature); DoCastSpellIfCan(m_creature, SPELL_TRANSFORMATION); m_uiPreviousTimer *= 0.8; m_uiTransformationTimer = m_uiPreviousTimer; } else m_uiTransformationTimer -= uiDiff; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_moorabi(Creature* pCreature) { return new boss_moorabiAI(pCreature); } void AddSC_boss_moorabi() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_moorabi"; pNewScript->GetAI = &GetAI_boss_moorabi; pNewScript->RegisterSelf(); }
Exxenoz/mangos-wotlk
src/scriptdev2/scripts/northrend/gundrak/boss_moorabi.cpp
C++
gpl-2.0
5,803
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: boss_erekem SD%Complete: 90 SDComment: Timers may need adjustments SDCategory: Violet Hold EndScriptData */ #include "precompiled.h" #include "violet_hold.h" enum { SAY_AGGRO = -1608012, SAY_ADD_DIE_1 = -1608013, SAY_ADD_DIE_2 = -1608014, SAY_DEATH = -1608018, // A few Sound IDs on SLAY, if there _is_ text related, fields -1608015 to -1608017 are free SOUND_ID_SLAY_1 = 14222, SOUND_ID_SLAY_2 = 14223, SOUND_ID_SLAY_3 = 14224, SPELL_BLOODLUST = 54516, SPELL_BREAK_BONDS_H = 59463, SPELL_CHAIN_HEAL = 54481, SPELL_CHAIN_HEAL_H = 59473, SPELL_EARTH_SHIELD = 54479, SPELL_EARTH_SHIELD_H = 59471, SPELL_EARTH_SHOCK = 54511, SPELL_LIGHTNING_BOLT = 53044, SPELL_STORMSTRIKE = 51876, // Spells of adds SPELL_GUSHING_WOUND = 39215, SPELL_HOWLING_SCREECH = 54463, SPELL_STRIKE = 14516 }; struct boss_erekemAI : public ScriptedAI { boss_erekemAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_violet_hold*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } instance_violet_hold* m_pInstance; bool m_bIsRegularMode; uint32 m_uiBreakBondsTimer; uint32 m_uiChainHealTimer; uint32 m_uiEarthShieldTimer; uint32 m_uiEarthShockTimer; uint32 m_uiSpecialSpellTimer; uint8 m_uiGuardiansDead; void Reset() override { m_uiSpecialSpellTimer = 0; m_uiEarthShieldTimer = urand(2000, 3000); m_uiEarthShockTimer = urand(4000, 9000); m_uiChainHealTimer = urand(5000, 15000); m_uiBreakBondsTimer = urand(25000, 30000); m_uiGuardiansDead = 0; } void Aggro(Unit* /*pWho*/) override { DoScriptText(SAY_AGGRO, m_creature); } void JustDied(Unit* /*pKiller*/) override { DoScriptText(SAY_DEATH, m_creature); } void KilledUnit(Unit* /*pVictim*/) override { switch (urand(0, 2)) { case 0: DoPlaySoundToSet(m_creature, SOUND_ID_SLAY_1); break; case 1: DoPlaySoundToSet(m_creature, SOUND_ID_SLAY_2); break; case 2: DoPlaySoundToSet(m_creature, SOUND_ID_SLAY_3); break; } } void GuardianJustDied() { DoScriptText(!m_uiGuardiansDead ? SAY_ADD_DIE_1 : SAY_ADD_DIE_2, m_creature); ++m_uiGuardiansDead; // cast bloodlust if both guards are dead if (m_uiGuardiansDead == 2) DoCastSpellIfCan(m_creature, SPELL_BLOODLUST, CAST_INTERRUPT_PREVIOUS); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_uiEarthShieldTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_EARTH_SHIELD : SPELL_EARTH_SHIELD_H, CAST_AURA_NOT_PRESENT) == CAST_OK) m_uiEarthShieldTimer = urand(25000, 30000); } else m_uiEarthShieldTimer -= uiDiff; if (m_uiEarthShockTimer < uiDiff) { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) { if (DoCastSpellIfCan(pTarget, SPELL_EARTH_SHOCK) == CAST_OK) m_uiEarthShockTimer = urand(8000, 13000); } } else m_uiEarthShockTimer -= uiDiff; if (m_uiChainHealTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_CHAIN_HEAL : SPELL_CHAIN_HEAL_H) == CAST_OK) m_uiChainHealTimer = urand(15000, 25000); } else m_uiChainHealTimer -= uiDiff; // Cast Stormstrike only if both guards are down if (m_uiSpecialSpellTimer < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), m_uiGuardiansDead == 2 ? SPELL_STORMSTRIKE : SPELL_LIGHTNING_BOLT) == CAST_OK) m_uiSpecialSpellTimer = urand(2000, 3000); } else m_uiSpecialSpellTimer -= uiDiff; // Break bonds only on heroic if (!m_bIsRegularMode) { if (m_uiBreakBondsTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_BREAK_BONDS_H) == CAST_OK) m_uiBreakBondsTimer = urand(25000, 30000); } else m_uiBreakBondsTimer -= uiDiff; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_erekem(Creature* pCreature) { return new boss_erekemAI(pCreature); } struct npc_erekem_guardAI : public ScriptedAI { npc_erekem_guardAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = ((instance_violet_hold*)pCreature->GetInstanceData()); Reset(); } instance_violet_hold* m_pInstance; uint32 m_uiGushingWoundTimer; uint32 m_uiHowlingScreechTimer; uint32 m_uiStrikeTimer; void Reset() override { m_uiGushingWoundTimer = urand(9000, 14000); m_uiHowlingScreechTimer = urand(8000, 12000); m_uiStrikeTimer = urand(5000, 7000); } void JustDied(Unit* /*pKiller*/) override { if (!m_pInstance) return; if (Creature* pBoss = m_pInstance->GetSingleCreatureFromStorage(m_pInstance->GetData(TYPE_EREKEM) != DONE ? NPC_EREKEM : NPC_ARAKKOA)) { if (!pBoss->isAlive()) return; ((boss_erekemAI*)pBoss->AI())->GuardianJustDied(); } } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_uiGushingWoundTimer < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_GUSHING_WOUND) == CAST_OK) m_uiGushingWoundTimer = urand(25000, 30000); } else m_uiGushingWoundTimer -= uiDiff; if (m_uiHowlingScreechTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_HOWLING_SCREECH) == CAST_OK) m_uiHowlingScreechTimer = urand(10000, 16000); } else m_uiHowlingScreechTimer -= uiDiff; if (m_uiStrikeTimer < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_STRIKE) == CAST_OK) m_uiStrikeTimer = urand(5000, 7000); } else m_uiStrikeTimer -= uiDiff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_npc_erekem_guard(Creature* pCreature) { return new npc_erekem_guardAI(pCreature); } void AddSC_boss_erekem() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_erekem"; pNewScript->GetAI = &GetAI_boss_erekem; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "npc_erekem_guard"; pNewScript->GetAI = &GetAI_npc_erekem_guard; pNewScript->RegisterSelf(); }
Exxenoz/mangos-wotlk
src/scriptdev2/scripts/northrend/violet_hold/boss_erekem.cpp
C++
gpl-2.0
8,075
<?php /** * Outputs the RSS2 XML format comment feed using the feed-rss2.php file in * wp-includes folder. This file only sets the feed format and includes the * feed-rss2-comments.php. * * This file is no longer used in WordPress and while it is not deprecated now. * This file will most likely be deprecated or removed in a later version. * * The link for the rss2 comment feed is /index.php?feed=rss2&withcomments=1 * with permalinks off. * * @package WordPress */ if (empty($wp)) { require_once('./wp-load.php'); wp('feed=rss2&withcomments=1'); } require (ABSPATH . WPINC . '/feed-rss2-comments.php'); ?>
localshred/dtraders
wp-commentsrss2.php
PHP
gpl-2.0
625
<?php /** * Credits administration panel. * * @package WordPress * @subpackage Administration */ /** WordPress Administration Bootstrap */ require_once __DIR__ . '/admin.php'; require_once __DIR__ . '/includes/credits.php'; $title = __( 'Credits' ); list( $display_version ) = explode( '-', get_bloginfo( 'version' ) ); require_once ABSPATH . 'wp-admin/admin-header.php'; $credits = wp_credits(); ?> <div class="wrap about__container"> <div class="about__header"> <div class="about__header-image"> <img alt="<?php _e( 'Code is Poetry' ); ?>" src="<?php echo admin_url( 'images/about-badge.svg' ); ?>" /> </div> <div class="about__header-container"> <div class="about__header-title"> <p> <?php _e( 'WordPress' ); ?> <?php echo $display_version; ?> </p> </div> <div class="about__header-text"> <?php _e( 'Jazz up your stories in an editor that’s cleaner, crisper, and does more to get out of your way.' ); ?> </div> </div> <nav class="about__header-navigation nav-tab-wrapper wp-clearfix" aria-label="<?php esc_attr_e( 'Secondary menu' ); ?>"> <a href="about.php" class="nav-tab"><?php _e( 'What&#8217;s New' ); ?></a> <a href="credits.php" class="nav-tab nav-tab-active" aria-current="page"><?php _e( 'Credits' ); ?></a> <a href="freedoms.php" class="nav-tab"><?php _e( 'Freedoms' ); ?></a> <a href="privacy.php" class="nav-tab"><?php _e( 'Privacy' ); ?></a> </nav> </div> <div class="about__section is-feature"> <div class="column"> <h1><?php _e( 'Credits' ); ?></h1> <?php if ( ! $credits ) : ?> <p> <?php printf( /* translators: 1: https://wordpress.org/about/, 2: https://make.wordpress.org/ */ __( 'WordPress is created by a <a href="%1$s">worldwide team</a> of passionate individuals. <a href="%2$s">Get involved in WordPress</a>.' ), __( 'https://wordpress.org/about/' ), __( 'https://make.wordpress.org/' ) ); ?> </p> <?php else : ?> <p> <?php _e( 'WordPress is created by a worldwide team of passionate individuals.' ); ?> </p> <p> <?php printf( /* translators: %s: https://make.wordpress.org/ */ __( 'Want to see your name in lights on this page? <a href="%s">Get involved in WordPress</a>.' ), __( 'https://make.wordpress.org/' ) ); ?> </p> <?php endif; ?> </div> </div> <?php if ( ! $credits ) { echo '</div>'; require_once ABSPATH . 'wp-admin/admin-footer.php'; exit; } ?> <hr /> <div class="about__section"> <div class="column has-subtle-background-color"> <?php wp_credits_section_title( $credits['groups']['core-developers'] ); ?> <?php wp_credits_section_list( $credits, 'core-developers' ); ?> <?php wp_credits_section_list( $credits, 'contributing-developers' ); ?> </div> </div> <hr /> <div class="about__section"> <div class="column"> <?php wp_credits_section_title( $credits['groups']['props'] ); ?> <?php wp_credits_section_list( $credits, 'props' ); ?> </div> </div> <hr /> <?php if ( isset( $credits['groups']['translators'] ) || isset( $credits['groups']['validators'] ) ) : ?> <div class="about__section"> <div class="column"> <?php wp_credits_section_title( $credits['groups']['validators'] ); ?> <?php wp_credits_section_list( $credits, 'validators' ); ?> <?php wp_credits_section_list( $credits, 'translators' ); ?> </div> </div> <hr /> <?php endif; ?> <div class="about__section"> <div class="column"> <?php wp_credits_section_title( $credits['groups']['libraries'] ); ?> <?php wp_credits_section_list( $credits, 'libraries' ); ?> </div> </div> </div> <?php require_once ABSPATH . 'wp-admin/admin-footer.php'; return; // These are strings returned by the API that we want to be translatable. __( 'Project Leaders' ); /* translators: %s: The current WordPress version number. */ __( 'Core Contributors to WordPress %s' ); __( 'Noteworthy Contributors' ); __( 'Cofounder, Project Lead' ); __( 'Lead Developer' ); __( 'Release Lead' ); __( 'Release Design Lead' ); __( 'Release Deputy' ); __( 'Core Developer' ); __( 'External Libraries' );
TheThumbsupguy/Ross-Upholstery-Inc
wp-admin/credits.php
PHP
gpl-2.0
4,135
from Source import Source from Components.Element import cached from Components.SystemInfo import SystemInfo from enigma import eServiceReference StreamServiceList = [] class StreamService(Source): def __init__(self, navcore): Source.__init__(self) self.ref = None self.__service = None self.navcore = navcore def serviceEvent(self, event): pass @cached def getService(self): return self.__service service = property(getService) def handleCommand(self, cmd): print "[StreamService] handle command", cmd self.ref = eServiceReference(cmd) def recordEvent(self, service, event): if service is self.__service: return print "[StreamService] RECORD event for us:", service self.changed((self.CHANGED_ALL, )) def execBegin(self): if self.ref is None: print "[StreamService] has no service ref set" return print "[StreamService]e execBegin", self.ref.toString() if SystemInfo["CanNotDoSimultaneousTranscodeAndPIP"]: from Screens.InfoBar import InfoBar if InfoBar.instance and hasattr(InfoBar.instance.session, 'pipshown') and InfoBar.instance.session.pipshown: hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP() print "[StreamService] try to disable pip before start stream" if hasattr(InfoBar.instance.session, 'pip'): del InfoBar.instance.session.pip InfoBar.instance.session.pipshown = False self.__service = self.navcore.recordService(self.ref) self.navcore.record_event.append(self.recordEvent) if self.__service is not None: if self.__service.__deref__() not in StreamServiceList: StreamServiceList.append(self.__service.__deref__()) self.__service.prepareStreaming() self.__service.start() def execEnd(self): print "[StreamService] execEnd", self.ref.toString() self.navcore.record_event.remove(self.recordEvent) if self.__service is not None: if self.__service.__deref__() in StreamServiceList: StreamServiceList.remove(self.__service.__deref__()) self.navcore.stopRecordService(self.__service) self.__service = None self.ref = None
Dima73/enigma2
lib/python/Components/Sources/StreamService.py
Python
gpl-2.0
2,074
<?php /** * Template Name: Wide Page Template * * Description: A page template that provides a key component of WordPress as a CMS * by meeting the need for a carefully crafted introductory page. The front page template * in Twenty Twelve consists of a page content area for adding text, images, video -- * anything you'd like -- followed by front-page-only widgets in one or two columns. * * @package WordPress * @subpackage Plum_Tree * @since Plum Tree 0.1 */ get_header(); ?> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php if ( (get_option('blog_spacer_bg_color') != '') && (get_option('blog_spacer_bg_color') != '#fff') ) { $spacer_bg = 'style="background:'.get_option('blog_spacer_bg_color').';"'; } elseif ( get_option('blog_spacer_custom_pattern') != '' ) { $spacer_bg = 'style="background: url('.get_option('blog_spacer_custom_pattern').') repeat;"'; } else { $spacer_bg = 'style="background: url('.get_template_directory_uri().'/assets/spacer-'.get_option('blog_spacer_default_pattern').'.png) repeat;"'; } ?> <div class="spacer" <?php echo $spacer_bg; ?> data-stellar-background-ratio="0.5"> <div class="container-fluid"> <div class="row-fluid"> <h1 class="spacer-title" data-stellar-ratio="0.93"><?php the_title(); ?></h1> </div> </div> </div> <section id="content" role="main" class="site-content"><!-- Main content --> <div class="entry-content"> <?php the_content(); ?> </div><!-- .entry-content --> <?php endwhile; ?> <?php endif; ?> </section><!-- Main content --> <?php get_footer(); ?>
as1anhawk/ICT2_Team3
wp-content/themes/clickboutique/page-templates/page-wide.php
PHP
gpl-2.0
1,843
int main() { if(true) {return 1;} else if(true) {return 1;} else {return 1;} }
brmqk3/uncrustify
tests/output/cpp/34171-i1181.cpp
C++
gpl-2.0
81
#!/usr/bin/python # -*- coding: utf-8 -*- # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: aci_tenant_span_dst_group short_description: Manage SPAN destination groups (span:DestGrp) description: - Manage SPAN destination groups on Cisco ACI fabrics. notes: - The C(tenant) used must exist before using this module in your playbook. The M(aci_tenant) module can be used for this. - More information about the internal APIC class B(span:DestGrp) from L(the APIC Management Information Model reference,https://developer.cisco.com/docs/apic-mim-ref/). author: - Dag Wieers (@dagwieers) version_added: '2.4' options: dst_group: description: - The name of the SPAN destination group. required: yes aliases: [ name ] description: description: - The description of the SPAN destination group. aliases: [ descr ] tenant: description: - The name of the tenant. required: yes aliases: [ tenant_name ] state: description: - Use C(present) or C(absent) for adding or removing. - Use C(query) for listing an object or multiple objects. choices: [ absent, present, query ] default: present extends_documentation_fragment: aci ''' # FIXME: Add more, better examples EXAMPLES = r''' - aci_tenant_span_dst_group: host: apic username: admin password: SomeSecretPassword dst_group: '{{ dst_group }}' description: '{{ descr }}' tenant: '{{ tenant }}' ''' RETURN = r''' current: description: The existing configuration from the APIC after the module has finished returned: success type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production environment", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] error: description: The error information as returned from the APIC returned: failure type: dict sample: { "code": "122", "text": "unknown managed object class foo" } raw: description: The raw output returned by the APIC REST API (xml or json) returned: parse error type: string sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class foo"/></imdata>' sent: description: The actual/minimal configuration pushed to the APIC returned: info type: list sample: { "fvTenant": { "attributes": { "descr": "Production environment" } } } previous: description: The original configuration from the APIC before the module has started returned: info type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] proposed: description: The assembled configuration from the user-provided parameters returned: info type: dict sample: { "fvTenant": { "attributes": { "descr": "Production environment", "name": "production" } } } filter_string: description: The filter string used for the request returned: failure or debug type: string sample: ?rsp-prop-include=config-only method: description: The HTTP method used for the request to the APIC returned: failure or debug type: string sample: POST response: description: The HTTP response from the APIC returned: failure or debug type: string sample: OK (30 bytes) status: description: The HTTP status from the APIC returned: failure or debug type: int sample: 200 url: description: The HTTP url used for the request to the APIC returned: failure or debug type: string sample: https://10.11.12.13/api/mo/uni/tn-production.json ''' from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec from ansible.module_utils.basic import AnsibleModule def main(): argument_spec = aci_argument_spec() argument_spec.update( dst_group=dict(type='str', required=False, aliases=['name']), # Not required for querying all objects tenant=dict(type='str', required=False, aliases=['tenant_name']), # Not required for querying all objects description=dict(type='str', aliases=['descr']), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['dst_group', 'tenant']], ['state', 'present', ['dst_group', 'tenant']], ], ) dst_group = module.params['dst_group'] description = module.params['description'] state = module.params['state'] tenant = module.params['tenant'] aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class='fvTenant', aci_rn='tn-{0}'.format(tenant), filter_target='eq(fvTenant.name, "{0}")'.format(tenant), module_object=tenant, ), subclass_1=dict( aci_class='spanDestGrp', aci_rn='destgrp-{0}'.format(dst_group), filter_target='eq(spanDestGrp.name, "{0}")'.format(dst_group), module_object=dst_group, ), ) aci.get_existing() if state == 'present': aci.payload( aci_class='spanDestGrp', class_config=dict( name=dst_group, descr=description, ), ) aci.get_diff(aci_class='spanDestGrp') aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json() if __name__ == "__main__": main()
hryamzik/ansible
lib/ansible/modules/network/aci/aci_tenant_span_dst_group.py
Python
gpl-3.0
6,414
Clazz.declarePackage ("JSV.common"); Clazz.load (["java.lang.Enum", "JSV.source.JDXDataObject", "JU.Lst"], "JSV.common.Spectrum", ["java.lang.Boolean", "$.Double", "java.util.Hashtable", "JU.PT", "JSV.common.Coordinate", "$.Parameters", "$.PeakInfo", "JSV.source.JDXSourceStreamTokenizer", "JU.Logger"], function () { c$ = Clazz.decorateAsClass (function () { this.subSpectra = null; this.peakList = null; this.piUnitsX = null; this.piUnitsY = null; this.selectedPeak = null; this.highlightedPeak = null; this.specShift = 0; this.currentSubSpectrumIndex = 0; this.$isForcedSubset = false; this.id = ""; this.convertedSpectrum = null; this.userYFactor = 1; this.exportXAxisLeftToRight = false; this.fillColor = null; Clazz.instantialize (this, arguments); }, JSV.common, "Spectrum", JSV.source.JDXDataObject); Clazz.prepareFields (c$, function () { this.peakList = new JU.Lst (); }); Clazz.overrideMethod (c$, "finalize", function () { System.out.println ("JDXSpectrum " + this + " finalized " + this.title); }); Clazz.defineMethod (c$, "dispose", function () { }); Clazz.defineMethod (c$, "isForcedSubset", function () { return this.$isForcedSubset; }); Clazz.defineMethod (c$, "setId", function (id) { this.id = id; }, "~S"); Clazz.makeConstructor (c$, function () { Clazz.superConstructor (this, JSV.common.Spectrum, []); this.headerTable = new JU.Lst (); this.xyCoords = new Array (0); this.parent = this; }); Clazz.defineMethod (c$, "copy", function () { var newSpectrum = new JSV.common.Spectrum (); this.copyTo (newSpectrum); newSpectrum.setPeakList (this.peakList, this.piUnitsX, null); newSpectrum.fillColor = this.fillColor; return newSpectrum; }); Clazz.defineMethod (c$, "getXYCoords", function () { return this.getCurrentSubSpectrum ().xyCoords; }); Clazz.defineMethod (c$, "getPeakList", function () { return this.peakList; }); Clazz.defineMethod (c$, "setPeakList", function (list, piUnitsX, piUnitsY) { this.peakList = list; this.piUnitsX = piUnitsX; this.piUnitsY = piUnitsY; for (var i = list.size (); --i >= 0; ) this.peakList.get (i).spectrum = this; if (JU.Logger.debugging) JU.Logger.info ("Spectrum " + this.getTitle () + " peaks: " + list.size ()); return list.size (); }, "JU.Lst,~S,~S"); Clazz.defineMethod (c$, "selectPeakByFileIndex", function (filePath, index, atomKey) { if (this.peakList != null && this.peakList.size () > 0 && (atomKey == null || this.sourceID.equals (index))) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkFileIndex (filePath, index, atomKey)) { System.out.println ("selecting peak by FileIndex " + this + " " + this.peakList.get (i)); return (this.selectedPeak = this.peakList.get (i)); } return null; }, "~S,~S,~S"); Clazz.defineMethod (c$, "selectPeakByFilePathTypeModel", function (filePath, type, model) { if (this.peakList != null && this.peakList.size () > 0) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkFileTypeModel (filePath, type, model)) { System.out.println ("selecting peak byFilePathTypeModel " + this + " " + this.peakList.get (i)); return (this.selectedPeak = this.peakList.get (i)); } return null; }, "~S,~S,~S"); Clazz.defineMethod (c$, "matchesPeakTypeModel", function (type, model) { if (type.equals ("ID")) return (this.sourceID.equalsIgnoreCase (model)); if (this.peakList != null && this.peakList.size () > 0) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkTypeModel (type, model)) return true; return false; }, "~S,~S"); Clazz.defineMethod (c$, "setSelectedPeak", function (peak) { this.selectedPeak = peak; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "setHighlightedPeak", function (peak) { this.highlightedPeak = peak; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "getSelectedPeak", function () { return this.selectedPeak; }); Clazz.defineMethod (c$, "getModelPeakInfoForAutoSelectOnLoad", function () { if (this.peakList != null) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).autoSelectOnLoad ()) return this.peakList.get (i); return null; }); Clazz.defineMethod (c$, "getAssociatedPeakInfo", function (xPixel, coord) { this.selectedPeak = this.findPeakByCoord (xPixel, coord); return (this.selectedPeak == null ? this.getBasePeakInfo () : this.selectedPeak); }, "~N,JSV.common.Coordinate"); Clazz.defineMethod (c$, "findPeakByCoord", function (xPixel, coord) { if (coord != null && this.peakList != null && this.peakList.size () > 0) { var xVal = coord.getXVal (); var iBest = -1; var dBest = 1e100; for (var i = 0; i < this.peakList.size (); i++) { var d = this.peakList.get (i).checkRange (xPixel, xVal); if (d < dBest) { dBest = d; iBest = i; }} if (iBest >= 0) return this.peakList.get (iBest); }return null; }, "~N,JSV.common.Coordinate"); Clazz.defineMethod (c$, "getPeakTitle", function () { return (this.selectedPeak != null ? this.selectedPeak.getTitle () : this.highlightedPeak != null ? this.highlightedPeak.getTitle () : this.getTitleLabel ()); }); Clazz.defineMethod (c$, "getTitleLabel", function () { var type = (this.peakList == null || this.peakList.size () == 0 ? this.getQualifiedDataType () : this.peakList.get (0).getType ()); if (type != null && type.startsWith ("NMR")) { if (this.nucleusY != null && !this.nucleusY.equals ("?")) { type = "2D" + type; } else { type = this.nucleusX + type; }}return (type != null && type.length > 0 ? type + " " : "") + this.getTitle (); }); Clazz.defineMethod (c$, "setNextPeak", function (coord, istep) { if (this.peakList == null || this.peakList.size () == 0) return -1; var x0 = coord.getXVal () + istep * 0.000001; var ipt1 = -1; var ipt2 = -1; var dmin1 = 1.7976931348623157E308 * istep; var dmin2 = 0; for (var i = this.peakList.size (); --i >= 0; ) { var x = this.peakList.get (i).getX (); if (istep > 0) { if (x > x0 && x < dmin1) { ipt1 = i; dmin1 = x; } else if (x < x0 && x - x0 < dmin2) { ipt2 = i; dmin2 = x - x0; }} else { if (x < x0 && x > dmin1) { ipt1 = i; dmin1 = x; } else if (x > x0 && x - x0 > dmin2) { ipt2 = i; dmin2 = x - x0; }}} if (ipt1 < 0) { if (ipt2 < 0) return -1; ipt1 = ipt2; }return ipt1; }, "JSV.common.Coordinate,~N"); Clazz.defineMethod (c$, "getPercentYValueAt", function (x) { if (!this.isContinuous ()) return NaN; return this.getYValueAt (x); }, "~N"); Clazz.defineMethod (c$, "getYValueAt", function (x) { return JSV.common.Coordinate.getYValueAt (this.xyCoords, x); }, "~N"); Clazz.defineMethod (c$, "setUserYFactor", function (userYFactor) { this.userYFactor = userYFactor; }, "~N"); Clazz.defineMethod (c$, "getUserYFactor", function () { return this.userYFactor; }); Clazz.defineMethod (c$, "getConvertedSpectrum", function () { return this.convertedSpectrum; }); Clazz.defineMethod (c$, "setConvertedSpectrum", function (spectrum) { this.convertedSpectrum = spectrum; }, "JSV.common.Spectrum"); c$.taConvert = Clazz.defineMethod (c$, "taConvert", function (spectrum, mode) { if (!spectrum.isContinuous ()) return spectrum; switch (mode) { case JSV.common.Spectrum.IRMode.NO_CONVERT: return spectrum; case JSV.common.Spectrum.IRMode.TO_ABS: if (!spectrum.isTransmittance ()) return spectrum; break; case JSV.common.Spectrum.IRMode.TO_TRANS: if (!spectrum.isAbsorbance ()) return spectrum; break; case JSV.common.Spectrum.IRMode.TOGGLE: break; } var spec = spectrum.getConvertedSpectrum (); return (spec != null ? spec : spectrum.isAbsorbance () ? JSV.common.Spectrum.toT (spectrum) : JSV.common.Spectrum.toA (spectrum)); }, "JSV.common.Spectrum,JSV.common.Spectrum.IRMode"); c$.toT = Clazz.defineMethod (c$, "toT", function (spectrum) { if (!spectrum.isAbsorbance ()) return null; var xyCoords = spectrum.getXYCoords (); var newXYCoords = new Array (xyCoords.length); if (!JSV.common.Coordinate.isYInRange (xyCoords, 0, 4.0)) xyCoords = JSV.common.Coordinate.normalise (xyCoords, 0, 4.0); for (var i = 0; i < xyCoords.length; i++) newXYCoords[i] = new JSV.common.Coordinate ().set (xyCoords[i].getXVal (), JSV.common.Spectrum.toTransmittance (xyCoords[i].getYVal ())); return JSV.common.Spectrum.newSpectrum (spectrum, newXYCoords, "TRANSMITTANCE"); }, "JSV.common.Spectrum"); c$.toA = Clazz.defineMethod (c$, "toA", function (spectrum) { if (!spectrum.isTransmittance ()) return null; var xyCoords = spectrum.getXYCoords (); var newXYCoords = new Array (xyCoords.length); var isPercent = JSV.common.Coordinate.isYInRange (xyCoords, -2, 2); for (var i = 0; i < xyCoords.length; i++) newXYCoords[i] = new JSV.common.Coordinate ().set (xyCoords[i].getXVal (), JSV.common.Spectrum.toAbsorbance (xyCoords[i].getYVal (), isPercent)); return JSV.common.Spectrum.newSpectrum (spectrum, newXYCoords, "ABSORBANCE"); }, "JSV.common.Spectrum"); c$.newSpectrum = Clazz.defineMethod (c$, "newSpectrum", function (spectrum, newXYCoords, units) { var specNew = spectrum.copy (); specNew.setOrigin ("JSpecView Converted"); specNew.setOwner ("JSpecView Generated"); specNew.setXYCoords (newXYCoords); specNew.setYUnits (units); spectrum.setConvertedSpectrum (specNew); specNew.setConvertedSpectrum (spectrum); return specNew; }, "JSV.common.Spectrum,~A,~S"); c$.toAbsorbance = Clazz.defineMethod (c$, "toAbsorbance", function (x, isPercent) { return (Math.min (4.0, isPercent ? 2 - JSV.common.Spectrum.log10 (x) : -JSV.common.Spectrum.log10 (x))); }, "~N,~B"); c$.toTransmittance = Clazz.defineMethod (c$, "toTransmittance", function (x) { return (x <= 0 ? 1 : Math.pow (10, -x)); }, "~N"); c$.log10 = Clazz.defineMethod (c$, "log10", function (value) { return Math.log (value) / Math.log (10); }, "~N"); c$.process = Clazz.defineMethod (c$, "process", function (specs, irMode) { if (irMode === JSV.common.Spectrum.IRMode.TO_ABS || irMode === JSV.common.Spectrum.IRMode.TO_TRANS) for (var i = 0; i < specs.size (); i++) specs.set (i, JSV.common.Spectrum.taConvert (specs.get (i), irMode)); return true; }, "JU.Lst,JSV.common.Spectrum.IRMode"); Clazz.defineMethod (c$, "getSubSpectra", function () { return this.subSpectra; }); Clazz.defineMethod (c$, "getCurrentSubSpectrum", function () { return (this.subSpectra == null ? this : this.subSpectra.get (this.currentSubSpectrumIndex)); }); Clazz.defineMethod (c$, "advanceSubSpectrum", function (dir) { return this.setCurrentSubSpectrum (this.currentSubSpectrumIndex + dir); }, "~N"); Clazz.defineMethod (c$, "setCurrentSubSpectrum", function (n) { return (this.currentSubSpectrumIndex = JSV.common.Coordinate.intoRange (n, 0, this.subSpectra.size () - 1)); }, "~N"); Clazz.defineMethod (c$, "addSubSpectrum", function (spectrum, forceSub) { if (!forceSub && (this.numDim < 2 || this.blockID != spectrum.blockID) || !JSV.common.Spectrum.allowSubSpec (this, spectrum)) return false; this.$isForcedSubset = forceSub; if (this.subSpectra == null) { this.subSpectra = new JU.Lst (); this.addSubSpectrum (this, true); }this.subSpectra.addLast (spectrum); spectrum.parent = this; return true; }, "JSV.common.Spectrum,~B"); Clazz.defineMethod (c$, "getSubIndex", function () { return (this.subSpectra == null ? -1 : this.currentSubSpectrumIndex); }); Clazz.defineMethod (c$, "setExportXAxisDirection", function (leftToRight) { this.exportXAxisLeftToRight = leftToRight; }, "~B"); Clazz.defineMethod (c$, "isExportXAxisLeftToRight", function () { return this.exportXAxisLeftToRight; }); Clazz.defineMethod (c$, "getInfo", function (key) { var info = new java.util.Hashtable (); if ("id".equalsIgnoreCase (key)) { info.put (key, this.id); return info; }info.put ("id", this.id); JSV.common.Parameters.putInfo (key, info, "specShift", Double.$valueOf (this.specShift)); var justHeader = ("header".equals (key)); if (!justHeader && key != null) { for (var i = this.headerTable.size (); --i >= 0; ) { var entry = this.headerTable.get (i); if (entry[0].equalsIgnoreCase (key) || entry[2].equalsIgnoreCase (key)) { info.put (key, entry[1]); return info; }} }var head = new java.util.Hashtable (); var list = this.getHeaderRowDataAsArray (); for (var i = 0; i < list.length; i++) { var label = JSV.source.JDXSourceStreamTokenizer.cleanLabel (list[i][0]); if (key != null && !justHeader && !label.equals (key)) continue; var val = JSV.common.Spectrum.fixInfoValue (list[i][1]); if (key == null) { var data = new java.util.Hashtable (); data.put ("value", val); data.put ("index", Integer.$valueOf (i + 1)); info.put (label, data); } else { info.put (label, val); }} if (head.size () > 0) info.put ("header", head); if (!justHeader) { JSV.common.Parameters.putInfo (key, info, "titleLabel", this.getTitleLabel ()); JSV.common.Parameters.putInfo (key, info, "type", this.getDataType ()); JSV.common.Parameters.putInfo (key, info, "isHZToPPM", Boolean.$valueOf (this.$isHZtoPPM)); JSV.common.Parameters.putInfo (key, info, "subSpectrumCount", Integer.$valueOf (this.subSpectra == null ? 0 : this.subSpectra.size ())); }return info; }, "~S"); c$.fixInfoValue = Clazz.defineMethod (c$, "fixInfoValue", function (info) { try { return (Integer.$valueOf (info)); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } try { return (Double.$valueOf (info)); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } return info; }, "~S"); Clazz.overrideMethod (c$, "toString", function () { return this.getTitleLabel (); }); Clazz.defineMethod (c$, "findMatchingPeakInfo", function (pi) { for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkTypeMatch (pi)) return this.peakList.get (i); return null; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "getBasePeakInfo", function () { return (this.peakList.size () == 0 ? new JSV.common.PeakInfo () : new JSV.common.PeakInfo (" baseModel=\"\" " + this.peakList.get (0))); }); Clazz.defineMethod (c$, "getAxisLabel", function (isX) { var units = (isX ? this.piUnitsX : this.piUnitsY); if (units == null) units = (isX ? this.xLabel : this.yLabel); if (units == null) units = (isX ? this.xUnits : this.yUnits); return (units == null ? "" : units.equalsIgnoreCase ("WAVENUMBERS") ? "1/cm" : units.equalsIgnoreCase ("nanometers") ? "nm" : units); }, "~B"); Clazz.defineMethod (c$, "findXForPeakNearest", function (x) { return JSV.common.Coordinate.findXForPeakNearest (this.xyCoords, x, this.isInverted ()); }, "~N"); Clazz.defineMethod (c$, "addSpecShift", function (dx) { if (dx != 0) { this.specShift += dx; JSV.common.Coordinate.shiftX (this.xyCoords, dx); if (this.subSpectra != null) for (var i = this.subSpectra.size (); --i >= 0; ) { var spec = this.subSpectra.get (i); if (spec !== this && spec !== this.parent) spec.addSpecShift (dx); } }return this.specShift; }, "~N"); c$.allowSubSpec = Clazz.defineMethod (c$, "allowSubSpec", function (s1, s2) { return (s1.is1D () == s2.is1D () && s1.xUnits.equalsIgnoreCase (s2.xUnits) && s1.isHNMR () == s2.isHNMR ()); }, "JSV.common.Spectrum,JSV.common.Spectrum"); c$.areXScalesCompatible = Clazz.defineMethod (c$, "areXScalesCompatible", function (s1, s2, isSubspecCheck, isLinkCheck) { var isNMR1 = s1.isNMR (); if (isNMR1 != s2.isNMR () || s1.isContinuous () != s2.isContinuous () || !isLinkCheck && !JSV.common.Spectrum.areUnitsCompatible (s1.xUnits, s2.xUnits)) return false; if (isSubspecCheck) { if (s1.is1D () != s2.is1D ()) return false; } else if (isLinkCheck) { if (!isNMR1) return true; } else if (!s1.is1D () || !s2.is1D ()) { return false; }return (!isNMR1 || s2.is1D () && s1.parent.nucleusX.equals (s2.parent.nucleusX)); }, "JSV.common.Spectrum,JSV.common.Spectrum,~B,~B"); c$.areUnitsCompatible = Clazz.defineMethod (c$, "areUnitsCompatible", function (u1, u2) { if (u1.equalsIgnoreCase (u2)) return true; u1 = u1.toUpperCase (); u2 = u2.toUpperCase (); return (u1.equals ("HZ") && u2.equals ("PPM") || u1.equals ("PPM") && u2.equals ("HZ")); }, "~S,~S"); c$.areLinkableX = Clazz.defineMethod (c$, "areLinkableX", function (s1, s2) { return (s1.isNMR () && s2.isNMR () && s1.nucleusX.equals (s2.nucleusX)); }, "JSV.common.Spectrum,JSV.common.Spectrum"); c$.areLinkableY = Clazz.defineMethod (c$, "areLinkableY", function (s1, s2) { return (s1.isNMR () && s2.isNMR () && s1.nucleusX.equals (s2.nucleusY)); }, "JSV.common.Spectrum,JSV.common.Spectrum"); Clazz.defineMethod (c$, "setNHydrogens", function (nH) { this.nH = nH; }, "~N"); Clazz.defineMethod (c$, "getPeakWidth", function () { var w = this.getLastX () - this.getFirstX (); return (w / 100); }); Clazz.defineMethod (c$, "setSimulated", function (filePath) { this.isSimulation = true; var s = this.sourceID; if (s.length == 0) s = JU.PT.rep (filePath, "http://SIMULATION/", ""); if (s.indexOf ("MOL=") >= 0) s = ""; this.title = "SIMULATED " + JU.PT.rep (s, "$", ""); }, "~S"); Clazz.defineMethod (c$, "setFillColor", function (color) { this.fillColor = color; if (this.convertedSpectrum != null) this.convertedSpectrum.fillColor = color; }, "javajs.api.GenericColor"); Clazz.pu$h(self.c$); c$ = Clazz.declareType (JSV.common.Spectrum, "IRMode", Enum); c$.getMode = Clazz.defineMethod (c$, "getMode", function (a) { switch (a == null ? 'I' : a.toUpperCase ().charAt (0)) { case 'A': return JSV.common.Spectrum.IRMode.TO_ABS; case 'T': return (a.equalsIgnoreCase ("TOGGLE") ? JSV.common.Spectrum.IRMode.TOGGLE : JSV.common.Spectrum.IRMode.TO_TRANS); case 'N': return JSV.common.Spectrum.IRMode.NO_CONVERT; default: return JSV.common.Spectrum.IRMode.TOGGLE; } }, "~S"); Clazz.defineEnumConstant (c$, "NO_CONVERT", 0, []); Clazz.defineEnumConstant (c$, "TO_TRANS", 1, []); Clazz.defineEnumConstant (c$, "TO_ABS", 2, []); Clazz.defineEnumConstant (c$, "TOGGLE", 3, []); c$ = Clazz.p0p (); Clazz.defineStatics (c$, "MAXABS", 4); });
davidbuzatto/CryProteinModelsComparisonLab
web/j2s/JSV/common/Spectrum.js
JavaScript
gpl-3.0
18,056
<?php return array( 'group_exists' => 'குழு ஏற்கனவே உள்ளது!', 'group_not_found' => 'குழு [: id] இல்லை.', 'group_name_required' => 'பெயர் புலம் தேவை', 'success' => array( 'create' => 'குழு வெற்றிகரமாக உருவாக்கப்பட்டது.', 'update' => 'குழு வெற்றிகரமாக புதுப்பிக்கப்பட்டது.', 'delete' => 'குழு வெற்றிகரமாக நீக்கப்பட்டது.', ), 'delete' => array( 'confirm' => 'இந்த குழுவையை நிச்சயமாக நீக்க விரும்புகிறீர்களா?', 'create' => 'குழுவை உருவாக்கும் ஒரு சிக்கல் இருந்தது. தயவு செய்து மீண்டும் முயற்சிக்கவும்.', 'update' => 'குழுவை புதுப்பிப்பதில் சிக்கல் ஏற்பட்டது. தயவு செய்து மீண்டும் முயற்சிக்கவும்.', 'delete' => 'குழுவை நீக்குவதில் ஒரு சிக்கல் இருந்தது. தயவு செய்து மீண்டும் முயற்சிக்கவும்.', ), );
uberbrady/snipe-it
resources/lang/ta/admin/groups/message.php
PHP
agpl-3.0
1,553
/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * * 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. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "PrecompiledHeaders.h" #include "Uuid.h" // http://stackoverflow.com/a/1626302 extern "C" { #ifdef WIN32 #include <rpc.h> #else #include <uuid/uuid.h> #endif } #include <boost/filesystem.hpp> namespace Orthanc { namespace Toolbox { std::string GenerateUuid() { #ifdef WIN32 UUID uuid; UuidCreate ( &uuid ); unsigned char * str; UuidToStringA ( &uuid, &str ); std::string s( ( char* ) str ); RpcStringFreeA ( &str ); #else uuid_t uuid; uuid_generate_random ( uuid ); char s[37]; uuid_unparse ( uuid, s ); #endif return s; } bool IsUuid(const std::string& str) { if (str.size() != 36) { return false; } for (size_t i = 0; i < str.length(); i++) { if (i == 8 || i == 13 || i == 18 || i == 23) { if (str[i] != '-') return false; } else { if (!isalnum(str[i])) return false; } } return true; } bool StartsWithUuid(const std::string& str) { if (str.size() < 36) { return false; } if (str.size() == 36) { return IsUuid(str); } assert(str.size() > 36); if (!isspace(str[36])) { return false; } return IsUuid(str.substr(0, 36)); } static std::string CreateTemporaryPath(const char* extension) { #if BOOST_HAS_FILESYSTEM_V3 == 1 boost::filesystem::path tmpDir = boost::filesystem::temp_directory_path(); #elif defined(__linux__) boost::filesystem::path tmpDir("/tmp"); #else #error Support your platform here #endif // We use UUID to create unique path to temporary files std::string filename = "Orthanc-" + Orthanc::Toolbox::GenerateUuid(); if (extension != NULL) { filename.append(extension); } tmpDir /= filename; return tmpDir.string(); } TemporaryFile::TemporaryFile() : path_(CreateTemporaryPath(NULL)) { } TemporaryFile::TemporaryFile(const char* extension) : path_(CreateTemporaryPath(extension)) { } TemporaryFile::~TemporaryFile() { boost::filesystem::remove(path_); } } }
rbetancor/orthanc-webviewer
Orthanc/Uuid.cpp
C++
agpl-3.0
3,863
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.ui.faces.components.util; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import org.apache.struts.util.MessageResources; import org.fenixedu.academic.domain.Exam; import org.fenixedu.academic.domain.ExecutionCourse; import org.fenixedu.academic.domain.Project; import org.fenixedu.academic.domain.WrittenEvaluation; import org.fenixedu.academic.domain.WrittenTest; import org.fenixedu.academic.util.Bundle; import org.fenixedu.academic.util.DateFormatUtil; public class CalendarLink { private Calendar objectOccurrence; private String objectLinkLabel; private Map<String, String> linkParameters = new HashMap<String, String>(); private boolean asLink; public CalendarLink(boolean asLink) { setAsLink(asLink); } public CalendarLink() { this(true); } public CalendarLink(final ExecutionCourse executionCourse, final WrittenEvaluation writtenEvaluation, final Locale locale) { setObjectOccurrence(writtenEvaluation.getDay()); setObjectLinkLabel(constructCalendarPresentation(executionCourse, writtenEvaluation, locale)); } public CalendarLink(final ExecutionCourse executionCourse, final Project project, final Date date, final String tail, final Locale locale) { setObjectOccurrence(date); setObjectLinkLabel(constructCalendarPresentation(executionCourse, project, date, tail, locale)); } public void setObjectOccurrence(Calendar objectOccurrence) { this.objectOccurrence = objectOccurrence; } public void setObjectOccurrence(Date objectOccurrence) { final Calendar calendar = Calendar.getInstance(); calendar.setTime(objectOccurrence); this.objectOccurrence = calendar; } public Calendar getObjectOccurrence() { return this.objectOccurrence; } public void setObjectLinkLabel(String objectLinkLabel) { this.objectLinkLabel = objectLinkLabel; } public String getObjectLinkLabel() { return this.objectLinkLabel; } public void setLinkParameters(Map<String, String> linkParameters) { this.linkParameters = linkParameters; } public String giveLink(String editLinkPage) { final StringBuilder linkParameters = new StringBuilder(); linkParameters.append(editLinkPage); if (this.linkParameters != null && !this.linkParameters.isEmpty()) { linkParameters.append(editLinkPage.indexOf('?') > 0 ? '&' : '?'); for (final Iterator<Entry<String, String>> iterator = this.linkParameters.entrySet().iterator(); iterator.hasNext();) { final Entry<String, String> entry = iterator.next(); linkParameters.append(entry.getKey()); linkParameters.append('='); linkParameters.append(entry.getValue()); if (iterator.hasNext()) { linkParameters.append('&'); } } } return linkParameters.toString(); } public void addLinkParameter(final String key, final String value) { linkParameters.put(key, value); } private static final MessageResources messages = MessageResources.getMessageResources(Bundle.DEGREE); private String constructCalendarPresentation(final ExecutionCourse executionCourse, final WrittenEvaluation writtenEvaluation, final Locale locale) { final StringBuilder stringBuilder = new StringBuilder(); if (writtenEvaluation instanceof WrittenTest) { stringBuilder.append(messages.getMessage(locale, "label.evaluation.shortname.test")); } else if (writtenEvaluation instanceof Exam) { stringBuilder.append(messages.getMessage(locale, "label.evaluation.shortname.exam")); } stringBuilder.append(" "); stringBuilder.append(executionCourse.getSigla()); stringBuilder.append(" ("); stringBuilder.append(DateFormatUtil.format("HH:mm", writtenEvaluation.getBeginningDate())); stringBuilder.append("-"); stringBuilder.append(DateFormatUtil.format("HH:mm", writtenEvaluation.getEndDate())); stringBuilder.append(")"); return stringBuilder.toString(); } private String constructCalendarPresentation(final ExecutionCourse executionCourse, final Project project, final Date time, final String tail, final Locale locale) { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(messages.getMessage(locale, "label.evaluation.shortname.project")); stringBuilder.append(" "); stringBuilder.append(executionCourse.getSigla()); stringBuilder.append(" ("); stringBuilder.append(DateFormatUtil.format("HH:mm", time)); stringBuilder.append(") "); stringBuilder.append(tail); return stringBuilder.toString(); } public boolean isAsLink() { return asLink; } public void setAsLink(boolean asLink) { this.asLink = asLink; } }
pedrosan7os/fenixedu-academic
src/main/java/org/fenixedu/academic/ui/faces/components/util/CalendarLink.java
Java
lgpl-3.0
5,981
// personal includes ".h" #include "EUTELESCOPE.h" #include "EUTelBaseDetector.h" #include "EUTelTLUDetector.h" // system includes <> #include <iostream> #include <iomanip> #include <vector> #include <string> using namespace std; using namespace eutelescope; EUTelTLUDetector::EUTelTLUDetector() : EUTelBaseDetector() { _name = "TLU"; // nothing else to do ! } void EUTelTLUDetector::setAndMask(unsigned short value) { _andMask = value; } void EUTelTLUDetector::setOrMask(unsigned short value) { _orMask = value; } void EUTelTLUDetector::setVetoMask(unsigned short value) { _vetoMask = value; } void EUTelTLUDetector::setDUTMask(unsigned short value) { _dutMask = value; } void EUTelTLUDetector::setFirmwareID(unsigned short value) { _firmwareID = value; } void EUTelTLUDetector::setTimeInterval(short value) { _timeInterval = value; } void EUTelTLUDetector::print(ostream &os) const { size_t w = 35; os << resetiosflags(ios::right) << setiosflags(ios::left) << setfill('.') << setw(w) << setiosflags(ios::left) << "Detector name " << resetiosflags(ios::left) << " " << _name << endl << setw(w) << setiosflags(ios::left) << "AndMask " << resetiosflags(ios::left) << " 0x" << to_hex(_andMask, 2) << endl << setw(w) << setiosflags(ios::left) << "OrMask " << resetiosflags(ios::left) << " 0x" << to_hex(_orMask, 2) << endl << setw(w) << setiosflags(ios::left) << "VetoMask " << resetiosflags(ios::left) << " 0x" << to_hex(_vetoMask, 2) << endl << setw(w) << setiosflags(ios::left) << "DUTMask " << resetiosflags(ios::left) << " 0x" << to_hex(_dutMask, 2) << endl << setw(w) << setiosflags(ios::left) << "FirmwareID " << resetiosflags(ios::left) << " " << _firmwareID << endl << setw(w) << setiosflags(ios::left) << "TimeInterval " << resetiosflags(ios::left) << " " << _timeInterval << setfill(' ') << endl; }
freidt/eudaq
nreader/detdescription/EUTelTLUDetector.cc
C++
lgpl-3.0
1,905
package uk.co.alt236.bluetoothlelib.device.beacon.ibeacon; /** * */ public class IBeaconConstants { public static final byte[] MANUFACTURER_DATA_IBEACON_PREFIX = {0x4C, 0x00, 0x02, 0x15}; }
StuartGuo/Bluetooth-LE-Library---Android
library/src/main/java/uk/co/alt236/bluetoothlelib/device/beacon/ibeacon/IBeaconConstants.java
Java
apache-2.0
198
// This is a generated file. Not intended for manual editing. package com.intellij.sh.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.intellij.sh.ShTypes.*; import com.intellij.sh.psi.*; public class ShUnaryExpressionImpl extends ShExpressionImpl implements ShUnaryExpression { public ShUnaryExpressionImpl(ASTNode node) { super(node); } @Override public void accept(@NotNull ShVisitor visitor) { visitor.visitUnaryExpression(this); } @Override public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof ShVisitor) accept((ShVisitor)visitor); else super.accept(visitor); } @Override @Nullable public ShExpression getExpression() { return findChildByClass(ShExpression.class); } @Override @Nullable public PsiElement getMinus() { return findChildByType(MINUS); } @Override @Nullable public PsiElement getPlus() { return findChildByType(PLUS); } }
smmribeiro/intellij-community
plugins/sh/gen/com/intellij/sh/psi/impl/ShUnaryExpressionImpl.java
Java
apache-2.0
1,138
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.das.analytics.rest.beans; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * This class represents a facet object bean. facet object defines the hierarchical fieldName, * which can be drilled down. This can be used as a value in a record. * Example : * Assume a record represents a book. * Then the record field : value pairs will be, e.g. * Price : $50.00 * Author : firstName LastName * ISBN : 234325435445435436 * Published Date : "1987" , "March", "21" * * Here Publish Date will be a facet/categoryPath, since it can be drilled down to Year, then month and date * and categorizes by each level. * */ @XmlRootElement(name = "categoryPath") @XmlAccessorType(XmlAccessType.FIELD) public class DrillDownPathBean { @XmlElement(name = "path") private String[] path; @XmlElement(name = "fieldName") private String fieldName; /** * This constructor is for jax-rs json serialization/deserialization */ public DrillDownPathBean() { } public String[] getPath() { return path; } public String getFieldName() { return fieldName; } public void setPath(String[] path) { this.path = path; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } }
wso2/product-das
modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/das/analytics/rest/beans/DrillDownPathBean.java
Java
apache-2.0
2,162
/* * 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.facebook.presto.sql.planner.assertions; import com.facebook.presto.Session; import com.facebook.presto.cost.PlanNodeCost; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.sql.planner.plan.LimitNode; import com.facebook.presto.sql.planner.plan.PlanNode; import static com.google.common.base.Preconditions.checkState; public class LimitMatcher implements Matcher { private final long limit; public LimitMatcher(long limit) { this.limit = limit; } @Override public boolean shapeMatches(PlanNode node) { if (!(node instanceof LimitNode)) { return false; } LimitNode limitNode = (LimitNode) node; return limitNode.getCount() == limit; } @Override public MatchResult detailMatches(PlanNode node, PlanNodeCost planNodeCost, Session session, Metadata metadata, SymbolAliases symbolAliases) { checkState(shapeMatches(node)); return MatchResult.match(); } }
gh351135612/presto
presto-main/src/test/java/com/facebook/presto/sql/planner/assertions/LimitMatcher.java
Java
apache-2.0
1,577
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.util; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * NOTE: If you add a new method here you must also add it to {@link io.undertow.server.protocol.http.HttpRequestParser} * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class Methods { private Methods() { } public static final String OPTIONS_STRING = "OPTIONS"; public static final String GET_STRING = "GET"; public static final String HEAD_STRING = "HEAD"; public static final String POST_STRING = "POST"; public static final String PUT_STRING = "PUT"; public static final String DELETE_STRING = "DELETE"; public static final String TRACE_STRING = "TRACE"; public static final String CONNECT_STRING = "CONNECT"; public static final String PROPFIND_STRING = "PROPFIND"; public static final String PROPPATCH_STRING = "PROPPATCH"; public static final String MKCOL_STRING = "MKCOL"; public static final String COPY_STRING = "COPY"; public static final String MOVE_STRING = "MOVE"; public static final String LOCK_STRING = "LOCK"; public static final String UNLOCK_STRING = "UNLOCK"; public static final String ACL_STRING = "ACL"; public static final String REPORT_STRING = "REPORT"; public static final String VERSION_CONTROL_STRING = "VERSION-CONTROL"; public static final String CHECKIN_STRING = "CHECKIN"; public static final String CHECKOUT_STRING = "CHECKOUT"; public static final String UNCHECKOUT_STRING = "UNCHECKOUT"; public static final String SEARCH_STRING = "SEARCH"; public static final String MKWORKSPACE_STRING = "MKWORKSPACE"; public static final String UPDATE_STRING = "UPDATE"; public static final String LABEL_STRING = "LABEL"; public static final String MERGE_STRING = "MERGE"; public static final String BASELINE_CONTROL_STRING = "BASELINE_CONTROL"; public static final String MKACTIVITY_STRING = "MKACTIVITY"; public static final HttpString OPTIONS = new HttpString(OPTIONS_STRING); public static final HttpString GET = new HttpString(GET_STRING); public static final HttpString HEAD = new HttpString(HEAD_STRING); public static final HttpString POST = new HttpString(POST_STRING); public static final HttpString PUT = new HttpString(PUT_STRING); public static final HttpString DELETE = new HttpString(DELETE_STRING); public static final HttpString TRACE = new HttpString(TRACE_STRING); public static final HttpString CONNECT = new HttpString(CONNECT_STRING); public static final HttpString PROPFIND = new HttpString(PROPFIND_STRING); public static final HttpString PROPPATCH = new HttpString(PROPPATCH_STRING); public static final HttpString MKCOL = new HttpString(MKCOL_STRING); public static final HttpString COPY = new HttpString(COPY_STRING); public static final HttpString MOVE = new HttpString(MOVE_STRING); public static final HttpString LOCK = new HttpString(LOCK_STRING); public static final HttpString UNLOCK = new HttpString(UNLOCK_STRING); public static final HttpString ACL = new HttpString(ACL_STRING); public static final HttpString REPORT = new HttpString(REPORT_STRING); public static final HttpString VERSION_CONTROL = new HttpString(VERSION_CONTROL_STRING); public static final HttpString CHECKIN = new HttpString(CHECKIN_STRING); public static final HttpString CHECKOUT = new HttpString(CHECKOUT_STRING); public static final HttpString UNCHECKOUT = new HttpString(UNCHECKOUT_STRING); public static final HttpString SEARCH = new HttpString(SEARCH_STRING); public static final HttpString MKWORKSPACE = new HttpString(MKWORKSPACE_STRING); public static final HttpString UPDATE = new HttpString(UPDATE_STRING); public static final HttpString LABEL = new HttpString(LABEL_STRING); public static final HttpString MERGE = new HttpString(MERGE_STRING); public static final HttpString BASELINE_CONTROL = new HttpString(BASELINE_CONTROL_STRING); public static final HttpString MKACTIVITY = new HttpString(MKACTIVITY_STRING); private static final Map<String, HttpString> METHODS; static { Map<String, HttpString> methods = new HashMap<>(); putString(methods, OPTIONS); putString(methods, GET); putString(methods, HEAD); putString(methods, POST); putString(methods, PUT); putString(methods, DELETE); putString(methods, TRACE); putString(methods, CONNECT); putString(methods, PROPFIND); putString(methods, PROPPATCH); putString(methods, MKCOL); putString(methods, COPY); putString(methods, MOVE); putString(methods, LOCK); putString(methods, UNLOCK); putString(methods, ACL); putString(methods, REPORT); putString(methods, VERSION_CONTROL); putString(methods, CHECKIN); putString(methods, CHECKOUT); putString(methods, UNCHECKOUT); putString(methods, SEARCH); putString(methods, MKWORKSPACE); putString(methods, UPDATE); putString(methods, LABEL); putString(methods, MERGE); putString(methods, BASELINE_CONTROL); putString(methods, MKACTIVITY); METHODS = Collections.unmodifiableMap(methods); } private static void putString(Map<String, HttpString> methods, HttpString options) { methods.put(options.toString(), options); } public static HttpString fromString(String method) { HttpString res = METHODS.get(method); if(res == null) { return new HttpString(method); } return res; } }
TomasHofman/undertow
core/src/main/java/io/undertow/util/Methods.java
Java
apache-2.0
6,437
package com.intellij.execution.configurations; /** * Configuration of such type can't be manually added or removed by the user; the template entry is hidden. */ public interface VirtualConfigurationType { }
siosio/intellij-community
platform/lang-api/src/com/intellij/execution/configurations/VirtualConfigurationType.java
Java
apache-2.0
210
@org.osgi.annotation.bundle.Export @org.osgi.annotation.versioning.Version("2.0.0") package bndtools.editor.model;
psoreide/bnd
bndtools.core/src/bndtools/editor/model/package-info.java
Java
apache-2.0
115
/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package grpc import ( "net" "testing" "time" "golang.org/x/net/context" "google.golang.org/grpc/credentials" ) const tlsDir = "testdata/" func TestDialTimeout(t *testing.T) { conn, err := Dial("Non-Existent.Server:80", WithTimeout(time.Millisecond), WithBlock(), WithInsecure()) if err == nil { conn.Close() } if err != context.DeadlineExceeded { t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) } } func TestTLSDialTimeout(t *testing.T) { creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com") if err != nil { t.Fatalf("Failed to create credentials %v", err) } conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds), WithTimeout(time.Millisecond), WithBlock()) if err == nil { conn.Close() } if err != context.DeadlineExceeded { t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) } } func TestTLSServerNameOverwrite(t *testing.T) { overwriteServerName := "over.write.server.name" creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", overwriteServerName) if err != nil { t.Fatalf("Failed to create credentials %v", err) } conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds)) if err != nil { t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) } conn.Close() if conn.authority != overwriteServerName { t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) } } func TestDialContextCancel(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() if _, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure()); err != context.Canceled { t.Fatalf("DialContext(%v, _) = _, %v, want _, %v", ctx, err, context.Canceled) } } // blockingBalancer mimics the behavior of balancers whose initialization takes a long time. // In this test, reading from blockingBalancer.Notify() blocks forever. type blockingBalancer struct { ch chan []Address } func newBlockingBalancer() Balancer { return &blockingBalancer{ch: make(chan []Address)} } func (b *blockingBalancer) Start(target string, config BalancerConfig) error { return nil } func (b *blockingBalancer) Up(addr Address) func(error) { return nil } func (b *blockingBalancer) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) { return Address{}, nil, nil } func (b *blockingBalancer) Notify() <-chan []Address { return b.ch } func (b *blockingBalancer) Close() error { close(b.ch) return nil } func TestDialWithBlockingBalancer(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) dialDone := make(chan struct{}) go func() { DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure(), WithBalancer(newBlockingBalancer())) close(dialDone) }() cancel() <-dialDone } // securePerRPCCredentials always requires transport security. type securePerRPCCredentials struct{} func (c securePerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { return nil, nil } func (c securePerRPCCredentials) RequireTransportSecurity() bool { return true } func TestCredentialsMisuse(t *testing.T) { tlsCreds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com") if err != nil { t.Fatalf("Failed to create authenticator %v", err) } // Two conflicting credential configurations if _, err := Dial("Non-Existent.Server:80", WithTransportCredentials(tlsCreds), WithBlock(), WithInsecure()); err != errCredentialsConflict { t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errCredentialsConflict) } // security info on insecure connection if _, err := Dial("Non-Existent.Server:80", WithPerRPCCredentials(securePerRPCCredentials{}), WithBlock(), WithInsecure()); err != errTransportCredentialsMissing { t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errTransportCredentialsMissing) } } func TestWithBackoffConfigDefault(t *testing.T) { testBackoffConfigSet(t, &DefaultBackoffConfig) } func TestWithBackoffConfig(t *testing.T) { b := BackoffConfig{MaxDelay: DefaultBackoffConfig.MaxDelay / 2} expected := b setDefaults(&expected) // defaults should be set testBackoffConfigSet(t, &expected, WithBackoffConfig(b)) } func TestWithBackoffMaxDelay(t *testing.T) { md := DefaultBackoffConfig.MaxDelay / 2 expected := BackoffConfig{MaxDelay: md} setDefaults(&expected) testBackoffConfigSet(t, &expected, WithBackoffMaxDelay(md)) } func testBackoffConfigSet(t *testing.T, expected *BackoffConfig, opts ...DialOption) { opts = append(opts, WithInsecure()) conn, err := Dial("foo:80", opts...) if err != nil { t.Fatalf("unexpected error dialing connection: %v", err) } if conn.dopts.bs == nil { t.Fatalf("backoff config not set") } actual, ok := conn.dopts.bs.(BackoffConfig) if !ok { t.Fatalf("unexpected type of backoff config: %#v", conn.dopts.bs) } if actual != *expected { t.Fatalf("unexpected backoff config on connection: %v, want %v", actual, expected) } conn.Close() } type testErr struct { temp bool } func (e *testErr) Error() string { return "test error" } func (e *testErr) Temporary() bool { return e.temp } var nonTemporaryError = &testErr{false} func nonTemporaryErrorDialer(addr string, timeout time.Duration) (net.Conn, error) { return nil, nonTemporaryError } func TestDialWithBlockErrorOnNonTemporaryErrorDialer(t *testing.T) { ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(nonTemporaryErrorDialer), WithBlock(), FailOnNonTempDialError(true)); err != nonTemporaryError { t.Fatalf("Dial(%q) = %v, want %v", "", err, nonTemporaryError) } // Without FailOnNonTempDialError, gRPC will retry to connect, and dial should exit with time out error. if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(nonTemporaryErrorDialer), WithBlock()); err != context.DeadlineExceeded { t.Fatalf("Dial(%q) = %v, want %v", "", err, context.DeadlineExceeded) } }
otsimo/analytics
vendor/src/google.golang.org/grpc/clientconn_test.go
GO
apache-2.0
7,643
/* * Copyright 2003-2013 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ig.abstraction; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.fixes.IntroduceConstantFix; import com.siyeh.ig.fixes.SuppressForTestsScopeFix; import com.siyeh.ig.psiutils.ClassUtils; import com.siyeh.ig.psiutils.ExpressionUtils; import com.siyeh.ig.psiutils.MethodUtils; import com.siyeh.ig.psiutils.TypeUtils; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class MagicNumberInspection extends BaseInspection { @SuppressWarnings("PublicField") public boolean ignoreInHashCode = true; @SuppressWarnings({"PublicField", "UnusedDeclaration"}) public boolean ignoreInTestCode = false; // keep for compatibility @SuppressWarnings("PublicField") public boolean ignoreInAnnotations = true; @SuppressWarnings("PublicField") public boolean ignoreInitialCapacity = false; @Override protected InspectionGadgetsFix @NotNull [] buildFixes(Object... infos) { final PsiElement context = (PsiElement)infos[0]; final InspectionGadgetsFix fix = SuppressForTestsScopeFix.build(this, context); if (fix == null) { return new InspectionGadgetsFix[] {new IntroduceConstantFix()}; } return new InspectionGadgetsFix[] {new IntroduceConstantFix(), fix}; } @Override protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { return true; } @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message("magic.number.problem.descriptor"); } @Override public JComponent createOptionsPanel() { final MultipleCheckboxOptionsPanel panel = new MultipleCheckboxOptionsPanel(this); panel.addCheckbox(InspectionGadgetsBundle.message("inspection.option.ignore.in.hashcode"), "ignoreInHashCode"); panel.addCheckbox(InspectionGadgetsBundle.message("inspection.option.ignore.in.annotations"), "ignoreInAnnotations"); panel.addCheckbox(InspectionGadgetsBundle.message("inspection.option.ignore.as.initial.capacity"), "ignoreInitialCapacity"); return panel; } @Override public BaseInspectionVisitor buildVisitor() { return new MagicNumberVisitor(); } private class MagicNumberVisitor extends BaseInspectionVisitor { @Override public void visitLiteralExpression(@NotNull PsiLiteralExpression expression) { super.visitLiteralExpression(expression); final PsiType type = expression.getType(); if (!ClassUtils.isPrimitiveNumericType(type) || PsiType.CHAR.equals(type)) { return; } if (isSpecialCaseLiteral(expression) || isFinalVariableInitialization(expression)) { return; } if (ignoreInHashCode) { final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(expression, PsiMethod.class, true, PsiClass.class, PsiLambdaExpression.class); if (MethodUtils.isHashCode(containingMethod)) { return; } } if (ignoreInAnnotations) { final boolean insideAnnotation = AnnotationUtil.isInsideAnnotation(expression); if (insideAnnotation) { return; } } if (ignoreInitialCapacity && isInitialCapacity(expression)) { return; } final PsiField field = PsiTreeUtil.getParentOfType(expression, PsiField.class, true, PsiCallExpression.class); if (field != null && PsiUtil.isCompileTimeConstant(field)) { return; } final PsiElement parent = expression.getParent(); if (parent instanceof PsiPrefixExpression) { registerError(parent, parent); } else { registerError(expression, expression); } } private boolean isInitialCapacity(PsiLiteralExpression expression) { final PsiElement element = PsiTreeUtil.skipParentsOfType(expression, PsiTypeCastExpression.class, PsiParenthesizedExpression.class); if (!(element instanceof PsiExpressionList)) { return false; } final PsiElement parent = element.getParent(); if (!(parent instanceof PsiNewExpression)) { return false; } final PsiNewExpression newExpression = (PsiNewExpression)parent; return TypeUtils.expressionHasTypeOrSubtype(newExpression, CommonClassNames.JAVA_LANG_ABSTRACT_STRING_BUILDER, CommonClassNames.JAVA_UTIL_MAP, CommonClassNames.JAVA_UTIL_COLLECTION, "java.io.ByteArrayOutputStream", "java.awt.Dimension") != null; } private boolean isSpecialCaseLiteral(PsiLiteralExpression expression) { final Object object = ExpressionUtils.computeConstantExpression(expression); if (object instanceof Integer) { final int i = ((Integer)object).intValue(); return i >= 0 && i <= 10 || i == 100 || i == 1000; } else if (object instanceof Long) { final long l = ((Long)object).longValue(); return l >= 0L && l <= 2L; } else if (object instanceof Double) { final double d = ((Double)object).doubleValue(); return d == 1.0 || d == 0.0; } else if (object instanceof Float) { final float f = ((Float)object).floatValue(); return f == 1.0f || f == 0.0f; } return false; } public boolean isFinalVariableInitialization(PsiExpression expression) { final PsiElement parent = PsiTreeUtil.getParentOfType(expression, PsiVariable.class, PsiAssignmentExpression.class); final PsiVariable variable; if (!(parent instanceof PsiVariable)) { if (!(parent instanceof PsiAssignmentExpression)) { return false; } final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)parent; final PsiExpression lhs = assignmentExpression.getLExpression(); if (!(lhs instanceof PsiReferenceExpression)) { return false; } final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)lhs; final PsiElement target = referenceExpression.resolve(); if (!(target instanceof PsiVariable)) { return false; } variable = (PsiVariable)target; } else { variable = (PsiVariable)parent; } return variable.hasModifierProperty(PsiModifier.FINAL); } } }
siosio/intellij-community
plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/MagicNumberInspection.java
Java
apache-2.0
7,475
package main import ( "fmt" "os" "path/filepath" "github.com/karrick/godirwalk" "github.com/pkg/errors" ) func main() { if len(os.Args) < 2 { fmt.Fprintf(os.Stderr, "usage: %s dir1 [dir2 [dir3...]]\n", filepath.Base(os.Args[0])) os.Exit(2) } scratchBuffer := make([]byte, 64*1024) // allocate once and re-use each time var count, total int var err error for _, arg := range os.Args[1:] { count, err = pruneEmptyDirectories(arg, scratchBuffer) total += count if err != nil { break } } fmt.Fprintf(os.Stderr, "Removed %d empty directories\n", total) if err != nil { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) os.Exit(1) } } func pruneEmptyDirectories(osDirname string, scratchBuffer []byte) (int, error) { var count int err := godirwalk.Walk(osDirname, &godirwalk.Options{ Unsorted: true, ScratchBuffer: scratchBuffer, Callback: func(_ string, _ *godirwalk.Dirent) error { // no-op while diving in; all the fun happens in PostChildrenCallback return nil }, PostChildrenCallback: func(osPathname string, _ *godirwalk.Dirent) error { deChildren, err := godirwalk.ReadDirents(osPathname, scratchBuffer) if err != nil { return errors.Wrap(err, "cannot ReadDirents") } // NOTE: ReadDirents skips "." and ".." if len(deChildren) > 0 { return nil // this directory has children; no additional work here } if osPathname == osDirname { return nil // do not remove provided root directory } err = os.Remove(osPathname) if err == nil { count++ } return err }, }) return count, err }
pweil-/origin
vendor/github.com/karrick/godirwalk/examples/clean-empties/main.go
GO
apache-2.0
1,592
/* * Copyright 2014 Open Networking Laboratory * * 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.onosproject.provider.pcep.tunnel.impl; import org.onosproject.net.DeviceId; import org.onosproject.pcep.api.PcepController; import org.onosproject.pcep.api.PcepDpid; import org.onosproject.pcep.api.PcepLinkListener; import org.onosproject.pcep.api.PcepSwitch; import org.onosproject.pcep.api.PcepSwitchListener; import org.onosproject.pcep.api.PcepTunnel; import org.onosproject.pcep.api.PcepTunnelListener; public class PcepControllerAdapter implements PcepController { @Override public Iterable<PcepSwitch> getSwitches() { return null; } @Override public PcepSwitch getSwitch(PcepDpid did) { return null; } @Override public void addListener(PcepSwitchListener listener) { } @Override public void removeListener(PcepSwitchListener listener) { } @Override public void addLinkListener(PcepLinkListener listener) { } @Override public void removeLinkListener(PcepLinkListener listener) { } @Override public void addTunnelListener(PcepTunnelListener listener) { } @Override public void removeTunnelListener(PcepTunnelListener listener) { } @Override public PcepTunnel applyTunnel(DeviceId srcDid, DeviceId dstDid, long srcPort, long dstPort, long bandwidth, String name) { return null; } @Override public Boolean deleteTunnel(String id) { return null; } @Override public Boolean updateTunnelBandwidth(String id, long bandwidth) { return null; } @Override public void getTunnelStatistics(String pcepTunnelId) { } }
packet-tracker/onos
providers/pcep/tunnel/src/test/java/org/onosproject/provider/pcep/tunnel/impl/PcepControllerAdapter.java
Java
apache-2.0
2,267
/* * Copyright 2005-2013 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.ldap.core.support; import org.springframework.ldap.core.ContextMapper; import javax.naming.NamingException; import javax.naming.ldap.HasControls; /** * Extension of the {@link org.springframework.ldap.core.ContextMapper} interface that allows * controls to be passed to the mapper implementation. Uses Java 5 covariant * return types to override the return type of the * {@link #mapFromContextWithControls(Object, javax.naming.ldap.HasControls)} method to be the * type parameter T. * * @author Tim Terry * @author Ulrik Sandberg * @param <T> return type of the * {@link #mapFromContextWithControls(Object, javax.naming.ldap.HasControls)} method */ public interface ContextMapperWithControls<T> extends ContextMapper<T> { T mapFromContextWithControls(final Object ctx, final HasControls hasControls) throws NamingException; }
likaiwalkman/spring-ldap
core/src/main/java/org/springframework/ldap/core/support/ContextMapperWithControls.java
Java
apache-2.0
1,490
# Copyright 2008-2015 Nokia Solutions and Networks # # 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. """Implementation of the public test library logging API. This is exposed via :py:mod:`robot.api.logger`. Implementation must reside here to avoid cyclic imports. """ import sys import threading from robot.errors import DataError from robot.utils import unic, encode_output from .logger import LOGGER from .loggerhelper import Message LOGGING_THREADS = ('MainThread', 'RobotFrameworkTimeoutThread') def write(msg, level, html=False): # Callable messages allow lazy logging internally, but we don't want to # expose this functionality publicly. See the following issue for details: # http://code.google.com/p/robotframework/issues/detail?id=1505 if callable(msg): msg = unic(msg) if level.upper() not in ('TRACE', 'DEBUG', 'INFO', 'HTML', 'WARN', 'ERROR'): raise DataError("Invalid log level '%s'." % level) if threading.currentThread().getName() in LOGGING_THREADS: LOGGER.log_message(Message(msg, level, html)) def trace(msg, html=False): write(msg, 'TRACE', html) def debug(msg, html=False): write(msg, 'DEBUG', html) def info(msg, html=False, also_console=False): write(msg, 'INFO', html) if also_console: console(msg) def warn(msg, html=False): write(msg, 'WARN', html) def error(msg, html=False): write(msg, 'ERROR', html) def console(msg, newline=True, stream='stdout'): msg = unic(msg) if newline: msg += '\n' stream = sys.__stdout__ if stream.lower() != 'stderr' else sys.__stderr__ stream.write(encode_output(msg)) stream.flush()
caio2k/RIDE
src/robotide/lib/robot/output/librarylogger.py
Python
apache-2.0
2,175
/* * 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.jackrabbit.oak.plugins.nodetype; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry; import org.apache.jackrabbit.oak.spi.state.NodeState; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.addAll; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.contains; import static com.google.common.collect.Lists.newArrayListWithCapacity; import static com.google.common.collect.Sets.newHashSet; import static org.apache.jackrabbit.JcrConstants.JCR_DEFAULTPRIMARYTYPE; import static org.apache.jackrabbit.JcrConstants.JCR_MANDATORY; import static org.apache.jackrabbit.JcrConstants.JCR_MIXINTYPES; import static org.apache.jackrabbit.JcrConstants.JCR_NODETYPENAME; import static org.apache.jackrabbit.JcrConstants.JCR_PRIMARYTYPE; import static org.apache.jackrabbit.JcrConstants.JCR_SAMENAMESIBLINGS; import static org.apache.jackrabbit.JcrConstants.JCR_UUID; import static org.apache.jackrabbit.oak.api.Type.UNDEFINED; import static org.apache.jackrabbit.oak.api.Type.UNDEFINEDS; import static org.apache.jackrabbit.oak.commons.PathUtils.dropIndexFromName; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_MANDATORY_CHILD_NODES; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_MANDATORY_PROPERTIES; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_NAMED_CHILD_NODE_DEFINITIONS; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_NAMED_PROPERTY_DEFINITIONS; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_RESIDUAL_CHILD_NODE_DEFINITIONS; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_RESIDUAL_PROPERTY_DEFINITIONS; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_SUPERTYPES; class EffectiveType { private final List<NodeState> types; EffectiveType(@Nonnull List<NodeState> types) { this.types = checkNotNull(types); } /** * Checks whether this effective type contains the named type. * * @param name node type name * @return {@code true} if the named type is included, * {@code false} otherwise */ boolean isNodeType(@Nonnull String name) { for (NodeState type : types) { if (name.equals(type.getName(JCR_NODETYPENAME)) || contains(type.getNames(REP_SUPERTYPES), name)) { return true; } } return false; } boolean isMandatoryProperty(@Nonnull String name) { return nameSetContains(REP_MANDATORY_PROPERTIES, name); } @Nonnull Set<String> getMandatoryProperties() { return getNameSet(REP_MANDATORY_PROPERTIES); } boolean isMandatoryChildNode(@Nonnull String name) { return nameSetContains(REP_MANDATORY_CHILD_NODES, name); } @Nonnull Set<String> getMandatoryChildNodes() { return getNameSet(REP_MANDATORY_CHILD_NODES); } /** * Finds a matching definition for a property with the given name and type. * * @param property modified property * @return matching property definition, or {@code null} */ @CheckForNull NodeState getDefinition(@Nonnull PropertyState property) { String propertyName = property.getName(); Type<?> propertyType = property.getType(); String escapedName; if (JCR_PRIMARYTYPE.equals(propertyName)) { escapedName = NodeTypeConstants.REP_PRIMARY_TYPE; } else if (JCR_MIXINTYPES.equals(propertyName)) { escapedName = NodeTypeConstants.REP_MIXIN_TYPES; } else if (JCR_UUID.equals(propertyName)) { escapedName = NodeTypeConstants.REP_UUID; } else { escapedName = propertyName; } String definedType = propertyType.toString(); String undefinedType; if (propertyType.isArray()) { undefinedType = UNDEFINEDS.toString(); } else { undefinedType = UNDEFINED.toString(); } // Find matching named property definition for (NodeState type : types) { NodeState definitions = type .getChildNode(REP_NAMED_PROPERTY_DEFINITIONS) .getChildNode(escapedName); NodeState definition = definitions.getChildNode(definedType); if (definition.exists()) { return definition; } definition = definitions.getChildNode(undefinedType); if (definition.exists()) { return definition; } // OAK-822: a mandatory definition always overrides residual ones // TODO: unnecessary if the OAK-713 fallback wasn't needed below for (ChildNodeEntry entry : definitions.getChildNodeEntries()) { definition = entry.getNodeState(); if (definition.getBoolean(JCR_MANDATORY)) { return definition; } } // TODO: Fall back to residual definitions until we have consensus on OAK-713 // throw new ConstraintViolationException( // "No matching definition found for property " + propertyName); } // Find matching residual property definition for (NodeState type : types) { NodeState residual = type.getChildNode(REP_RESIDUAL_PROPERTY_DEFINITIONS); NodeState definition = residual.getChildNode(definedType); if (!definition.exists()) { definition = residual.getChildNode(undefinedType); } if (definition.exists()) { return definition; } } return null; } /** * Finds a matching definition for a child node with the given name and * types. * * @param nameWithIndex child node name, possibly with an SNS index * @param effective effective types of the child node * @return {@code true} if there's a matching child node definition, * {@code false} otherwise */ boolean isValidChildNode(@Nonnull String nameWithIndex, @Nonnull EffectiveType effective) { String name = dropIndexFromName(nameWithIndex); boolean sns = !name.equals(nameWithIndex); Set<String> typeNames = effective.getTypeNames(); // Find matching named child node definition for (NodeState type : types) { NodeState definitions = type .getChildNode(REP_NAMED_CHILD_NODE_DEFINITIONS) .getChildNode(name); for (String typeName : typeNames) { NodeState definition = definitions.getChildNode(typeName); if (definition.exists() && snsMatch(sns, definition)) { return true; } } // OAK-822: a mandatory definition always overrides alternatives // TODO: unnecessary if the OAK-713 fallback wasn't needed below for (ChildNodeEntry entry : definitions.getChildNodeEntries()) { NodeState definition = entry.getNodeState(); if (definition.getBoolean(JCR_MANDATORY)) { return false; } } // TODO: Fall back to residual definitions until we have consensus on OAK-713 // throw new ConstraintViolationException( // "Incorrect node type of child node " + nodeName); } // Find matching residual child node definition for (NodeState type : types) { NodeState residual = type.getChildNode(REP_RESIDUAL_CHILD_NODE_DEFINITIONS); for (String typeName : typeNames) { NodeState definition = residual.getChildNode(typeName); if (definition.exists() && snsMatch(sns, definition)) { return true; } } } return false; } /** * Finds the default node type for a child node with the given name. * * @param nameWithIndex child node name, possibly with an SNS index * @return default type, or {@code null} if not found */ @CheckForNull String getDefaultType(@Nonnull String nameWithIndex) { String name = dropIndexFromName(nameWithIndex); boolean sns = !name.equals(nameWithIndex); for (NodeState type : types) { NodeState named = type .getChildNode(REP_NAMED_CHILD_NODE_DEFINITIONS) .getChildNode(name); NodeState residual = type .getChildNode(REP_RESIDUAL_CHILD_NODE_DEFINITIONS); for (ChildNodeEntry entry : concat( named.getChildNodeEntries(), residual.getChildNodeEntries())) { NodeState definition = entry.getNodeState(); String defaultType = definition.getName(JCR_DEFAULTPRIMARYTYPE); if (defaultType != null && snsMatch(sns, definition)) { return defaultType; } } } return null; } @Nonnull Set<String> getTypeNames() { Set<String> names = newHashSet(); for (NodeState type : types) { names.add(type.getName(JCR_NODETYPENAME)); addAll(names, type.getNames(REP_SUPERTYPES)); } return names; } //------------------------------------------------------------< Object >-- @Override public String toString() { List<String> names = newArrayListWithCapacity(types.size()); for (NodeState type : types) { names.add(type.getName(JCR_NODETYPENAME)); } return names.toString(); } //-----------------------------------------------------------< private >-- /** * Depending on the given SNS flag, checks whether the given child node * definition allows same-name-siblings. * * @param sns SNS flag, {@code true} if processing an SNS node * @param definition child node definition */ private boolean snsMatch(boolean sns, @Nonnull NodeState definition) { return !sns || definition.getBoolean(JCR_SAMENAMESIBLINGS); } private boolean nameSetContains(@Nonnull String set, @Nonnull String name) { for (NodeState type : types) { if (contains(type.getNames(set), name)) { return true; } } return false; } @Nonnull private Set<String> getNameSet(@Nonnull String set) { Set<String> names = newHashSet(); for (NodeState type : types) { addAll(names, type.getNames(set)); } return names; } }
AndreasAbdi/jackrabbit-oak
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/nodetype/EffectiveType.java
Java
apache-2.0
11,952