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 |
|---|---|---|---|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Collections.Internal
{
/// <summary>
/// Provides static methods to invoke <see cref="IEnumerable{T}"/> members on value types that explicitly implement
/// the member.
/// </summary>
/// <remarks>
/// Normally, invocation of explicit interface members requires boxing or copying the value type, which is
/// especially problematic for operations that mutate the value. Invocation through these helpers behaves like a
/// normal call to an implicitly implemented member.
/// </remarks>
internal static class IEnumerableCalls<T>
{
public static IEnumerator<T> GetEnumerator<TEnumerable>(ref TEnumerable enumerable)
where TEnumerable : IEnumerable<T>
{
return enumerable.GetEnumerator();
}
}
}
| mavasani/roslyn | src/Dependencies/Collections/Internal/IEnumerableCalls`1.cs | C# | mit | 1,063 |
require 'parslet'
require 'parslet/ignore'
module EDN
class Parser < Parslet::Parser
def parse_prefix(str, options={})
source = Parslet::Source.new(str.to_s)
success, value = setup_and_apply(source, nil)
unless success
reporter = options[:reporter] || Parslet::ErrorReporter::Tree.new
success, value = setup_and_apply(source, reporter)
fail "Assertion failed: success was true when parsing with reporter" if success
value.raise
end
rest = nil
if !source.eof?
rest = source.consume(source.chars_left).to_s
end
return [flatten(value), rest]
end
root(:top)
rule(:top) {
space? >> element >> space?
}
rule(:element) {
base_element |
tagged_element |
metadata.maybe >> metadata_capable_element.as(:element)
}
rule(:metadata_capable_element) {
vector |
list |
set |
map |
symbol
}
rule(:tagged_element) {
tag >> space? >> base_element.as(:element)
}
rule(:base_element) {
vector |
list |
set |
map |
boolean |
str('nil').as(:nil) |
keyword |
string |
character |
float |
integer |
symbol
}
# Collections
rule(:vector) {
str('[') >>
top.repeat.as(:vector) >>
space? >>
str(']')
}
rule(:list) {
str('(') >>
top.repeat.as(:list) >>
space? >>
str(')')
}
rule(:set) {
str('#{') >>
top.repeat.as(:set) >>
space? >>
str('}')
}
rule(:map) {
str('{') >>
(top.as(:key) >> top.as(:value)).repeat.as(:map) >>
space? >>
str('}')
}
# Primitives
rule(:integer) {
(match['\-\+'].maybe >>
(str('0') | match('[1-9]') >> digit.repeat)).as(:integer) >>
(str('N') | str("M") ).maybe.as(:precision)
}
rule(:float) {
(match['\-\+'].maybe >>
(str('0') | (match('[1-9]') >> digit.repeat)) >>
str('.') >> digit.repeat(1) >>
(match('[eE]') >> match('[\-+]').maybe >> digit.repeat).maybe).as(:float) >>
str('M').maybe.as(:precision)
}
rule(:string) {
str('"') >>
(str('\\') >> any | str('"').absent? >> any).repeat.as(:string) >>
str('"')
}
rule(:character) {
str("\\") >>
(str('newline') | str('space') | str('tab') | str('return') |
match['[:graph:]']).as(:character)
}
rule(:keyword) {
str(':') >> symbol.as(:keyword)
}
rule(:symbol) {
(symbol_chars >> (str('/') >> symbol_chars).maybe |
str('/')).as(:symbol)
}
rule(:boolean) {
str('true').as(:true) | str('false').as(:false)
}
# Parts
rule(:metadata) {
((metadata_map | metadata_symbol | metadata_keyword) >> space?).repeat.as(:metadata)
}
rule(:metadata_map) {
str('^{') >>
((keyword | symbol | string).as(:key) >> top.as(:value)).repeat.as(:map) >>
space? >>
str('}')
}
rule(:metadata_symbol) {
str('^') >> symbol
}
rule(:metadata_keyword) {
str('^') >> keyword
}
rule(:tag) {
str('#') >> match['[:alpha:]'].present? >> symbol.as(:tag)
}
rule(:symbol_chars) {
(symbol_first_char >>
valid_chars.repeat) |
match['\-\+\.']
}
rule(:symbol_first_char) {
(match['\-\+\.'] >> match['0-9'].absent? |
match['\#\:0-9'].absent?) >> valid_chars
}
rule(:valid_chars) {
match['[:alnum:]'] | sym_punct
}
rule(:sym_punct) {
match['\.\*\+\!\-\?\$_%&=:#']
}
rule(:digit) {
match['0-9']
}
rule(:newline) { str("\r").maybe >> str("\n") }
rule(:comment) {
str(';') >> (newline.absent? >> any).repeat
}
rule(:discard) {
str('#_') >> space? >> (tagged_element | base_element).ignore
}
rule(:space) {
(discard | comment | match['\s,']).repeat(1)
}
rule(:space?) { space.maybe }
end
end
| samaaron/defining-pi | vendor/bundle/ruby/1.9.1/gems/edn-1.0.2/lib/edn/parser.rb | Ruby | mit | 4,040 |
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class MdBeachAccess extends React.Component<IconBaseProps, any> { }
| smrq/DefinitelyTyped | types/react-icons/md/beach-access.d.ts | TypeScript | mit | 164 |
using System;
namespace SlackAPI.WebSocketMessages
{
[SlackSocketRouting("message", "message_deleted")]
public class DeletedMessage : SlackSocketMessage
{
public string channel;
public DateTime ts;
public DateTime deleted_ts;
public bool hidden;
}
}
| smanabat/SlackAPI | WebSocketMessages/DeletedMessage.cs | C# | mit | 302 |
var WOLF_WIDTH = 55;
var WOLF_HEIGHT = 37;
var WOLF_Y_OFFSET = 5;
function Wolf(x, y, direction) {
LandEnemy.call(this, x, y, direction, 'wolf', [0, 1], [2, 3], 150);
this.sprite.body.setSize(WOLF_WIDTH, WOLF_HEIGHT, 0, WOLF_Y_OFFSET);
}
Wolf.spawn = function(spawnSettings, group) {
spawnSettings.forEach(function(settings) {
group.add(new Wolf(settings.x * TILE_SIZE, settings.y * TILE_SIZE - (WOLF_HEIGHT + WOLF_Y_OFFSET - TILE_SIZE), settings.direction).sprite);
}, this);
};
$.extend(Wolf.prototype, LandEnemy.prototype)
module.exports = Wolf; | nickchulani99/ITE-445 | final/alien/js/LandEnemy.js | JavaScript | mit | 561 |
// Copyright (c) 2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <consensus/amount.h>
#include <policy/fees.h>
#include <boost/test/unit_test.hpp>
#include <set>
BOOST_AUTO_TEST_SUITE(policy_fee_tests)
BOOST_AUTO_TEST_CASE(FeeRounder)
{
FeeFilterRounder fee_rounder{CFeeRate{1000}};
// check that 1000 rounds to 974 or 1071
std::set<CAmount> results;
while (results.size() < 2) {
results.emplace(fee_rounder.round(1000));
}
BOOST_CHECK_EQUAL(*results.begin(), 974);
BOOST_CHECK_EQUAL(*++results.begin(), 1071);
// check that negative amounts rounds to 0
BOOST_CHECK_EQUAL(fee_rounder.round(-0), 0);
BOOST_CHECK_EQUAL(fee_rounder.round(-1), 0);
// check that MAX_MONEY rounds to 9170997
BOOST_CHECK_EQUAL(fee_rounder.round(MAX_MONEY), 9170997);
}
BOOST_AUTO_TEST_SUITE_END()
| domob1812/bitcoin | src/test/policy_fee_tests.cpp | C++ | mit | 972 |
#include <streamer/core/Endian.h>
#include <streamer/core/BitStream.h>
#include <streamer/amf/types/AMFTypes.h>
#include <streamer/amf/types/AMF0Object.h>
#include <sstream>
AMF0Object::AMF0Object(BitStream& bs)
:AMFType(AMF0_TYPE_OBJECT, bs)
{
}
AMF0Object::~AMF0Object() {
removeElements();
}
void AMF0Object::removeElements() {
for(std::vector<AMF0Property*>::iterator it = values.begin(); it != values.end(); ++it) {
AMF0Property* p = *it;
delete p;
p = NULL;
}
values.clear();
}
void AMF0Object::print() {
std::stringstream ss;
for(std::vector<AMF0Property*>::iterator it = values.begin(); it != values.end(); ++it) {
AMF0Property* p = *it;
AMFType* el = p->value;
ss << p->name->value << " = ";
switch(el->type) {
case AMF0_TYPE_STRING: {
AMF0String* str = static_cast<AMF0String*>(el);
ss << str->value << "\n";
break;
}
case AMF0_TYPE_NUMBER: {
AMF0Number* num = static_cast<AMF0Number*>(el);
ss << num->value << "\n";
break;
}
case AMF0_TYPE_BOOLEAN: {
AMF0Boolean* b = static_cast<AMF0Boolean*>(el);
ss << ((b->value) ? 'Y' : 'N') << "\n";
break;
}
default: break;
}
}
std::string str = ss.str();
printf("%s\n", str.c_str());
}
void AMF0Object::add(std::string name, AMFType* v) {
AMF0String* s = new AMF0String(bs);
s->value = name;
add(s, v);
}
void AMF0Object::add(AMF0String* name, AMFType* v) {
AMF0Property* p = new AMF0Property();
p->name = name;
p->value = v;
values.push_back(p);
}
void AMF0Object::read() {
/*
uint8_t marker = bs.getU8();
if(marker != AMF0_TYPE_OBJECT) {
printf("error: the current marker is not a valid object, marker = %02X\n", marker);
return;
}
*/
readElements();
}
void AMF0Object::readElements() {
while(true) {
AMF0String* name = new AMF0String(bs);
name->read();
uint8_t type = bs.getU8();
switch(type) {
case AMF0_TYPE_NUMBER: {
AMF0Number* el = new AMF0Number(bs);
el->read();
add(name, el);
break;
}
case AMF0_TYPE_BOOLEAN: {
AMF0Boolean* el = new AMF0Boolean(bs);
el->read();
add(name, el);
break;
}
case AMF0_TYPE_STRING: {
AMF0String* el = new AMF0String(bs);
el->read();
add(name, el);
break;
}
case AMF0_TYPE_OBJECT_END: {
return;
}
default: {
printf("unhandled ecma array element: %02X\n", type);
return;
}
}
}
}
void AMF0Object::write() {
bs.putU8(AMF0_TYPE_OBJECT);
writeElements();
}
void AMF0Object::writeElements() {
for(std::vector<AMF0Property*>::iterator it = values.begin(); it != values.end(); ++it) {
AMF0Property* p = *it;
p->name->write();
bs.putU8(p->value->type);
p->value->write();
}
AMF0String str(bs);
str.write();
bs.putU8(AMF0_TYPE_OBJECT_END);
}
| silky/ProjectVictory | Test_VideoFX_Streamer_Two_Cameras/src/ofxVideoStreamer/src/streamer/amf/types/AMF0Object.cpp | C++ | mit | 2,975 |
<?php
/**
* REST API Product Attribute Terms controller
*
* Handles requests to the products/attributes/<attribute_id>/terms endpoint.
*
* @author WooThemes
* @category API
* @package WooCommerce/API
* @since 2.6.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* REST API Product Attribute Terms controller class.
*
* @package WooCommerce/API
* @extends WC_REST_Terms_Controller
*/
class WC_REST_Product_Attribute_Terms_Controller extends WC_REST_Terms_Controller {
/**
* Endpoint namespace.
*
* @var string
*/
protected $namespace = 'wc/v1';
/**
* Route base.
*
* @var string
*/
protected $rest_base = 'products/attributes/(?P<attribute_id>[\d]+)/terms';
/**
* Register the routes for terms.
*/
public function register_routes() {
register_rest_route( $this->namespace, '/' . $this->rest_base, array(
'args' => array(
'attribute_id' => array(
'description' => __( 'Unique identifier for the attribute of the terms.', 'woocommerce' ),
'type' => 'integer',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'create_item' ),
'permission_callback' => array( $this, 'create_item_permissions_check' ),
'args' => array_merge( $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ), array(
'name' => array(
'type' => 'string',
'description' => __( 'Name for the resource.', 'woocommerce' ),
'required' => true,
),
) ),
),
'schema' => array( $this, 'get_public_item_schema' ),
));
register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
'args' => array(
'id' => array(
'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
'type' => 'integer',
),
'attribute_id' => array(
'description' => __( 'Unique identifier for the attribute of the terms.', 'woocommerce' ),
'type' => 'integer',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => array( $this, 'delete_item' ),
'permission_callback' => array( $this, 'delete_item_permissions_check' ),
'args' => array(
'force' => array(
'default' => false,
'type' => 'boolean',
'description' => __( 'Required to be true, as resource does not support trashing.', 'woocommerce' ),
),
),
),
'schema' => array( $this, 'get_public_item_schema' ),
) );
register_rest_route( $this->namespace, '/' . $this->rest_base . '/batch', array(
'args' => array(
'attribute_id' => array(
'description' => __( 'Unique identifier for the attribute of the terms.', 'woocommerce' ),
'type' => 'integer',
),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'batch_items' ),
'permission_callback' => array( $this, 'batch_items_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
'schema' => array( $this, 'get_public_batch_schema' ),
) );
}
/**
* Prepare a single product attribute term output for response.
*
* @param WP_Term $item Term object.
* @param WP_REST_Request $request
* @return WP_REST_Response $response
*/
public function prepare_item_for_response( $item, $request ) {
// Get term order.
$menu_order = get_woocommerce_term_meta( $item->term_id, 'order_' . $this->taxonomy );
$data = array(
'id' => (int) $item->term_id,
'name' => $item->name,
'slug' => $item->slug,
'description' => $item->description,
'menu_order' => (int) $menu_order,
'count' => (int) $item->count,
);
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
$response = rest_ensure_response( $data );
$response->add_links( $this->prepare_links( $item, $request ) );
/**
* Filter a term item returned from the API.
*
* Allows modification of the term data right before it is returned.
*
* @param WP_REST_Response $response The response object.
* @param object $item The original term object.
* @param WP_REST_Request $request Request used to generate the response.
*/
return apply_filters( "woocommerce_rest_prepare_{$this->taxonomy}", $response, $item, $request );
}
/**
* Update term meta fields.
*
* @param WP_Term $term
* @param WP_REST_Request $request
* @return bool|WP_Error
*/
protected function update_term_meta_fields( $term, $request ) {
$id = (int) $term->term_id;
update_woocommerce_term_meta( $id, 'order_' . $this->taxonomy, $request['menu_order'] );
return true;
}
/**
* Get the Attribute Term's schema, conforming to JSON Schema.
*
* @return array
*/
public function get_item_schema() {
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'product_attribute_term',
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'name' => array(
'description' => __( 'Term name.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
),
'slug' => array(
'description' => __( 'An alphanumeric identifier for the resource unique to its type.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'arg_options' => array(
'sanitize_callback' => 'sanitize_title',
),
),
'description' => array(
'description' => __( 'HTML description of the resource.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'arg_options' => array(
'sanitize_callback' => 'wp_filter_post_kses',
),
),
'menu_order' => array(
'description' => __( 'Menu order, used to custom sort the resource.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'count' => array(
'description' => __( 'Number of published products for the resource.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
),
);
return $this->add_additional_fields_schema( $schema );
}
}
| Kilbourne/biosphaera | web/app/plugins/woocommerce/includes/api/class-wc-rest-product-attribute-terms-controller.php | PHP | mit | 7,765 |
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
var isWebGL2 = capabilities.isWebGL2;
var mode;
function setMode( value ) {
mode = value;
}
function render( start, count ) {
gl.drawArrays( mode, start, count );
info.update( count, mode );
}
function renderInstances( geometry, start, count, primcount ) {
if ( primcount === 0 ) return;
var extension, methodName;
if ( isWebGL2 ) {
extension = gl;
methodName = 'drawArraysInstanced';
} else {
extension = extensions.get( 'ANGLE_instanced_arrays' );
methodName = 'drawArraysInstancedANGLE';
if ( extension === null ) {
console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
return;
}
}
extension[ methodName ]( mode, start, count, primcount );
info.update( count, mode, primcount );
}
//
this.setMode = setMode;
this.render = render;
this.renderInstances = renderInstances;
}
export { WebGLBufferRenderer };
| SpinVR/three.js | src/renderers/webgl/WebGLBufferRenderer.js | JavaScript | mit | 1,103 |
// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2008-2016 National ICT Australia (NICTA)
//
// 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.
// ------------------------------------------------------------------------
//! \addtogroup spglue_plus
//! @{
template<typename T1, typename T2>
arma_hot
inline
void
spglue_plus::apply(SpMat<typename T1::elem_type>& out, const SpGlue<T1,T2,spglue_plus>& X)
{
arma_extra_debug_sigprint();
typedef typename T1::elem_type eT;
const SpProxy<T1> pa(X.A);
const SpProxy<T2> pb(X.B);
const bool is_alias = pa.is_alias(out) || pb.is_alias(out);
if(is_alias == false)
{
spglue_plus::apply_noalias(out, pa, pb);
}
else
{
SpMat<eT> tmp;
spglue_plus::apply_noalias(tmp, pa, pb);
out.steal_mem(tmp);
}
}
template<typename eT, typename T1, typename T2>
arma_hot
inline
void
spglue_plus::apply_noalias(SpMat<eT>& out, const SpProxy<T1>& pa, const SpProxy<T2>& pb)
{
arma_extra_debug_sigprint();
arma_debug_assert_same_size(pa.get_n_rows(), pa.get_n_cols(), pb.get_n_rows(), pb.get_n_cols(), "addition");
if( (pa.get_n_nonzero() != 0) && (pb.get_n_nonzero() != 0) )
{
out.zeros(pa.get_n_rows(), pa.get_n_cols());
// Resize memory to correct size.
out.mem_resize(n_unique(pa, pb, op_n_unique_add()));
// Now iterate across both matrices.
typename SpProxy<T1>::const_iterator_type x_it = pa.begin();
typename SpProxy<T2>::const_iterator_type y_it = pb.begin();
typename SpProxy<T1>::const_iterator_type x_end = pa.end();
typename SpProxy<T2>::const_iterator_type y_end = pb.end();
uword cur_val = 0;
while( (x_it != x_end) || (y_it != y_end) )
{
if(x_it == y_it)
{
const eT val = (*x_it) + (*y_it);
if(val != eT(0))
{
access::rw(out.values[cur_val]) = val;
access::rw(out.row_indices[cur_val]) = x_it.row();
++access::rw(out.col_ptrs[x_it.col() + 1]);
++cur_val;
}
++x_it;
++y_it;
}
else
{
const uword x_it_row = x_it.row();
const uword x_it_col = x_it.col();
const uword y_it_row = y_it.row();
const uword y_it_col = y_it.col();
if((x_it_col < y_it_col) || ((x_it_col == y_it_col) && (x_it_row < y_it_row))) // if y is closer to the end
{
const eT val = (*x_it);
if(val != eT(0))
{
access::rw(out.values[cur_val]) = val;
access::rw(out.row_indices[cur_val]) = x_it_row;
++access::rw(out.col_ptrs[x_it_col + 1]);
++cur_val;
}
++x_it;
}
else
{
const eT val = (*y_it);
if(val != eT(0))
{
access::rw(out.values[cur_val]) = val;
access::rw(out.row_indices[cur_val]) = y_it_row;
++access::rw(out.col_ptrs[y_it_col + 1]);
++cur_val;
}
++y_it;
}
}
}
const uword out_n_cols = out.n_cols;
uword* col_ptrs = access::rwp(out.col_ptrs);
// Fix column pointers to be cumulative.
for(uword c = 1; c <= out_n_cols; ++c)
{
col_ptrs[c] += col_ptrs[c - 1];
}
}
else
{
if(pa.get_n_nonzero() == 0)
{
out = pb.Q;
return;
}
if(pb.get_n_nonzero() == 0)
{
out = pa.Q;
return;
}
}
}
//
//
// spglue_plus2: scalar*(A + B)
template<typename T1, typename T2>
arma_hot
inline
void
spglue_plus2::apply(SpMat<typename T1::elem_type>& out, const SpGlue<T1,T2,spglue_plus2>& X)
{
arma_extra_debug_sigprint();
typedef typename T1::elem_type eT;
const SpProxy<T1> pa(X.A);
const SpProxy<T2> pb(X.B);
const bool is_alias = pa.is_alias(out) || pb.is_alias(out);
if(is_alias == false)
{
spglue_plus::apply_noalias(out, pa, pb);
}
else
{
SpMat<eT> tmp;
spglue_plus::apply_noalias(tmp, pa, pb);
out.steal_mem(tmp);
}
out *= X.aux;
}
//! @}
| ragnarstroberg/ragnar_imsrg | src/armadillo/armadillo_bits/spglue_plus_meat.hpp | C++ | gpl-2.0 | 4,741 |
// (C) Copyright Raffi Enficiaud 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
/// @file
/// @brief tests order of the running unit tests under shuffling
// ***************************************************************************
// Boost.Test
#define BOOST_TEST_MODULE test unit order shuffled test
#include <boost/test/included/unit_test.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/test/tree/visitor.hpp>
#include <boost/test/utils/string_cast.hpp>
#include <boost/test/utils/nullstream.hpp>
typedef boost::onullstream onullstream_type;
namespace ut = boost::unit_test;
namespace tt = boost::test_tools;
#include <cstddef>
#include <iostream>
//____________________________________________________________________________//
void some_test() {}
#define TC( name ) \
boost::unit_test::make_test_case( boost::function<void ()>(some_test), \
BOOST_TEST_STRINGIZE( name ), \
__FILE__, __LINE__ )
//____________________________________________________________________________//
struct tu_order_collector : ut::test_observer {
virtual void test_unit_start( ut::test_unit const& tu )
{
//std::cout << "## TU: " << tu.full_name() << std::endl;
m_order.push_back( tu.p_id );
}
std::vector<ut::test_unit_id> m_order;
};
//____________________________________________________________________________//
static tu_order_collector
run_tree( ut::test_suite* master )
{
std::cout << "## TU: START" << std::endl;
tu_order_collector c;
ut::framework::register_observer( c );
master->p_default_status.value = ut::test_unit::RS_ENABLED;
ut::framework::finalize_setup_phase( master->p_id );
ut::framework::impl::setup_for_execution( *master );
onullstream_type null_output;
ut::unit_test_log.set_stream( null_output );
ut::framework::run( master );
ut::unit_test_log.set_stream( std::cout );
ut::framework::deregister_observer( c );
return c;
}
//____________________________________________________________________________//
struct test_tree {
test_tree() {
master = BOOST_TEST_SUITE( "master" );
std::size_t nb_ts = (std::max)(3, std::rand() % 17);
std::vector<ut::test_suite*> tsuites(1, master); // master is in there
for(std::size_t s = 0; s < nb_ts; s++)
{
tsuites.push_back(BOOST_TEST_SUITE( "ts1_" + boost::unit_test::utils::string_cast(s)));
master->add( tsuites.back() );
}
std::size_t nb_ts2 = (std::max)(3, std::rand() % 11);
for(std::size_t s = 0; s < nb_ts2; s++)
{
tsuites.push_back(BOOST_TEST_SUITE( "ts2_" + boost::unit_test::utils::string_cast(s)));
tsuites[std::rand() % nb_ts]->add( tsuites.back() ); // picking a random one in the first level
}
// generating N tests units, associating them to an aribtrary test suite
for(std::size_t s = 0; s < 10; s++)
{
ut::test_case* tc = boost::unit_test::make_test_case(
boost::function<void ()>(some_test),
"tc_" + boost::unit_test::utils::string_cast(s),
__FILE__, __LINE__ );
tsuites[std::rand() % tsuites.size()]->add(tc);
}
}
ut::test_suite* master;
};
//____________________________________________________________________________//
BOOST_FIXTURE_TEST_CASE( test_no_seed, test_tree )
{
// no seed set
ut::runtime_config::s_arguments_store.set<unsigned int>(ut::runtime_config::RANDOM_SEED, 0);
tu_order_collector res1 = run_tree( master );
tu_order_collector res2 = run_tree( master );
BOOST_TEST( res1.m_order == res2.m_order, tt::per_element() );
}
BOOST_FIXTURE_TEST_CASE( test_seed_to_time, test_tree )
{
// seed = 1 means current time is used.
ut::runtime_config::s_arguments_store.set<unsigned int>(ut::runtime_config::RANDOM_SEED, 1);
tu_order_collector res1 = run_tree( master );
tu_order_collector res2 = run_tree( master );
BOOST_TEST( res1.m_order != res2.m_order ); // some elements might be the same, but not the full sequences
}
BOOST_FIXTURE_TEST_CASE( test_seed_identical, test_tree )
{
// seed = 1 means current time is used.
unsigned int seed = static_cast<unsigned int>( std::time( 0 ) );
ut::runtime_config::s_arguments_store.set<unsigned int>(ut::runtime_config::RANDOM_SEED, seed);
tu_order_collector res1 = run_tree( master );
ut::runtime_config::s_arguments_store.set<unsigned int>(ut::runtime_config::RANDOM_SEED, seed);
tu_order_collector res2 = run_tree( master );
BOOST_TEST( res1.m_order == res2.m_order, tt::per_element() );
// using time seed now
ut::runtime_config::s_arguments_store.set<unsigned int>(ut::runtime_config::RANDOM_SEED, 1);
tu_order_collector res3 = run_tree( master );
BOOST_TEST( res1.m_order != res3.m_order ); // some elements might be the same, but not the full sequences
}
| FFMG/myoddweb.piger | myodd/boost/libs/test/test/test-organization-ts/test_unit-order-shuffled-test.cpp | C++ | gpl-2.0 | 5,316 |
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
///////////////////////////////////////////////////////////////////////////////
// No Warranty
// Except as may be otherwise agreed to in writing, no warranties of any
// kind, whether express or implied, are given by MTK with respect to any MTK
// Deliverables or any use thereof, and MTK Deliverables are provided on an
// "AS IS" basis. MTK hereby expressly disclaims all such warranties,
// including any implied warranties of merchantability, non-infringement and
// fitness for a particular purpose and any warranties arising out of course
// of performance, course of dealing or usage of trade. Parties further
// acknowledge that Company may, either presently and/or in the future,
// instruct MTK to assist it in the development and the implementation, in
// accordance with Company's designs, of certain softwares relating to
// Company's product(s) (the "Services"). Except as may be otherwise agreed
// to in writing, no warranties of any kind, whether express or implied, are
// given by MTK with respect to the Services provided, and the Services are
// provided on an "AS IS" basis. Company further acknowledges that the
// Services may contain errors, that testing is important and Company is
// solely responsible for fully testing the Services and/or derivatives
// thereof before they are used, sublicensed or distributed. Should there be
// any third party action brought against MTK, arising out of or relating to
// the Services, Company agree to fully indemnify and hold MTK harmless.
// If the parties mutually agree to enter into or continue a business
// relationship or other arrangement, the terms and conditions set forth
// hereunder shall remain effective and, unless explicitly stated otherwise,
// shall prevail in the event of a conflict in the terms in any agreements
// entered into between the parties.
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008, MediaTek Inc.
// All rights reserved.
//
// Unauthorized use, practice, perform, copy, distribution, reproduction,
// or disclosure of this information in whole or in part is prohibited.
////////////////////////////////////////////////////////////////////////////////
//! \file AcdkMhalEng.cpp
#define LOG_TAG "AcdkMhalEng"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <linux/rtpm_prio.h>
#include <sys/prctl.h>
#include <unistd.h>
#include <vector>
#include <sys/resource.h>
#include <utils/Errors.h>
#include <utils/threads.h>
#include <utils/String8.h>
#include <utils/KeyedVector.h>
#include <linux/cache.h>
#include <cutils/properties.h>
#include <semaphore.h>
#include <mtkcam/v1/config/PriorityDefs.h>
#include <cutils/pmem.h>
#include "mtkcam/acdk/AcdkTypes.h"
#include "AcdkErrCode.h"
#include "AcdkLog.h"
#include "mtkcam/acdk/AcdkCommon.h"
#include "AcdkCallback.h"
#include "AcdkSurfaceView.h"
#include "AcdkBase.h"
#include "AcdkMhalBase.h"
#include "AcdkUtility.h"
using namespace NSACDK;
using namespace NSAcdkMhal;
#include <mtkcam/camshot/ICamShot.h>
#include <mtkcam/camshot/ISingleShot.h>
#include "mtkcam/exif/IBaseCamExif.h"
#include "mtkcam/exif/CamExif.h"
#include <binder/IMemory.h>
#include <binder/MemoryBase.h>
#include <binder/MemoryHeapBase.h>
#include <utils/RefBase.h>
#include <system/camera.h>
#include <hardware/camera.h>
#include <dlfcn.h>
#include <camera/MtkCamera.h>
namespace
{
camera_module_t *mModule = NULL;
camera_device_t *mDevice = NULL;
int mNumberOfCameras = 0;
}
using namespace android;
using namespace NSCamShot;
#include "AcdkMhalEng.h"
#define MEDIA_PATH "/data"
#define ACDK_MT6582_MDP_WO_IRQ 1 //SL test ACDK_6582_MDP without IRQ don
/*******************************************************************************
* Global variable
*******************************************************************************/
static sem_t g_SemMainHigh, g_SemMainHighBack, g_SemMainHighEnd;
static pthread_t g_threadMainHigh;
static AcdkMhalEng *g_pAcdkMHalEngObj = NULL;
static acdkObserver g_acdkMhalObserver;
static acdkObserver g_acdkMhalCapObserver;
static MUINT32 is_yuv_sensor = 0;
static MINT32 g_acdkMhalEngDebug = 0;
static MBOOL mCaptureDone = MFALSE;
void AcdkMhalLoadModule()
{
if(mNumberOfCameras)
return;
if (hw_get_module(CAMERA_HARDWARE_MODULE_ID,
(const hw_module_t **)&mModule) < 0) {
ACDK_LOGD("Could not load camera HAL module");
mNumberOfCameras = 0;
}
else {
ACDK_LOGD("Loaded \"%s\" camera module", mModule->common.name);
mNumberOfCameras = mModule->get_number_of_cameras();
}
}
status_t AcdkMhalOpenDevice(hw_module_t *module, const char *name)
{
String8 const mName(name);
ACDK_LOGD("Opening camera %s + \n", mName.string());
int rc = module->methods->open(module, mName.string(),
(hw_device_t **)&mDevice);
if (rc != OK) {
ACDK_LOGE("Could not open camera %s: %d", mName.string(), rc);
return rc;
}
ACDK_LOGD("Opening camera %s - \n", mName.string());
return rc;
}
void AcdkMhalReleaseDevice() {
ACDK_LOGD(" AcdkMhalReleaseDevice \n");
if (mDevice->ops->release)
{
mDevice->ops->release(mDevice);
}
//ACDK_LOGD("Destroying camera %s", mName.string());
if(mDevice) {
int rc = mDevice->common.close(&mDevice->common);
if (rc != OK)
ACDK_LOGD("Could not close camera %d", rc);
}
mDevice = NULL;
}
static void __put_memory(camera_memory_t *data);
class CameraHeapMemory : public RefBase {
public:
CameraHeapMemory(int fd, size_t buf_size, uint_t num_buffers = 1) :
mBufSize(buf_size),
mNumBufs(num_buffers)
{
mHeap = new MemoryHeapBase(fd, buf_size * num_buffers);
commonInitialization();
}
CameraHeapMemory(size_t buf_size, uint_t num_buffers = 1) :
mBufSize(buf_size),
mNumBufs(num_buffers)
{
mHeap = new MemoryHeapBase(buf_size * num_buffers);
commonInitialization();
}
void commonInitialization()
{
handle.data = mHeap->base();
handle.size = mBufSize * mNumBufs;
handle.handle = this;
mBuffers = new sp<MemoryBase>[mNumBufs];
for (uint_t i = 0; i < mNumBufs; i++)
mBuffers[i] = new MemoryBase(mHeap,
i * mBufSize,
mBufSize);
handle.release = __put_memory;
}
virtual ~CameraHeapMemory()
{
delete [] mBuffers;
}
size_t mBufSize;
uint_t mNumBufs;
sp<MemoryHeapBase> mHeap;
sp<MemoryBase> *mBuffers;
camera_memory_t handle;
};
static camera_memory_t* __get_memory(int fd, size_t buf_size, uint_t num_bufs,
void *user __attribute__((unused)))
{
ACDK_LOGD("%s __get_memory +", __FUNCTION__);
CameraHeapMemory *mem;
if (fd < 0)
mem = new CameraHeapMemory(buf_size, num_bufs);
else
mem = new CameraHeapMemory(fd, buf_size, num_bufs);
mem->incStrong(mem);
ACDK_LOGD("%s __get_memory -", __FUNCTION__);
return &mem->handle;
}
static void __put_memory(camera_memory_t *data)
{
if (!data)
return;
CameraHeapMemory *mem = static_cast<CameraHeapMemory *>(data->handle);
mem->decStrong(mem);
}
static void __notify_cb(int32_t msg_type, int32_t ext1,
int32_t ext2, void *user)
{
ACDK_LOGD("%s", __FUNCTION__);
}
static void handleMtkExtDataCompressedImage(const sp<IMemory>& dataPtr)
{
MtkCamMsgExtDataHelper MtkExtDataHelper;
if ( ! MtkExtDataHelper.init(dataPtr) ) {
ACDK_LOGE("[%s] MtkCamMsgExtDataHelper::init fail - \r\n", __FUNCTION__);
return;
}
//
uint_t const*const pExtParam = (uint_t const*)MtkExtDataHelper.getExtParamBase();
uint_t const uShutIndex = pExtParam[0];
//
size_t const imageSize = MtkExtDataHelper.getExtParamSize() - sizeof(uint_t) * 1;
ssize_t const imageOffset = MtkExtDataHelper.getExtParamOffset() + sizeof(uint_t) * 1;
// sp<MemoryBase> image = new MemoryBase(MtkExtDataHelper.getHeap(), imageOffset, imageSize);
uint8_t* va = (((uint8_t*)MtkExtDataHelper.getHeap()->getBase())+imageOffset);
ACDK_LOGD("%s va=%p, size=%d, offset=%d", __FUNCTION__, va, imageSize,imageOffset);
g_acdkMhalCapObserver.notify(ACDK_CB_CAPTURE,(MUINT32)va, 0, (MUINT32)imageSize,0);
//
MtkExtDataHelper.uninit();
}
static void __data_cb(int32_t msg_type,
const camera_memory_t *data, unsigned int index,
camera_frame_metadata_t *metadata,
void *user)
{
ACDK_LOGD("%s type %x", __FUNCTION__,msg_type);
sp<CameraHeapMemory> mem(static_cast<CameraHeapMemory *>(data->handle));
if (index >= mem->mNumBufs) {
ACDK_LOGE("%s: invalid buffer index %d, max allowed is %d", __FUNCTION__,
index, mem->mNumBufs);
return;
}
ssize_t offset = 0;
size_t size = 0;
sp<IMemoryHeap> heap = mem->mBuffers[index]->getMemory(&offset, &size);
uint8_t* va = (((uint8_t*)heap->getBase())+offset);
ACDK_LOGD("%s va=%p, size=%d, offset=%d", __FUNCTION__, va, size,offset);
switch (msg_type & ~CAMERA_MSG_PREVIEW_METADATA)
{
case CAMERA_MSG_PREVIEW_FRAME:
//Callback to upper layer
g_acdkMhalObserver.notify(ACDK_CB_PREVIEW,(MUINT32)va,(MUINT32)size,(MUINT32)size,0);
break;
case CAMERA_MSG_POSTVIEW_FRAME:
//Callback to upper layer
ACDK_LOGD("CAMERA_MSG_POSTVIEW_FRAME=%d",CAMERA_MSG_POSTVIEW_FRAME);
g_acdkMhalObserver.notify(ACDK_CB_PREVIEW,(MUINT32)va,(MUINT32)size,(MUINT32)size,0);
break;
case MTK_CAMERA_MSG_EXT_DATA:{
MtkCamMsgExtDataHelper MtkExtDataHelper;
if ( ! MtkExtDataHelper.init(mem->mBuffers[index]) ) {
ACDK_LOGE("[%s] MtkCamMsgExtDataHelper::init fail", __FUNCTION__);
return;
}
void* const pvExtParam = MtkExtDataHelper.getExtParamBase();
size_t const ExtParamSize = MtkExtDataHelper.getExtParamSize();
switch (MtkExtDataHelper.getExtMsgType())
{
case MTK_CAMERA_MSG_EXT_DATA_COMPRESSED_IMAGE:
handleMtkExtDataCompressedImage(mem->mBuffers[index]);
mCaptureDone = MTRUE;
break;
default:
break;
}
}
break;
default:
return;
}
#if 0
MINT32 i4WriteCnt = 0;
char szFileName[256];
ACDK_LOGD("%s va=%p, size=%d, offset=%d", __FUNCTION__, va, size,offset);
sprintf(szFileName, "%s/acdkCap.yuv",MEDIA_PATH);
FILE *pFp = fopen(szFileName, "wb");
if(NULL == pFp)
{
ACDK_LOGE("Can't open file to save image");
}
i4WriteCnt = fwrite(va, 1, size, pFp);
fflush(pFp);
if(0 != fsync(fileno(pFp)))
{
fclose(pFp);
}
#endif
}
static void __data_cb_timestamp(nsecs_t timestamp, int32_t msg_type,
const camera_memory_t *data, unsigned index,
void *user)
{
}
String8 flatten(DefaultKeyedVector<String8,String8>const& rMap)
{
String8 flattened("");
size_t size = rMap.size();
for (size_t i = 0; i < size; i++) {
String8 k, v;
k = rMap.keyAt(i);
v = rMap.valueAt(i);
flattened += k;
flattened += "=";
flattened += v;
if (i != size-1)
flattened += ";";
}
return flattened;
}
void unflatten(const String8 ¶ms, DefaultKeyedVector<String8,String8>& rMap)
{
const char *a = params.string();
const char *b;
rMap.clear();
for (;;) {
// Find the bounds of the key name.
b = strchr(a, '=');
if (b == 0)
break;
// Create the key string.
String8 k(a, (size_t)(b-a));
// Find the value.
a = b+1;
b = strchr(a, ';');
if (b == 0) {
// If there's no semicolon, this is the last item.
String8 v(a);
rMap.add(k, v);
break;
}
String8 v(a, (size_t)(b-a));
rMap.add(k, v);
a = b+1;
}
}
void set(DefaultKeyedVector<String8,String8>& rMap, const char *key, const char *value)
{
// XXX i think i can do this with strspn()
if (strchr(key, '=') || strchr(key, ';')) {
//XXX ALOGE("Key \"%s\"contains invalid character (= or ;)", key);
return;
}
if (strchr(value, '=') || strchr(value, ';')) {
//XXX ALOGE("Value \"%s\"contains invalid character (= or ;)", value);
return;
}
rMap.replaceValueFor(String8(key), String8(value));
}
/*******************************************************************************
* AcdkMhalEng
* brif : Constructor
*******************************************************************************/
AcdkMhalEng::AcdkMhalEng()
{
mAcdkMhalState = ACDK_MHAL_NONE;
mFocusDone = MFALSE;
mFocusSucceed = MFALSE;
mReadyForCap = MFALSE;
mCaptureDone = MFALSE;
memset(&mAcdkMhalPrvParam,0,sizeof(acdkMhalPrvParam_t));
g_pAcdkMHalEngObj = this;
}
/*******************************************************************************
* acdkMhalGetState
* brif : get state of acdk mhal
*******************************************************************************/
MVOID AcdkMhalEng::acdkMhalSetState(acdkMhalState_e newState)
{
Mutex::Autolock lock(mLock);
ACDK_LOGD("Now(0x%04x), Next(0x%04x)", mAcdkMhalState, newState);
if(newState == ACDK_MHAL_ERROR)
{
goto ACDK_MHAL_SET_STATE_EXIT;
}
switch(mAcdkMhalState)
{
case ACDK_MHAL_NONE:
switch(newState)
{
case ACDK_MHAL_INIT:
case ACDK_MHAL_UNINIT:
break;
default:
//ACDK_ASSERT(0, "State error ACDK_MHAL_NONE");
ACDK_LOGE("State error ACDK_MHAL_NONE");
break;
}
break;
case ACDK_MHAL_INIT:
switch(newState)
{
case ACDK_MHAL_IDLE:
break;
default:
//ACDK_ASSERT(0, "State error MHAL_CAM_INIT");
ACDK_LOGE("State error ACDK_MHAL_INIT");
break;
}
break;
case ACDK_MHAL_IDLE:
switch(newState)
{
case ACDK_MHAL_IDLE:
case ACDK_MHAL_PREVIEW:
case ACDK_MHAL_CAPTURE:
case ACDK_MHAL_UNINIT:
break;
default:
//ACDK_ASSERT(0, "State error MHAL_CAM_IDLE");
ACDK_LOGE("State error ACDK_MHAL_IDLE");
break;
}
break;
case ACDK_MHAL_PREVIEW:
switch(newState)
{
case ACDK_MHAL_IDLE:
case ACDK_MHAL_PREVIEW:
case ACDK_MHAL_PRE_CAPTURE:
case ACDK_MHAL_PREVIEW_STOP:
break;
default:
//ACDK_ASSERT(0, "State error MHAL_CAM_PREVIEW");
ACDK_LOGE("State error ACDK_MHAL_PREVIEW");
break;
}
break;
case ACDK_MHAL_PRE_CAPTURE:
switch(newState)
{
case ACDK_MHAL_PREVIEW_STOP:
break;
default:
//ACDK_ASSERT(0, "State error MHAL_CAM_PRE_CAPTURE");
ACDK_LOGE("State error ACDK_MHAL_PRE_CAPTURE");
break;
}
break;
case ACDK_MHAL_PREVIEW_STOP:
switch(newState)
{
case ACDK_MHAL_IDLE:
break;
default:
//ACDK_ASSERT(0, "State error ACDK_MHAL_PREVIEW_STOP");
ACDK_LOGE("State error ACDK_MHAL_PREVIEW_STOP");
break;
}
break;
case ACDK_MHAL_CAPTURE:
switch(newState)
{
case ACDK_MHAL_IDLE:
break;
default:
//ACDK_ASSERT(0, "State error MHAL_CAM_CAPTURE");
ACDK_LOGE("State error ACDK_MHAL_CAPTURE");
break;
}
break;
case ACDK_MHAL_ERROR:
switch(newState)
{
case ACDK_MHAL_IDLE:
case ACDK_MHAL_UNINIT:
break;
default:
//ACDK_ASSERT(0, "State error ACDK_MHAL_ERROR");
ACDK_LOGE("State error ACDK_MHAL_ERROR");
break;
}
break;
default:
//ACDK_ASSERT(0, "Unknown state");
ACDK_LOGE("Unknown state");
break;
}
ACDK_MHAL_SET_STATE_EXIT:
mAcdkMhalState = newState;
ACDK_LOGD("X, state(0x%04x)", mAcdkMhalState);
}
/*******************************************************************************
* acdkMhalGetState
* brif : get state of acdk mhal
*******************************************************************************/
acdkMhalState_e AcdkMhalEng::acdkMhalGetState()
{
Mutex::Autolock _l(mLock);
return mAcdkMhalState;
}
/*******************************************************************************
* acdkMhalReadyForCap
* brif : get status of mReadyForCap falg
*******************************************************************************/
MBOOL AcdkMhalEng::acdkMhalReadyForCap()
{
return mReadyForCap;
}
/*******************************************************************************
* acdkMhalProcLoop
* brif : preview and capture thread executing function
*******************************************************************************/
static MVOID *acdkMhalProcLoop(MVOID *arg)
{
::prctl(PR_SET_NAME,"acdkMhalProcLoop",0,0,0);
MINT32 const policy = SCHED_RR;
MINT32 const priority = PRIO_RT_CAMERA_PREVIEW;
struct sched_param sched_p;
::sched_getparam(0, &sched_p);
sched_p.sched_priority = priority;
::sched_setscheduler(0, policy, &sched_p);
::sched_getparam(0, &sched_p);
ACDK_LOGD("policy:(expect, result)=(%d, %d), priority:(expect, result)=(%d, %d),tid=%d", policy,
::sched_getscheduler(0),
priority,
sched_p.sched_priority,
::gettid());
// detach thread => cannot be join
::pthread_detach(::pthread_self());
acdkMhalState_e eState;
eState = g_pAcdkMHalEngObj->acdkMhalGetState();
while(eState != ACDK_MHAL_UNINIT)
{
ACDK_LOGD("Wait semMainHigh");
::sem_wait(&g_SemMainHigh); // wait here until someone use sem_post() to wake this semaphore up
ACDK_LOGD("Got semMainHigh");
eState = g_pAcdkMHalEngObj->acdkMhalGetState();
switch(eState)
{
case ACDK_MHAL_PREVIEW:
g_pAcdkMHalEngObj->acdkMhalPreviewProc();
::sem_post(&g_SemMainHighBack);
break;
case ACDK_MHAL_CAPTURE:
g_pAcdkMHalEngObj->acdkMhalCaptureProc();
break;
case ACDK_MHAL_UNINIT:
break;
default:
ACDK_LOGD("T.B.D");
break;
}
eState = g_pAcdkMHalEngObj->acdkMhalGetState();
}
::sem_post(&g_SemMainHighEnd);
ACDK_LOGD("-");
return NULL;
}
/*******************************************************************************
* destroyInstanc
* brif : destroy AcdkMhalEng object
*******************************************************************************/
void AcdkMhalEng::destroyInstance()
{
g_pAcdkMHalEngObj = NULL;
delete this;
}
/*******************************************************************************
* acdkMhalInit
* brif : initialize camera
*******************************************************************************/
MINT32 AcdkMhalEng::acdkMhalInit()
{
ACDK_LOGD("+");
//====== Loca Variable Declaration ======
MINT32 err = ACDK_RETURN_NO_ERROR;
//====== Acdk Mhal State Setting ======
mAcdkMhalState = ACDK_MHAL_INIT; //set state to Init state
//====== Get Debug Property ======
char value[PROPERTY_VALUE_MAX] = {'\0'};
property_get("camera.acdk.debug", value, "0");
g_acdkMhalEngDebug = atoi(value);
ACDK_LOGD("g_acdkMhalEngDebug(%d)",g_acdkMhalEngDebug);
//====== Init Thread for Preview and Capture ======
// Init semphore
::sem_init(&g_SemMainHigh, 0, 0);
::sem_init(&g_SemMainHighBack, 0, 0);
::sem_init(&g_SemMainHighEnd, 0, 0);
// Create main thread for preview and capture
pthread_attr_t const attr = {0, NULL, 1024 * 1024, 4096, SCHED_RR, PRIO_RT_CAMERA_PREVIEW};
pthread_create(&g_threadMainHigh, &attr, acdkMhalProcLoop, NULL);
//=== Set State to Idle State ======
acdkMhalSetState(ACDK_MHAL_IDLE);
ACDK_LOGD("-");
return err;
}
/*******************************************************************************
* acdkMhalUninit
* brif : Uninitialize camera
*******************************************************************************/
MINT32 AcdkMhalEng::acdkMhalUninit()
{
ACDK_LOGD("+");
//====== Local Variable Declaration ======
MINT32 err = ACDK_RETURN_NO_ERROR;
acdkMhalState_e eState;
//====== Uninitialization ======
// Check it is in the idle mode
// If it is not, has to wait until idle
eState = acdkMhalGetState();
ACDK_LOGD("eState(0x%x)",eState);
if(eState != ACDK_MHAL_NONE)
{
if((eState != ACDK_MHAL_IDLE) && (eState != ACDK_MHAL_ERROR))
{
ACDK_LOGD("Camera is not in the idle state");
if(eState & ACDK_MHAL_PREVIEW_MASK)
{
err = acdkMhalPreviewStop();
if(err != ACDK_RETURN_NO_ERROR)
{
ACDK_LOGE("acdkMhalPreviewStop fail(0x%x)",err);
}
}
else if(eState & ACDK_MHAL_CAPTURE_MASK)
{
err = acdkMhalCaptureStop();
if(err != ACDK_RETURN_NO_ERROR)
{
ACDK_LOGE("acdkMhalCaptureStop fail(0x%x)",err);
}
}
// Polling until idle
while(eState != ACDK_MHAL_IDLE)
{
// Wait 10 ms per time
usleep(10000);
eState = acdkMhalGetState();
}
ACDK_LOGD("Now camera is in the idle state");
}
//====== Set State to Uninit State ======
acdkMhalSetState(ACDK_MHAL_UNINIT);
//====== Semephore Process ======
//post sem
ACDK_LOGD("post g_SemMainHigh");
::sem_post(&g_SemMainHigh);
//wait sem
ACDK_LOGD("wait for g_SemMainHighEnd");
::sem_wait(&g_SemMainHighEnd);
ACDK_LOGD("got g_SemMainHighEnd");
}
else
{
acdkMhalSetState(ACDK_MHAL_UNINIT);
}
ACDK_LOGD("-");
return err;
}
/*******************************************************************************
* acdkMhalCBHandle
* brif : callback handler
*******************************************************************************/
MVOID AcdkMhalEng::acdkMhalCBHandle(MUINT32 a_type, MUINT32 a_addr1, MUINT32 a_addr2, MUINT32 const a_dataSize)
{
ACDK_LOGD_DYN(g_acdkMhalEngDebug,"+");
if(!g_acdkMhalObserver)
{
ACDK_LOGE("callback is NULL");
}
// Callback to upper layer
g_acdkMhalObserver.notify(a_type, a_addr1, a_addr2, a_dataSize);
}
/*******************************************************************************
* acdkMhal3ASetParm
* brif : set 3A parameter
*******************************************************************************/
MINT32 AcdkMhalEng::acdkMhal3ASetParam(MINT32 devID, MUINT8 IsFactory)
{
ACDK_LOGD("devID(%d)",devID);
return ACDK_RETURN_NO_ERROR;
}
#define PASS2_FULLG
/*******************************************************************************
* acdkMhalPreviewStart
* brif : Start preview
*******************************************************************************/
MINT32 AcdkMhalEng::acdkMhalPreviewStart(MVOID *a_pBuffIn)
{
ACDK_LOGD("+");
char szUser[32] = "acdk_preview";
ACDK_ASSERT(acdkMhalGetState() == ACDK_MHAL_IDLE, "[acdkMhalPreviewStart] Camera State is not IDLE");
//====== Local Variable Declaration ======
MINT32 err = ACDK_RETURN_NO_ERROR;
memcpy(&mAcdkMhalPrvParam, a_pBuffIn, sizeof(acdkMhalPrvParam_t));
ACDK_LOGD("%s test Cam Device", __FUNCTION__);
AcdkMhalLoadModule();
char const* sym = "MtkCam_setProperty";
void* pfn = ::dlsym(mModule->common.dso, sym);
if ( ! pfn ) {
ACDK_LOGE("Cannot find symbol: %s", sym);
// return INVALID_OPERATION;
}
String8 key = String8("client.appmode");
String8 value = String8("MtkEng");
reinterpret_cast<status_t(*)(String8 const&, String8 const&)>(pfn)(key, value);
if(mAcdkMhalPrvParam.sensorIndex == 0)
AcdkMhalOpenDevice((hw_module_t *)mModule, "0");
else
AcdkMhalOpenDevice((hw_module_t *)mModule, "1");
ACDK_LOGD("+ set_callbacks \n");
if (mDevice->ops->set_callbacks) {
mDevice->ops->set_callbacks(mDevice,
__notify_cb,
__data_cb,
__data_cb_timestamp,
__get_memory,
&mDevice);
}
ACDK_LOGD("- set_callbacks");
//if (mDevice->ops->enable_msg_type)
// mDevice->ops->enable_msg_type(mDevice, CAMERA_MSG_PREVIEW_FRAME);
if (mDevice->ops->enable_msg_type)
mDevice->ops->enable_msg_type(mDevice, CAMERA_MSG_PREVIEW_FRAME |CAMERA_MSG_COMPRESSED_IMAGE | CAMERA_MSG_POSTVIEW_FRAME);
DefaultKeyedVector<String8,String8> map;
if (mDevice->ops->get_parameters) {
char *temp = mDevice->ops->get_parameters(mDevice);
String8 str_parms(temp);
if (mDevice->ops->put_parameters)
mDevice->ops->put_parameters(mDevice, temp);
else
free(temp);
unflatten(str_parms, map);
}
String8 sPrvSize = String8("");
if( 1 == mAcdkMhalPrvParam.frmParam.orientation % 2 )
{
//odd means 90 or 270 rotation
sPrvSize = String8::format("%dx%d", mAcdkMhalPrvParam.frmParam.h, mAcdkMhalPrvParam.frmParam.w);
}
else
{
//even means 0 or 180 rotation
sPrvSize = String8::format("%dx%d", mAcdkMhalPrvParam.frmParam.w, mAcdkMhalPrvParam.frmParam.h);
}
String8 sPrvList = map.valueFor( String8("preview-size-values") );
ACDK_LOGD("Prv Size: %s; PrvList: %s", sPrvSize.string(), sPrvList.string() );
if( NULL == strstr( sPrvList, sPrvSize ) )
{
ACDK_LOGE("Prv Size : %s is not supported. Try 640x480", sPrvSize.string());
sPrvSize = String8("640x480");
if( 1 == mAcdkMhalPrvParam.frmParam.orientation % 2 )
{
mAcdkMhalPrvParam.frmParam.h = 640;
mAcdkMhalPrvParam.frmParam.w = 480;
}
else
{
mAcdkMhalPrvParam.frmParam.h = 480;
mAcdkMhalPrvParam.frmParam.w = 640;
}
if( NULL == strstr( sPrvList, sPrvSize ) )
{
ACDK_LOGE("640x480 is not supported.");
err = ACDK_RETURN_INVALID_PARA;
goto acdkMhalPreviewStart_Exit;
}
}
set(map, "preview-size", sPrvSize);
/*if(mAcdkMhalPrvParam.frmParam.orientation == 1)
{
if(mAcdkMhalPrvParam.frmParam.h > 1280)
set(map, "preview-size", "1440x1080");
else if(mAcdkMhalPrvParam.frmParam.h > 800)
set(map, "preview-size", "1280x720");
else
set(map, "preview-size", "800x600");
}
else
{
if(mAcdkMhalPrvParam.frmParam.w > 1280)
set(map, "preview-size", "1440x1080");
else if(mAcdkMhalPrvParam.frmParam.w > 800)
set(map, "preview-size", "1280x720");
else
set(map, "preview-size", "800x600");
}*/
set(map, "preview-format", "yuv420p");
switch( mAcdkMhalPrvParam.mHDR_EN )
{
case 1: //ivhdr: only video mode supports
set(map, "video-hdr", "on");
set(map, "rawsave-mode", "4");
break;
case 2: //mvhdr: only preview/capture modes support
set(map, "video-hdr", "on");
set(map, "rawsave-mode", "1");
break;
default:
set(map, "video-hdr", "off");
}
ACDK_LOGD("%s: mHDR_EN(%d)", __FUNCTION__, mAcdkMhalPrvParam.mHDR_EN );
mDevice->ops->set_parameters(mDevice, flatten(map).string());
//====== Setting Callback ======
g_acdkMhalObserver = mAcdkMhalPrvParam.acdkMainObserver;
//====== Set State to Preview State ======
acdkMhalSetState(ACDK_MHAL_PREVIEW);
//====== Post Sem ======
::sem_post(&g_SemMainHigh);
acdkMhalPreviewStart_Exit:
ACDK_LOGD("-");
return err;
}
/*******************************************************************************
* acdkMhalPreviewStop
* brif : stop preview
*******************************************************************************/
MINT32 AcdkMhalEng::acdkMhalPreviewStop()
{
ACDK_LOGD("+");
//====== Local Variable Declaration ======
MINT32 err = ACDK_RETURN_NO_ERROR;
acdkMhalState_e state = acdkMhalGetState();
//====== Check State ======
//check AcdkMhal state
ACDK_LOGD("state(%d)", state);
if(state == ACDK_MHAL_IDLE)
{
ACDK_LOGD("is in IDLE state");
return err;
}
else if(state != ACDK_MHAL_PREVIEW_STOP)
{
if(state & ACDK_MHAL_PREVIEW_MASK)
{
acdkMhalSetState(ACDK_MHAL_PREVIEW_STOP);
}
else if(state == ACDK_MHAL_PRE_CAPTURE)
{
// In preCapture, has to wait 3A ready flag
ACDK_LOGD("it is ACDK_MHAL_PRE_CAPTURE state");
acdkMhalSetState(ACDK_MHAL_PREVIEW_STOP);
}
else if(state == ACDK_MHAL_CAPTURE)
{
// It is in capture flow now, preview has been already stopped
ACDK_LOGD("it is ACDK_MHAL_CAPTURE state");
state = acdkMhalGetState();
while(state == ACDK_MHAL_CAPTURE)
{
usleep(20);
state = acdkMhalGetState();
}
acdkMhalSetState(ACDK_MHAL_IDLE);
}
else
{
// Unknown
ACDK_LOGE("un know state(%d)", state);
}
}
//====== Wait Semaphore ======
ACDK_LOGD("Wait g_SemMainHighBack");
::sem_wait(&g_SemMainHighBack);
ACDK_LOGD("Got g_SemMainHighBack");
//====== Stop Preview ======
//====== Initialize Member Variable =====
memset(&mAcdkMhalPrvParam,0,sizeof(acdkMhalPrvParam_t));
//====== Set Acdk Mhal State ======
acdkMhalSetState(ACDK_MHAL_IDLE);
ACDK_LOGD("-");
return err;
}
/*******************************************************************************
* acdkMhalPreCapture
* brif : change ACDK mhal state to preCapture
*******************************************************************************/
MINT32 AcdkMhalEng::acdkMhalPreCapture()
{
ACDK_LOGD("+");
MINT32 err = ACDK_RETURN_NO_ERROR;
//====== Change State ======
acdkMhalSetState(ACDK_MHAL_PRE_CAPTURE);
mReadyForCap = MTRUE;
ACDK_LOGD("-");
return err;
}
/*******************************************************************************
* acdkMhalCaptureStart
* brif : init capture
*******************************************************************************/
MINT32 AcdkMhalEng::acdkMhalCaptureStart(MVOID *a_pBuffIn)
{
MINT32 err = ACDK_RETURN_NO_ERROR;
MUINT32 CaptureMode;
MUINT32 MFLL_EN;
MUINT32 HDR_EN;
eACDK_CAP_FORMAT eImgType;
char szName[256];
ACDK_LOGD("+");
memcpy(&mAcdkMhalCapParam, a_pBuffIn, sizeof(acdkMhalCapParam_t));
CaptureMode = mAcdkMhalCapParam.CaptureMode;
eImgType = (eACDK_CAP_FORMAT)mAcdkMhalCapParam.mCapType;
MFLL_EN = mAcdkMhalCapParam.mMFLL_EN;
HDR_EN = mAcdkMhalCapParam.mHDR_EN;
EMultiNR_Mode eMultiNR = (EMultiNR_Mode)mAcdkMhalCapParam.mEMultiNR;
sprintf(szName, "%04dx%04d ", mAcdkMhalCapParam.mCapWidth, mAcdkMhalCapParam.mCapHeight);
ACDK_LOGD("Picture Size:%s\n", szName);
ACDK_LOGD("CaptureMode(%d), eImgType(%d),MFLL_En(%d), eMultiNR(%d)", CaptureMode, eImgType, MFLL_EN, eMultiNR);
// set parameter
DefaultKeyedVector<String8,String8> map;
if (mDevice->ops->get_parameters) {
char *temp = mDevice->ops->get_parameters(mDevice);
String8 str_parms(temp);
if (mDevice->ops->put_parameters)
mDevice->ops->put_parameters(mDevice, temp);
else
free(temp);
unflatten(str_parms, map);
}
//Set picture size
set(map, "picture-size", szName);
// PURE_RAW8_TYPE =0x04, PURE_RAW10_TYPE = 0x08
// PROCESSED_RAW8_TYPE = 0x10, PROCESSED_RAW10_TYPE = 0x20
if(eImgType & 0x3C)
{
// rawsave-mode : 1,preview 2,Capture 3,jpeg only 4,video 5,slim video1 6,slim video2
// 7,custom1 8,custom2 9,custom3 10,custom4 11,custom5
// isp-mode : 0: process raw, 1:pure raw
set(map, "camera-mode", "0");
set(map, "afeng_raw_dump_flag", "1");
set(map, "rawfname", "/data/");
switch(eImgType)
{
case PURE_RAW8_TYPE:
set(map, "isp-mode", "1");
set(map, "rawsave-mode", "2");
break;
case PURE_RAW10_TYPE:
set(map, "isp-mode", "1");
set(map, "rawsave-mode", "2");
break;
case PROCESSED_RAW8_TYPE:
set(map, "isp-mode", "0");
set(map, "rawsave-mode", "2");
break;
case PROCESSED_RAW10_TYPE:
set(map, "isp-mode", "0");
set(map, "rawsave-mode", "2");
break;
default:
break;
}
}
switch(CaptureMode)
{
case SENSOR_SCENARIO_ID_NORMAL_PREVIEW:
set(map, "rawsave-mode", "1");
break;
case SENSOR_SCENARIO_ID_NORMAL_CAPTURE:
set(map, "rawsave-mode", "2");
break;
case SENSOR_SCENARIO_ID_NORMAL_VIDEO:
set(map, "rawsave-mode", "4");
break;
case SENSOR_SCENARIO_ID_SLIM_VIDEO1:
set(map, "rawsave-mode", "5");
break;
case SENSOR_SCENARIO_ID_SLIM_VIDEO2:
set(map, "rawsave-mode", "6");
break;
case SENSOR_SCENARIO_ID_CUSTOM1:
set(map, "rawsave-mode", "7");
break;
case SENSOR_SCENARIO_ID_CUSTOM2:
set(map, "rawsave-mode", "8");
break;
case SENSOR_SCENARIO_ID_CUSTOM3:
set(map, "rawsave-mode", "9");
break;
case SENSOR_SCENARIO_ID_CUSTOM4:
set(map, "rawsave-mode", "10");
break;
case SENSOR_SCENARIO_ID_CUSTOM5:
set(map, "rawsave-mode", "11");
break;
default:
set(map, "rawsave-mode", "1");
break;
}
if(MFLL_EN == 1)
{
set(map, "mfb", "mfll");
set(map, "isp-mode", "0");
}
else
set(map, "mfb", "off");
if(HDR_EN == 1 || HDR_EN == 2) // ivhdr(1) or mvhdr(2)
set(map, "video-hdr", "on");
else
set(map, "video-hdr", "off");
ACDK_LOGD("acdkMhalCaptureStart: HDR_EN = %d\n", HDR_EN);
set(map, "mnr-e", "1");//enable manual multi-NR
/* manual multi-NR type:
0: Disable
1: HWNR
2: SWNR
*/
if(eMultiNR == EMultiNR_Off) set(map, "mnr-t", "0");
else if (eMultiNR == EMultiNR_HW) set(map, "mnr-t", "1");
else if (eMultiNR == EMultiNR_SW) set(map, "mnr-t", "2");
else
{
ACDK_LOGD("Error: eMultiNR = %d\n", eMultiNR);
set(map, "mnr-t", "0");
}
mDevice->ops->set_parameters(mDevice, flatten(map).string());
//====== Setting Callback ======
g_acdkMhalCapObserver = mAcdkMhalCapParam.acdkMainObserver;
mDevice->ops->take_picture(mDevice);
ACDK_LOGD("-");
return err;
}
/*******************************************************************************
* acdkMhalCaptureStop
* brif : stop capture
*******************************************************************************/
MINT32 AcdkMhalEng::acdkMhalCaptureStop()
{
ACDK_LOGD("+");
MINT32 err = ACDK_RETURN_NO_ERROR;
while(mCaptureDone == MFALSE)
{
usleep(200);
}
mCaptureDone = MFALSE;
ACDK_LOGD("-");
return err;
}
/*******************************************************************************
* acdkMhalPreviewProc
* brif : handle flow control of preview
*******************************************************************************/
MINT32 AcdkMhalEng::acdkMhalPreviewProc()
{
ACDK_LOGD_DYN(g_acdkMhalEngDebug,"+");
ACDK_LOGD("Preview start");
mDevice->ops->start_preview(mDevice);
//pass1 continuous
while((ACDK_MHAL_PREVIEW_STOP != acdkMhalGetState()))
{
usleep(500);
}
mDevice->ops->stop_preview(mDevice);
AcdkMhalReleaseDevice();
ACDK_LOGD_DYN(g_acdkMhalEngDebug,"-");
return ACDK_RETURN_NO_ERROR;
}
/*******************************************************************************
* acdkMhalCaptureProc
* brif : handle flow control of capture
*******************************************************************************/
MINT32 AcdkMhalEng::acdkMhalCaptureProc()
{
return ACDK_RETURN_NO_ERROR;
}
/*******************************************************************************
*
*******************************************************************************/
MUINT32 AcdkMhalEng::acdkMhalGetShutTime()
{
return ACDK_RETURN_NO_ERROR;
}
/*******************************************************************************
*
*******************************************************************************/
MVOID AcdkMhalEng::acdkMhalSetShutTime(MUINT32 a_time)
{
}
/*******************************************************************************
*
*******************************************************************************/
MUINT32 AcdkMhalEng::acdkMhalGetAFInfo()
{
MUINT32 u32AFInfo;
ACDK_LOGD("acdkMhalGetAFInfo");
u32AFInfo = g_pAcdkMHalEngObj->mFocusSucceed;
return u32AFInfo;
}
/*******************************************************************************
* doNotifyCb
*******************************************************************************/
void AcdkMhalEng::doNotifyCb(int32_t _msgType,
int32_t _ext1,
int32_t _ext2,
int32_t _ext3)
{
ACDK_LOGD("_msgType(%d),_ext1(%d)",_msgType,_ext1);
ACDK_LOGD("-");
}
/*******************************************************************************
* doDataCb
*******************************************************************************/
void AcdkMhalEng::doDataCb(int32_t _msgType,
void *_data,
uint32_t _size)
{
}
| visi0nary/mediatek | mt6732/mediatek/platform/mt6752/hardware/mtkcam/acdk/src/acdk/AcdkMhalEng.cpp | C++ | gpl-2.0 | 41,998 |
// Copyright (C) 2008-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 22.2.6.1.1 money_get members
#include <locale>
#include <sstream>
#include <testsuite_hooks.h>
class my_moneypunct : public std::moneypunct<char>
{
protected:
//this should disable fraction part of monetary value
int do_frac_digits() const { return 0; }
};
// libstdc++/38399
void test01()
{
using namespace std;
locale loc(locale(), new my_moneypunct());
stringstream ss("123.455");
ss.imbue(loc);
string digits;
ios_base::iostate err;
istreambuf_iterator<char> iter =
use_facet<money_get<char> >(loc).get(ss, 0, false, ss, err, digits);
string rest = string(iter, istreambuf_iterator<char>());
VERIFY( digits == "123" );
VERIFY( rest == ".455" );
}
int main()
{
test01();
return 0;
}
| mickael-guene/gcc | libstdc++-v3/testsuite/22_locale/money_get/get/char/38399.cc | C++ | gpl-2.0 | 1,494 |
<?php
/**
* @version $Id$
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
class RokSprocket_Item
{
/**
* @var
*/
protected $id;
/**
* @var string
*/
protected $alias;
/**
* @var bool
*/
protected $published;
/**
* @var string
*/
protected $author;
/**
* @var string
*/
protected $date;
/**
* @var string
*/
protected $title;
/**
* @var string
*/
protected $text;
/**
* @var string
*/
protected $provider;
/**
* @var RokSprocket_Item_Image
*/
protected $primaryImage;
/**
* @var \RokSprocket_Item_Image[]
*/
protected $images;
/**
* @var RokSprocket_Item_Link
*/
protected $primaryLink;
/**
* @var \RokSprocket_Item_Link[]
*/
protected $links;
/**
* @var RokSprocket_Item_Field[]
*/
protected $textFields;
/**
* @var string[]
*/
protected $tags;
/**
* @var int
*/
protected $order;
/**
* @var int
*/
protected $commentCount;
/**
* @var int
*/
protected $hits;
/**
* @var int
*/
protected $rating;
/**
* @var
*/
protected $metaKey;
/**
* @var
*/
protected $metaDesc;
/**
* @var
*/
protected $metaData;
/**
* @var string
*/
protected $category;
/**
* @var array
*/
protected $params = array();
/**
* @var
*/
protected $dborder;
/**
* @var
*/
protected $publish_up;
/**
* @var
*/
protected $publish_down;
/**
* @param string $alias
*/
public function setAlias($alias)
{
$this->alias = $alias;
}
/**
* @return string
*/
public function getAlias()
{
return $this->alias;
}
/**
* @param string $author
*/
public function setAuthor($author)
{
$this->author = $author;
}
/**
* @return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* @param string $date
*/
public function setDate($date)
{
$this->date = $date;
}
/**
* @return string
*/
public function getDate()
{
return $this->date;
}
/**
* @param $fields
*/
public function setTextFields($fields)
{
$this->textFields = $fields;
}
/**
* @return RokSprocket_Item_Field[]
*/
public function getTextFields()
{
return $this->textFields;
}
/**
* @param $identifier
*
* @return null|\RokSprocket_Item_Field
*/
public function getTextField($identifier)
{
if (isset($this->textFields[$identifier])) {
return $this->textFields[$identifier];
}
return null;
}
/**
* @param $identifier
* @param $value
*/
public function addTextField($identifier, $value)
{
$this->textFields[$identifier] = $value;
}
/**
* @param $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param $images
*/
public function setImages($images)
{
$this->images = $images;
}
/**
* @return RokSprocket_Item_Image[]
*/
public function getImages()
{
return $this->images;
}
/**
* @param $identifier
*
* @return null|RokSprocket_Item_Image
*/
public function getImage($identifier)
{
if (isset($this->images[$identifier])) {
return $this->images[$identifier];
}
return null;
}
/**
* @param $identifier
* @param $image
*/
public function addImage($identifier, RokSprocket_Item_Image $image)
{
$this->images[$identifier] = $image;
}
/**
* @param string $introtext
*/
public function setText($introtext)
{
$this->text = $introtext;
}
/**
* @return string
*/
public function getText()
{
return $this->text;
}
/**
* @param $links
*/
public function setLinks($links)
{
$this->links = $links;
}
/**
* @return RokSprocket_Item_Link[]
*/
public function getLinks()
{
return $this->links;
}
/**
* @param $identifier
*
* @return null|RokSprocket_Item_Link
*/
public function getLink($identifier)
{
if (isset($this->links[$identifier])) {
return $this->links[$identifier];
}
return null;
}
/**
* @param $identifier
* @param $link
*/
public function addLink($identifier, RokSprocket_Item_Link $link)
{
$this->links[$identifier] = $link;
}
/**
* @param \RokSprocket_Item_Image $primaryImage
*/
public function setPrimaryImage($primaryImage)
{
$this->primaryImage = $primaryImage;
}
/**
* @return \RokSprocket_Item_Image
*/
public function &getPrimaryImage()
{
return $this->primaryImage;
}
/**
* @param \RokSprocket_Item_Link $primaryLink
*/
public function setPrimaryLink($primaryLink)
{
$this->primaryLink = $primaryLink;
}
/**
* @return \RokSprocket_Item_Link
*/
public function &getPrimaryLink()
{
return $this->primaryLink;
}
/**
* @param string $provider
*/
public function setProvider($provider)
{
$this->provider = $provider;
}
/**
* @return string
*/
public function getProvider()
{
return $this->provider;
}
/**
* @param boolean $published
*/
public function setPublished($published)
{
$this->published = $published;
}
/**
* @return boolean
*/
public function getPublished()
{
return $this->published;
}
/**
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @param int $order
*/
public function setOrder($order)
{
$this->order = $order;
}
/**
* @return int
*/
public function getOrder()
{
return $this->order;
}
/**
* @param $tags
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* @return string[]
*/
public function getTags()
{
return $this->tags;
}
/**
* @param $commentCount
*/
public function setCommentCount($commentCount)
{
$this->commentCount = $commentCount;
}
/**
* @return int
*/
public function getCommentCount()
{
return $this->commentCount;
}
/**
* @param int $hits
*/
public function setHits($hits)
{
$this->hits = $hits;
}
/**
* @return int
*/
public function getHits()
{
return $this->hits;
}
/**
* @param int $rating
*/
public function setRating($rating)
{
$this->rating = $rating;
}
/**
* @return int
*/
public function getRating()
{
return $this->rating;
}
/**
* @param $metaData
*/
public function setMetaData($metaData)
{
$this->metaData = $metaData;
}
/**
* @return
*/
public function getMetaData()
{
return $this->metaData;
}
/**
* @param $metaDesc
*/
public function setMetaDesc($metaDesc)
{
$this->metaDesc = $metaDesc;
}
/**
* @return
*/
public function getMetaDesc()
{
return $this->metaDesc;
}
/**
* @param $metaKey
*/
public function setMetaKey($metaKey)
{
$this->metaKey = $metaKey;
}
/**
* @return
*/
public function getMetaKey()
{
return $this->metaKey;
}
/**
* @param $category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* @return string
*/
public function getCategory()
{
return $this->category;
}
/**
* @return string
*/
public function getArticleId()
{
return $this->provider . '-' . $this->id;
}
/**
* @param $parameters
*/
public function setParams($parameters)
{
$this->params = $parameters;
}
/**
* @return array
*/
public function getParams()
{
return $this->params;
}
/**
* @param $name
* @param null $default
*
* @return null
*/
public function getParam($name, $default = null)
{
if (isset($this->params[$name])) {
return $this->params[$name];
} else {
return $default;
}
}
/**
* @param $dborder
*/
public function setDbOrder($dborder)
{
$this->dborder = $dborder;
}
/**
* @return mixed
*/
public function getDbOrder()
{
return $this->dborder;
}
/**
* @param $name
* @param $value
*/
public function setParam($name, $value)
{
$this->params[$name] = $value;
}
/**
* @return mixed
*/
public function getPublishUp()
{
return $this->publish_up;
}
/**
* @param $datetime
*/
public function setPublishUp($datetime)
{
$this->publish_up = $datetime;
}
/**
* @return mixed
*/
public function getPublishDown()
{
return $this->publish_down;
}
/**
* @param $datetime
*/
public function setPublishDown($datetime)
{
$this->publish_down = $datetime;
}
}
| C3Style/appuihec | tmp/install_5141d25be0783/com_roksprocket/site/lib/RokSprocket/Item.php | PHP | gpl-2.0 | 10,313 |
// { dg-do compile { target c++11 } }
// Copyright (C) 2010-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <complex>
#include <testsuite_common_types.h>
namespace __gnu_test
{
struct constexpr_member_functions
{
template<typename _Ttesttype>
void
operator()()
{
struct _Concept
{
void __constraint()
{
typedef typename _Ttesttype::_ComplexT _ComplexT;
constexpr _ComplexT cc = { 1.1 };
constexpr _Ttesttype a(cc);
constexpr auto v1 __attribute__((unused)) = a.real();
constexpr auto v2 __attribute__((unused)) = a.imag();
}
};
_Concept c;
c.__constraint();
}
};
}
int main()
{
__gnu_test::constexpr_member_functions test;
test.operator()<std::complex<float>>();
test.operator()<std::complex<double>>();
test.operator()<std::complex<long double>>();
return 0;
}
| mickael-guene/gcc | libstdc++-v3/testsuite/26_numerics/complex/requirements/constexpr_functions.cc | C++ | gpl-2.0 | 1,553 |
/****************************************************************************
**
** This file is part of the Qt Extended Opensource Package.
**
** Copyright (C) 2009 Trolltech ASA.
**
** Contact: Qt Extended Information (info@qtextended.org)
**
** This file may be used under the terms of the GNU General Public License
** version 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
#include <qmodemsimfiles.h>
#include "qmodemsimfiles_p.h"
#include <qmodemservice.h>
#include <qatresultparser.h>
#include <qatutils.h>
/*!
\class QModemSimFiles
\inpublicgroup QtCellModule
\brief The QModemSimFiles class implements SIM file access for AT-based modems.
\ingroup telephony::modem
This class implements the QSimFiles telephony interface and uses the \c{AT+CRSM}
or \c{AT+CSIM} commands from 3GPP TS 27.007 to access the files on the SIM.
Client applications should use QBinarySimFile, QRecordBasedSimFile, or
QSimFiles to access the files on a SIM rather than QModemSimFiles.
\sa QSimFiles, QBinarySimFile, QRecordBasedSimFile
*/
class QModemSimFilesPrivate
{
public:
QModemService *service;
};
/*!
Create a new modem SIM file access object for \a service.
*/
QModemSimFiles::QModemSimFiles( QModemService *service )
: QSimFiles( service->service(), service, QCommInterface::Server )
{
d = new QModemSimFilesPrivate();
d->service = service;
}
/*!
Destroy this modem SIM file access object.
*/
QModemSimFiles::~QModemSimFiles()
{
delete d;
}
/*!
\reimp
*/
void QModemSimFiles::requestFileInfo
( const QString& reqid, const QString& fileid )
{
// Send the "GET RESPONSE" request.
QModemSimFileRequest *request;
request = new QModemSimFileInfoRequest
( d->service, reqid, fileid, useCSIM(), this );
connect( request, SIGNAL(error(QString,QTelephony::SimFileError)),
this, SIGNAL(error(QString,QTelephony::SimFileError)) );
connect( request, SIGNAL(fileInfo(QString,int,int,QTelephony::SimFileType)),
this, SIGNAL(fileInfo(QString,int,int,QTelephony::SimFileType)) );
request->chat( 192, 0, 0, 0 );
}
/*!
\reimp
*/
void QModemSimFiles::readBinary
( const QString& reqid, const QString& fileid, int pos, int len )
{
// Sanity-check the position and length parameters.
if ( pos < 0 || pos > 65535 || len < 1 || len > 256 ||
( pos + len ) > 65536 ) {
emit error( reqid, QTelephony::SimFileInvalidRead );
return;
}
// Send the "READ BINARY" request.
QModemSimFileRequest *request;
request = new QModemSimFileReadRequest
( d->service, reqid, fileid, pos, useCSIM(), this );
connect( request, SIGNAL(error(QString,QTelephony::SimFileError)),
this, SIGNAL(error(QString,QTelephony::SimFileError)) );
connect( request, SIGNAL(readDone(QString,QByteArray,int)),
this, SIGNAL(readDone(QString,QByteArray,int)) );
request->chat( 176, (pos >> 8) & 0xFF, pos & 0xFF, len & 0xFF );
}
/*!
\reimp
*/
void QModemSimFiles::writeBinary
( const QString& reqid, const QString& fileid,
int pos, const QByteArray& data )
{
// Sanity-check the position and length parameters.
int len = data.size();
if ( pos < 0 || pos > 65535 || len < 1 || len > 256 ||
( pos + len ) > 65536 ) {
emit error( reqid, QTelephony::SimFileInvalidWrite );
return;
}
// Send the "UPDATE BINARY" request.
QModemSimFileRequest *request;
request = new QModemSimFileWriteRequest
( d->service, reqid, fileid, pos, useCSIM(), this );
connect( request, SIGNAL(error(QString,QTelephony::SimFileError)),
this, SIGNAL(error(QString,QTelephony::SimFileError)) );
connect( request, SIGNAL(writeDone(QString,int)),
this, SIGNAL(writeDone(QString,int)) );
request->chat( 214, (pos >> 8) & 0xFF, pos & 0xFF, len & 0xFF,
QAtUtils::toHex( data ) );
}
/*!
\reimp
*/
void QModemSimFiles::readRecord
( const QString& reqid, const QString& fileid, int recno,
int recordSize )
{
// Sanity-check the record number parameter.
if ( recno < 0 || recno >= 255 ||
( recordSize != -1 && ( recordSize < 1 || recordSize > 255 ) ) ) {
emit error( reqid, QTelephony::SimFileInvalidRead );
return;
}
// If we already know the record size, then send the "READ RECORD" now.
if ( recordSize != -1 ) {
QModemSimFileRequest *request;
request = new QModemSimFileReadRequest
( d->service, reqid, fileid, recno, useCSIM(), this );
connect( request, SIGNAL(error(QString,QTelephony::SimFileError)),
this, SIGNAL(error(QString,QTelephony::SimFileError)) );
connect( request, SIGNAL(readDone(QString,QByteArray,int)),
this, SIGNAL(readDone(QString,QByteArray,int)) );
request->chat( 178, recno + 1, 4, recordSize & 0xFF );
return;
}
// Send a "GET RESPONSE" command to determine the record limit
// and record size for this read. The done() method will then
// cause the "READ RECORD" request once the parameters are validated.
QModemSimFileRequest *request1;
QModemSimFileRequest *request2;
request1 = new QModemSimFileInfoRequest
( d->service, reqid, fileid, useCSIM(), this );
request2 = new QModemSimFileReadRequest
( d->service, reqid, fileid, recno, useCSIM(), this );
connect( request1,
SIGNAL(fileInfo(QString,int,int,QTelephony::SimFileType)),
request2, SLOT(fileInfo(QString,int,int)) );
connect( request2, SIGNAL(readDone(QString,QByteArray,int)),
this, SIGNAL(readDone(QString,QByteArray,int)) );
connect( request1, SIGNAL(error(QString,QTelephony::SimFileError)),
request2, SLOT(infoError(QString,QTelephony::SimFileError)) );
connect( request2, SIGNAL(error(QString,QTelephony::SimFileError)),
this, SIGNAL(error(QString,QTelephony::SimFileError)) );
request1->chat( 192, 0, 0, 0 );
}
/*!
\reimp
*/
void QModemSimFiles::writeRecord
( const QString& reqid, const QString& fileid,
int recno, const QByteArray& data )
{
// Sanity-check the record and length parameters.
int len = data.size();
if ( recno < 0 || recno >= 255 || len < 1 || len > 255 ) {
emit error( reqid, QTelephony::SimFileInvalidWrite );
return;
}
// Send the "UPDATE RECORD" request.
QModemSimFileRequest *request;
request = new QModemSimFileWriteRequest
( d->service, reqid, fileid, recno, useCSIM(), this );
connect( request, SIGNAL(error(QString,QTelephony::SimFileError)),
this, SIGNAL(error(QString,QTelephony::SimFileError)) );
connect( request, SIGNAL(writeDone(QString,int)),
this, SIGNAL(writeDone(QString,int)) );
request->chat( 220, recno + 1, 0x04, len & 0xFF, QAtUtils::toHex( data ) );
}
/*!
Returns true if the modem SIM file access object should use \c{AT+CSIM}
to access SIM files instead of \c{AT+CRSM}; false otherwise. The default implementation
returns false. The \c{AT+CRSM} command is more reliable, so modem
vendor plug-ins should use it wherever possible.
*/
bool QModemSimFiles::useCSIM() const
{
return false;
}
QModemSimFileRequest::QModemSimFileRequest
( QModemService *service, const QString& reqid,
const QString& fileid, bool useCSIM, QObject *parent )
: QObject( parent )
{
this->service = service;
this->reqid = reqid;
this->fileid = fileid;
this->isWriting = false;
this->retryRequested = false;
this->retryFromRoot = false;
this->selectFailed = false;
this->errorReported = false;
this->useCSIM = useCSIM;
}
QModemSimFileRequest::~QModemSimFileRequest()
{
}
void QModemSimFileRequest::chat
( int cmd, int p1, int p2, int p3, const QString& extra )
{
command = formatRequest( cmd, fileid, p1, p2, p3, extra );
sendSelects( false );
service->chat( command, this, SLOT(chatResult(bool,QAtResult)) );
}
QString QModemSimFileRequest::formatRequest
( int cmd, const QString& fileid, int p1, int p2, int p3,
const QString& extra )
{
QString command;
if ( useCSIM ) {
QByteArray data;
data.append( (char)0xA0 );
data.append( (char)cmd );
data.append( (char)p1 );
data.append( (char)p2 );
if ( cmd == 164 )
p3 = 2; // Always send 2 bytes with "SELECT".
else if ( cmd == 192 )
p3 = 15; // Always return 15 bytes with "GET RESPONSE".
data.append( (char)p3 );
if ( !extra.isEmpty() )
data += QAtUtils::fromHex( extra );
else if ( cmd == 164 )
data += QAtUtils::fromHex( fileid.right(4) );
command = "AT+CSIM=" + QString::number( data.size() * 2 ) + "," +
QAtUtils::toHex( data );
} else {
if ( cmd == 164 ) {
// Request for simple "SELECT" command - turn into "GET RESPONSE"
// because AT+CRSM does not have a separate "SELECT" command.
cmd = 192;
}
command = "AT+CRSM=" + QString::number( cmd );
command += "," + QString::number( fileid.right(4).toInt( 0, 16 ) );
if ( cmd != 192 ) {
command += "," + QString::number( p1 );
command += "," + QString::number( p2 );
command += "," + QString::number( p3 );
if ( !extra.isEmpty() )
command += "," + extra;
}
}
return command;
}
// Select directories leading up to the file we want.
void QModemSimFileRequest::sendSelects( bool fromRoot )
{
bool sentSelect = false;
if ( fileid.length() >= 12 ) {
// Always start from the root for 3rd-level files, because
// we'll probably need to retry anyway.
fromRoot = true;
}
if ( fromRoot && !fileid.startsWith( "3F" ) ) {
service->chat( formatRequest( 164, "3F00", 0, 0, 0 ),
this, SLOT(selectResult(bool,QAtResult)) );
sentSelect = true;
}
int posn = 0;
while ( ( posn + 8 ) <= fileid.length() ) {
QString dirid = fileid.mid( posn, 4 );
service->chat( formatRequest( 164, dirid, 0, 0, 0 ),
this, SLOT(selectResult(bool,QAtResult)) );
sentSelect = true;
posn += 4;
}
errorReported = false;
retryFromRoot = false;
if ( !fromRoot ) {
// Determine if it is worth the effort retrying from root next time.
// We need a top-level DF or EF at the front of the fileid.
retryRequested = ( fileid.startsWith( "7F" ) ||
fileid.startsWith( "2F" ) );
if ( retryRequested && !sentSelect )
retryFromRoot = true; // No selects sent, so force retry.
} else {
// We are doing the retry, so don't request another one.
retryRequested = false;
}
if ( useCSIM ) {
// Now select the actual file that we are interested in.
// The AT+CRSM command has an implicit in-built select,
// so this only needs to be done for AT+CSIM.
service->chat( formatRequest( 164, fileid.right(4), 0, 0, 0 ),
this, SLOT(selectResult(bool,QAtResult)) );
}
}
void QModemSimFileRequest::selectResult( bool ok, const QAtResult& result )
{
// Check for errors in the response.
if ( ok ) {
QAtResultParser parser( result );
uint sw1 = 0;
QString line;
uint posn = 0;
if ( parser.next( "+CRSM:" ) ) {
line = parser.line();
sw1 = QAtUtils::parseNumber( line, posn );
} else if ( parser.next( "+CSIM:" ) ) {
line = parser.line();
QAtUtils::parseNumber( line, posn ); // Skip length.
if ( ((int)posn) < line.length() && line[posn] == ',' )
++posn;
QByteArray data = QAtUtils::fromHex( line.mid( (int)posn ) );
sw1 = ( data.size() >= 2 ? (data[data.size() - 2] & 0xFF) : 0 );
}
if ( sw1 != 0x90 && sw1 != 0x91 && sw1 != 0x9E && sw1 != 0x9F ) {
ok = false;
}
}
// Determine if we should retry the request from the root
// directory, or bail out once control reaches chatResult().
if ( !ok && !errorReported ) {
if ( retryRequested && !retryFromRoot )
retryFromRoot = true;
else
selectFailed = true;
errorReported = true;
}
}
void QModemSimFileRequest::chatResult( bool ok, const QAtResult& result )
{
if ( !ok ) {
// The command failed outright, so AT+CRSM is probably not
// supported by the modem or the SIM is not inserted. Report
// the SIM as unavailable.
emit error( reqid, QTelephony::SimFileSimUnavailable );
deleteLater();
return;
}
QAtResultParser parser( result );
if ( useCSIM ) {
if ( !parser.next( "+CSIM:" ) ) {
// Shouldn't happen, but do something useful.
emit error( reqid, QTelephony::SimFileSimUnavailable );
deleteLater();
return;
}
} else {
if ( !parser.next( "+CRSM:" ) ) {
// Shouldn't happen, but do something useful.
emit error( reqid, QTelephony::SimFileSimUnavailable );
deleteLater();
return;
}
}
// Extract the fields from the line.
QString line = parser.line();
uint posn = 0;
uint sw1, sw2;
QString data;
if ( useCSIM ) {
QAtUtils::parseNumber( line, posn ); // Skip length.
if ( ((int)posn) < line.length() && line[posn] == ',' )
data = line.mid( posn + 1 );
else
data = line.mid( posn );
if ( data.contains( QChar('"') ) )
data = data.remove( QChar('"') );
if ( data.length() <= 4 ) {
// Need at least sw1 and sw2 on the end of the command.
emit error( reqid, QTelephony::SimFileSimUnavailable );
deleteLater();
return;
}
sw1 = data.mid( data.length() - 4, 2 ).toUInt( 0, 16 );
sw2 = data.mid( data.length() - 2, 2 ).toUInt( 0, 16 );
data = data.left( data.length() - 4 );
} else {
sw1 = QAtUtils::parseNumber( line, posn );
sw2 = QAtUtils::parseNumber( line, posn );
if ( ((int)posn) < line.length() && line[posn] == ',' )
data = line.mid( posn + 1 );
else
data = line.mid( posn );
}
// Determine if the command succeeded or failed.
if ( sw1 == 0x90 || sw1 == 0x91 || sw1 == 0x9E || sw1 == 0x9F ) {
done( QAtUtils::fromHex( data ) );
} else if ( selectFailed ) {
// One of the directory select commands failed, so file was not found.
emit error( reqid, QTelephony::SimFileNotFound );
} else if ( retryFromRoot ) {
// We need to retry the command, starting at the root directory.
sendSelects( true );
service->chat( command, this, SLOT(chatResult(bool,QAtResult)) );
return;
} else if ( sw1 == 0x94 && ( sw2 == 0x02 || sw2 == 0x08 ) ) {
if ( isWriting )
emit error( reqid, QTelephony::SimFileInvalidWrite );
else
emit error( reqid, QTelephony::SimFileInvalidRead );
} else {
emit error( reqid, QTelephony::SimFileNotFound );
}
// This object is no longer required.
deleteLater();
}
QModemSimFileInfoRequest::QModemSimFileInfoRequest
( QModemService *service, const QString& reqid,
const QString& fileid, bool useCSIM, QObject *parent )
: QModemSimFileRequest( service, reqid, fileid, useCSIM, parent )
{
}
QModemSimFileInfoRequest::~QModemSimFileInfoRequest()
{
}
void QModemSimFileInfoRequest::done( const QByteArray& data )
{
// The file size is stored in the third and fourth bytes of the data.
int size;
if ( data.size() >= 4 ) {
size = ((((int)(data[2])) & 0xFF) << 8) |
(((int)(data[3])) & 0xFF);
} else {
size = 0;
}
// Get the file type and structure.
int type, structure;
if ( data.size() >= 7 ) {
type = (((int)(data[6])) & 0xFF);
} else {
type = -1;
}
if ( type == 0x04 && data.size() >= 14 ) {
structure = (((int)(data[13])) & 0xFF);
} else {
structure = -1;
}
// Convert the raw file type information into something more useful.
QTelephony::SimFileType ftype;
if ( type == 0x01 ) {
ftype = QTelephony::SimFileRootDirectory;
} else if ( type == 0x02 ) {
ftype = QTelephony::SimFileDirectory;
} else if ( type == 0x04 ) {
if ( structure == 0x00 )
ftype = QTelephony::SimFileTransparent;
else if ( structure == 0x01 )
ftype = QTelephony::SimFileLinearFixed;
else if ( structure == 0x03 )
ftype = QTelephony::SimFileCyclic;
else
ftype = QTelephony::SimFileUnknown;
} else {
ftype = QTelephony::SimFileUnknown;
}
// If this is a record-based file, then the record size is in
// the fifteenth byte of the data (offset 14 counting from zero).
int recordSize = 1;
if ( ftype == QTelephony::SimFileLinearFixed ||
ftype == QTelephony::SimFileCyclic ) {
if ( data.size() >= 15 )
recordSize = (((int)(data[14])) & 0xFF);
}
// Report the file information to the requestor.
emit fileInfo( reqid, size, recordSize, ftype );
}
QModemSimFileReadRequest::QModemSimFileReadRequest
( QModemService *service, const QString& reqid,
const QString& fileid, int pos, bool useCSIM, QObject *parent )
: QModemSimFileRequest( service, reqid, fileid, useCSIM, parent )
{
this->pos = pos;
}
QModemSimFileReadRequest::~QModemSimFileReadRequest()
{
}
void QModemSimFileReadRequest::fileInfo
( const QString&, int size, int recordSize )
{
// This is called when we are doing a "READ RECORD" to notify
// us of the file's record size.
// Check the validity of the record number.
if ( pos >= ( size / recordSize ) ) {
emit error( reqid, QTelephony::SimFileInvalidRead );
deleteLater();
return;
}
// Now send the "READ RECORD" request.
chat( 178, pos + 1, 0x04, recordSize & 0xFF );
}
void QModemSimFileReadRequest::infoError
( const QString& reqid, QTelephony::SimFileError err )
{
// This is called to tell us that the "GET RESPONSE" command
// failed. Pass the error on and then delete ourselves.
emit error( reqid, err );
deleteLater();
}
void QModemSimFileReadRequest::done( const QByteArray& data )
{
emit readDone( reqid, data, pos );
}
QModemSimFileWriteRequest::QModemSimFileWriteRequest
( QModemService *service, const QString& reqid, const QString& fileid,
int pos, bool useCSIM, QObject *parent )
: QModemSimFileRequest( service, reqid, fileid, useCSIM, parent )
{
this->pos = pos;
this->isWriting = true;
}
QModemSimFileWriteRequest::~QModemSimFileWriteRequest()
{
}
void QModemSimFileWriteRequest::done( const QByteArray& )
{
emit writeDone( reqid, pos );
}
| radekp/qtmoko | src/libraries/qtopiaphonemodem/qmodemsimfiles.cpp | C++ | gpl-2.0 | 19,738 |
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xalan.internal.res;
import java.util.ListResourceBundle;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* Set up error messages.
* We build a two dimensional array of message keys and
* message strings. In order to add a new message here,
* you need to first add a String constant. And
* you need to enter key , value pair as part of contents
* Array. You also need to update MAX_CODE for error strings
* and MAX_WARNING for warnings ( Needed for only information
* purpose )
*/
public class XSLTErrorResources_fr extends ListResourceBundle
{
/*
* This file contains error and warning messages related to Xalan Error
* Handling.
*
* General notes to translators:
*
* 1) Xalan (or more properly, Xalan-interpretive) and XSLTC are names of
* components.
* XSLT is an acronym for "XML Stylesheet Language: Transformations".
* XSLTC is an acronym for XSLT Compiler.
*
* 2) A stylesheet is a description of how to transform an input XML document
* into a resultant XML document (or HTML document or text). The
* stylesheet itself is described in the form of an XML document.
*
* 3) A template is a component of a stylesheet that is used to match a
* particular portion of an input document and specifies the form of the
* corresponding portion of the output document.
*
* 4) An element is a mark-up tag in an XML document; an attribute is a
* modifier on the tag. For example, in <elem attr='val' attr2='val2'>
* "elem" is an element name, "attr" and "attr2" are attribute names with
* the values "val" and "val2", respectively.
*
* 5) A namespace declaration is a special attribute that is used to associate
* a prefix with a URI (the namespace). The meanings of element names and
* attribute names that use that prefix are defined with respect to that
* namespace.
*
* 6) "Translet" is an invented term that describes the class file that
* results from compiling an XML stylesheet into a Java class.
*
* 7) XPath is a specification that describes a notation for identifying
* nodes in a tree-structured representation of an XML document. An
* instance of that notation is referred to as an XPath expression.
*
*/
/*
* Static variables
*/
public static final String ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX =
"ER_INVALID_SET_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX";
public static final String ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX_FOR_DEFAULT =
"ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX_FOR_DEFAULT";
public static final String ER_NO_CURLYBRACE = "ER_NO_CURLYBRACE";
public static final String ER_FUNCTION_NOT_SUPPORTED = "ER_FUNCTION_NOT_SUPPORTED";
public static final String ER_ILLEGAL_ATTRIBUTE = "ER_ILLEGAL_ATTRIBUTE";
public static final String ER_NULL_SOURCENODE_APPLYIMPORTS = "ER_NULL_SOURCENODE_APPLYIMPORTS";
public static final String ER_CANNOT_ADD = "ER_CANNOT_ADD";
public static final String ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES="ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES";
public static final String ER_NO_NAME_ATTRIB = "ER_NO_NAME_ATTRIB";
public static final String ER_TEMPLATE_NOT_FOUND = "ER_TEMPLATE_NOT_FOUND";
public static final String ER_CANT_RESOLVE_NAME_AVT = "ER_CANT_RESOLVE_NAME_AVT";
public static final String ER_REQUIRES_ATTRIB = "ER_REQUIRES_ATTRIB";
public static final String ER_MUST_HAVE_TEST_ATTRIB = "ER_MUST_HAVE_TEST_ATTRIB";
public static final String ER_BAD_VAL_ON_LEVEL_ATTRIB =
"ER_BAD_VAL_ON_LEVEL_ATTRIB";
public static final String ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML =
"ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML";
public static final String ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME =
"ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME";
public static final String ER_NEED_MATCH_ATTRIB = "ER_NEED_MATCH_ATTRIB";
public static final String ER_NEED_NAME_OR_MATCH_ATTRIB =
"ER_NEED_NAME_OR_MATCH_ATTRIB";
public static final String ER_CANT_RESOLVE_NSPREFIX =
"ER_CANT_RESOLVE_NSPREFIX";
public static final String ER_ILLEGAL_VALUE = "ER_ILLEGAL_VALUE";
public static final String ER_NO_OWNERDOC = "ER_NO_OWNERDOC";
public static final String ER_ELEMTEMPLATEELEM_ERR ="ER_ELEMTEMPLATEELEM_ERR";
public static final String ER_NULL_CHILD = "ER_NULL_CHILD";
public static final String ER_NEED_SELECT_ATTRIB = "ER_NEED_SELECT_ATTRIB";
public static final String ER_NEED_TEST_ATTRIB = "ER_NEED_TEST_ATTRIB";
public static final String ER_NEED_NAME_ATTRIB = "ER_NEED_NAME_ATTRIB";
public static final String ER_NO_CONTEXT_OWNERDOC = "ER_NO_CONTEXT_OWNERDOC";
public static final String ER_COULD_NOT_CREATE_XML_PROC_LIAISON =
"ER_COULD_NOT_CREATE_XML_PROC_LIAISON";
public static final String ER_PROCESS_NOT_SUCCESSFUL =
"ER_PROCESS_NOT_SUCCESSFUL";
public static final String ER_NOT_SUCCESSFUL = "ER_NOT_SUCCESSFUL";
public static final String ER_ENCODING_NOT_SUPPORTED =
"ER_ENCODING_NOT_SUPPORTED";
public static final String ER_COULD_NOT_CREATE_TRACELISTENER =
"ER_COULD_NOT_CREATE_TRACELISTENER";
public static final String ER_KEY_REQUIRES_NAME_ATTRIB =
"ER_KEY_REQUIRES_NAME_ATTRIB";
public static final String ER_KEY_REQUIRES_MATCH_ATTRIB =
"ER_KEY_REQUIRES_MATCH_ATTRIB";
public static final String ER_KEY_REQUIRES_USE_ATTRIB =
"ER_KEY_REQUIRES_USE_ATTRIB";
public static final String ER_REQUIRES_ELEMENTS_ATTRIB =
"ER_REQUIRES_ELEMENTS_ATTRIB";
public static final String ER_MISSING_PREFIX_ATTRIB =
"ER_MISSING_PREFIX_ATTRIB";
public static final String ER_BAD_STYLESHEET_URL = "ER_BAD_STYLESHEET_URL";
public static final String ER_FILE_NOT_FOUND = "ER_FILE_NOT_FOUND";
public static final String ER_IOEXCEPTION = "ER_IOEXCEPTION";
public static final String ER_NO_HREF_ATTRIB = "ER_NO_HREF_ATTRIB";
public static final String ER_STYLESHEET_INCLUDES_ITSELF =
"ER_STYLESHEET_INCLUDES_ITSELF";
public static final String ER_PROCESSINCLUDE_ERROR ="ER_PROCESSINCLUDE_ERROR";
public static final String ER_MISSING_LANG_ATTRIB = "ER_MISSING_LANG_ATTRIB";
public static final String ER_MISSING_CONTAINER_ELEMENT_COMPONENT =
"ER_MISSING_CONTAINER_ELEMENT_COMPONENT";
public static final String ER_CAN_ONLY_OUTPUT_TO_ELEMENT =
"ER_CAN_ONLY_OUTPUT_TO_ELEMENT";
public static final String ER_PROCESS_ERROR = "ER_PROCESS_ERROR";
public static final String ER_UNIMPLNODE_ERROR = "ER_UNIMPLNODE_ERROR";
public static final String ER_NO_SELECT_EXPRESSION ="ER_NO_SELECT_EXPRESSION";
public static final String ER_CANNOT_SERIALIZE_XSLPROCESSOR =
"ER_CANNOT_SERIALIZE_XSLPROCESSOR";
public static final String ER_NO_INPUT_STYLESHEET = "ER_NO_INPUT_STYLESHEET";
public static final String ER_FAILED_PROCESS_STYLESHEET =
"ER_FAILED_PROCESS_STYLESHEET";
public static final String ER_COULDNT_PARSE_DOC = "ER_COULDNT_PARSE_DOC";
public static final String ER_COULDNT_FIND_FRAGMENT =
"ER_COULDNT_FIND_FRAGMENT";
public static final String ER_NODE_NOT_ELEMENT = "ER_NODE_NOT_ELEMENT";
public static final String ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB =
"ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB";
public static final String ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB =
"ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB";
public static final String ER_NO_CLONE_OF_DOCUMENT_FRAG =
"ER_NO_CLONE_OF_DOCUMENT_FRAG";
public static final String ER_CANT_CREATE_ITEM = "ER_CANT_CREATE_ITEM";
public static final String ER_XMLSPACE_ILLEGAL_VALUE =
"ER_XMLSPACE_ILLEGAL_VALUE";
public static final String ER_NO_XSLKEY_DECLARATION =
"ER_NO_XSLKEY_DECLARATION";
public static final String ER_CANT_CREATE_URL = "ER_CANT_CREATE_URL";
public static final String ER_XSLFUNCTIONS_UNSUPPORTED =
"ER_XSLFUNCTIONS_UNSUPPORTED";
public static final String ER_PROCESSOR_ERROR = "ER_PROCESSOR_ERROR";
public static final String ER_NOT_ALLOWED_INSIDE_STYLESHEET =
"ER_NOT_ALLOWED_INSIDE_STYLESHEET";
public static final String ER_RESULTNS_NOT_SUPPORTED =
"ER_RESULTNS_NOT_SUPPORTED";
public static final String ER_DEFAULTSPACE_NOT_SUPPORTED =
"ER_DEFAULTSPACE_NOT_SUPPORTED";
public static final String ER_INDENTRESULT_NOT_SUPPORTED =
"ER_INDENTRESULT_NOT_SUPPORTED";
public static final String ER_ILLEGAL_ATTRIB = "ER_ILLEGAL_ATTRIB";
public static final String ER_UNKNOWN_XSL_ELEM = "ER_UNKNOWN_XSL_ELEM";
public static final String ER_BAD_XSLSORT_USE = "ER_BAD_XSLSORT_USE";
public static final String ER_MISPLACED_XSLWHEN = "ER_MISPLACED_XSLWHEN";
public static final String ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE =
"ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE";
public static final String ER_MISPLACED_XSLOTHERWISE =
"ER_MISPLACED_XSLOTHERWISE";
public static final String ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE =
"ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE";
public static final String ER_NOT_ALLOWED_INSIDE_TEMPLATE =
"ER_NOT_ALLOWED_INSIDE_TEMPLATE";
public static final String ER_UNKNOWN_EXT_NS_PREFIX =
"ER_UNKNOWN_EXT_NS_PREFIX";
public static final String ER_IMPORTS_AS_FIRST_ELEM =
"ER_IMPORTS_AS_FIRST_ELEM";
public static final String ER_IMPORTING_ITSELF = "ER_IMPORTING_ITSELF";
public static final String ER_XMLSPACE_ILLEGAL_VAL ="ER_XMLSPACE_ILLEGAL_VAL";
public static final String ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL =
"ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL";
public static final String ER_SAX_EXCEPTION = "ER_SAX_EXCEPTION";
public static final String ER_XSLT_ERROR = "ER_XSLT_ERROR";
public static final String ER_CURRENCY_SIGN_ILLEGAL=
"ER_CURRENCY_SIGN_ILLEGAL";
public static final String ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM =
"ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM";
public static final String ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER =
"ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER";
public static final String ER_REDIRECT_COULDNT_GET_FILENAME =
"ER_REDIRECT_COULDNT_GET_FILENAME";
public static final String ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT =
"ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT";
public static final String ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX =
"ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX";
public static final String ER_MISSING_NS_URI = "ER_MISSING_NS_URI";
public static final String ER_MISSING_ARG_FOR_OPTION =
"ER_MISSING_ARG_FOR_OPTION";
public static final String ER_INVALID_OPTION = "ER_INVALID_OPTION";
public static final String ER_MALFORMED_FORMAT_STRING =
"ER_MALFORMED_FORMAT_STRING";
public static final String ER_STYLESHEET_REQUIRES_VERSION_ATTRIB =
"ER_STYLESHEET_REQUIRES_VERSION_ATTRIB";
public static final String ER_ILLEGAL_ATTRIBUTE_VALUE =
"ER_ILLEGAL_ATTRIBUTE_VALUE";
public static final String ER_CHOOSE_REQUIRES_WHEN ="ER_CHOOSE_REQUIRES_WHEN";
public static final String ER_NO_APPLY_IMPORT_IN_FOR_EACH =
"ER_NO_APPLY_IMPORT_IN_FOR_EACH";
public static final String ER_CANT_USE_DTM_FOR_OUTPUT =
"ER_CANT_USE_DTM_FOR_OUTPUT";
public static final String ER_CANT_USE_DTM_FOR_INPUT =
"ER_CANT_USE_DTM_FOR_INPUT";
public static final String ER_CALL_TO_EXT_FAILED = "ER_CALL_TO_EXT_FAILED";
public static final String ER_PREFIX_MUST_RESOLVE = "ER_PREFIX_MUST_RESOLVE";
public static final String ER_INVALID_UTF16_SURROGATE =
"ER_INVALID_UTF16_SURROGATE";
public static final String ER_XSLATTRSET_USED_ITSELF =
"ER_XSLATTRSET_USED_ITSELF";
public static final String ER_CANNOT_MIX_XERCESDOM ="ER_CANNOT_MIX_XERCESDOM";
public static final String ER_TOO_MANY_LISTENERS = "ER_TOO_MANY_LISTENERS";
public static final String ER_IN_ELEMTEMPLATEELEM_READOBJECT =
"ER_IN_ELEMTEMPLATEELEM_READOBJECT";
public static final String ER_DUPLICATE_NAMED_TEMPLATE =
"ER_DUPLICATE_NAMED_TEMPLATE";
public static final String ER_INVALID_KEY_CALL = "ER_INVALID_KEY_CALL";
public static final String ER_REFERENCING_ITSELF = "ER_REFERENCING_ITSELF";
public static final String ER_ILLEGAL_DOMSOURCE_INPUT =
"ER_ILLEGAL_DOMSOURCE_INPUT";
public static final String ER_CLASS_NOT_FOUND_FOR_OPTION =
"ER_CLASS_NOT_FOUND_FOR_OPTION";
public static final String ER_REQUIRED_ELEM_NOT_FOUND =
"ER_REQUIRED_ELEM_NOT_FOUND";
public static final String ER_INPUT_CANNOT_BE_NULL ="ER_INPUT_CANNOT_BE_NULL";
public static final String ER_URI_CANNOT_BE_NULL = "ER_URI_CANNOT_BE_NULL";
public static final String ER_FILE_CANNOT_BE_NULL = "ER_FILE_CANNOT_BE_NULL";
public static final String ER_SOURCE_CANNOT_BE_NULL =
"ER_SOURCE_CANNOT_BE_NULL";
public static final String ER_CANNOT_INIT_BSFMGR = "ER_CANNOT_INIT_BSFMGR";
public static final String ER_CANNOT_CMPL_EXTENSN = "ER_CANNOT_CMPL_EXTENSN";
public static final String ER_CANNOT_CREATE_EXTENSN =
"ER_CANNOT_CREATE_EXTENSN";
public static final String ER_INSTANCE_MTHD_CALL_REQUIRES =
"ER_INSTANCE_MTHD_CALL_REQUIRES";
public static final String ER_INVALID_ELEMENT_NAME ="ER_INVALID_ELEMENT_NAME";
public static final String ER_ELEMENT_NAME_METHOD_STATIC =
"ER_ELEMENT_NAME_METHOD_STATIC";
public static final String ER_EXTENSION_FUNC_UNKNOWN =
"ER_EXTENSION_FUNC_UNKNOWN";
public static final String ER_MORE_MATCH_CONSTRUCTOR =
"ER_MORE_MATCH_CONSTRUCTOR";
public static final String ER_MORE_MATCH_METHOD = "ER_MORE_MATCH_METHOD";
public static final String ER_MORE_MATCH_ELEMENT = "ER_MORE_MATCH_ELEMENT";
public static final String ER_INVALID_CONTEXT_PASSED =
"ER_INVALID_CONTEXT_PASSED";
public static final String ER_POOL_EXISTS = "ER_POOL_EXISTS";
public static final String ER_NO_DRIVER_NAME = "ER_NO_DRIVER_NAME";
public static final String ER_NO_URL = "ER_NO_URL";
public static final String ER_POOL_SIZE_LESSTHAN_ONE =
"ER_POOL_SIZE_LESSTHAN_ONE";
public static final String ER_INVALID_DRIVER = "ER_INVALID_DRIVER";
public static final String ER_NO_STYLESHEETROOT = "ER_NO_STYLESHEETROOT";
public static final String ER_ILLEGAL_XMLSPACE_VALUE =
"ER_ILLEGAL_XMLSPACE_VALUE";
public static final String ER_PROCESSFROMNODE_FAILED =
"ER_PROCESSFROMNODE_FAILED";
public static final String ER_RESOURCE_COULD_NOT_LOAD =
"ER_RESOURCE_COULD_NOT_LOAD";
public static final String ER_BUFFER_SIZE_LESSTHAN_ZERO =
"ER_BUFFER_SIZE_LESSTHAN_ZERO";
public static final String ER_UNKNOWN_ERROR_CALLING_EXTENSION =
"ER_UNKNOWN_ERROR_CALLING_EXTENSION";
public static final String ER_NO_NAMESPACE_DECL = "ER_NO_NAMESPACE_DECL";
public static final String ER_ELEM_CONTENT_NOT_ALLOWED =
"ER_ELEM_CONTENT_NOT_ALLOWED";
public static final String ER_STYLESHEET_DIRECTED_TERMINATION =
"ER_STYLESHEET_DIRECTED_TERMINATION";
public static final String ER_ONE_OR_TWO = "ER_ONE_OR_TWO";
public static final String ER_TWO_OR_THREE = "ER_TWO_OR_THREE";
public static final String ER_COULD_NOT_LOAD_RESOURCE =
"ER_COULD_NOT_LOAD_RESOURCE";
public static final String ER_CANNOT_INIT_DEFAULT_TEMPLATES =
"ER_CANNOT_INIT_DEFAULT_TEMPLATES";
public static final String ER_RESULT_NULL = "ER_RESULT_NULL";
public static final String ER_RESULT_COULD_NOT_BE_SET =
"ER_RESULT_COULD_NOT_BE_SET";
public static final String ER_NO_OUTPUT_SPECIFIED = "ER_NO_OUTPUT_SPECIFIED";
public static final String ER_CANNOT_TRANSFORM_TO_RESULT_TYPE =
"ER_CANNOT_TRANSFORM_TO_RESULT_TYPE";
public static final String ER_CANNOT_TRANSFORM_SOURCE_TYPE =
"ER_CANNOT_TRANSFORM_SOURCE_TYPE";
public static final String ER_NULL_CONTENT_HANDLER ="ER_NULL_CONTENT_HANDLER";
public static final String ER_NULL_ERROR_HANDLER = "ER_NULL_ERROR_HANDLER";
public static final String ER_CANNOT_CALL_PARSE = "ER_CANNOT_CALL_PARSE";
public static final String ER_NO_PARENT_FOR_FILTER ="ER_NO_PARENT_FOR_FILTER";
public static final String ER_NO_STYLESHEET_IN_MEDIA =
"ER_NO_STYLESHEET_IN_MEDIA";
public static final String ER_NO_STYLESHEET_PI = "ER_NO_STYLESHEET_PI";
public static final String ER_NOT_SUPPORTED = "ER_NOT_SUPPORTED";
public static final String ER_PROPERTY_VALUE_BOOLEAN =
"ER_PROPERTY_VALUE_BOOLEAN";
public static final String ER_COULD_NOT_FIND_EXTERN_SCRIPT =
"ER_COULD_NOT_FIND_EXTERN_SCRIPT";
public static final String ER_RESOURCE_COULD_NOT_FIND =
"ER_RESOURCE_COULD_NOT_FIND";
public static final String ER_OUTPUT_PROPERTY_NOT_RECOGNIZED =
"ER_OUTPUT_PROPERTY_NOT_RECOGNIZED";
public static final String ER_FAILED_CREATING_ELEMLITRSLT =
"ER_FAILED_CREATING_ELEMLITRSLT";
public static final String ER_VALUE_SHOULD_BE_NUMBER =
"ER_VALUE_SHOULD_BE_NUMBER";
public static final String ER_VALUE_SHOULD_EQUAL = "ER_VALUE_SHOULD_EQUAL";
public static final String ER_FAILED_CALLING_METHOD =
"ER_FAILED_CALLING_METHOD";
public static final String ER_FAILED_CREATING_ELEMTMPL =
"ER_FAILED_CREATING_ELEMTMPL";
public static final String ER_CHARS_NOT_ALLOWED = "ER_CHARS_NOT_ALLOWED";
public static final String ER_ATTR_NOT_ALLOWED = "ER_ATTR_NOT_ALLOWED";
public static final String ER_BAD_VALUE = "ER_BAD_VALUE";
public static final String ER_ATTRIB_VALUE_NOT_FOUND =
"ER_ATTRIB_VALUE_NOT_FOUND";
public static final String ER_ATTRIB_VALUE_NOT_RECOGNIZED =
"ER_ATTRIB_VALUE_NOT_RECOGNIZED";
public static final String ER_NULL_URI_NAMESPACE = "ER_NULL_URI_NAMESPACE";
public static final String ER_NUMBER_TOO_BIG = "ER_NUMBER_TOO_BIG";
public static final String ER_CANNOT_FIND_SAX1_DRIVER =
"ER_CANNOT_FIND_SAX1_DRIVER";
public static final String ER_SAX1_DRIVER_NOT_LOADED =
"ER_SAX1_DRIVER_NOT_LOADED";
public static final String ER_SAX1_DRIVER_NOT_INSTANTIATED =
"ER_SAX1_DRIVER_NOT_INSTANTIATED" ;
public static final String ER_SAX1_DRIVER_NOT_IMPLEMENT_PARSER =
"ER_SAX1_DRIVER_NOT_IMPLEMENT_PARSER";
public static final String ER_PARSER_PROPERTY_NOT_SPECIFIED =
"ER_PARSER_PROPERTY_NOT_SPECIFIED";
public static final String ER_PARSER_ARG_CANNOT_BE_NULL =
"ER_PARSER_ARG_CANNOT_BE_NULL" ;
public static final String ER_FEATURE = "ER_FEATURE";
public static final String ER_PROPERTY = "ER_PROPERTY" ;
public static final String ER_NULL_ENTITY_RESOLVER ="ER_NULL_ENTITY_RESOLVER";
public static final String ER_NULL_DTD_HANDLER = "ER_NULL_DTD_HANDLER" ;
public static final String ER_NO_DRIVER_NAME_SPECIFIED =
"ER_NO_DRIVER_NAME_SPECIFIED";
public static final String ER_NO_URL_SPECIFIED = "ER_NO_URL_SPECIFIED";
public static final String ER_POOLSIZE_LESS_THAN_ONE =
"ER_POOLSIZE_LESS_THAN_ONE";
public static final String ER_INVALID_DRIVER_NAME = "ER_INVALID_DRIVER_NAME";
public static final String ER_ERRORLISTENER = "ER_ERRORLISTENER";
public static final String ER_ASSERT_NO_TEMPLATE_PARENT =
"ER_ASSERT_NO_TEMPLATE_PARENT";
public static final String ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR =
"ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR";
public static final String ER_NOT_ALLOWED_IN_POSITION =
"ER_NOT_ALLOWED_IN_POSITION";
public static final String ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION =
"ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION";
public static final String ER_NAMESPACE_CONTEXT_NULL_NAMESPACE =
"ER_NAMESPACE_CONTEXT_NULL_NAMESPACE";
public static final String ER_NAMESPACE_CONTEXT_NULL_PREFIX =
"ER_NAMESPACE_CONTEXT_NULL_PREFIX";
public static final String ER_XPATH_RESOLVER_NULL_QNAME =
"ER_XPATH_RESOLVER_NULL_QNAME";
public static final String ER_XPATH_RESOLVER_NEGATIVE_ARITY =
"ER_XPATH_RESOLVER_NEGATIVE_ARITY";
public static final String INVALID_TCHAR = "INVALID_TCHAR";
public static final String INVALID_QNAME = "INVALID_QNAME";
public static final String INVALID_ENUM = "INVALID_ENUM";
public static final String INVALID_NMTOKEN = "INVALID_NMTOKEN";
public static final String INVALID_NCNAME = "INVALID_NCNAME";
public static final String INVALID_BOOLEAN = "INVALID_BOOLEAN";
public static final String INVALID_NUMBER = "INVALID_NUMBER";
public static final String ER_ARG_LITERAL = "ER_ARG_LITERAL";
public static final String ER_DUPLICATE_GLOBAL_VAR ="ER_DUPLICATE_GLOBAL_VAR";
public static final String ER_DUPLICATE_VAR = "ER_DUPLICATE_VAR";
public static final String ER_TEMPLATE_NAME_MATCH = "ER_TEMPLATE_NAME_MATCH";
public static final String ER_INVALID_PREFIX = "ER_INVALID_PREFIX";
public static final String ER_NO_ATTRIB_SET = "ER_NO_ATTRIB_SET";
public static final String ER_FUNCTION_NOT_FOUND =
"ER_FUNCTION_NOT_FOUND";
public static final String ER_CANT_HAVE_CONTENT_AND_SELECT =
"ER_CANT_HAVE_CONTENT_AND_SELECT";
public static final String ER_INVALID_SET_PARAM_VALUE = "ER_INVALID_SET_PARAM_VALUE";
public static final String ER_SET_FEATURE_NULL_NAME =
"ER_SET_FEATURE_NULL_NAME";
public static final String ER_GET_FEATURE_NULL_NAME =
"ER_GET_FEATURE_NULL_NAME";
public static final String ER_UNSUPPORTED_FEATURE =
"ER_UNSUPPORTED_FEATURE";
public static final String ER_EXTENSION_ELEMENT_NOT_ALLOWED_IN_SECURE_PROCESSING =
"ER_EXTENSION_ELEMENT_NOT_ALLOWED_IN_SECURE_PROCESSING";
public static final String WG_FOUND_CURLYBRACE = "WG_FOUND_CURLYBRACE";
public static final String WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR =
"WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR";
public static final String WG_EXPR_ATTRIB_CHANGED_TO_SELECT =
"WG_EXPR_ATTRIB_CHANGED_TO_SELECT";
public static final String WG_NO_LOCALE_IN_FORMATNUMBER =
"WG_NO_LOCALE_IN_FORMATNUMBER";
public static final String WG_LOCALE_NOT_FOUND = "WG_LOCALE_NOT_FOUND";
public static final String WG_CANNOT_MAKE_URL_FROM ="WG_CANNOT_MAKE_URL_FROM";
public static final String WG_CANNOT_LOAD_REQUESTED_DOC =
"WG_CANNOT_LOAD_REQUESTED_DOC";
public static final String WG_CANNOT_FIND_COLLATOR ="WG_CANNOT_FIND_COLLATOR";
public static final String WG_FUNCTIONS_SHOULD_USE_URL =
"WG_FUNCTIONS_SHOULD_USE_URL";
public static final String WG_ENCODING_NOT_SUPPORTED_USING_UTF8 =
"WG_ENCODING_NOT_SUPPORTED_USING_UTF8";
public static final String WG_ENCODING_NOT_SUPPORTED_USING_JAVA =
"WG_ENCODING_NOT_SUPPORTED_USING_JAVA";
public static final String WG_SPECIFICITY_CONFLICTS =
"WG_SPECIFICITY_CONFLICTS";
public static final String WG_PARSING_AND_PREPARING =
"WG_PARSING_AND_PREPARING";
public static final String WG_ATTR_TEMPLATE = "WG_ATTR_TEMPLATE";
public static final String WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESPACE = "WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESP";
public static final String WG_ATTRIB_NOT_HANDLED = "WG_ATTRIB_NOT_HANDLED";
public static final String WG_NO_DECIMALFORMAT_DECLARATION =
"WG_NO_DECIMALFORMAT_DECLARATION";
public static final String WG_OLD_XSLT_NS = "WG_OLD_XSLT_NS";
public static final String WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED =
"WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED";
public static final String WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE =
"WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE";
public static final String WG_ILLEGAL_ATTRIBUTE = "WG_ILLEGAL_ATTRIBUTE";
public static final String WG_COULD_NOT_RESOLVE_PREFIX =
"WG_COULD_NOT_RESOLVE_PREFIX";
public static final String WG_STYLESHEET_REQUIRES_VERSION_ATTRIB =
"WG_STYLESHEET_REQUIRES_VERSION_ATTRIB";
public static final String WG_ILLEGAL_ATTRIBUTE_NAME =
"WG_ILLEGAL_ATTRIBUTE_NAME";
public static final String WG_ILLEGAL_ATTRIBUTE_VALUE =
"WG_ILLEGAL_ATTRIBUTE_VALUE";
public static final String WG_EMPTY_SECOND_ARG = "WG_EMPTY_SECOND_ARG";
public static final String WG_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML =
"WG_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML";
public static final String WG_PROCESSINGINSTRUCTION_NOTVALID_NCNAME =
"WG_PROCESSINGINSTRUCTION_NOTVALID_NCNAME";
public static final String WG_ILLEGAL_ATTRIBUTE_POSITION =
"WG_ILLEGAL_ATTRIBUTE_POSITION";
public static final String NO_MODIFICATION_ALLOWED_ERR =
"NO_MODIFICATION_ALLOWED_ERR";
/*
* Now fill in the message text.
* Then fill in the message text for that message code in the
* array. Use the new error code as the index into the array.
*/
// Error messages...
/** Get the lookup table for error messages.
*
* @return The message lookup table.
*/
public Object[][] getContents()
{
return new Object[][] {
/** Error message ID that has a null message, but takes in a single object. */
{"ER0000" , "{0}" },
{ ER_NO_CURLYBRACE,
"Erreur : l'expression ne peut pas contenir le caract\u00E8re '{'"},
{ ER_ILLEGAL_ATTRIBUTE ,
"{0} a un attribut non admis : {1}"},
{ER_NULL_SOURCENODE_APPLYIMPORTS ,
"La valeur de sourceNode est NULL dans xsl:apply-imports."},
{ER_CANNOT_ADD,
"Impossible d''ajouter {0} \u00E0 {1}"},
{ ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES,
"La valeur de sourceNode est NULL dans handleApplyTemplatesInstruction."},
{ ER_NO_NAME_ATTRIB,
"{0} doit avoir un attribut ''name''."},
{ER_TEMPLATE_NOT_FOUND,
"Mod\u00E8le nomm\u00E9 {0} introuvable"},
{ER_CANT_RESOLVE_NAME_AVT,
"Impossible de r\u00E9soudre le nom AVT dans xsl:call-template."},
{ER_REQUIRES_ATTRIB,
"{0} exige l''attribut : {1}"},
{ ER_MUST_HAVE_TEST_ATTRIB,
"{0} doit avoir un attribut ''test''."},
{ER_BAD_VAL_ON_LEVEL_ATTRIB,
"Valeur incorrecte sur l''attribut de niveau : {0}"},
{ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML,
"Le nom de processing-instruction ne peut pas \u00EAtre 'xml'"},
{ ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME,
"Le nom de processing-instruction doit \u00EAtre un NCName valide : {0}"},
{ ER_NEED_MATCH_ATTRIB,
"{0} doit avoir un attribut de correspondance s''il a un mode."},
{ ER_NEED_NAME_OR_MATCH_ATTRIB,
"{0} exige un nom ou un attribut de correspondance."},
{ER_CANT_RESOLVE_NSPREFIX,
"Impossible de r\u00E9soudre le pr\u00E9fixe de l''espace de noms : {0}"},
{ ER_ILLEGAL_VALUE,
"xml:space a une valeur non admise : {0}"},
{ ER_NO_OWNERDOC,
"Le noeud enfant ne poss\u00E8de pas de document propri\u00E9taire."},
{ ER_ELEMTEMPLATEELEM_ERR,
"Erreur ElemTemplateElement : {0}"},
{ ER_NULL_CHILD,
"Tentative d'ajout d'un enfant NULL."},
{ ER_NEED_SELECT_ATTRIB,
"{0} exige un attribut \"select\"."},
{ ER_NEED_TEST_ATTRIB ,
"xsl:when doit avoir un attribut \"test\"."},
{ ER_NEED_NAME_ATTRIB,
"xsl:with-param doit avoir un attribut \"name\"."},
{ ER_NO_CONTEXT_OWNERDOC,
"le contexte ne poss\u00E8de pas de document propri\u00E9taire."},
{ER_COULD_NOT_CREATE_XML_PROC_LIAISON,
"Impossible de cr\u00E9er la liaison XML?? TransformerFactory : {0}"},
{ER_PROCESS_NOT_SUCCESSFUL,
"Xalan : le processus a \u00E9chou\u00E9."},
{ ER_NOT_SUCCESSFUL,
"Xalan : \u00E9chec."},
{ ER_ENCODING_NOT_SUPPORTED,
"Encodage non pris en charge : {0}"},
{ER_COULD_NOT_CREATE_TRACELISTENER,
"Impossible de cr\u00E9er TraceListener : {0}"},
{ER_KEY_REQUIRES_NAME_ATTRIB,
"xsl:key exige un attribut \"name\"."},
{ ER_KEY_REQUIRES_MATCH_ATTRIB,
"xsl:key exige un attribut \"match\"."},
{ ER_KEY_REQUIRES_USE_ATTRIB,
"xsl:key exige un attribut \"use\"."},
{ ER_REQUIRES_ELEMENTS_ATTRIB,
"(StylesheetHandler) {0} exige un attribut ''elements''."},
{ ER_MISSING_PREFIX_ATTRIB,
"(StylesheetHandler) L''attribut ''prefix'' {0} est manquant"},
{ ER_BAD_STYLESHEET_URL,
"L''URL de feuille de style est incorrecte : {0}"},
{ ER_FILE_NOT_FOUND,
"Fichier de feuille de style introuvable : {0}"},
{ ER_IOEXCEPTION,
"Exception d''E/S avec le fichier de feuille de style : {0}"},
{ ER_NO_HREF_ATTRIB,
"(StylesheetHandler) Attribut href introuvable pour {0}"},
{ ER_STYLESHEET_INCLUDES_ITSELF,
"(StylesheetHandler) {0} s''inclut directement ou indirectement lui-m\u00EAme."},
{ ER_PROCESSINCLUDE_ERROR,
"Erreur StylesheetHandler.processInclude, {0}"},
{ ER_MISSING_LANG_ATTRIB,
"(StylesheetHandler) L''attribut \"lang\" {0} est manquant"},
{ ER_MISSING_CONTAINER_ELEMENT_COMPONENT,
"(StylesheetHandler) l''\u00E9l\u00E9ment {0} est-il mal plac\u00E9? El\u00E9ment ''component'' du conteneur manquant"},
{ ER_CAN_ONLY_OUTPUT_TO_ELEMENT,
"Sortie unique vers Element, DocumentFragment, Document ou PrintWriter."},
{ ER_PROCESS_ERROR,
"Erreur StylesheetRoot.process"},
{ ER_UNIMPLNODE_ERROR,
"Erreur UnImplNode : {0}"},
{ ER_NO_SELECT_EXPRESSION,
"Erreur : expression de s\u00E9lection Xpath introuvable (-select)."},
{ ER_CANNOT_SERIALIZE_XSLPROCESSOR,
"Impossible de s\u00E9rialiser un processeur XSL."},
{ ER_NO_INPUT_STYLESHEET,
"L'entr\u00E9e de feuille de style n'a pas \u00E9t\u00E9 sp\u00E9cifi\u00E9e."},
{ ER_FAILED_PROCESS_STYLESHEET,
"Echec du traitement de la feuille de style."},
{ ER_COULDNT_PARSE_DOC,
"Impossible d''analyser le document {0}."},
{ ER_COULDNT_FIND_FRAGMENT,
"Fragment introuvable : {0}"},
{ ER_NODE_NOT_ELEMENT,
"Le noeud sur lequel pointe l''identificateur de fragment n''\u00E9tait pas un \u00E9l\u00E9ment : {0}"},
{ ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB,
"l'\u00E9l\u00E9ment for-each doit avoir un attribut de nom ou de correspondance"},
{ ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB,
"les mod\u00E8les doivent avoir un attribut de nom ou de correspondance"},
{ ER_NO_CLONE_OF_DOCUMENT_FRAG,
"Aucun clone d'un fragment de document."},
{ ER_CANT_CREATE_ITEM,
"Impossible de cr\u00E9er l''\u00E9l\u00E9ment dans l''arborescence de r\u00E9sultats : {0}"},
{ ER_XMLSPACE_ILLEGAL_VALUE,
"xml:space dans le fichier XML source a une valeur non admise : {0}"},
{ ER_NO_XSLKEY_DECLARATION,
"Il n''existe aucune d\u00E9claration xsl:key pour {0}."},
{ ER_CANT_CREATE_URL,
"Erreur : impossible de cr\u00E9er l''URL pour : {0}"},
{ ER_XSLFUNCTIONS_UNSUPPORTED,
"xsl:functions n'est pas pris en charge"},
{ ER_PROCESSOR_ERROR,
"Erreur TransformerFactory XSLT"},
{ ER_NOT_ALLOWED_INSIDE_STYLESHEET,
"(StylesheetHandler) {0} non autoris\u00E9 dans une feuille de style."},
{ ER_RESULTNS_NOT_SUPPORTED,
"\u00E9l\u00E9ment result-ns plus pris en charge. Utilisez plut\u00F4t xsl:output."},
{ ER_DEFAULTSPACE_NOT_SUPPORTED,
"\u00E9l\u00E9ment default-space plus pris en charge. Utilisez plut\u00F4t xsl:strip-space ou xsl:preserve-space."},
{ ER_INDENTRESULT_NOT_SUPPORTED,
"\u00E9l\u00E9ment indent-result plus pris en charge. Utilisez plut\u00F4t xsl:output."},
{ ER_ILLEGAL_ATTRIB,
"(StylesheetHandler) {0} a un attribut non admis : {1}"},
{ ER_UNKNOWN_XSL_ELEM,
"El\u00E9ment XSL inconnu : {0}"},
{ ER_BAD_XSLSORT_USE,
"(StylesheetHandler) xsl:sort ne peut \u00EAtre utilis\u00E9 qu'avec xsl:apply-templates ou xsl:for-each."},
{ ER_MISPLACED_XSLWHEN,
"(StylesheetHandler) xsl:when mal plac\u00E9."},
{ ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE,
"(StylesheetHandler) xsl:choose n'a affect\u00E9 aucun parent \u00E0 xsl:when."},
{ ER_MISPLACED_XSLOTHERWISE,
"(StylesheetHandler) xsl:otherwise mal plac\u00E9."},
{ ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE,
"(StylesheetHandler) xsl:choose n'a affect\u00E9 aucun parent \u00E0 xsl:otherwise."},
{ ER_NOT_ALLOWED_INSIDE_TEMPLATE,
"(StylesheetHandler) {0} n''est pas autoris\u00E9 dans un mod\u00E8le."},
{ ER_UNKNOWN_EXT_NS_PREFIX,
"(StylesheetHandler) Pr\u00E9fixe {1} de l''espace de noms de l''extension {0} inconnu"},
{ ER_IMPORTS_AS_FIRST_ELEM,
"(StylesheetHandler) Les imports ne peuvent s'appliquer que sur les premiers \u00E9l\u00E9ments de la feuille de style."},
{ ER_IMPORTING_ITSELF,
"(StylesheetHandler) {0} s''importe directement ou indirectement lui-m\u00EAme."},
{ ER_XMLSPACE_ILLEGAL_VAL,
"(StylesheetHandler) xml:space a une valeur non admise : {0}"},
{ ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL,
"Echec de processStylesheet."},
{ ER_SAX_EXCEPTION,
"Exception SAX"},
// add this message to fix bug 21478
{ ER_FUNCTION_NOT_SUPPORTED,
"Fonction non prise en charge."},
{ ER_XSLT_ERROR,
"Erreur XSLT"},
{ ER_CURRENCY_SIGN_ILLEGAL,
"le symbole de devise n'est pas autoris\u00E9 dans la cha\u00EEne du mod\u00E8le de format"},
{ ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM,
"Fonction de document non prise en charge dans l'objet DOM de la feuille de style."},
{ ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER,
"Impossible de r\u00E9soudre le pr\u00E9fixe du r\u00E9solveur non-Prefix."},
{ ER_REDIRECT_COULDNT_GET_FILENAME,
"Extension Redirect : impossible d'obtenir le nom de fichier. L'attribut \"file\" ou \"select\" doit renvoyer une cha\u00EEne valide."},
{ ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT,
"Impossible de cr\u00E9er FormatterListener dans l'extension Redirect."},
{ ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX,
"Le pr\u00E9fixe de l''\u00E9l\u00E9ment exclude-result-prefixes n''est pas valide : {0}"},
{ ER_MISSING_NS_URI,
"URI d'espace de noms manquant pour le pr\u00E9fixe sp\u00E9cifi\u00E9"},
{ ER_MISSING_ARG_FOR_OPTION,
"Argument manquant pour l''option : {0}"},
{ ER_INVALID_OPTION,
"Option non valide : {0}"},
{ ER_MALFORMED_FORMAT_STRING,
"Format de cha\u00EEne incorrect : {0}"},
{ ER_STYLESHEET_REQUIRES_VERSION_ATTRIB,
"xsl:stylesheet exige un attribut de version."},
{ ER_ILLEGAL_ATTRIBUTE_VALUE,
"L''attribut {0} a une valeur non admise : {1}"},
{ ER_CHOOSE_REQUIRES_WHEN,
"xsl:choose exige un \u00E9l\u00E9ment xsl:when"},
{ ER_NO_APPLY_IMPORT_IN_FOR_EACH,
"xsl:apply-imports non autoris\u00E9 dans un \u00E9l\u00E9ment xsl:for-each"},
{ ER_CANT_USE_DTM_FOR_OUTPUT,
"Impossible d'utiliser un \u00E9l\u00E9ment DTMLiaison pour un noeud DOM de sortie... Transmettez plut\u00F4t un \u00E9l\u00E9ment com.sun.org.apache.xpath.internal.DOM2Helper."},
{ ER_CANT_USE_DTM_FOR_INPUT,
"Impossible d'utiliser un \u00E9l\u00E9ment DTMLiaison pour un noeud DOM d'entr\u00E9e... Transmettez plut\u00F4t un \u00E9l\u00E9ment com.sun.org.apache.xpath.internal.DOM2Helper."},
{ ER_CALL_TO_EXT_FAILED,
"Echec de l''appel de l''\u00E9l\u00E9ment d''extension : {0}"},
{ ER_PREFIX_MUST_RESOLVE,
"Le pr\u00E9fixe doit \u00EAtre r\u00E9solu en espace de noms : {0}"},
{ ER_INVALID_UTF16_SURROGATE,
"Substitut UTF-16 non valide d\u00E9tect\u00E9 : {0} ?"},
{ ER_XSLATTRSET_USED_ITSELF,
"xsl:attribute-set {0} s''est utilis\u00E9 lui-m\u00EAme, ce qui g\u00E9n\u00E8re une boucle sans fin."},
{ ER_CANNOT_MIX_XERCESDOM,
"Impossible de combiner une entr\u00E9e non Xerces-DOM et une sortie Xerces-DOM."},
{ ER_TOO_MANY_LISTENERS,
"addTraceListenersToStylesheet - TooManyListenersException"},
{ ER_IN_ELEMTEMPLATEELEM_READOBJECT,
"Dans ElemTemplateElement.readObject : {0}"},
{ ER_DUPLICATE_NAMED_TEMPLATE,
"Plusieurs mod\u00E8les nomm\u00E9s {0} ont \u00E9t\u00E9 trouv\u00E9s"},
{ ER_INVALID_KEY_CALL,
"Appel de fonction non valide : les appels de touche r\u00E9cursive () ne sont pas autoris\u00E9s"},
{ ER_REFERENCING_ITSELF,
"La variable {0} fait directement ou indirectement r\u00E9f\u00E9rence \u00E0 elle-m\u00EAme."},
{ ER_ILLEGAL_DOMSOURCE_INPUT,
"Le noeud d'entr\u00E9e ne peut pas \u00EAtre NULL pour un \u00E9l\u00E9ment DOMSource de newTemplates."},
{ ER_CLASS_NOT_FOUND_FOR_OPTION,
"Fichier de classe introuvable pour l''option {0}"},
{ ER_REQUIRED_ELEM_NOT_FOUND,
"El\u00E9ment obligatoire introuvable : {0}"},
{ ER_INPUT_CANNOT_BE_NULL,
"InputStream ne peut pas \u00EAtre NULL"},
{ ER_URI_CANNOT_BE_NULL,
"L'URI ne peut pas \u00EAtre NULL"},
{ ER_FILE_CANNOT_BE_NULL,
"Le fichier ne peut pas \u00EAtre NULL"},
{ ER_SOURCE_CANNOT_BE_NULL,
"InputSource ne peut pas \u00EAtre NULL"},
{ ER_CANNOT_INIT_BSFMGR,
"Impossible d'initialiser le gestionnaire BSF"},
{ ER_CANNOT_CMPL_EXTENSN,
"Impossible de compiler l'extension"},
{ ER_CANNOT_CREATE_EXTENSN,
"Impossible de cr\u00E9er l''extension {0}. Cause : {1}"},
{ ER_INSTANCE_MTHD_CALL_REQUIRES,
"L''appel de la m\u00E9thode d''instance {0} exige une instance d''objet comme premier argument"},
{ ER_INVALID_ELEMENT_NAME,
"Nom d''\u00E9l\u00E9ment sp\u00E9cifi\u00E9 {0} non valide"},
{ ER_ELEMENT_NAME_METHOD_STATIC,
"La m\u00E9thode du nom d''\u00E9l\u00E9ment doit \u00EAtre statique {0}"},
{ ER_EXTENSION_FUNC_UNKNOWN,
"La fonction d''extension {0} : {1} est inconnue"},
{ ER_MORE_MATCH_CONSTRUCTOR,
"Plusieurs meilleures concordances du constructeur pour {0}"},
{ ER_MORE_MATCH_METHOD,
"Plusieurs meilleures concordances pour la m\u00E9thode {0}"},
{ ER_MORE_MATCH_ELEMENT,
"Plusieurs meilleures concordances pour la m\u00E9thode d''\u00E9l\u00E9ment {0}"},
{ ER_INVALID_CONTEXT_PASSED,
"Contexte transmis pour \u00E9valuation {0} non valide"},
{ ER_POOL_EXISTS,
"Le pool existe d\u00E9j\u00E0"},
{ ER_NO_DRIVER_NAME,
"Aucun nom de pilote indiqu\u00E9"},
{ ER_NO_URL,
"Aucune URL indiqu\u00E9e"},
{ ER_POOL_SIZE_LESSTHAN_ONE,
"La taille de pool est inf\u00E9rieure \u00E0 1."},
{ ER_INVALID_DRIVER,
"Nom de pilote indiqu\u00E9 non valide."},
{ ER_NO_STYLESHEETROOT,
"Racine de la feuille de style introuvable."},
{ ER_ILLEGAL_XMLSPACE_VALUE,
"Valeur non admise pour xml:space"},
{ ER_PROCESSFROMNODE_FAILED,
"Echec de processFromNode"},
{ ER_RESOURCE_COULD_NOT_LOAD,
"La ressource [ {0} ] n''a pas pu charger : {1} \n {2} \t {3}"},
{ ER_BUFFER_SIZE_LESSTHAN_ZERO,
"Taille du tampon <=0"},
{ ER_UNKNOWN_ERROR_CALLING_EXTENSION,
"Erreur inconnue lors de l'appel de l'extension"},
{ ER_NO_NAMESPACE_DECL,
"Le pr\u00E9fixe {0} n''a pas de d\u00E9claration d''espace de noms correspondante"},
{ ER_ELEM_CONTENT_NOT_ALLOWED,
"Contenu d''\u00E9l\u00E9ment non autoris\u00E9 pour lang=javaclass {0}"},
{ ER_STYLESHEET_DIRECTED_TERMINATION,
"Fin du r\u00E9acheminement de la feuille de style"},
{ ER_ONE_OR_TWO,
"1 ou 2"},
{ ER_TWO_OR_THREE,
"2 ou 3"},
{ ER_COULD_NOT_LOAD_RESOURCE,
"Impossible de charger {0} (v\u00E9rifier CLASSPATH), les valeurs par d\u00E9faut sont donc employ\u00E9es"},
{ ER_CANNOT_INIT_DEFAULT_TEMPLATES,
"Impossible d'initialiser les mod\u00E8les default"},
{ ER_RESULT_NULL,
"Le r\u00E9sultat ne doit pas \u00EAtre NULL"},
{ ER_RESULT_COULD_NOT_BE_SET,
"Le r\u00E9sultat n'a pas pu \u00EAtre d\u00E9fini"},
{ ER_NO_OUTPUT_SPECIFIED,
"Aucune sortie sp\u00E9cifi\u00E9e"},
{ ER_CANNOT_TRANSFORM_TO_RESULT_TYPE,
"Impossible de transformer le r\u00E9sultat en r\u00E9sultat de type {0}"},
{ ER_CANNOT_TRANSFORM_SOURCE_TYPE,
"Impossible de transformer une source de type {0}"},
{ ER_NULL_CONTENT_HANDLER,
"Gestionnaire de contenu NULL"},
{ ER_NULL_ERROR_HANDLER,
"Gestionnaire d'erreurs NULL"},
{ ER_CANNOT_CALL_PARSE,
"impossible d'appeler l'analyse si le gestionnaire de contenu n'est pas d\u00E9fini"},
{ ER_NO_PARENT_FOR_FILTER,
"Aucun parent pour le filtre"},
{ ER_NO_STYLESHEET_IN_MEDIA,
"Aucune feuille de style trouv\u00E9e dans : {0}, support = {1}"},
{ ER_NO_STYLESHEET_PI,
"Aucune instruction de traitement (PI) xml-stylesheet trouv\u00E9e dans : {0}"},
{ ER_NOT_SUPPORTED,
"Non pris en charge : {0}"},
{ ER_PROPERTY_VALUE_BOOLEAN,
"La valeur de la propri\u00E9t\u00E9 {0} doit \u00EAtre une instance Boolean"},
{ ER_COULD_NOT_FIND_EXTERN_SCRIPT,
"Impossible d''acc\u00E9der au script externe \u00E0 {0}"},
{ ER_RESOURCE_COULD_NOT_FIND,
"La ressource [ {0} ] est introuvable.\n {1}"},
{ ER_OUTPUT_PROPERTY_NOT_RECOGNIZED,
"Propri\u00E9t\u00E9 de sortie non reconnue : {0}"},
{ ER_FAILED_CREATING_ELEMLITRSLT,
"Echec de la cr\u00E9ation de l'instance ElemLiteralResult"},
//Earlier (JDK 1.4 XALAN 2.2-D11) at key code '204' the key name was ER_PRIORITY_NOT_PARSABLE
// In latest Xalan code base key name is ER_VALUE_SHOULD_BE_NUMBER. This should also be taken care
//in locale specific files like XSLTErrorResources_de.java, XSLTErrorResources_fr.java etc.
//NOTE: Not only the key name but message has also been changed.
{ ER_VALUE_SHOULD_BE_NUMBER,
"La valeur de {0} doit contenir un nombre pouvant \u00EAtre analys\u00E9"},
{ ER_VALUE_SHOULD_EQUAL,
"La valeur de {0} doit \u00EAtre \u00E9gale \u00E0 oui ou non"},
{ ER_FAILED_CALLING_METHOD,
"Echec de l''appel de la m\u00E9thode {0}"},
{ ER_FAILED_CREATING_ELEMTMPL,
"Echec de la cr\u00E9ation de l'instance ElemTemplateElement"},
{ ER_CHARS_NOT_ALLOWED,
"Les caract\u00E8res ne sont pas autoris\u00E9s \u00E0 ce point du document"},
{ ER_ATTR_NOT_ALLOWED,
"L''attribut \"{0}\" n''est pas autoris\u00E9 sur l''\u00E9l\u00E9ment {1}."},
{ ER_BAD_VALUE,
"Valeur incorrecte de {0} : {1} "},
{ ER_ATTRIB_VALUE_NOT_FOUND,
"Valeur d''attribut {0} introuvable "},
{ ER_ATTRIB_VALUE_NOT_RECOGNIZED,
"Valeur d''attribut {0} non reconnue "},
{ ER_NULL_URI_NAMESPACE,
"Tentative de g\u00E9n\u00E9ration d'un pr\u00E9fixe d'espace de noms avec un URI NULL"},
{ ER_NUMBER_TOO_BIG,
"Tentative de formatage d'un nombre sup\u00E9rieur \u00E0 l'entier de type Long le plus grand"},
{ ER_CANNOT_FIND_SAX1_DRIVER,
"Classe de pilote SAX1 {0} introuvable"},
{ ER_SAX1_DRIVER_NOT_LOADED,
"Classe de pilote SAX1 {0} trouv\u00E9e mais pas charg\u00E9e"},
{ ER_SAX1_DRIVER_NOT_INSTANTIATED,
"Classe de pilote SAX1 {0} charg\u00E9e mais pas instanci\u00E9e"},
{ ER_SAX1_DRIVER_NOT_IMPLEMENT_PARSER,
"La classe de pilote SAX1 {0} n''impl\u00E9mente pas org.xml.sax.Parser"},
{ ER_PARSER_PROPERTY_NOT_SPECIFIED,
"Propri\u00E9t\u00E9 syst\u00E8me org.xml.sax.parser non indiqu\u00E9e"},
{ ER_PARSER_ARG_CANNOT_BE_NULL,
"L'argument d'analyseur ne doit pas \u00EAtre NULL"},
{ ER_FEATURE,
"Fonctionnalit\u00E9 : {0}"},
{ ER_PROPERTY,
"Propri\u00E9t\u00E9 : {0}"},
{ ER_NULL_ENTITY_RESOLVER,
"R\u00E9solveur d'entit\u00E9 NULL"},
{ ER_NULL_DTD_HANDLER,
"Gestionnaire DTD NULL"},
{ ER_NO_DRIVER_NAME_SPECIFIED,
"Aucun nom de pilote indiqu\u00E9."},
{ ER_NO_URL_SPECIFIED,
"Aucune URL indiqu\u00E9e."},
{ ER_POOLSIZE_LESS_THAN_ONE,
"La taille de pool est inf\u00E9rieure \u00E0 1."},
{ ER_INVALID_DRIVER_NAME,
"Nom de pilote indiqu\u00E9 non valide."},
{ ER_ERRORLISTENER,
"ErrorListener"},
// Note to translators: The following message should not normally be displayed
// to users. It describes a situation in which the processor has detected
// an internal consistency problem in itself, and it provides this message
// for the developer to help diagnose the problem. The name
// 'ElemTemplateElement' is the name of a class, and should not be
// translated.
{ ER_ASSERT_NO_TEMPLATE_PARENT,
"Erreur du programmeur. L'expression n'a pas de parent ElemTemplateElement."},
// Note to translators: The following message should not normally be displayed
// to users. It describes a situation in which the processor has detected
// an internal consistency problem in itself, and it provides this message
// for the developer to help diagnose the problem. The substitution text
// provides further information in order to diagnose the problem. The name
// 'RedundentExprEliminator' is the name of a class, and should not be
// translated.
{ ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR,
"Assertion du programmeur dans RedundentExprEliminator : {0}"},
{ ER_NOT_ALLOWED_IN_POSITION,
"{0} n''est pas autoris\u00E9 \u00E0 cet emplacement de la feuille de style."},
{ ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION,
"Le texte imprimable n'est pas autoris\u00E9 \u00E0 cet emplacement de la feuille de style."},
// This code is shared with warning codes.
// SystemId Unknown
{ INVALID_TCHAR,
"Valeur non admise {1} utilis\u00E9e pour l''attribut CHAR : {0}. Un attribut de type CHAR ne doit \u00EAtre compos\u00E9 que d''un caract\u00E8re."},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "QNAME" is the XML data-type of
// the attribute, and should not be translated. The substitution text {1} is
// the attribute value and {0} is the attribute name.
//The following codes are shared with the warning codes...
{ INVALID_QNAME,
"Valeur non admise {1} utilis\u00E9e pour l''attribut QNAME : {0}"},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "ENUM" is the XML data-type of
// the attribute, and should not be translated. The substitution text {1} is
// the attribute value, {0} is the attribute name, and {2} is a list of valid
// values.
{ INVALID_ENUM,
"Valeur non admise {1} utilis\u00E9e pour l''attribut ENUM : {0}. Les valeurs valides sont les suivantes : {2}."},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "NMTOKEN" is the XML data-type
// of the attribute, and should not be translated. The substitution text {1} is
// the attribute value and {0} is the attribute name.
{ INVALID_NMTOKEN,
"Valeur non admise {1} utilis\u00E9e pour l''attribut NMTOKEN : {0} "},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "NCNAME" is the XML data-type
// of the attribute, and should not be translated. The substitution text {1} is
// the attribute value and {0} is the attribute name.
{ INVALID_NCNAME,
"Valeur non admise {1} utilis\u00E9e pour l''attribut NCNAME : {0} "},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "boolean" is the XSLT data-type
// of the attribute, and should not be translated. The substitution text {1} is
// the attribute value and {0} is the attribute name.
{ INVALID_BOOLEAN,
"Valeur non admise {1} utilis\u00E9e pour l''attribut \"boolean\" : {0} "},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "number" is the XSLT data-type
// of the attribute, and should not be translated. The substitution text {1} is
// the attribute value and {0} is the attribute name.
{ INVALID_NUMBER,
"Valeur non admise {1} utilis\u00E9e pour l''attribut \"number\" : {0} "},
// End of shared codes...
// Note to translators: A "match pattern" is a special form of XPath expression
// that is used for matching patterns. The substitution text is the name of
// a function. The message indicates that when this function is referenced in
// a match pattern, its argument must be a string literal (or constant.)
// ER_ARG_LITERAL - new error message for bugzilla //5202
{ ER_ARG_LITERAL,
"L''argument pour {0} dans le mod\u00E8le de recherche doit \u00EAtre un litt\u00E9ral."},
// Note to translators: The following message indicates that two definitions of
// a variable. A "global variable" is a variable that is accessible everywher
// in the stylesheet.
// ER_DUPLICATE_GLOBAL_VAR - new error message for bugzilla #790
{ ER_DUPLICATE_GLOBAL_VAR,
"D\u00E9claration de variable globale en double."},
// Note to translators: The following message indicates that two definitions of
// a variable were encountered.
// ER_DUPLICATE_VAR - new error message for bugzilla #790
{ ER_DUPLICATE_VAR,
"D\u00E9claration de variable en double."},
// Note to translators: "xsl:template, "name" and "match" are XSLT keywords
// which must not be translated.
// ER_TEMPLATE_NAME_MATCH - new error message for bugzilla #789
{ ER_TEMPLATE_NAME_MATCH,
"xsl:template doit avoir un attribut \"name\" ou \"match\" (ou les deux)"},
// Note to translators: "exclude-result-prefixes" is an XSLT keyword which
// should not be translated. The message indicates that a namespace prefix
// encountered as part of the value of the exclude-result-prefixes attribute
// was in error.
// ER_INVALID_PREFIX - new error message for bugzilla #788
{ ER_INVALID_PREFIX,
"Le pr\u00E9fixe de l''\u00E9l\u00E9ment exclude-result-prefixes n''est pas valide : {0}"},
// Note to translators: An "attribute set" is a set of attributes that can
// be added to an element in the output document as a group. The message
// indicates that there was a reference to an attribute set named {0} that
// was never defined.
// ER_NO_ATTRIB_SET - new error message for bugzilla #782
{ ER_NO_ATTRIB_SET,
"L''ensemble d''attributs nomm\u00E9 {0} n''existe pas"},
// Note to translators: This message indicates that there was a reference
// to a function named {0} for which no function definition could be found.
{ ER_FUNCTION_NOT_FOUND,
"La fonction nomm\u00E9e {0} n''existe pas"},
// Note to translators: This message indicates that the XSLT instruction
// that is named by the substitution text {0} must not contain other XSLT
// instructions (content) or a "select" attribute. The word "select" is
// an XSLT keyword in this case and must not be translated.
{ ER_CANT_HAVE_CONTENT_AND_SELECT,
"L''\u00E9l\u00E9ment {0} ne doit pas avoir \u00E0 la fois un attribut \"select\" et un attribut de contenu."},
// Note to translators: This message indicates that the value argument
// of setParameter must be a valid Java Object.
{ ER_INVALID_SET_PARAM_VALUE,
"La valeur du param\u00E8tre {0} doit \u00EAtre un objet Java valide"},
{ ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX_FOR_DEFAULT,
"L'attribut result-prefix d'un \u00E9l\u00E9ment xsl:namespace-alias a la valeur \"#default\", mais il n'existe aucune d\u00E9claration de l'espace de noms par d\u00E9faut dans la port\u00E9e pour l'\u00E9l\u00E9ment"},
{ ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX,
"L''attribut result-prefix d''un \u00E9l\u00E9ment xsl:namespace-alias a la valeur ''{0}'', mais il n''existe aucune d\u00E9claration d''espace de noms pour le pr\u00E9fixe ''{0}'' dans la port\u00E9e pour l''\u00E9l\u00E9ment."},
{ ER_SET_FEATURE_NULL_NAME,
"Le nom de la fonctionnalit\u00E9 ne peut pas \u00EAtre NULL dans TransformerFactory.setFeature (cha\u00EEne pour le nom, valeur bool\u00E9enne)."},
{ ER_GET_FEATURE_NULL_NAME,
"Le nom de la fonctionnalit\u00E9 ne peut pas \u00EAtre NULL dans TransformerFactory.getFeature (cha\u00EEne pour le nom)."},
{ ER_UNSUPPORTED_FEATURE,
"Impossible de d\u00E9finir la fonctionnalit\u00E9 ''{0}'' sur cette propri\u00E9t\u00E9 TransformerFactory."},
{ ER_EXTENSION_ELEMENT_NOT_ALLOWED_IN_SECURE_PROCESSING,
"L''utilisation de l''\u00E9l\u00E9ment d''extension ''{0}'' n''est pas autoris\u00E9e lorsque la fonctionnalit\u00E9 de traitement s\u00E9curis\u00E9 est d\u00E9finie sur True."},
{ ER_NAMESPACE_CONTEXT_NULL_NAMESPACE,
"Impossible d'obtenir le pr\u00E9fixe pour un URI d'espace de noms NULL."},
{ ER_NAMESPACE_CONTEXT_NULL_PREFIX,
"Impossible d'obtenir l'URI d'espace de noms pour le pr\u00E9fixe NULL."},
{ ER_XPATH_RESOLVER_NULL_QNAME,
"Le nom de fonction ne peut pas \u00EAtre NULL."},
{ ER_XPATH_RESOLVER_NEGATIVE_ARITY,
"L'arit\u00E9 ne peut pas \u00EAtre n\u00E9gative."},
// Warnings...
{ WG_FOUND_CURLYBRACE,
"'}' trouv\u00E9 mais aucun mod\u00E8le d'attribut ouvert."},
{ WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR,
"Avertissement : l''attribut \"count\" ne correspond pas \u00E0 un anc\u00EAtre dans xsl:number ! Cible = {0}"},
{ WG_EXPR_ATTRIB_CHANGED_TO_SELECT,
"Ancienne syntaxe : le nom de l'attribut \"expr\" a \u00E9t\u00E9 modifi\u00E9 en \"select\"."},
{ WG_NO_LOCALE_IN_FORMATNUMBER,
"Xalan ne g\u00E8re pas encore le nom de l'environnement local dans la fonction format-number."},
{ WG_LOCALE_NOT_FOUND,
"Avertissement : environnement local introuvable pour xml:lang={0}"},
{ WG_CANNOT_MAKE_URL_FROM,
"Impossible de cr\u00E9er une URL \u00E0 partir de : {0}"},
{ WG_CANNOT_LOAD_REQUESTED_DOC,
"Impossible de charger le document demand\u00E9 : {0}"},
{ WG_CANNOT_FIND_COLLATOR,
"Collator introuvable pour <sort xml:lang={0}"},
{ WG_FUNCTIONS_SHOULD_USE_URL,
"Ancienne syntaxe : l''instruction de la fonction doit utiliser une URL de {0}"},
{ WG_ENCODING_NOT_SUPPORTED_USING_UTF8,
"encodage non pris en charge : {0}, avec UTF-8"},
{ WG_ENCODING_NOT_SUPPORTED_USING_JAVA,
"encodage non pris en charge : {0}, avec Java {1}"},
{ WG_SPECIFICITY_CONFLICTS,
"Conflits de sp\u00E9cificit\u00E9 d\u00E9tect\u00E9s : {0} Les derniers \u00E9l\u00E9ments trouv\u00E9s dans la feuille de style seront utilis\u00E9s."},
{ WG_PARSING_AND_PREPARING,
"========= Analyse et pr\u00E9paration de {0} =========="},
{ WG_ATTR_TEMPLATE,
"Mod\u00E8le attr, {0}"},
{ WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESPACE,
"Conflit de correspondance entre xsl:strip-space et xsl:preserve-space"},
{ WG_ATTRIB_NOT_HANDLED,
"Xalan ne g\u00E8re pas encore l''attribut {0}."},
{ WG_NO_DECIMALFORMAT_DECLARATION,
"Aucune d\u00E9claration trouv\u00E9e pour le format d\u00E9cimal : {0}"},
{ WG_OLD_XSLT_NS,
"Espace de noms XSLT incorrect ou manquant. "},
{ WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED,
"Une seule d\u00E9claration xsl:decimal-format par d\u00E9faut est autoris\u00E9e."},
{ WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE,
"Les noms xsl:decimal-format doivent \u00EAtre uniques. Le nom \"{0}\" a \u00E9t\u00E9 dupliqu\u00E9."},
{ WG_ILLEGAL_ATTRIBUTE,
"{0} a un attribut non admis : {1}"},
{ WG_COULD_NOT_RESOLVE_PREFIX,
"Impossible de r\u00E9soudre le pr\u00E9fixe d''espace de noms : {0}. Le noeud ne sera pas pris en compte."},
{ WG_STYLESHEET_REQUIRES_VERSION_ATTRIB,
"xsl:stylesheet exige un attribut de version."},
{ WG_ILLEGAL_ATTRIBUTE_NAME,
"Nom d''attribut non admis : {0}"},
{ WG_ILLEGAL_ATTRIBUTE_VALUE,
"Valeur non admise utilis\u00E9e pour l''attribut {0} : {1}"},
{ WG_EMPTY_SECOND_ARG,
"Le jeu de noeuds r\u00E9sultant du deuxi\u00E8me argument de la fonction de document est vide. Renvoyez un jeu de noeuds vide."},
//Following are the new WARNING keys added in XALAN code base after Jdk 1.4 (Xalan 2.2-D11)
// Note to translators: "name" and "xsl:processing-instruction" are keywords
// and must not be translated.
{ WG_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML,
"La valeur de l'attribut \"name\" du nom xsl:processing-instruction ne doit pas \u00EAtre \"xml\""},
// Note to translators: "name" and "xsl:processing-instruction" are keywords
// and must not be translated. "NCName" is an XML data-type and must not be
// translated.
{ WG_PROCESSINGINSTRUCTION_NOTVALID_NCNAME,
"La valeur de l''attribut ''name'' de xsl:processing-instruction doit \u00EAtre un NCName valide : {0}"},
// Note to translators: This message is reported if the stylesheet that is
// being processed attempted to construct an XML document with an attribute in a
// place other than on an element. The substitution text specifies the name of
// the attribute.
{ WG_ILLEGAL_ATTRIBUTE_POSITION,
"Impossible d''ajouter l''attribut {0} apr\u00E8s des noeuds enfant ou avant la production d''un \u00E9l\u00E9ment. L''attribut est ignor\u00E9."},
{ NO_MODIFICATION_ALLOWED_ERR,
"Une tentative de modification d'un objet a \u00E9t\u00E9 effectu\u00E9e alors que les modifications ne sont pas autoris\u00E9es."
},
//Check: WHY THERE IS A GAP B/W NUMBERS in the XSLTErrorResources properties file?
// Other miscellaneous text used inside the code...
{ "ui_language", "fr"},
{ "help_language", "fr" },
{ "language", "fr" },
{ "BAD_CODE", "Le param\u00E8tre createMessage \u00E9tait hors limites"},
{ "FORMAT_FAILED", "Exception g\u00E9n\u00E9r\u00E9e pendant l'appel messageFormat"},
{ "version", ">>>>>>> Version Xalan "},
{ "version2", "<<<<<<<"},
{ "yes", "oui"},
{ "line", "Ligne n\u00B0"},
{ "column","Colonne n\u00B0"},
{ "xsldone", "XSLProcessor : termin\u00E9"},
// Note to translators: The following messages provide usage information
// for the Xalan Process command line. "Process" is the name of a Java class,
// and should not be translated.
{ "xslProc_option", "Options de classe \"Process\" de ligne de commande Xalan-J :"},
{ "xslProc_option", "Options de classe \"Process\" de ligne de commande Xalan-J :"},
{ "xslProc_invalid_xsltc_option", "L''option {0} n''est pas prise en charge dans le mode XSLTC."},
{ "xslProc_invalid_xalan_option", "L''option {0} ne peut \u00EAtre utilis\u00E9e qu''avec -XSLTC."},
{ "xslProc_no_input", "Erreur : aucune feuille de style ou aucun fichier XML d'entr\u00E9e n'est sp\u00E9cifi\u00E9. Ex\u00E9cutez cette commande sans option concernant les instructions d'utilisation."},
{ "xslProc_common_options", "-Options communes-"},
{ "xslProc_xalan_options", "-Options pour Xalan-"},
{ "xslProc_xsltc_options", "-Options pour XSLTC-"},
{ "xslProc_return_to_continue", "(appuyez sur la touche <Entr\u00E9e> pour continuer)"},
// Note to translators: The option name and the parameter name do not need to
// be translated. Only translate the messages in parentheses. Note also that
// leading whitespace in the messages is used to indent the usage information
// for each option in the English messages.
// Do not translate the keywords: XSLTC, SAX, DOM and DTM.
{ "optionXSLTC", " [-XSLTC (utiliser XSLTC pour la transformation)]"},
{ "optionIN", " [-IN inputXMLURL]"},
{ "optionXSL", " [-XSL XSLTransformationURL]"},
{ "optionOUT", " [-OUT outputFileName]"},
{ "optionLXCIN", " [-LXCIN compiledStylesheetFileNameIn]"},
{ "optionLXCOUT", " [-LXCOUT compiledStylesheetFileNameOutOut]"},
{ "optionPARSER", " [Nom de classe qualifi\u00E9 complet -PARSER de liaison d'analyseur]"},
{ "optionE", " [-E (Ne pas d\u00E9velopper les r\u00E9f\u00E9rences d'entit\u00E9)]"},
{ "optionV", " [-E (Ne pas d\u00E9velopper les r\u00E9f\u00E9rences d'entit\u00E9)]"},
{ "optionQC", " [-QC (Avertissements de conflits de mod\u00E8les en mode silencieux)]"},
{ "optionQ", " [-Q (Mode silencieux)]"},
{ "optionLF", " [-LF (Utiliser les retours \u00E0 la ligne uniquement en sortie {valeur par d\u00E9faut : CR/LF})]"},
{ "optionCR", " [-CR (Utiliser les retours chariot uniquement en sortie {valeur par d\u00E9faut : CR/LF})]"},
{ "optionESCAPE", " [-ESCAPE (Avec caract\u00E8res d'espacement {valeur par d\u00E9faut : <>&\"'\\r\\n}]"},
{ "optionINDENT", " [-INDENT (Contr\u00F4ler le nombre d'espaces \u00E0 mettre en retrait {valeur par d\u00E9faut : 0})]"},
{ "optionTT", " [-TT (G\u00E9n\u00E9rer une trace des mod\u00E8les pendant qu'ils sont appel\u00E9s.)]"},
{ "optionTG", " [-TG (G\u00E9n\u00E9rer une trace de chaque \u00E9v\u00E9nement de g\u00E9n\u00E9ration.)]"},
{ "optionTS", " [-TS (G\u00E9n\u00E9rer une trace de chaque \u00E9v\u00E9nement de s\u00E9lection.)]"},
{ "optionTTC", " [-TTC (G\u00E9n\u00E9rer une trace des enfants de mod\u00E8le pendant qu'ils sont trait\u00E9s.)]"},
{ "optionTCLASS", " [-TCLASS (Classe TraceListener pour les extensions de trace.)]"},
{ "optionVALIDATE", " [-VALIDATE (D\u00E9finir si la validation est effectu\u00E9e. Par d\u00E9faut, la validation est d\u00E9sactiv\u00E9e.)]"},
{ "optionEDUMP", " [-EDUMP {nom de fichier facultatif} (Effectuer le vidage de la pile sur l'erreur.)]"},
{ "optionXML", " [-XML (Utiliser le programme de formatage XML et ajouter un en-t\u00EAte XML.)]"},
{ "optionTEXT", " [-TEXT (Utiliser le formatage de texte simple.)]"},
{ "optionHTML", " [-HTML (Utiliser le formatage HTML.)]"},
{ "optionPARAM", " [-PARAM Expression de nom (D\u00E9finir un param\u00E8tre de feuille de style)]"},
{ "noParsermsg1", "Echec du processus XSL."},
{ "noParsermsg2", "** Analyseur introuvable **"},
{ "noParsermsg3", "V\u00E9rifiez votre variable d'environnement CLASSPATH."},
{ "noParsermsg4", "Si vous ne disposez pas de l'analyseur XML pour Java d'IBM, vous pouvez le t\u00E9l\u00E9charger sur le site"},
{ "noParsermsg5", "AlphaWorks d'IBM : http://www.alphaworks.ibm.com/formula/xml"},
{ "optionURIRESOLVER", " [-URIRESOLVER Nom de classe complet (URIResolver \u00E0 utiliser pour r\u00E9soudre les URI)]"},
{ "optionENTITYRESOLVER", " [-ENTITYRESOLVER Nom de classe complet (EntityResolver \u00E0 utiliser pour r\u00E9soudre les entit\u00E9s)]"},
{ "optionCONTENTHANDLER", " [-CONTENTHANDLER Nom de classe complet (ContentHandler \u00E0 utiliser pour s\u00E9rialiser la sortie)]"},
{ "optionLINENUMBERS", " [-L Utiliser les num\u00E9ros de ligne pour le document source]"},
{ "optionSECUREPROCESSING", " [-SECURE (D\u00E9finir la fonctionnalit\u00E9 de traitement s\u00E9curis\u00E9 sur True)]"},
// Following are the new options added in XSLTErrorResources.properties files after Jdk 1.4 (Xalan 2.2-D11)
{ "optionMEDIA", " [-MEDIA mediaType (Utiliser l'attribut de support pour trouver la feuille de style associ\u00E9e \u00E0 un document)]"},
{ "optionFLAVOR", " [-FLAVOR flavorName (Utiliser explicitement s2s=SAX ou d2d=DOM pour effectuer la transformation)] "}, // Added by sboag/scurcuru; experimental
{ "optionDIAG", " [-DIAG (Afficher la dur\u00E9e totale de la transformation, en millisecondes)]"},
{ "optionINCREMENTAL", " [-INCREMENTAL (Demander la construction DTM incr\u00E9mentielle en d\u00E9finissant http://xml.apache.org/xalan/features/incremental true)]"},
{ "optionNOOPTIMIMIZE", " [-NOOPTIMIMIZE (Ne demander aucune optimisation de la feuille de style en d\u00E9finissant http://xml.apache.org/xalan/features/optimize false)]"},
{ "optionRL", " [-RL recursionlimit (Assertion d'une limite num\u00E9rique sur la profondeur de r\u00E9cursivit\u00E9 de la feuille de style)]"},
{ "optionXO", " [-XO [transletName] (Affecter le nom au translet g\u00E9n\u00E9r\u00E9)]"},
{ "optionXD", " [-XD destinationDirectory (Indiquer un r\u00E9pertoire de destination pour le translet)]"},
{ "optionXJ", " [-XJ jarfile (Packager les classes de translet dans un fichier JAR nomm\u00E9 <jarfile>)]"},
{ "optionXP", " [-XP package (Indique un pr\u00E9fixe de nom de package pour toutes les classes de translet g\u00E9n\u00E9r\u00E9es)]"},
//AddITIONAL STRINGS that need L10n
// Note to translators: The following message describes usage of a particular
// command-line option that is used to enable the "template inlining"
// optimization. The optimization involves making a copy of the code
// generated for a template in another template that refers to it.
{ "optionXN", " [-XN (Activer automatiquement l'image \"inline\" du mod\u00E8le)]" },
{ "optionXX", " [-XX (Activer la sortie de messages de d\u00E9bogage suppl\u00E9mentaires)]"},
{ "optionXT" , " [-XT (Utiliser le translet pour la transformation si possible)]"},
{ "diagTiming"," --------- La transformation de {0} via {1} a pris {2} ms" },
{ "recursionTooDeep","Imbrication de mod\u00E8le trop profonde. Imbrication = {0}, mod\u00E8le {1} {2}" },
{ "nameIs", "le nom est" },
{ "matchPatternIs", "le mod\u00E8le de recherche est" }
};
}
// ================= INFRASTRUCTURE ======================
/** String for use when a bad error code was encountered. */
public static final String BAD_CODE = "BAD_CODE";
/** String for use when formatting of the error string failed. */
public static final String FORMAT_FAILED = "FORMAT_FAILED";
/** General error string. */
public static final String ERROR_STRING = "#error";
/** String to prepend to error messages. */
public static final String ERROR_HEADER = "Error: ";
/** String to prepend to warning messages. */
public static final String WARNING_HEADER = "Warning: ";
/** String to specify the XSLT module. */
public static final String XSL_HEADER = "XSLT ";
/** String to specify the XML parser module. */
public static final String XML_HEADER = "XML ";
/** I don't think this is used any more.
* @deprecated */
public static final String QUERY_HEADER = "PATTERN ";
}
| YouDiSN/OpenJDK-Research | jdk9/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/res/XSLTErrorResources_fr.java | Java | gpl-2.0 | 67,290 |
<?php
/**
* @file
* Definition of Drupal\jssor\Plugin\views\style\Jssor.
*/
namespace Drupal\jssor\Plugin\views\style;
use Drupal\views\Plugin\views\style\StylePluginBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Style plugin to render each item in an ordered or unordered list.
*
* @ingroup views_style_plugins
*
* @ViewsStyle(
* id = "jssor",
* title = @Translation("Jssor Slider"),
* help = @Translation("Display rows or entity in a Jssor Slider."),
* theme = "views_view_jssor",
* display_types = {"normal"}
* )
*/
class Jssor extends StylePluginBase {
/**
* Does the style plugin for itself support to add fields to it's output.
*
* @var bool
*/
protected $usesFields = TRUE;
/**
* Denotes whether the plugin has an additional options form.
*
* @var bool
*/
protected $usesOptions = TRUE;
/**
* Does the style plugin allows to use style plugins.
*
* @var bool
*/
protected $usesRowPlugin = TRUE;
/**
* Does the style plugin support custom css class for the rows.
*
* @var bool
*/
protected $usesRowClass = FALSE;
/**
* Does the style plugin support grouping.
*
* @var bool
*/
protected $usesGrouping = FALSE;
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['slide_duration'] = array('default' => 500);
$options['slide_spacing'] = array('default' => 0);
$options['drag_orientation'] = array('default' => 1);
$options['key_navigation'] = array('default' => TRUE);
$options['autoplay'] = array('default' => TRUE);
$options['autoplayinterval'] = array('default' => 3000);
$options['autoplaysteps'] = array('default' => 1);
$options['pauseonhover'] = array('default' => 1);
$options['arrownavigator'] = array('default' => FALSE);
$options['bulletnavigator'] = array('default' => FALSE);
$options['chancetoshow'] = array('default' => 0);
$options['arrowskin'] = array('default' => 1);
$options['bulletskin'] = array('default' => 1);
$options['autocenter'] = array('default' => 2);
$options['spacingx'] = array('default' => 0);
$options['spacingy'] = array('default' => 0);
$options['orientation'] = array('default' => 1);
$options['steps'] = array('default' => 1);
$options['rows'] = array('default' => 1);
$options['lanes'] = array('default' => 1);
$options['transition'] = array('default' => 'transition0000');
$options['action_mode'] = array('default' => 1);
$options['scale'] = array('default' => TRUE);
return $options;
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['global'] = array(
'#type' => 'fieldset',
'#title' => 'Global',
);
$form['global']['autoplay'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Autoplay'),
'#default_value' => (isset($this->options['global']['autoplay'])) ?
$this->options['global']['autoplay'] : $this->options['autoplay'],
'#description' => t('Enable to auto play.'),
);
$form['global']['arrownavigator'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Arrow navigator'),
'#default_value' => (isset($this->options['global']['arrownavigator'])) ?
$this->options['global']['arrownavigator'] : $this->options['arrownavigator'],
'#description' => t('Enable arrow navigator.'),
);
$form['global']['bulletnavigator'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Bullet navigator'),
'#default_value' => (isset($this->options['global']['bulletnavigator'])) ?
$this->options['global']['bulletnavigator'] : $this->options['bulletnavigator'],
'#description' => t('Enable bullet navigator.'),
);
// Slider.
$form['general'] = array(
'#type' => 'fieldset',
'#title' => $this->t('General'),
);
$form['general']['slide_duration'] = array(
'#type' => 'number',
'#title' => $this->t('Slide duration'),
'#attributes' => array(
'min' => 0,
'step' => 1,
'value' => (isset($this->options['general']['slide_duration'])) ?
$this->options['general']['slide_duration'] : $this->options['slide_duration'],
),
'#description' => t('Specifies default duration (swipe) for slide in milliseconds.'),
);
/*$form['general']['slide_spacing'] = array(
'#type' => 'number',
'#title' => $this->t('Slide spacing'),
'#attributes' => array(
'min' => 0,
'step' => 1,
'value' => (isset($this->options['general']['slide_spacing'])) ?
$this->options['general']['slide_spacing'] : $this->options['slide_spacing'],
),
'#description' => t('Space between each slide in pixels.'),
);*/
$form['general']['drag_orientation'] = array(
'#type' => 'select',
'#title' => $this->t('Drag orientation'),
'#description' => t('Orientation to drag slide.'),
'#default_value' => (isset($this->options['general']['drag_orientation'])) ?
$this->options['general']['drag_orientation'] : $this->options['drag_orientation'],
'#options' => array(
0 => $this->t('No drag'),
1 => $this->t('Horizontal'),
2 => $this->t('Vertical'),
3 => $this->t('Horizontal and vertical'),
),
);
$form['general']['key_navigation'] = array(
'#type' => 'checkbox',
'#title' => t('Key navigation'),
'#default_value' => (isset($this->options['general']['key_navigation'])) ?
$this->options['general']['key_navigation'] : $this->options['key_navigation'],
'#description' => t('Allows keyboard (arrow key) navigation or not.'),
);
// Autoplay.
$form['autoplay'] = array(
'#type' => 'fieldset',
'#title' => $this->t('Autoplay'),
'#states' => array(
'visible' => array(
':input[name="style_options[global][autoplay]"]' => array('checked' => TRUE),
),
),
);
$form['autoplay']['autoplayinterval'] = array(
'#type' => 'number',
'#title' => $this->t('Autoplay interval'),
'#attributes' => array(
'min' => 0,
'step' => 1,
'value' => (isset($this->options['autoplay']['autoplayinterval'])) ?
$this->options['autoplay']['autoplayinterval'] : $this->options['autoplayinterval'],
),
'#description' => t('Interval (in milliseconds) to go for next slide since the previous stopped.'),
);
$form['autoplay']['autoplaysteps'] = array(
'#type' => 'number',
'#title' => $this->t('Autoplay step'),
'#attributes' => array(
'min' => 1,
'step' => 1,
'value' => (isset($this->options['autoplay']['autoplaysteps'])) ?
$this->options['autoplay']['autoplaysteps'] : $this->options['autoplaysteps'],
),
'#description' => t('Steps to go for each navigation request.'),
);
$form['autoplay']['pauseonhover'] = array(
'#type' => 'select',
'#title' => $this->t('Pause on hover'),
'#description' => t('Whether to pause when mouse over if a slider is auto playing.'),
'#default_value' => (isset($this->options['autoplay']['pauseonhover'])) ?
$this->options['autoplay']['pauseonhover'] : $this->options['pauseonhover'],
'#options' => array(
0 => $this->t('No pause'),
1 => $this->t('Pause for desktop'),
2 => $this->t('Pause for touch device'),
3 => $this->t('Pause for desktop and touch device'),
4 => $this->t('Freeze for desktop'),
8 => $this->t('Freeze for touch device'),
12 => $this->t('Freeze for desktop and touch device'),
),
);
$form['autoplay']['transition'] = [
'#type' => 'select',
'#title' => $this->t('Transition'),
'#description' => t('Whether to pause when mouse over if a slider is auto playing.'),
'#default_value' => (isset($this->options['autoplay']['transition'])) ?
$this->options['autoplay']['transition'] : $this->options['transition'],
'#options' => [
'Twins Effects' => [
'transition0000' => $this->t('Basic'),
'transition0001' => $this->t('Fade Twins'),
'transition0002' => $this->t('Rotate Overlap'),
'transition0003' => $this->t('Switch'),
'transition0004' => $this->t('Rotate Relay'),
'transition0005' => $this->t('Doors'),
'transition0006' => $this->t('Rotate in+ out-'),
'transition0007' => $this->t('Fly Twins'),
'transition0008' => $this->t('Rotate in- out+'),
'transition0009' => $this->t('Rotate Axis up overlap'),
'transition0010' => $this->t('Chess Replace TB'),
'transition0011' => $this->t('Chess Replace LR'),
'transition0012' => $this->t('Shift TB'),
'transition0013' => $this->t('Shift LR'),
'transition0014' => $this->t('Return TB'),
'transition0015' => $this->t('Return LR'),
'transition0016' => $this->t('Rotate Axis down'),
'transition0017' => $this->t('Extrude Replace'),
],
'Fade Effects' => [
'transition0101' => $this->t('Fade'),
'transition0102' => $this->t('Fade in L'),
'transition0103' => $this->t('Fade in R'),
'transition0104' => $this->t('Fade in T'),
'transition0105' => $this->t('Fade in B'),
'transition0106' => $this->t('Fade in LR'),
'transition0107' => $this->t('Fade in LR Chess'),
'transition0108' => $this->t('Fade in TB'),
'transition0109' => $this->t('Fade in TB Chess'),
'transition0110' => $this->t('Fade in Corners'),
'transition0111' => $this->t('Fade out L'),
'transition0112' => $this->t('Fade out R'),
'transition0113' => $this->t('Fade out T'),
'transition0114' => $this->t('Fade out B'),
'transition0115' => $this->t('Fade out LR'),
'transition0116' => $this->t('Fade out LR Chess'),
'transition0117' => $this->t('Fade out TB'),
'transition0118' => $this->t('Fade out TB Chess'),
'transition0119' => $this->t('Fade out Corners'),
'transition0120' => $this->t('Fade Fly in L'),
'transition0121' => $this->t('Fade Fly in R'),
'transition0122' => $this->t('Fade Fly in T'),
'transition0123' => $this->t('Fade Fly in B'),
'transition0124' => $this->t('Fade Fly in LR'),
'transition0125' => $this->t('Fade Fly in LR Chess'),
'transition0126' => $this->t('Fade Fly in TB'),
'transition0127' => $this->t('Fade Fly in TB Chess'),
'transition0128' => $this->t('Fade Fly in Corners'),
'transition0129' => $this->t('Fade Fly out L'),
'transition0130' => $this->t('Fade Fly out R'),
'transition0131' => $this->t('Fade Fly out T'),
'transition0132' => $this->t('Fade Fly out B'),
'transition0133' => $this->t('Fade Fly out LR'),
'transition0134' => $this->t('Fade Fly out LR Chess'),
'transition0135' => $this->t('Fade Fly out TB'),
'transition0136' => $this->t('Fade Fly out TB Chess'),
'transition0137' => $this->t('Fade Fly out Corners'),
'transition0138' => $this->t('Fade Clip in H'),
'transition0139' => $this->t('Fade Clip in V'),
'transition0140' => $this->t('Fade Clip out H'),
'transition0141' => $this->t('Fade Clip out V'),
'transition0142' => $this->t('Fade Stairs'),
'transition0143' => $this->t('Fade Random'),
'transition0144' => $this->t('Fade Swirl'),
'transition0145' => $this->t('Fade ZigZag'),
],
'Swing Outside Effects' => [
'transition0201' => $this->t('Swing Outside in Stairs'),
'transition0202' => $this->t('Swing Outside in ZigZag'),
'transition0203' => $this->t('Swing Outside in Swirl'),
'transition0204' => $this->t('Swing Outside in Random'),
'transition0205' => $this->t('Swing Outside in Random Chess'),
'transition0206' => $this->t('Swing Outside in Square'),
'transition0207' => $this->t('Swing Outside out Stairs'),
'transition0208' => $this->t('Swing Outside out ZigZag'),
'transition0209' => $this->t('Swing Outside out Swirl'),
'transition0210' => $this->t('Swing Outside out Random'),
'transition0211' => $this->t('Swing Outside out Random Chess'),
'transition0212' => $this->t('Swing Outside out Square'),
],
'Swing Inside Effects' => [
'transition0301' => $this->t('Swing Inside in Stairs'),
'transition0302' => $this->t('Swing Inside in ZigZag'),
'transition0303' => $this->t('Swing Inside in Swirl'),
'transition0304' => $this->t('Swing Inside in Random'),
'transition0305' => $this->t('Swing Inside in Random Chess'),
'transition0306' => $this->t('Swing Inside in Square'),
'transition0307' => $this->t('Swing Inside out ZigZag'),
'transition0308' => $this->t('Swing Inside out Swirl'),
],
'Dodge Dance Outside Effects' => [
'transition0401' => $this->t('Dodge Dance Outside in Stairs'),
'transition0402' => $this->t('Dodge Dance Outside in Swirl'),
'transition0403' => $this->t('Dodge Dance Outside in ZigZag'),
'transition0404' => $this->t('Dodge Dance Outside in Random'),
'transition0405' => $this->t('Dodge Dance Outside in Random Chess'),
'transition0406' => $this->t('Dodge Dance Outside in Square'),
'transition0407' => $this->t('Dodge Dance Outside out Stairs'),
'transition0408' => $this->t('Dodge Dance Outside out Swirl'),
'transition0409' => $this->t('Dodge Dance Outside out ZigZag'),
'transition0410' => $this->t('Dodge Dance Outside out Random'),
'transition0411' => $this->t('Dodge Dance Outside out Random Chess'),
'transition0412' => $this->t('Dodge Dance Outside out Square'),
],
'Dodge Dance Inside Effects' => [
'transition0501' => $this->t('Dodge Dance Inside in Stairs'),
'transition0502' => $this->t('Dodge Dance Inside in Swirl'),
'transition0503' => $this->t('Dodge Dance Inside in ZigZag'),
'transition0504' => $this->t('Dodge Dance Inside in Random'),
'transition0505' => $this->t('Dodge Dance Inside in Random Chess'),
'transition0506' => $this->t('Dodge Dance Inside in Square'),
'transition0507' => $this->t('Dodge Dance Inside out Stairs'),
'transition0508' => $this->t('Dodge Dance Inside out Swirl'),
'transition0509' => $this->t('Dodge Dance Inside out ZigZag'),
'transition0510' => $this->t('Dodge Dance Inside out Random'),
'transition0511' => $this->t('Dodge Dance Inside out Random Chess'),
'transition0512' => $this->t('Dodge Dance Inside out Square'),
],
'Dodge Pet Outside Effects' => [
'transition0601' => $this->t('Dodge Pet Outside in Stairs'),
'transition0602' => $this->t('Dodge Pet Outside in Swirl'),
'transition0603' => $this->t('Dodge Pet Outside in ZigZag'),
'transition0604' => $this->t('Dodge Pet Outside in Random'),
'transition0605' => $this->t('Dodge Pet Outside in Random Chess'),
'transition0606' => $this->t('Dodge Pet Outside in Square'),
'transition0607' => $this->t('Dodge Pet Outside out Stairs'),
'transition0608' => $this->t('Dodge Pet Outside out Swirl'),
'transition0609' => $this->t('Dodge Pet Outside out ZigZag'),
'transition0610' => $this->t('Dodge Pet Outside out Random'),
'transition0611' => $this->t('Dodge Pet Outside out Random Chess'),
'transition0612' => $this->t('Dodge Pet Outside out Square'),
],
'Dodge Pet Inside Effects' => [
'transition0701' => $this->t('Dodge Pet Inside in Stairs'),
'transition0702' => $this->t('Dodge Pet Inside in Swirl'),
'transition0703' => $this->t('Dodge Pet Inside in ZigZag'),
'transition0704' => $this->t('Dodge Pet Inside in Random'),
'transition0705' => $this->t('Dodge Pet Inside in Random Chess'),
'transition0706' => $this->t('Dodge Pet Inside in Square'),
'transition0707' => $this->t('Dodge Pet Inside out Stairs'),
'transition0708' => $this->t('Dodge Pet Inside out Swirl'),
'transition0709' => $this->t('Dodge Pet Inside out ZigZag'),
'transition0710' => $this->t('Dodge Pet Inside out Random'),
'transition0711' => $this->t('Dodge Pet Inside out Random Chess'),
'transition0712' => $this->t('Dodge Pet Inside out Square'),
],
'Dodge Outside Effects' => [
'transition0801' => $this->t('Dodge Outside out Stairs'),
'transition0802' => $this->t('Dodge Outside out Swirl'),
'transition0803' => $this->t('Dodge Outside out ZigZag'),
'transition0804' => $this->t('Dodge Outside out Random'),
'transition0805' => $this->t('Dodge Outside out Random Chess'),
'transition0806' => $this->t('Dodge Outside out Square'),
'transition0807' => $this->t('Dodge Outside in Stairs'),
'transition0808' => $this->t('Dodge Outside in Swirl'),
'transition0809' => $this->t('Dodge Outside in ZigZag'),
'transition0810' => $this->t('Dodge Outside in Random'),
'transition0811' => $this->t('Dodge Outside in Random Chess'),
'transition0812' => $this->t('Dodge Outside in Square'),
],
$this->t('Dodge Inside Effects') => [
'transition0901' => $this->t('Dodge Inside out Stairs'),
'transition0902' => $this->t('Dodge Inside out Swirl'),
'transition0903' => $this->t('Dodge Inside out ZigZag'),
'transition0904' => $this->t('Dodge Inside out Random'),
'transition0905' => $this->t('Dodge Inside out Random Chess'),
'transition0906' => $this->t('Dodge Inside out Square'),
'transition0907' => $this->t('Dodge Inside in Stairs'),
'transition0908' => $this->t('Dodge Inside in Swirl'),
'transition0909' => $this->t('Dodge Inside in ZigZag'),
'transition0910' => $this->t('Dodge Inside in Random'),
'transition0911' => $this->t('Dodge Inside in Random Chess'),
'transition0912' => $this->t('Dodge Inside in Square'),
'transition0913' => $this->t('Dodge Inside in TL'),
'transition0914' => $this->t('Dodge Inside in TR'),
'transition0915' => $this->t('Dodge Inside in BL'),
'transition0916' => $this->t('Dodge Inside in BR'),
'transition0917' => $this->t('Dodge Inside out TL'),
'transition0918' => $this->t('Dodge Inside out TR'),
'transition0919' => $this->t('Dodge Inside out BL'),
'transition0920' => $this->t('Dodge Inside out BR'),
],
'Flutter Outside Effects' => [
'transition1001' => $this->t('Flutter Outside in'),
'transition1002' => $this->t('Flutter Outside in Wind'),
'transition1003' => $this->t('Flutter Outside in Swirl'),
'transition1004' => $this->t('Flutter Outside in Column'),
'transition1005' => $this->t('Flutter Outside out'),
'transition1006' => $this->t('Flutter Outside out Wind'),
'transition1007' => $this->t('Flutter Outside out Swirl'),
'transition1008' => $this->t('Flutter Outside out Column'),
],
'Flutter Inside Effects' => [
'transition1101' => $this->t('Flutter Inside in'),
'transition1102' => $this->t('Flutter Inside in Wind'),
'transition1103' => $this->t('Flutter Inside in Swirl'),
'transition1104' => $this->t('Flutter Inside in Column'),
'transition1105' => $this->t('Flutter Inside out'),
'transition1106' => $this->t('Flutter Inside out Wind'),
'transition1107' => $this->t('Flutter Inside out Swirl'),
'transition1108' => $this->t('Flutter Inside out Column'),
],
'Rotate Effects' => [
'transition1201' => $this->t('Rotate VDouble+ in'),
'transition1202' => $this->t('Rotate HDouble+ in'),
'transition1203' => $this->t('Rotate VDouble- in'),
'transition1204' => $this->t('Rotate HDouble- in'),
'transition1205' => $this->t('Rotate VDouble+ out'),
'transition1206' => $this->t('Rotate HDouble+ out'),
'transition1207' => $this->t('Rotate VDouble- out'),
'transition1208' => $this->t('Rotate HDouble- out'),
'transition1209' => $this->t('Rotate VFork+ in'),
'transition1210' => $this->t('Rotate HFork+ in'),
'transition1211' => $this->t('Rotate VFork+ out'),
'transition1212' => $this->t('Rotate HFork+ out'),
'transition1213' => $this->t('Rotate Zoom+ in'),
'transition1214' => $this->t('Rotate Zoom+ in L'),
'transition1215' => $this->t('Rotate Zoom+ in R'),
'transition1216' => $this->t('Rotate Zoom+ in T'),
'transition1217' => $this->t('Rotate Zoom+ in B'),
'transition1218' => $this->t('Rotate Zoom+ in TL'),
'transition1219' => $this->t('Rotate Zoom+ in TR'),
'transition1220' => $this->t('Rotate Zoom+ in BL'),
'transition1221' => $this->t('Rotate Zoom+ in BR'),
'transition1222' => $this->t('Rotate Zoom+ out'),
'transition1223' => $this->t('Rotate Zoom+ out L'),
'transition1224' => $this->t('Rotate Zoom+ out R'),
'transition1225' => $this->t('Rotate Zoom+ out T'),
'transition1226' => $this->t('Rotate Zoom+ out B'),
'transition1227' => $this->t('Rotate Zoom+ out TL'),
'transition1228' => $this->t('Rotate Zoom+ out TR'),
'transition1229' => $this->t('Rotate Zoom+ out BL'),
'transition1230' => $this->t('Rotate Zoom+ out BR'),
'transition1231' => $this->t('Rotate Zoom+ in'),
'transition1232' => $this->t('Rotate Zoom+ in L'),
'transition1233' => $this->t('Rotate Zoom+ in R'),
'transition1234' => $this->t('Rotate Zoom+ in T'),
'transition1235' => $this->t('Rotate Zoom+ in B'),
'transition1236' => $this->t('Rotate Zoom+ in TL'),
'transition1237' => $this->t('Rotate Zoom+ in TR'),
'transition1238' => $this->t('Rotate Zoom+ in BL'),
'transition1239' => $this->t('Rotate Zoom+ in BR'),
'transition1240' => $this->t('Rotate Zoom- out'),
'transition1241' => $this->t('Rotate Zoom- out L'),
'transition1242' => $this->t('Rotate Zoom- out R'),
'transition1243' => $this->t('Rotate Zoom- out T'),
'transition1244' => $this->t('Rotate Zoom- out B'),
'transition1245' => $this->t('Rotate Zoom- out TL'),
'transition1246' => $this->t('Rotate Zoom- out TR'),
'transition1247' => $this->t('Rotate Zoom- out BL'),
'transition1248' => $this->t('Rotate Zoom- out BR'),
],
'Zoom Effects' => [
'transition1301' => $this->t('Zoom VDouble+ in'),
'transition1302' => $this->t('Zoom HDouble+ in'),
'transition1303' => $this->t('Zoom VDouble- in'),
'transition1304' => $this->t('Zoom HDouble- in'),
'transition1305' => $this->t('Zoom VDouble+ out'),
'transition1306' => $this->t('Zoom HDouble+ out'),
'transition1307' => $this->t('Zoom VDouble- out'),
'transition1308' => $this->t('Zoom HDouble- out'),
'transition1309' => $this->t('Zoom+ in'),
'transition1310' => $this->t('Zoom+ in L'),
'transition1311' => $this->t('Zoom+ in R'),
'transition1312' => $this->t('Zoom+ in T'),
'transition1313' => $this->t('Zoom+ in B'),
'transition1314' => $this->t('Zoom+ in TL'),
'transition1315' => $this->t('Zoom+ in TR'),
'transition1316' => $this->t('Zoom+ in BL'),
'transition1317' => $this->t('Zoom+ in BR'),
'transition1318' => $this->t('Zoom+ out'),
'transition1319' => $this->t('Zoom+ out L'),
'transition1320' => $this->t('Zoom+ out R'),
'transition1321' => $this->t('Zoom+ out T'),
'transition1322' => $this->t('Zoom+ out B'),
'transition1323' => $this->t('Zoom+ out TL'),
'transition1324' => $this->t('Zoom+ out TR'),
'transition1325' => $this->t('Zoom+ out BL'),
'transition1326' => $this->t('Zoom+ out BR'),
'transition1327' => $this->t('Zoom- in'),
'transition1328' => $this->t('Zoom- in L'),
'transition1329' => $this->t('Zoom- in R'),
'transition1330' => $this->t('Zoom- in T'),
'transition1331' => $this->t('Zoom- in B'),
'transition1332' => $this->t('Zoom- in TL'),
'transition1333' => $this->t('Zoom- in TR'),
'transition1334' => $this->t('Zoom- in BL'),
'transition1335' => $this->t('Zoom- in BR'),
'transition1336' => $this->t('Zoom- out'),
'transition1337' => $this->t('Zoom- out L'),
'transition1338' => $this->t('Zoom- out R'),
'transition1339' => $this->t('Zoom- out T'),
'transition1340' => $this->t('Zoom- out B'),
'transition1341' => $this->t('Zoom- out TL'),
'transition1342' => $this->t('Zoom- out TR'),
'transition1343' => $this->t('Zoom- out BL'),
'transition1344' => $this->t('Zoom- out BR'),
],
'Collapse Effects' => [
'transition1401' => $this->t('Collapse Stairs'),
'transition1402' => $this->t('Collapse Swirl'),
'transition1403' => $this->t('Collapse Square'),
'transition1404' => $this->t('Collapse Rectangle Cross'),
'transition1405' => $this->t('Collapse Rectangle'),
'transition1406' => $this->t('Collapse Cross'),
'transition1407' => $this->t('Collapse Circle'),
'transition1408' => $this->t('Collapse ZigZag'),
'transition1409' => $this->t('Collapse Random'),
],
'Compound Effects' => [
'transition1501' => $this->t('Clip & Chess in'),
'transition1502' => $this->t('Clip & Chess out'),
'transition1503' => $this->t('Clip & Oblique Chess in'),
'transition1504' => $this->t('Clip & Oblique Chess out'),
'transition1505' => $this->t('Clip & Wave in'),
'transition1506' => $this->t('Clip & Wave out'),
'transition1507' => $this->t('Clip & Jump in'),
'transition1508' => $this->t('Clip & Jump out'),
],
'Expand Effects' => [
'transition1601' => $this->t('Expand Stairs'),
'transition1602' => $this->t('Expand Straight'),
'transition1603' => $this->t('Expand Swirl'),
'transition1604' => $this->t('Expand Square'),
'transition1605' => $this->t('Expand Rectangle Cross'),
'transition1606' => $this->t('Expand Rectangle'),
'transition1607' => $this->t('Expand Cross'),
'transition1608' => $this->t('Expand ZigZag'),
'transition1609' => $this->t('Expand Random'),
],
'Stripe Effects' => [
'transition1701' => $this->t('Dominoes Stripe'),
'transition1702' => $this->t('Extrude out Stripe'),
'transition1703' => $this->t('Extrude in Stripe'),
'transition1704' => $this->t('Horizontal Blind Stripe'),
'transition1705' => $this->t('Vertical Blind Stripe'),
'transition1706' => $this->t('Horizontal Stripe'),
'transition1707' => $this->t('Vertical Stripe'),
'transition1708' => $this->t('Horizontal Moving Stripe'),
'transition1709' => $this->t('Vertical Moving Stripe'),
'transition1710' => $this->t('Horizontal Fade Stripe'),
'transition1711' => $this->t('Vertical Fade Stripe'),
'transition1712' => $this->t('Horizontal Fly Stripe'),
'transition1713' => $this->t('Vertical Fly Stripe'),
'transition1714' => $this->t('Horizontal Chess Stripe'),
'transition1715' => $this->t('Vertical Chess Stripe'),
'transition1716' => $this->t('Horizontal Random Fade Stripe'),
'transition1717' => $this->t('Vertical Random Fade Stripe'),
'transition1718' => $this->t('Horizontal Bounce Stripe'),
'transition1719' => $this->t('Vertical Bounce Stripe'),
],
'Wave out Effects' => [
'transition1801' => $this->t('Wave out'),
'transition1802' => $this->t('Wave out Eagle'),
'transition1803' => $this->t('Wave out Swirl'),
'transition1804' => $this->t('Wave out ZigZag'),
'transition1805' => $this->t('Wave out Square'),
'transition1806' => $this->t('Wave out Rectangle'),
'transition1807' => $this->t('Wave out Circle'),
'transition1808' => $this->t('Wave out Cross'),
'transition1809' => $this->t('Wave out Rectangle Cross'),
],
'Wave in Effects' => [
'transition1901' => $this->t('Wave in'),
'transition1902' => $this->t('Wave in Eagle'),
'transition1903' => $this->t('Wave in Swirl'),
'transition1904' => $this->t('Wave in ZigZag'),
'transition1905' => $this->t('Wave in Square'),
'transition1906' => $this->t('Wave in Rectangle'),
'transition1907' => $this->t('Wave in Circle'),
'transition1908' => $this->t('Wave in Cross'),
'transition1909' => $this->t('Wave in Rectangle Cross'),
],
'Jump out Effects' => [
'transition2001' => $this->t('Jump out Straight'),
'transition2002' => $this->t('Jump out Swirl'),
'transition2003' => $this->t('Jump out ZigZag'),
'transition2004' => $this->t('Jump out Square'),
'transition2005' => $this->t('Jump out Square with Chess'),
'transition2006' => $this->t('Jump out Rectangle'),
'transition2007' => $this->t('Jump out Circle'),
'transition2008' => $this->t('Jump out Rectangle Cross'),
],
'Jump in Effects' => [
'transition2101' => $this->t('Jump in Straight'),
'transition2101' => $this->t('Jump in Straight'),
'transition2102' => $this->t('Jump in Swirl'),
'transition2103' => $this->t('Jump in ZigZag'),
'transition2104' => $this->t('Jump in Square'),
'transition2105' => $this->t('Jump in Square with Chess'),
'transition2106' => $this->t('Jump in Rectangle'),
'transition2107' => $this->t('Jump in Circle'),
'transition2108' => $this->t('Jump in Rectangle Cross'),
],
'Parabola Effects' => [
'transition2201' => $this->t('Parabola Swirl in'),
'transition2202' => $this->t('Parabola Swirl out'),
'transition2203' => $this->t('Parabola ZigZag in'),
'transition2204' => $this->t('Parabola ZigZag out'),
'transition2205' => $this->t('Parabola Stairs in'),
'transition2206' => $this->t('Parabola Stairs out'),
],
'Float Effects' => [
'transition2301' => $this->t('Float Right Random'),
'transition2302' => $this->t('Float up Random'),
'transition2303' => $this->t('Float up Random with Chess'),
'transition2304' => $this->t('Float Right ZigZag'),
'transition2305' => $this->t('Float up ZigZag'),
'transition2306' => $this->t('Float up ZigZag with Chess'),
'transition2307' => $this->t('Float Right Swirl'),
'transition2308' => $this->t('Float up Swirl'),
'transition2309' => $this->t('Float up Swirl with Chess'),
],
'Fly Effects' => [
'transition2401' => $this->t('Fly Right Random'),
'transition2402' => $this->t('Fly up Random'),
'transition2403' => $this->t('Fly up Random with Chess'),
'transition2404' => $this->t('Fly Right ZigZag'),
'transition2405' => $this->t('Fly up ZigZag'),
'transition2406' => $this->t('Fly up ZigZag with Chess'),
'transition2407' => $this->t('Fly Right Swirl'),
'transition2408' => $this->t('Fly up Swirl'),
'transition2409' => $this->t('Fly up Swirl with Chess'),
],
'Stone Effects' => [
'transition2501' => $this->t('Slide Down'),
'transition2502' => $this->t('Slide Right'),
'transition2503' => $this->t('Bounce Down'),
'transition2504' => $this->t('Bounce Right'),
],
],
];
// Arrow navigator.
$form['arrownavigator'] = array(
'#type' => 'fieldset',
'#title' => $this->t('Arrow navigator'),
'#states' => array(
'visible' => array(
':input[name="style_options[global][arrownavigator]"]' => array('checked' => TRUE),
),
),
);
$arrowskin = [];
for ($i = 1 ; $i < 22; $i++) {
$i = ($i < 10) ? '0' . $i : $i;
$arrowskin[$i] = $this->t('Arrow ') . $i;
}
$form['arrownavigator']['arrowskin'] = array(
'#type' => 'select',
'#title' => $this->t('Skin'),
'#default_value' => (isset($this->options['arrownavigator']['arrowskin'])) ?
$this->options['arrownavigator']['arrowskin'] : $this->options['arrowskin'],
'#options' => $arrowskin,
);
$form['arrownavigator']['autocenter'] = array(
'#type' => 'select',
'#title' => $this->t('Auto center'),
'#description' => $this->t('Auto center arrows in parent container.'),
'#default_value' => (isset($this->options['arrownavigator']['autocenter'])) ?
$this->options['arrownavigator']['autocenter'] : $this->options['autocenter'],
'#options' => array(
0 => $this->t('No'),
1 => $this->t('Horizontal'),
2 => $this->t('Vertical'),
3 => $this->t('Both'),
),
);
$form['arrownavigator']['chancetoshow'] = array(
'#type' => 'select',
'#title' => $this->t('Chance to show'),
'#description' => $this->t('How to react on the bullet navigator.'),
'#default_value' => (isset($this->options['arrownavigator']['chancetoshow'])) ?
$this->options['arrownavigator']['chancetoshow'] : $this->options['chancetoshow'],
'#options' => array(
0 => $this->t('Never'),
1 => $this->t('Mouse Over'),
2 => $this->t('Always'),
),
);
$form['arrownavigator']['steps'] = array(
'#type' => 'number',
'#title' => $this->t('Steps'),
'#description' => t('Steps to go for each navigation request.'),
'#attributes' => array(
'min' => 1,
'step' => 1,
'value' => (isset($this->options['arrownavigator']['steps'])) ?
$this->options['arrownavigator']['steps'] : $this->options['steps'],
),
);
$form['arrownavigator']['scale'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Scales bullet navigator'),
'#description' => t('Scales bullet navigator or not while slider scale.'),
'#default_value' => (isset($this->options['arrownavigator']['scale'])) ?
$this->options['arrownavigator']['scale'] : $this->options['scale'],
);
// Bullet navigators.
$form['bulletnavigator'] = array(
'#type' => 'fieldset',
'#title' => $this->t('Bullet navigator'),
'#states' => array(
'visible' => array(
':input[name="style_options[global][bulletnavigator]"]' => array('checked' => TRUE),
),
),
);
$bulletskin = [];
for ($i = 1 ; $i < 22; $i++) {
$i = ($i < 10) ? '0' . $i : $i;
$bulletskin[$i] = $this->t('Bullet ') . $i;
}
$form['bulletnavigator']['bulletskin'] = array(
'#type' => 'select',
'#title' => $this->t('Skin'),
'#default_value' => (isset($this->options['bulletnavigator']['bulletskin'])) ?
$this->options['bulletnavigator']['bulletskin'] : $this->options['bulletskin'],
'#options' => $bulletskin,
);
$form['bulletnavigator']['chancetoshow'] = array(
'#type' => 'select',
'#title' => $this->t('Chance to show'),
'#description' => $this->t('When to display the bullet navigator.'),
'#default_value' => (isset($this->options['bulletnavigator']['chancetoshow'])) ?
$this->options['bulletnavigator']['chancetoshow'] : $this->options['chancetoshow'],
'#options' => array(
0 => $this->t('Never'),
1 => $this->t('Mouse Over'),
2 => $this->t('Always'),
),
);
$form['bulletnavigator']['action_mode'] = array(
'#type' => 'select',
'#title' => $this->t('Action mode'),
'#description' => $this->t('How to react on the bullet navigator.'),
'#default_value' => (isset($this->options['bulletnavigator']['action_mode'])) ?
$this->options['bulletnavigator']['action_mode'] : $this->options['action_mode'],
'#options' => array(
0 => $this->t('None'),
1 => $this->t('Act by click'),
2 => $this->t('Act by mouse hover'),
3 => $this->t('Act by click or mouse hover'),
),
);
$form['bulletnavigator']['autocenter'] = array(
'#type' => 'select',
'#title' => $this->t('Auto center'),
'#description' => $this->t('Auto center arrows in parent container.'),
'#default_value' => (isset($this->options['bulletnavigator']['autocenter'])) ?
$this->options['bulletnavigator']['autocenter'] : $this->options['autocenter'],
'#options' => array(
0 => $this->t('No'),
1 => $this->t('Horizontal'),
2 => $this->t('Vertical'),
3 => $this->t('Both'),
),
);
$form['bulletnavigator']['rows'] = array(
'#type' => 'number',
'#title' => $this->t('Rows'),
'#description' => t('Rows to arrange bullets.'),
'#attributes' => array(
'min' => 1,
'step' => 1,
'value' => (isset($this->options['bulletnavigator']['rows'])) ?
$this->options['bulletnavigator']['rows'] : $this->options['rows'],
),
);
$form['bulletnavigator']['steps'] = array(
'#type' => 'number',
'#title' => $this->t('Steps'),
'#description' => t('Steps to go for each navigation request.'),
'#attributes' => array(
'min' => 1,
'step' => 1,
'value' => (isset($this->options['bulletnavigator']['steps'])) ?
$this->options['bulletnavigator']['steps'] : $this->options['steps'],
),
);
$form['bulletnavigator']['spacingx'] = array(
'#type' => 'number',
'#title' => $this->t('Horizontal space'),
'#description' => t('Horizontal space between each item in pixel.'),
'#attributes' => array(
'min' => 0,
'step' => 1,
'value' => (isset($this->options['bulletnavigator']['spacingx'])) ?
$this->options['bulletnavigator']['spacingx'] : $this->options['spacingx'],
),
);
$form['bulletnavigator']['spacingy'] = array(
'#type' => 'number',
'#title' => $this->t('Vertical space'),
'#description' => t('Vertical space between each item in pixel.'),
'#attributes' => array(
'min' => 0,
'step' => 1,
'value' => (isset($this->options['bulletnavigator']['spacingy'])) ?
$this->options['bulletnavigator']['spacingy'] : $this->options['spacingy'],
),
);
$form['bulletnavigator']['orientation'] = array(
'#type' => 'select',
'#title' => $this->t('Orientation'),
'#description' => t('The orientation of the navigator.'),
'#default_value' => (isset($this->options['bulletnavigator']['orientation'])) ?
$this->options['bulletnavigator']['orientation'] : $this->options['orientation'],
'#options' => array(
1 => $this->t('Horizontal'),
2 => $this->t('Vertical'),
),
);
$form['bulletnavigator']['scale'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Scales bullet navigator'),
'#description' => t('Scales bullet navigator or not while slider scale.'),
'#default_value' => (isset($this->options['bulletnavigator']['scale'])) ?
$this->options['bulletnavigator']['scale'] : $this->options['scale'],
);
}
}
| umandalroald/dcmanila2016 | sites/default/files/tmp/update-extraction-acad5454/jssor/src/Plugin/views/style/Jssor.php | PHP | gpl-2.0 | 40,764 |
<?php
/**
* @package Joomla.Platform
* @subpackage Table
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Viewlevels table class.
*
* @package Joomla.Platform
* @subpackage Table
* @since 11.1
*/
class JTableViewlevel extends JTable
{
/**
* Constructor
*
* @param JDatabaseDriver $db Database driver object.
*
* @since 11.1
*/
public function __construct(JDatabaseDriver $db)
{
parent::__construct('#__viewlevels', 'id', $db);
}
/**
* Method to bind the data.
*
* @param array $array The data to bind.
* @param mixed $ignore An array or space separated list of fields to ignore.
*
* @return boolean True on success, false on failure.
*
* @since 11.1
*/
public function bind($array, $ignore = '')
{
// Bind the rules as appropriate.
if (isset($array['rules']))
{
if (is_array($array['rules']))
{
$array['rules'] = json_encode($array['rules']);
}
}
return parent::bind($array, $ignore);
}
/**
* Method to check the current record to save
*
* @return boolean True on success
*
* @since 11.1
*/
public function check()
{
// Validate the title.
if ((trim($this->title)) == '')
{
$this->setError(JText::_('JLIB_DATABASE_ERROR_VIEWLEVEL'));
return false;
}
return true;
}
}
| songxiafeng/joomla-platform | libraries/joomla/table/viewlevel.php | PHP | gpl-2.0 | 1,478 |
/***************************************************************************
qgsprocessingtininputlayerswidget.cpp
---------------------
Date : August 2020
Copyright : (C) 2020 by Vincent Cloarec
Email : vcloarec at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsprocessingtininputlayerswidget.h"
#include "qgsproject.h"
#include "qgsprocessingcontext.h"
/// @cond PRIVATE
QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersWidget( QgsProject *project ):
mInputLayersModel( project )
{
setupUi( this );
mComboLayers->setFilters( QgsMapLayerProxyModel::VectorLayer );
connect( mComboLayers, &QgsMapLayerComboBox::layerChanged, this, &QgsProcessingTinInputLayersWidget::onLayerChanged );
connect( mButtonAdd, &QToolButton::clicked, this, &QgsProcessingTinInputLayersWidget::onCurrentLayerAdded );
connect( mButtonRemove, &QToolButton::clicked, this, &QgsProcessingTinInputLayersWidget::onLayersRemove );
connect( &mInputLayersModel, &QgsProcessingTinInputLayersModel::dataChanged, this, &QgsProcessingTinInputLayersWidget::changed );
onLayerChanged( mComboLayers->currentLayer() );
mTableView->setModel( &mInputLayersModel );
mTableView->setItemDelegateForColumn( 1, new Delegate( mTableView ) );
}
QVariant QgsProcessingTinInputLayersWidget::value() const
{
const QList<QgsProcessingParameterTinInputLayers::InputLayer> &layers = mInputLayersModel.layers();
QVariantList list;
for ( const QgsProcessingParameterTinInputLayers::InputLayer &layer : layers )
{
QVariantMap layerMap;
layerMap[QStringLiteral( "source" )] = layer.source;
layerMap[QStringLiteral( "type" )] = layer.type;
layerMap[QStringLiteral( "attributeIndex" )] = layer.attributeIndex;
list.append( layerMap );
}
return list;
}
void QgsProcessingTinInputLayersWidget::setValue( const QVariant &value )
{
mInputLayersModel.clear();
if ( !value.isValid() || value.type() != QVariant::List )
return;
QVariantList list = value.toList();
for ( const QVariant &layerValue : list )
{
if ( layerValue.type() != QVariant::Map )
continue;
const QVariantMap layerMap = layerValue.toMap();
QgsProcessingParameterTinInputLayers::InputLayer layer;
layer.source = layerMap.value( QStringLiteral( "source" ) ).toString();
layer.type = static_cast<QgsProcessingParameterTinInputLayers::Type>( layerMap.value( QStringLiteral( "type" ) ).toInt() );
layer.attributeIndex = layerMap.value( QStringLiteral( "attributeIndex" ) ).toInt();
mInputLayersModel.addLayer( layer );
}
emit changed();
}
void QgsProcessingTinInputLayersWidget::setProject( QgsProject *project )
{
mInputLayersModel.setProject( project );
}
void QgsProcessingTinInputLayersWidget::onLayerChanged( QgsMapLayer *layer )
{
QgsVectorLayer *newLayer = qobject_cast<QgsVectorLayer *>( layer );
if ( !newLayer || !newLayer->isValid() )
return;
QgsVectorDataProvider *provider = newLayer->dataProvider();
if ( !provider )
return;
mComboFields->setLayer( newLayer );
mComboFields->setCurrentIndex( 0 );
mCheckBoxUseZCoordinate->setEnabled( QgsWkbTypes::hasZ( provider->wkbType() ) );
}
void QgsProcessingTinInputLayersWidget::onCurrentLayerAdded()
{
QgsVectorLayer *currentLayer = qobject_cast<QgsVectorLayer *>( mComboLayers->currentLayer() );
if ( !currentLayer )
return;
QgsProcessingParameterTinInputLayers::InputLayer layer;
layer.source = mComboLayers->currentLayer()->id();
switch ( currentLayer->geometryType() )
{
case QgsWkbTypes::PointGeometry:
layer.type = QgsProcessingParameterTinInputLayers::Vertices;
break;
case QgsWkbTypes::LineGeometry:
case QgsWkbTypes::PolygonGeometry:
layer.type = QgsProcessingParameterTinInputLayers::BreakLines;
break;
case QgsWkbTypes::UnknownGeometry:
case QgsWkbTypes::NullGeometry:
return;
break;
}
if ( mCheckBoxUseZCoordinate->isChecked() && mCheckBoxUseZCoordinate->isEnabled() )
layer.attributeIndex = -1;
else
layer.attributeIndex = mComboFields->currentIndex();
mInputLayersModel.addLayer( layer );
emit changed();
}
void QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersWidget::onLayersRemove()
{
mInputLayersModel.removeLayer( mTableView->selectionModel()->currentIndex().row() );
emit changed();
}
QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::QgsProcessingTinInputLayersModel( QgsProject *project ):
mProject( project )
{}
int QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::rowCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent );
return mInputLayers.count();
}
int QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::columnCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent );
return 3;
}
QVariant QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::data( const QModelIndex &index, int role ) const
{
if ( !index.isValid() )
return QVariant();
if ( index.row() >= mInputLayers.count() )
return QVariant();
switch ( role )
{
case Qt::DisplayRole:
{
QgsVectorLayer *layer = QgsProject::instance()->mapLayer<QgsVectorLayer *>( mInputLayers.at( index.row() ).source );
switch ( index.column() )
{
case 0:
if ( layer )
return layer->name();
else
return QVariant();
break;
case 1:
switch ( mInputLayers.at( index.row() ).type )
{
case QgsProcessingParameterTinInputLayers::Vertices:
return tr( "Vertices" );
break;
case QgsProcessingParameterTinInputLayers::BreakLines:
return tr( "Break Lines" );
break;
default:
return QString();
break;
}
break;
case 2:
int attributeindex = mInputLayers.at( index.row() ).attributeIndex;
if ( attributeindex < 0 )
return tr( "Z coordinate" );
else
{
if ( attributeindex < layer->fields().count() )
return layer->fields().at( attributeindex ).name();
else
return tr( "Invalid field" );
}
break;
}
}
break;
case Qt::ForegroundRole:
if ( index.column() == 2 )
{
int attributeindex = mInputLayers.at( index.row() ).attributeIndex;
if ( attributeindex < 0 )
return QColor( Qt::darkGray );
}
break;
case Qt::FontRole:
if ( index.column() == 2 )
{
int attributeindex = mInputLayers.at( index.row() ).attributeIndex;
if ( attributeindex < 0 )
{
QFont font;
font.setItalic( true );
return font;
}
}
break;
case Type:
if ( index.column() == 1 )
return mInputLayers.at( index.row() ).type;
break;
default:
break;
}
return QVariant();
}
bool QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::setData( const QModelIndex &index, const QVariant &value, int role )
{
if ( index.column() == 1 && role == Qt::EditRole )
{
mInputLayers[index.row()].type = static_cast<QgsProcessingParameterTinInputLayers::Type>( value.toInt() );
emit dataChanged( QAbstractTableModel::index( index.row(), 1 ), QAbstractTableModel::index( index.row(), 1 ) );
return true;
}
return false;
}
Qt::ItemFlags QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::flags( const QModelIndex &index ) const
{
if ( !index.isValid() )
return Qt::NoItemFlags;
if ( index.column() == 1 )
return QAbstractTableModel::flags( index ) | Qt::ItemIsEditable;
return QAbstractTableModel::flags( index );
}
QVariant QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if ( orientation == Qt::Horizontal && role == Qt::DisplayRole )
{
switch ( section )
{
case 0:
return tr( "Vector Layer" );
break;
case 1:
return tr( "Type" );
break;
case 2:
return tr( "Z Value Attribute" );
break;
default:
return QVariant();
break;
}
}
return QVariant();
}
void QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::addLayer( QgsProcessingParameterTinInputLayers::InputLayer &layer )
{
beginInsertRows( QModelIndex(), mInputLayers.count() - 1, mInputLayers.count() - 1 );
mInputLayers.append( layer );
endInsertRows();
}
void QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::removeLayer( int index )
{
if ( index < 0 || index >= mInputLayers.count() )
return;
beginRemoveRows( QModelIndex(), index, index );
mInputLayers.removeAt( index );
endRemoveRows();
}
void QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::clear()
{
mInputLayers.clear();
}
QList<QgsProcessingParameterTinInputLayers::InputLayer> QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::layers() const
{
return mInputLayers;
}
void QgsProcessingTinInputLayersWidget::QgsProcessingTinInputLayersModel::setProject( QgsProject *project )
{
mProject = project;
}
QWidget *QgsProcessingTinInputLayersWidget::Delegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
Q_UNUSED( option );
Q_UNUSED( index );
QComboBox *comboType = new QComboBox( parent );
comboType->addItem( tr( "Vertices" ), QgsProcessingParameterTinInputLayers::Vertices );
comboType->addItem( tr( "Break Lines" ), QgsProcessingParameterTinInputLayers::BreakLines );
return comboType;
}
void QgsProcessingTinInputLayersWidget::Delegate::setEditorData( QWidget *editor, const QModelIndex &index ) const
{
QComboBox *comboType = qobject_cast<QComboBox *>( editor );
Q_ASSERT( comboType );
QgsProcessingParameterTinInputLayers::Type type =
static_cast<QgsProcessingParameterTinInputLayers::Type>( index.data( QgsProcessingTinInputLayersModel::Type ).toInt() );
int comboIndex = comboType->findData( type );
if ( comboIndex >= 0 )
comboType->setCurrentIndex( comboIndex );
else
comboType->setCurrentIndex( 0 );
}
void QgsProcessingTinInputLayersWidget::Delegate::setModelData( QWidget *editor, QAbstractItemModel *model, const QModelIndex &index ) const
{
QComboBox *comboType = qobject_cast<QComboBox *>( editor );
Q_ASSERT( comboType );
model->setData( index, comboType->currentData(), Qt::EditRole );
}
QgsProcessingTinInputLayersWidgetWrapper::QgsProcessingTinInputLayersWidgetWrapper( const QgsProcessingParameterDefinition *parameter, QgsProcessingGui::WidgetType type, QWidget *parent ):
QgsAbstractProcessingParameterWidgetWrapper( parameter, type, parent )
{}
QString QgsProcessingTinInputLayersWidgetWrapper::parameterType() const
{
return QStringLiteral( "tininputlayers" );
}
QgsAbstractProcessingParameterWidgetWrapper *QgsProcessingTinInputLayersWidgetWrapper::createWidgetWrapper( const QgsProcessingParameterDefinition *parameter, QgsProcessingGui::WidgetType type )
{
return new QgsProcessingTinInputLayersWidgetWrapper( parameter, type );
}
QStringList QgsProcessingTinInputLayersWidgetWrapper::compatibleParameterTypes() const {return QStringList();}
QStringList QgsProcessingTinInputLayersWidgetWrapper::compatibleOutputTypes() const {return QStringList();}
QWidget *QgsProcessingTinInputLayersWidgetWrapper::createWidget()
{
mWidget = new QgsProcessingTinInputLayersWidget( widgetContext().project() );
connect( mWidget, &QgsProcessingTinInputLayersWidget::changed, this, [ = ]
{
emit widgetValueHasChanged( this );
} );
return mWidget;
}
void QgsProcessingTinInputLayersWidgetWrapper::setWidgetValue( const QVariant &value, QgsProcessingContext &context )
{
if ( !mWidget )
return;
mWidget->setValue( value );
mWidget->setProject( context.project() );
}
QVariant QgsProcessingTinInputLayersWidgetWrapper::widgetValue() const
{
if ( mWidget )
return mWidget->value();
else
return QVariant();
}
/// @endcond PRIVATE
| ghtmtt/QGIS | src/gui/processing/qgsprocessingtininputlayerswidget.cpp | C++ | gpl-2.0 | 12,841 |
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../helpers/start-app';
import destroyModal from '../helpers/destroy-modal';
import getToastMessage from '../helpers/toast-message';
var application;
module('Acceptance: Account Activation', {
beforeEach: function() {
application = startApp();
},
afterEach: function() {
Ember.$('#hidden-login-form').off('submit.stopInTest');
destroyModal();
Ember.run(application, 'destroy');
Ember.$.mockjax.clear();
}
});
test('visiting /activation', function(assert) {
assert.expect(1);
visit('/activation');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
});
});
test('request activation link without entering e-mail', function(assert) {
assert.expect(2);
visit('/activation');
click('.activation-page form .btn-primary');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), 'Enter e-mail address.');
});
});
test('request activation link with invalid e-mail', function(assert) {
assert.expect(2);
var message = 'Entered e-mail is invalid.';
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 400,
responseText: {
'detail': message,
'code': 'invalid_email'
}
});
visit('/activation');
fillIn('.activation-page form input', 'not-valid-email');
click('.activation-page form .btn-primary');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), message);
});
});
test('request activation link with non-existing e-mail', function(assert) {
assert.expect(2);
var message = 'No user with this e-mail exists.';
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 400,
responseText: {
'detail': message,
'code': 'not_found'
}
});
visit('/activation');
fillIn('.activation-page form input', 'not-valid-email');
click('.activation-page form .btn-primary');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), message);
});
});
test('request activation link with user-activated account', function(assert) {
assert.expect(2);
var message = 'You have to activate your account before you will be able to sign in.';
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 400,
responseText: {
'detail': message,
'code': 'inactive_user'
}
});
visit('/activation');
fillIn('.activation-page form input', 'valid@mail.com');
click('.activation-page form .btn-primary');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), message);
});
});
test('request activation link with admin-activated account', function(assert) {
assert.expect(2);
var message = 'Your account has to be activated by Administrator before you will be able to sign in.';
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 400,
responseText: {
'detail': message,
'code': 'inactive_admin'
}
});
visit('/activation');
fillIn('.activation-page form input', 'valid@mail.com');
click('.activation-page form .btn-primary');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), message);
});
});
test('request activation link with banned account', function(assert) {
assert.expect(2);
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 400,
responseText: {
'detail': {
'expires_on': null,
'message': {
'plain': 'You are banned for trolling.',
'html': '<p>You are banned for trolling.</p>',
}
},
'code': 'banned'
}
});
visit('/activation');
fillIn('.activation-page form input', 'valid@mail.com');
click('.activation-page form .btn-primary');
andThen(function() {
var errorMessage = find('.error-page .lead p').text();
assert.equal(errorMessage, 'You are banned for trolling.');
var expirationMessage = Ember.$.trim(find('.error-message>p').text());
assert.equal(expirationMessage, 'This ban is permanent.');
});
});
test('request activation link', function(assert) {
assert.expect(1);
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 200,
responseText: {
'username': 'BobBoberson',
'email': 'valid@mail.com'
}
});
visit('/activation');
fillIn('.activation-page form input', 'valid@mail.com');
click('.activation-page form .btn-primary');
andThen(function() {
var pageHeader = Ember.$.trim(find('.page-header h1').text());
assert.equal(pageHeader, 'Activation link sent');
});
});
test('invalid token is handled', function(assert) {
assert.expect(2);
var message = 'Token was rejected.';
Ember.$.mockjax({
url: '/api/auth/activate-account/1/token/',
status: 400,
responseText: {
'detail': message
}
});
visit('/activation/1/token/');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), message);
});
});
test('permission denied is handled', function(assert) {
assert.expect(2);
var message = 'Token was rejected.';
Ember.$.mockjax({
url: '/api/auth/activate-account/1/token/',
status: 403,
responseText: {
'detail': message
}
});
visit('/activation/1/token/');
andThen(function() {
assert.equal(currentPath(), 'error-403');
var errorMessage = Ember.$.trim(find('.error-page .lead').text());
assert.equal(errorMessage, message);
});
});
test('account is activated', function(assert) {
assert.expect(2);
var message = 'Yur account has been activated!';
Ember.$.mockjax({
url: '/api/auth/activate-account/1/token/',
status: 200,
responseText: {
'detail': message
}
});
visit('/activation/1/token/');
andThen(function() {
assert.equal(currentPath(), 'index');
assert.equal(getToastMessage(), message);
});
});
| leture/Misago | misago/emberapp/tests/acceptance/activate-test.js | JavaScript | gpl-2.0 | 6,118 |
<?php
/**
* Dm test domain components
*
* No redirection nor database manipulation ( insert, update, delete ) here
*
*/
class dmTestDomainComponents extends myFrontModuleComponents
{
public function executeList()
{
$query = $this->getListQuery();
$this->dmTestDomainPager = $this->getPager($query);
}
public function executeShow()
{
$query = $this->getShowQuery();
$this->dmTestDomain = $this->getRecord($query);
}
public function executeListByTag()
{
$query = $this->getListQuery();
$this->dmTestDomainPager = $this->getPager($query);
}
}
| Teplitsa/bquest.ru | lib/vendor/diem/dmCorePlugin/test/project/apps/front/modules/dmTestDomain/actions/components.class.php | PHP | gpl-2.0 | 599 |
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.midp.midletsuite;
import java.util.Vector;
import com.sun.midp.io.Util;
/**
* Simple attribute storage for MIDlets in the descriptor/manifest.
*/
public class MIDletInfo {
/** The name of the MIDlet. */
public String name;
/** The icon of the MIDlet. */
public String icon;
/** The main class for the MIDlet. */
public String classname;
/**
* Parses out the name, icon and classname.
* @param attr contains the name, icon and classname line to be
* parsed
*/
public MIDletInfo(String attr) {
Vector args;
if (attr == null) {
return;
}
args = Util.getCommaSeparatedValues(attr);
if (args.size() > 0) {
name = (String)args.elementAt(0);
if (args.size() > 1) {
icon = (String)args.elementAt(1);
if (icon.length() == 0) {
icon = null;
}
if (args.size() > 2) {
classname = (String)args.elementAt(2);
if (classname.length() == 0) {
classname = null;
}
}
}
}
}
/**
* Container class to hold information about the current MIDlet.
* @param name the name of the MIDlet from descriptor file or
* manifest
* @param icon the icon to display when the user selects the MIDlet
* from a list
* @param classname the main class for this MIDlet
*/
public MIDletInfo(String name, String icon, String classname) {
this.name = name;
this.icon = icon;
this.classname = classname;
}
}
| brendandahl/j2me.js | java/midp/com/sun/midp/midletsuite/MIDletInfo.java | Java | gpl-2.0 | 2,732 |
Info<< "Reading field U\n" << endl;
volVectorField U
(
IOobject
(
"U",
runTime.timeName(),
mesh,
IOobject::MUST_READ,
IOobject::AUTO_WRITE
),
mesh
);
volTensorField gradU //= fvc::grad(U);
(
IOobject
(
"grad(U)",
runTime.timeName(),
mesh,
IOobject::NO_READ,
IOobject::NO_WRITE
),
mesh,
dimensionedTensor("zero", dimless, tensor::zero)
);
volSymmTensorField epsilon
(
IOobject
(
"epsilon",
runTime.timeName(),
mesh,
IOobject::READ_IF_PRESENT,
IOobject::AUTO_WRITE
),
mesh,
dimensionedSymmTensor("zero", dimless, symmTensor::zero)
);
volSymmTensorField sigma
(
IOobject
(
"sigma",
runTime.timeName(),
mesh,
IOobject::READ_IF_PRESENT,
IOobject::AUTO_WRITE
),
mesh,
dimensionedSymmTensor("zero", dimForce/dimArea, symmTensor::zero)
);
volVectorField divSigmaExp
(
IOobject
(
"divSigmaExp",
runTime.timeName(),
mesh,
IOobject::NO_READ,
IOobject::NO_WRITE
),
mesh,
dimensionedVector("zero", dimForce/dimVolume, vector::zero)
);
//- rheology
constitutiveModel rheology(sigma, U);
volSymmTensor4thOrderField C = rheology.C();
surfaceSymmTensor4thOrderField Cf = fvc::interpolate(C, "C");
volDiagTensorField K = rheology.K();
surfaceDiagTensorField Kf = fvc::interpolate(K, "K");
volScalarField rho = rheology.rho();
surfaceVectorField n = mesh.Sf()/mesh.magSf();
| tmaric/foam-extend-3.0 | applications/solvers/solidMechanics/elasticOrthoSolidFoam/createFields.H | C++ | gpl-2.0 | 1,818 |
<?php
namespace Drupal\commerce_payment\Plugin\Commerce\PaymentType;
/**
* Provides the manual payment type.
*
* @CommercePaymentType(
* id = "payment_manual",
* label = @Translation("Manual"),
* workflow = "payment_manual",
* )
*/
class PaymentManual extends PaymentTypeBase {
/**
* {@inheritdoc}
*/
public function buildFieldDefinitions() {
return [];
}
}
| jigish-addweb/d8commerce | web/modules/contrib/commerce/modules/payment/src/Plugin/Commerce/PaymentType/PaymentManual.php | PHP | gpl-2.0 | 392 |
// FreeBSD wants warning clean system headers:
// { dg-options "-Wall -Wsystem-headers" { target *-*-freebsd* *-*-dragonfly* } }
// { dg-do compile }
// 1999-05-12 bkoz
// Copyright (C) 1999-2014 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 17.4.1.2 Headers
#include <bits/stdc++.h>
// "C" compatibility headers
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <float.h>
#include <iso646.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef _GLIBCXX_HAVE_WCHAR_H
#include <wchar.h>
#endif
#ifdef _GLIBCXX_HAVE_WCTYPE_H
#include <wctype.h>
#endif
#include <bits/stdc++.h>
// "C" compatibility headers
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <float.h>
#include <iso646.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef _GLIBCXX_HAVE_WCHAR_H
#include <wchar.h>
#endif
#ifdef _GLIBCXX_HAVE_WCTYPE_H
#include <wctype.h>
#endif
| xinchoubiology/gcc | libstdc++-v3/testsuite/17_intro/headers/c++1998/stdc++_multiple_inclusion.cc | C++ | gpl-2.0 | 1,914 |
// varargs test
import varargs.*;
public class varargs_runme {
static {
try {
System.loadLibrary("varargs");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
System.exit(1);
}
}
public static void main(String argv[]) {
if (!varargs.test("Hello").equals("Hello"))
throw new RuntimeException("Failed");
Foo f = new Foo("BuonGiorno", 1);
if (!f.getStr().equals("BuonGiorno"))
throw new RuntimeException("Failed");
f = new Foo("Greetings");
if (!f.getStr().equals("Greetings"))
throw new RuntimeException("Failed");
if (!f.test("Hello").equals("Hello"))
throw new RuntimeException("Failed");
if (!Foo.statictest("Grussen", 1).equals("Grussen"))
throw new RuntimeException("Failed");
}
}
| DGA-MI-SSI/YaCo | deps/swig-3.0.7/Examples/test-suite/java/varargs_runme.java | Java | gpl-3.0 | 927 |
<?php
namespace Neos\Media\Validator;
/*
* This file is part of the Neos.Media package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Validation\Exception\InvalidValidationOptionsException;
use Neos\Flow\Validation\Validator\AbstractValidator;
use Neos\Media\Domain\Model\Image;
use Neos\Media\Domain\Model\ImageInterface;
/**
* Validator that checks the type of a given image
*
* Example:
* [at]Flow\Validate("$image", type="\Neos\Media\Validator\ImageTypeValidator", options={ "allowedTypes"={"jpeg", "png"} })
*/
class ImageTypeValidator extends AbstractValidator
{
/**
* @var array
*/
protected $supportedOptions = [
'allowedTypes' => [null, 'Allowed image types (using image/* IANA media subtypes)', 'array', true]
];
/**
* The given $value is valid if it is an \Neos\Media\Domain\Model\ImageInterface of the
* configured type (one of the image/* IANA media subtypes)
*
* Note: a value of NULL or empty string ('') is considered valid
*
* @param ImageInterface $image The image that should be validated
* @return void
* @api
*/
protected function isValid($image)
{
$this->validateOptions();
if (!$image instanceof Image) {
$this->addError('The given value was not an Image instance.', 1327947256);
return;
}
$allowedImageTypes = $this->options['allowedTypes'];
array_walk($allowedImageTypes, function (&$value) {
$value = 'image/' . $value;
});
if (!in_array($image->getMediaType(), $allowedImageTypes)) {
$this->addError('The media type "%s" is not allowed for this image.', 1327947647, [$image->getMediaType()]);
}
}
/**
* Checks if this validator is correctly configured
*
* @return void
* @throws InvalidValidationOptionsException if the configured validation options are incorrect
*/
protected function validateOptions()
{
if (!isset($this->options['allowedTypes'])) {
throw new InvalidValidationOptionsException('The option "allowedTypes" was not specified.', 1327947194);
} elseif (!is_array($this->options['allowedTypes']) || $this->options['allowedTypes'] === []) {
throw new InvalidValidationOptionsException('The option "allowedTypes" must be an array with at least one item.', 1327947224);
}
}
}
| daniellienert/neos-development-collection | Neos.Media/Classes/Validator/ImageTypeValidator.php | PHP | gpl-3.0 | 2,654 |
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2019 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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/>.
*
*/
package auth
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"sort"
"strconv"
"gopkg.in/macaroon.v1"
"github.com/snapcore/snapd/overlord/state"
)
// AuthState represents current authenticated users as tracked in state
type AuthState struct {
LastID int `json:"last-id"`
Users []UserState `json:"users"`
Device *DeviceState `json:"device,omitempty"`
MacaroonKey []byte `json:"macaroon-key,omitempty"`
}
// DeviceState represents the device's identity and store credentials
type DeviceState struct {
// Brand refers to the brand-id
Brand string `json:"brand,omitempty"`
Model string `json:"model,omitempty"`
Serial string `json:"serial,omitempty"`
KeyID string `json:"key-id,omitempty"`
SessionMacaroon string `json:"session-macaroon,omitempty"`
}
// UserState represents an authenticated user
type UserState struct {
ID int `json:"id"`
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Macaroon string `json:"macaroon,omitempty"`
Discharges []string `json:"discharges,omitempty"`
StoreMacaroon string `json:"store-macaroon,omitempty"`
StoreDischarges []string `json:"store-discharges,omitempty"`
}
// identificationOnly returns a *UserState with only the
// identification information from u.
func (u *UserState) identificationOnly() *UserState {
return &UserState{
ID: u.ID,
Username: u.Username,
Email: u.Email,
}
}
// HasStoreAuth returns true if the user has store authorization.
func (u *UserState) HasStoreAuth() bool {
if u == nil {
return false
}
return u.StoreMacaroon != ""
}
// MacaroonSerialize returns a store-compatible serialized representation of the given macaroon
func MacaroonSerialize(m *macaroon.Macaroon) (string, error) {
marshalled, err := m.MarshalBinary()
if err != nil {
return "", err
}
encoded := base64.RawURLEncoding.EncodeToString(marshalled)
return encoded, nil
}
// MacaroonDeserialize returns a deserialized macaroon from a given store-compatible serialization
func MacaroonDeserialize(serializedMacaroon string) (*macaroon.Macaroon, error) {
var m macaroon.Macaroon
decoded, err := base64.RawURLEncoding.DecodeString(serializedMacaroon)
if err != nil {
return nil, err
}
err = m.UnmarshalBinary(decoded)
if err != nil {
return nil, err
}
return &m, nil
}
// generateMacaroonKey generates a random key to sign snapd macaroons
func generateMacaroonKey() ([]byte, error) {
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
return nil, err
}
return key, nil
}
const snapdMacaroonLocation = "snapd"
// newUserMacaroon returns a snapd macaroon for the given username
func newUserMacaroon(macaroonKey []byte, userID int) (string, error) {
userMacaroon, err := macaroon.New(macaroonKey, strconv.Itoa(userID), snapdMacaroonLocation)
if err != nil {
return "", fmt.Errorf("cannot create macaroon for snapd user: %s", err)
}
serializedMacaroon, err := MacaroonSerialize(userMacaroon)
if err != nil {
return "", fmt.Errorf("cannot serialize macaroon for snapd user: %s", err)
}
return serializedMacaroon, nil
}
// TODO: possibly move users' related functions to a userstate package
// NewUser tracks a new authenticated user and saves its details in the state
func NewUser(st *state.State, username, email, macaroon string, discharges []string) (*UserState, error) {
var authStateData AuthState
err := st.Get("auth", &authStateData)
if err == state.ErrNoState {
authStateData = AuthState{}
} else if err != nil {
return nil, err
}
if authStateData.MacaroonKey == nil {
authStateData.MacaroonKey, err = generateMacaroonKey()
if err != nil {
return nil, err
}
}
authStateData.LastID++
localMacaroon, err := newUserMacaroon(authStateData.MacaroonKey, authStateData.LastID)
if err != nil {
return nil, err
}
sort.Strings(discharges)
authenticatedUser := UserState{
ID: authStateData.LastID,
Username: username,
Email: email,
Macaroon: localMacaroon,
Discharges: nil,
StoreMacaroon: macaroon,
StoreDischarges: discharges,
}
authStateData.Users = append(authStateData.Users, authenticatedUser)
st.Set("auth", authStateData)
return &authenticatedUser, nil
}
var ErrInvalidUser = errors.New("invalid user")
// RemoveUser removes a user from the state given its ID.
func RemoveUser(st *state.State, userID int) (removed *UserState, err error) {
return removeUser(st, func(u *UserState) bool { return u.ID == userID })
}
// RemoveUserByUsername removes a user from the state given its username. Returns a *UserState with the identification information for them.
func RemoveUserByUsername(st *state.State, username string) (removed *UserState, err error) {
return removeUser(st, func(u *UserState) bool { return u.Username == username })
}
// removeUser removes the first user matching given predicate.
func removeUser(st *state.State, p func(*UserState) bool) (*UserState, error) {
var authStateData AuthState
err := st.Get("auth", &authStateData)
if err == state.ErrNoState {
return nil, ErrInvalidUser
}
if err != nil {
return nil, err
}
for i := range authStateData.Users {
u := &authStateData.Users[i]
if p(u) {
removed := u.identificationOnly()
// delete without preserving order
n := len(authStateData.Users) - 1
authStateData.Users[i] = authStateData.Users[n]
authStateData.Users[n] = UserState{}
authStateData.Users = authStateData.Users[:n]
st.Set("auth", authStateData)
return removed, nil
}
}
return nil, ErrInvalidUser
}
func Users(st *state.State) ([]*UserState, error) {
var authStateData AuthState
err := st.Get("auth", &authStateData)
if err == state.ErrNoState {
return nil, nil
}
if err != nil {
return nil, err
}
users := make([]*UserState, len(authStateData.Users))
for i := range authStateData.Users {
users[i] = &authStateData.Users[i]
}
return users, nil
}
// User returns a user from the state given its ID.
func User(st *state.State, id int) (*UserState, error) {
return findUser(st, func(u *UserState) bool { return u.ID == id })
}
// UserByUsername returns a user from the state given its username.
func UserByUsername(st *state.State, username string) (*UserState, error) {
return findUser(st, func(u *UserState) bool { return u.Username == username })
}
// findUser finds the first user matching given predicate.
func findUser(st *state.State, p func(*UserState) bool) (*UserState, error) {
var authStateData AuthState
err := st.Get("auth", &authStateData)
if err == state.ErrNoState {
return nil, ErrInvalidUser
}
if err != nil {
return nil, err
}
for i := range authStateData.Users {
u := &authStateData.Users[i]
if p(u) {
return u, nil
}
}
return nil, ErrInvalidUser
}
// UpdateUser updates user in state
func UpdateUser(st *state.State, user *UserState) error {
var authStateData AuthState
err := st.Get("auth", &authStateData)
if err == state.ErrNoState {
return ErrInvalidUser
}
if err != nil {
return err
}
for i := range authStateData.Users {
if authStateData.Users[i].ID == user.ID {
authStateData.Users[i] = *user
st.Set("auth", authStateData)
return nil
}
}
return ErrInvalidUser
}
var ErrInvalidAuth = fmt.Errorf("invalid authentication")
// CheckMacaroon returns the UserState for the given macaroon/discharges credentials
func CheckMacaroon(st *state.State, macaroon string, discharges []string) (*UserState, error) {
var authStateData AuthState
err := st.Get("auth", &authStateData)
if err != nil {
return nil, ErrInvalidAuth
}
snapdMacaroon, err := MacaroonDeserialize(macaroon)
if err != nil {
return nil, ErrInvalidAuth
}
// attempt snapd macaroon verification
if snapdMacaroon.Location() == snapdMacaroonLocation {
// no caveats to check so far
check := func(caveat string) error { return nil }
// ignoring discharges, unused for snapd macaroons atm
err = snapdMacaroon.Verify(authStateData.MacaroonKey, check, nil)
if err != nil {
return nil, ErrInvalidAuth
}
macaroonID := snapdMacaroon.Id()
userID, err := strconv.Atoi(macaroonID)
if err != nil {
return nil, ErrInvalidAuth
}
user, err := User(st, userID)
if err != nil {
return nil, ErrInvalidAuth
}
if macaroon != user.Macaroon {
return nil, ErrInvalidAuth
}
return user, nil
}
// if macaroon is not a snapd macaroon, fallback to previous token-style check
NextUser:
for _, user := range authStateData.Users {
if user.Macaroon != macaroon {
continue
}
if len(user.Discharges) != len(discharges) {
continue
}
// sort discharges (stored users' discharges are already sorted)
sort.Strings(discharges)
for i, d := range user.Discharges {
if d != discharges[i] {
continue NextUser
}
}
return &user, nil
}
return nil, ErrInvalidAuth
}
// CloudInfo reflects cloud information for the system (as captured in the core configuration).
type CloudInfo struct {
Name string `json:"name"`
Region string `json:"region,omitempty"`
AvailabilityZone string `json:"availability-zone,omitempty"`
}
type ensureContextKey struct{}
// EnsureContextTODO returns a provisional context marked as
// pertaining to an Ensure loop.
// TODO: see Overlord.Loop to replace it with a proper context passed to all Ensures.
func EnsureContextTODO() context.Context {
ctx := context.TODO()
return context.WithValue(ctx, ensureContextKey{}, struct{}{})
}
// IsEnsureContext returns whether context was marked as pertaining to an Ensure loop.
func IsEnsureContext(ctx context.Context) bool {
return ctx.Value(ensureContextKey{}) != nil
}
| sergiocazzolato/snapd | overlord/auth/auth.go | GO | gpl-3.0 | 10,413 |
<?php
namespace Neos\Neos\Tests\Unit\Domain\Model;
/*
* This file is part of the Neos.Neos package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Tests\UnitTestCase;
use Neos\Neos\Domain\Model\Domain;
use Neos\Neos\Domain\Model\Site;
/**
* Testcase for the "Domain" domain model
*
*/
class DomainTest extends UnitTestCase
{
/**
* @test
*/
public function setHostPatternAllowsForSettingTheHostPatternOfTheDomain()
{
$domain = new Domain();
$domain->setHostname('neos.io');
self::assertSame('neos.io', $domain->getHostname());
}
/**
* @test
*/
public function setSiteSetsTheSiteTheDomainIsPointingTo()
{
/** @var Site $mockSite */
$mockSite = $this->getMockBuilder(Site::class)->disableOriginalConstructor()->getMock();
$domain = new Domain;
$domain->setSite($mockSite);
self::assertSame($mockSite, $domain->getSite());
}
}
| neos/neos | Tests/Unit/Domain/Model/DomainTest.php | PHP | gpl-3.0 | 1,148 |
<?php
class ModelPaymentSecureTradingWs extends Model {
public function getMethod($address, $total) {
$this->load->language('payment/securetrading_ws');
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('securetrading_ws_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");
if ($this->config->get('securetrading_ws_total') > $total) {
$status = false;
} elseif (!$this->config->get('securetrading_ws_geo_zone_id')) {
$status = true;
} elseif ($query->num_rows) {
$status = true;
} else {
$status = false;
}
$method_data = array();
if ($status) {
$method_data = array(
'code' => 'securetrading_ws',
'title' => $this->language->get('text_title'),
'terms' => '',
'sort_order' => $this->config->get('securetrading_ws_sort_order')
);
}
return $method_data;
}
public function call($data) {
$ch = curl_init();
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_URL => 'https://webservices.securetrading.net/xml/',
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => array(
'User-Agent: OpenCart - Secure Trading WS',
'Content-Length: ' . strlen($data),
'Authorization: Basic ' . base64_encode($this->config->get('securetrading_ws_username') . ':' . $this->config->get('securetrading_ws_password')),
),
CURLOPT_POSTFIELDS => $data,
);
curl_setopt_array($ch, $defaults);
$response = curl_exec($ch);
if ($response === False) {
$this->log->write('Secure Trading WS CURL Error: (' . curl_errno($ch) . ') ' . curl_error($ch));
}
curl_close($ch);
return $response;
}
public function getOrder($order_id) {
$qry = $this->db->query("SELECT * FROM `" . DB_PREFIX . "securetrading_ws_order` WHERE `order_id` = '" . (int)$order_id . "' LIMIT 1");
return $qry->row;
}
public function addMd($order_id, $md) {
$this->db->query("INSERT INTO " . DB_PREFIX . "securetrading_ws_order SET order_id = " . (int)$order_id . ", md = '" . $this->db->escape($md) . "', `created` = now(), `modified` = now()");
}
public function removeMd($md) {
$this->db->query("DELETE FROM " . DB_PREFIX . "securetrading_ws_order WHERE md = '" . $this->db->escape($md) . "'");
}
public function updateReference($order_id, $transaction_reference) {
$this->db->query("UPDATE " . DB_PREFIX . "securetrading_ws_order SET transaction_reference = '" . $this->db->escape($transaction_reference) . "' WHERE order_id = " . (int) $order_id);
if ($this->db->countAffected() == 0) {
$this->db->query("INSERT INTO " . DB_PREFIX . "securetrading_ws_order SET order_id = " . (int) $order_id . ", transaction_reference = '" . $this->db->escape($transaction_reference) . "', `created` = now(), `modified` = now()");
}
}
public function getOrderId($md) {
$row = $this->db->query("SELECT order_id FROM " . DB_PREFIX . "securetrading_ws_order WHERE md = '" . $this->db->escape($md) . "' LIMIT 1")->row;
if (isset($row['order_id']) && !empty($row['order_id'])) {
return $row['order_id'];
} else {
return false;
}
}
public function confirmOrder($order_id, $order_status_id, $comment = '', $notify = false) {
$this->load->model('checkout/order');
$this->db->query("UPDATE `" . DB_PREFIX . "order` SET order_status_id = 0 WHERE order_id = " . (int)$order_id);
$this->model_checkout_order->confirm($order_id, $order_status_id, $comment, $notify);
$order_info = $this->model_checkout_order->getOrder($order_id);
$securetrading_ws_order = $this->getOrder($order_info['order_id']);
$amount = $this->currency->format($order_info['total'], $order_info['currency_code'], false, false);
switch($this->config->get('securetrading_ws_settle_status')){
case 0:
$trans_type = 'auth';
break;
case 1:
$trans_type = 'auth';
break;
case 2:
$trans_type = 'suspended';
break;
case 100:
$trans_type = 'payment';
break;
default :
$trans_type = '';
}
$this->db->query("UPDATE `" . DB_PREFIX . "securetrading_ws_order` SET `settle_type`='" . $this->config->get('securetrading_ws_settle_status') . "', `modified` = now(), `currency_code` = '" . $this->db->escape($order_info['currency_code']) . "', `total` = '" . $amount . "' WHERE order_id = " . (int)$order_info['order_id']);
$this->db->query("INSERT INTO `" . DB_PREFIX . "securetrading_ws_order_transaction` SET `securetrading_ws_order_id` = '" . (int)$securetrading_ws_order['securetrading_ws_order_id'] . "', `amount` = '" . $amount . "', type = '" . $trans_type . "', `created` = now()");
}
public function updateOrder($order_id, $order_status_id, $comment = '', $notify = false) {
$this->load->model('checkout/order');
$this->db->query("UPDATE `" . DB_PREFIX . "order` SET order_status_id = " . (int) $order_status_id . " WHERE order_id = " . (int) $order_id);
$this->model_checkout_order->update($order_id, $order_status_id, $comment, $notify);
}
public function logger($message) {
$log = new Log('secure.log');
$log->write($message);
}
} | Foboy/GogoDesginer | upload/catalog/model/payment/securetrading_ws.php | PHP | gpl-3.0 | 5,325 |
'use strict';
var async = require('async'),
db = require('./database'),
topics = require('./topics'),
categories = require('./categories'),
posts = require('./posts'),
plugins = require('./plugins'),
batch = require('./batch');
(function(ThreadTools) {
ThreadTools.delete = function(tid, uid, callback) {
toggleDelete(tid, uid, true, callback);
};
ThreadTools.restore = function(tid, uid, callback) {
toggleDelete(tid, uid, false, callback);
};
function toggleDelete(tid, uid, isDelete, callback) {
topics.getTopicFields(tid, ['tid', 'cid', 'uid', 'deleted', 'title', 'mainPid'], function(err, topicData) {
if (err) {
return callback(err);
}
if (parseInt(topicData.deleted, 10) === 1 && isDelete) {
return callback(new Error('[[error:topic-already-deleted]]'));
} else if(parseInt(topicData.deleted, 10) !== 1 && !isDelete) {
return callback(new Error('[[error:topic-already-restored]]'));
}
topics[isDelete ? 'delete' : 'restore'](tid, function(err) {
if (err) {
return callback(err);
}
topicData.deleted = isDelete ? 1 : 0;
if (isDelete) {
plugins.fireHook('action:topic.delete', tid);
} else {
plugins.fireHook('action:topic.restore', topicData);
}
var data = {
tid: tid,
cid: topicData.cid,
isDelete: isDelete,
uid: uid
};
callback(null, data);
});
});
}
ThreadTools.purge = function(tid, uid, callback) {
var topic;
async.waterfall([
function(next) {
topics.exists(tid, next);
},
function(exists, next) {
if (!exists) {
return callback();
}
batch.processSortedSet('tid:' + tid + ':posts', function(pids, next) {
async.eachLimit(pids, 10, posts.purge, next);
}, {alwaysStartAt: 0}, next);
},
function(next) {
topics.getTopicFields(tid, ['mainPid', 'cid'], next);
},
function(_topic, next) {
topic = _topic;
posts.purge(topic.mainPid, next);
},
function(next) {
topics.purge(tid, next);
},
function(next) {
next(null, {tid: tid, cid: topic.cid, uid: uid});
}
], callback);
};
ThreadTools.lock = function(tid, uid, callback) {
toggleLock(tid, uid, true, callback);
};
ThreadTools.unlock = function(tid, uid, callback) {
toggleLock(tid, uid, false, callback);
};
function toggleLock(tid, uid, lock, callback) {
callback = callback || function() {};
topics.getTopicField(tid, 'cid', function(err, cid) {
if (err) {
return callback(err);
}
topics.setTopicField(tid, 'locked', lock ? 1 : 0);
var data = {
tid: tid,
isLocked: lock,
uid: uid,
cid: cid
};
plugins.fireHook('action:topic.lock', data);
callback(null, data);
});
}
ThreadTools.pin = function(tid, uid, callback) {
togglePin(tid, uid, true, callback);
};
ThreadTools.unpin = function(tid, uid, callback) {
togglePin(tid, uid, false, callback);
};
function togglePin(tid, uid, pin, callback) {
topics.getTopicFields(tid, ['cid', 'lastposttime'], function(err, topicData) {
if (err) {
return callback(err);
}
topics.setTopicField(tid, 'pinned', pin ? 1 : 0);
db.sortedSetAdd('cid:' + topicData.cid + ':tids', pin ? Math.pow(2, 53) : topicData.lastposttime, tid);
var data = {
tid: tid,
isPinned: pin,
uid: uid,
cid: topicData.cid
};
plugins.fireHook('action:topic.pin', data);
callback(null, data);
});
}
ThreadTools.move = function(tid, cid, uid, callback) {
var topic;
async.waterfall([
function(next) {
topics.getTopicFields(tid, ['cid', 'lastposttime', 'pinned', 'deleted', 'postcount'], next);
},
function(topicData, next) {
topic = topicData;
db.sortedSetsRemove([
'cid:' + topicData.cid + ':tids',
'cid:' + topicData.cid + ':tids:posts'
], tid, next);
},
function(next) {
var timestamp = parseInt(topic.pinned, 10) ? Math.pow(2, 53) : topic.lastposttime;
async.parallel([
function(next) {
db.sortedSetAdd('cid:' + cid + ':tids', timestamp, tid, next);
},
function(next) {
topic.postcount = topic.postcount || 0;
db.sortedSetAdd('cid:' + cid + ':tids:posts', topic.postcount, tid, next);
}
], next);
}
], function(err) {
if (err) {
return callback(err);
}
var oldCid = topic.cid;
if(!parseInt(topic.deleted, 10)) {
categories.incrementCategoryFieldBy(oldCid, 'topic_count', -1);
categories.incrementCategoryFieldBy(cid, 'topic_count', 1);
}
categories.moveRecentReplies(tid, oldCid, cid);
topics.setTopicField(tid, 'cid', cid, function(err) {
if (err) {
return callback(err);
}
plugins.fireHook('action:topic.move', {
tid: tid,
fromCid: oldCid,
toCid: cid,
uid: uid
});
callback();
});
});
};
}(exports));
| mario56/nodebb-cn-mongo | src/threadTools.js | JavaScript | gpl-3.0 | 4,819 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ClearCanvas.Common;
using ClearCanvas.Common.Utilities;
using ClearCanvas.ImageViewer.Common;
using ClearCanvas.ImageViewer.StudyManagement;
namespace ClearCanvas.ImageViewer.Volumes
{
/// <summary>
/// Represents a cached MPR volume.
/// </summary>
public interface ICachedVolume : IVolumeHeader
{
/// <summary>
/// Gets a GUID uniquely identifying the cached MPR volume.
/// </summary>
/// <remarks>
/// This identifier GUID will remain consistent for the same set of source frames, even if the volume is unloaded and reloaded by the <see cref="MemoryManager"/>.
/// </remarks>
Guid Identifier { get; }
/// <summary>
/// Gets the MPR volume, synchronously loading the volume if necessary.
/// </summary>
/// <remarks>
/// Client code should not hold on to the <see cref="Volumes.Volume"/> instance returned by this property.
/// If a long-term reference is desired, call and store the result from <see cref="CreateReference"/>,
/// accessing the <see cref="ICachedVolumeReference.Volume"/> property as necessary.
/// This is important, because the <see cref="MemoryManager"/> may decide to unload the actual volume at any time,
/// and a direct reference to a specific <see cref="Volumes.Volume"/> can point to a disposed object if held on to
/// for any significant period of time.
/// </remarks>
Volume Volume { get; }
/// <summary>
/// Creates a long-term reference to the cached MPR volume.
/// </summary>
/// <remarks>
/// Calling code should ensure that the <see cref="ICachedVolumeReference"/> instance returned by this method is properly disposed.
/// This will ensure that all resources held by the cache object, including the volume itself as well as the references to the source frames,
/// can be properly released when no other cache references exist.
/// </remarks>
ICachedVolumeReference CreateReference();
}
// TODO (CR Apr 2013): Not sure what the answer is right now, but I feel like the IsLoaded, Volume, Lock/Unlock is unnecessary
// and can cause confusion - people might not know they have to lock in order to guarantee that Load succeeds, or what
// the behaviour of accessing the Volume property is. Perhaps the answer is to have only Load and LoadAsync,
// but internally lock and guarantee that Load and Load Async always result in successfully loading the volume to completion.
/// <summary>
/// Represents a reference to a cached MPR volume.
/// </summary>
public interface ICachedVolumeReference : ICachedVolume, IVolumeReference
{
/// <summary>
/// Gets the MPR volume, synchronously loading the volume if necessary.
/// </summary>
/// <remarks>
/// Client code should not hold on to the <see cref="Volumes.Volume"/> instance returned by this property.
/// If a long-term reference is desired, call and store the result from <see cref="CreateReference"/>,
/// accessing the <see cref="ICachedVolumeReference.Volume"/> property as necessary.
/// This is important, because the <see cref="MemoryManager"/> may decide to unload the actual volume at any time,
/// and a direct reference to a specific <see cref="Volumes.Volume"/> can point to a disposed object if held on to
/// for any significant period of time.
/// </remarks>
new Volume Volume { get; }
/// <summary>
/// Creates a long-term reference to the cached MPR volume.
/// </summary>
/// <remarks>
/// Calling code should ensure that the <see cref="ICachedVolumeReference"/> instance returned by this method is properly disposed.
/// This will ensure that all resources held by the cache object, including the volume itself as well as the references to the source frames,
/// can be properly released when no other cache references exist.
/// </remarks>
new ICachedVolumeReference CreateReference();
/// <summary>
/// Gets a value indicating whether or not the MPR volume is loaded.
/// </summary>
bool IsLoaded { get; }
/// <summary>
/// Fired when the value of <see cref="Progress"/> changes.
/// </summary>
event EventHandler ProgressChanged;
/// <summary>
/// Gets a value between 0 and 100 indicating the loading progress of the MPR volume.
/// </summary>
float Progress { get; }
/// <summary>
/// Starts loading the MPR volume asynchronously.
/// </summary>
/// <param name="onProgress">Optionally specifies a callback method to be called periodically while the loading the volume.</param>
/// <param name="onComplete">Optionally specifies a callback method to be called when the volume has been successfully loaded.</param>
/// <param name="onError">Optionally specifies a callback method to be called if an exception was thrown while loading the volume.</param>
/// <returns>Returns a <see cref="Task"/> which can be used to wait for the MPR volume to finish loading.</returns>
Task LoadAsync(VolumeLoadProgressCallback onProgress = null, VolumeLoadCompletionCallback onComplete = null, VolumeLoadErrorCallback onError = null);
/// <summary>
/// Loads the MPR volume synchronously.
/// </summary>
/// <param name="onProgress">Optionally specifies a callback method to be called periodically while the loading the volume.</param>
void Load(VolumeLoadProgressCallback onProgress = null);
/// <summary>
/// Locks the MPR volume, preventing it from being unloaded by memory management.
/// </summary>
/// <remarks>
/// The lock will be automatically released if the reference is disposed.
/// </remarks>
void Lock();
/// <summary>
/// Unlocks the MPR volume, allowing memory management to unload it as necessary.
/// </summary>
void Unlock();
}
/// <summary>
/// Represents the callback method to be called periodically while the loading the volume.
/// </summary>
/// <param name="volume">A reference to the volume being loaded.</param>
/// <param name="completedOperations">The number of suboperations completed.</param>
/// <param name="totalOperations">The total number of suboperations.</param>
public delegate void VolumeLoadProgressCallback(ICachedVolume volume, int completedOperations, int totalOperations);
/// <summary>
/// Represents the callback method to be called when the volume has been successfully loaded.
/// </summary>
/// <param name="volume">A reference to the loaded volume.</param>
public delegate void VolumeLoadCompletionCallback(ICachedVolume volume);
/// <summary>
/// Represents the callback method to be called if an exception was thrown while loading the volume.
/// </summary>
/// <param name="volume">A reference to the failed volume.</param>
/// <param name="ex">The exception that was thrown.</param>
public delegate void VolumeLoadErrorCallback(ICachedVolume volume, Exception ex);
/// <summary>
/// Implementation of a memory-managed MPR volume cache.
/// </summary>
/// <remarks>
/// The <see cref="ICachedVolumeReference"/> items returned by this cache are container objects that hold the MPR volume,
/// references to the source frames, as well as implement memory management. Direct references to this object
/// (and the actual MPR Volume exposed by <see cref="ICachedVolumeReference.Volume"/>) should not be held on to by client code
/// for any significant period of time, as the underlying instance of <see cref="Volume"/> may be disposed of
/// at any time by the <see cref="MemoryManager"/>. Instead, if a long-term reference is desired, create a reference
/// with <see cref="ICachedVolumeReference.CreateReference"/>. When all outstanding references to the <see cref="ICachedVolumeReference"/>
/// have been disposed, the item will itself be removed from the cache, releasing the references to the source frames
/// as well as the <see cref="Volume"/> instance.
/// </remarks>
public sealed class VolumeCache : IDisposable
{
/// <summary>
/// Gets an instance of a <see cref="VolumeCache"/> whose lifetime is tied to a specific <see cref="IImageViewer"/> instance.
/// </summary>
public static VolumeCache GetInstance(IImageViewer imageViewer)
{
return imageViewer.GetVolumeCache();
}
private readonly object _syncRoot = new object();
private Dictionary<CacheKey, CachedVolume> _cache;
/// <summary>
/// Initializes a new instance of <see cref="VolumeCache"/>.
/// </summary>
public VolumeCache()
{
_cache = new Dictionary<CacheKey, CachedVolume>();
}
/// <summary>
/// Disposes the <see cref="VolumeCache"/>.
/// </summary>
public void Dispose()
{
// do not forcibly dispose the cached volumes, as things like clipboard items may still hold references to cached volumes
_cache = null;
}
/// <summary>
/// Creates a reference to a cached MPR volume based on the specified source display set.
/// </summary>
public ICachedVolumeReference GetVolumeReference(IDisplaySet displaySet)
{
return CreateVolumeCore(displaySet.PresentationImages.Cast<IImageSopProvider>().Select(i => i.Frame).ToList());
}
/// <summary>
/// Creates a reference to a cached MPR volume based on the specified source frames.
/// </summary>
/// <param name="frames">References to the source frames from which to create an MPR volume. This method does not take ownership of the specified frame references.</param>
public ICachedVolumeReference GetVolumeReference(IEnumerable<IFrameReference> frames)
{
return CreateVolumeCore(frames.Select(f => f.Frame).ToList());
}
/// <summary>
/// Creates a reference to a cached MPR volume based on the specified source frames.
/// </summary>
public ICachedVolumeReference GetVolumeReference(IEnumerable<Frame> frames)
{
return CreateVolumeCore(frames.ToList());
}
private ICachedVolumeReference CreateVolumeCore(IList<Frame> frames)
{
var cacheKey = new CacheKey(frames);
lock (_syncRoot)
{
CachedVolume cachedItem;
if (!_cache.TryGetValue(cacheKey, out cachedItem) || cachedItem.IsDisposed)
_cache[cacheKey] = cachedItem = new CachedVolume(this, cacheKey, frames);
return cachedItem.CreateReference(); // always return a new counted reference to the cache item
}
}
private void RemoveVolumeCore(CacheKey cacheKey, CachedVolume cachedItem)
{
lock (_syncRoot)
{
// cached volume is an orphan because viewer was closed, so just ignore this command
if (_cache == null) return;
// double check identity of item being removed, in case it's already been recreated before the previous item's dispose finishes
CachedVolume realItem;
if (_cache.TryGetValue(cacheKey, out realItem) && ReferenceEquals(realItem, cachedItem))
_cache.Remove(cacheKey);
}
}
#region Unit Test Support
#if UNIT_TESTS
public int Count
{
get { return _cache.Count; }
}
public bool IsCached(IDisplaySet displaySet)
{
return IsCached(displaySet.PresentationImages.Cast<IImageSopProvider>().Select(i => i.Frame).ToList());
}
public bool IsCached(IEnumerable<Frame> frames)
{
return _cache.ContainsKey(new CacheKey(frames.ToList()));
}
internal static volatile bool ThrowAsyncVolumeLoadException;
#endif
#endregion
/// <summary>
/// Cache item acting as a container for the volume and source frames.
/// </summary>
private class CachedVolume : VolumeHeaderBase, ICachedVolume, ILargeObjectContainer
{
private readonly object _syncRoot = new object();
private readonly CacheKey _cacheKey;
private readonly VolumeCache _cacheOwner;
private readonly VolumeHeaderData _volumeHeaderData;
private IList<IFrameReference> _frames;
private volatile IVolumeReference _volumeReference;
private bool _isDisposed = false;
private readonly SynchronizedEventHelper _progressChanged = new SynchronizedEventHelper();
private volatile float _progress = 0;
public CachedVolume(VolumeCache cacheOwner, CacheKey cacheKey, IEnumerable<Frame> frames)
{
_cacheOwner = cacheOwner;
_cacheKey = cacheKey;
_frames = frames.Select(f => f.CreateTransientReference()).ToList();
_volumeHeaderData = Volume.BuildHeader(_frames);
}
/// <summary>
/// Called when all references to the cached item are destroyed, and thus all held source frames and volume can be released.
/// </summary>
private void Dispose()
{
MemoryManager.Remove(this);
// this method is executed on a worker thread after no one else has a reference to this except maybe the memory manager
// so we lock it so that we don't accidentally dispose the real volume simultaneously from different threads
// blocking here isn't a big deal since we're also on a worker thread
lock (_syncRoot)
{
if (_volumeReference != null)
{
_volumeReference.Dispose();
_volumeReference = null;
}
}
if (_frames != null)
{
foreach (var frameReference in _frames)
frameReference.Dispose();
_frames.Clear();
_frames = null;
}
}
public Guid Identifier
{
get { return _cacheKey.Guid; }
}
public Volume Volume
{
get
{
AssertNotDisposed();
_largeObjectContainerData.UpdateLastAccessTime();
return LoadCore(null);
}
}
protected override VolumeHeaderData VolumeHeaderData
{
get { return _volumeHeaderData; }
}
private bool IsLoaded
{
get
{
AssertNotDisposed();
return _volumeReference != null;
}
}
private void Load(VolumeLoadProgressCallback callback = null)
{
AssertNotDisposed();
LoadCore(callback);
}
private float Progress
{
get { return _progress; }
set
{
_progress = value;
_progressChanged.Fire(this, new EventArgs());
}
}
private Volume LoadCore(VolumeLoadProgressCallback callback)
{
// TODO (CR Apr 2013): Same comment as with Fusion - shouldn't actually need to lock for
// the duration of volume creation. Should be enough to set a _loading flag, exit the lock,
// then re-enter the lock to reset the _loading flag and set any necessary fields.
// Locking for the duration means the memory manager could get hung up while trying to unload
// a big volume that is in the process of being created.
lock (_syncRoot)
{
if (_volumeReference != null) return _volumeReference.Volume;
Progress = 0;
using (var volume = Volume.Create(_frames, (n, total) =>
{
Progress = Math.Min(100f, 100f*n/total);
if (callback != null) callback.Invoke(this, n, total);
_largeObjectContainerData.UpdateLastAccessTime();
#if UNIT_TESTS
if (ThrowAsyncVolumeLoadException)
{
ThrowAsyncVolumeLoadException = false;
throw new CreateVolumeException("User manually triggered exception");
}
#endif
}))
{
_volumeReference = volume.CreateReference();
_largeObjectContainerData.LargeObjectCount = 1;
_largeObjectContainerData.BytesHeldCount = 2*volume.ArrayLength;
_largeObjectContainerData.UpdateLastAccessTime();
MemoryManager.Add(this);
}
Progress = 100f;
return _volumeReference.Volume;
}
}
public void Unload()
{
if (_volumeReference == null) return;
if (_largeObjectContainerData.IsLocked) return;
lock (_syncRoot)
{
if (_volumeReference == null) return;
if (_largeObjectContainerData.IsLocked) return;
Progress = 0;
MemoryManager.Remove(this);
_largeObjectContainerData.LargeObjectCount = 0;
_largeObjectContainerData.BytesHeldCount = 0;
// in general, this would be the only transient reference to the volume
// we can't stop external code from calling CreateTransientReference() too
// but if they did, the volume wouldn't really release here anyway, so that external code would still work
_volumeReference.Dispose();
_volumeReference = null;
}
}
private void AssertNotDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(typeof (CachedVolume).FullName, "Cached volume has already been disposed!");
}
#region Asynchronous Loader
private readonly object _backgroundLoadSyncRoot = new object();
private Task _backgroundLoadTask;
// TODO (CR Apr 2013): the reason this is overloaded is because there's not always a task to return. Would be better
// to return some other object, possibly with the task as a property, but also with the volume itself, if it's available.
private Task LoadAsync(VolumeLoadProgressCallback onProgress = null, VolumeLoadCompletionCallback onComplete = null, VolumeLoadErrorCallback onError = null)
{
AssertNotDisposed();
// TODO (CR Apr 2013): Not a good idea to return nothing; why not return a struct with the volume in it?
if (_volumeReference != null) return null;
if (_backgroundLoadTask != null) return _backgroundLoadTask;
lock (_backgroundLoadSyncRoot)
{
if (_volumeReference != null) return null;
if (_backgroundLoadTask != null) return _backgroundLoadTask;
_backgroundLoadTask = new Task(() => LoadCore(onProgress));
_backgroundLoadTask.ContinueWith(t =>
{
// TODO (CR Apr 2013): Can probably just lock the part that
// changes the _backgroundLoadTask variable.
lock (_backgroundLoadSyncRoot)
{
if (t.IsFaulted && t.Exception != null)
{
var ex = t.Exception.Flatten().InnerExceptions.FirstOrDefault();
if (onError != null)
onError.Invoke(this, ex);
else
Platform.Log(LogLevel.Warn, ex, "Unhandled exception thrown in background volume loader");
}
else
{
if (onComplete != null)
onComplete.Invoke(this);
}
if (ReferenceEquals(t, _backgroundLoadTask))
{
_backgroundLoadTask.Dispose();
_backgroundLoadTask = null;
}
}
});
_backgroundLoadTask.Start();
return _backgroundLoadTask;
}
}
#endregion
#region CachedVolume References
private readonly object _referenceSyncRoot = new object();
private int _referenceCount = 0;
public ICachedVolumeReference CreateReference()
{
AssertNotDisposed();
return new CachedVolumeReference(this);
}
public bool IsDisposed
{
get
{
lock (_referenceSyncRoot)
{
return _isDisposed;
}
}
}
private void IncrementReferenceCount()
{
lock (_referenceSyncRoot)
{
++_referenceCount;
}
}
private void DecrementReferenceCount()
{
lock (_referenceSyncRoot)
{
--_referenceCount;
if (_referenceCount == 0)
{
// we don't want to block too long especially if the calling code is disposing the LAST reference
// so just mark this as disposed and queue up a task to actually perform uncaching and disposal
// no one else should have a reference to this anyway, and the cache checks the disposed property too
_isDisposed = true;
ThreadPool.QueueUserWorkItem(s =>
{
_cacheOwner.RemoveVolumeCore(_cacheKey, this);
Dispose();
}, null);
}
}
}
private class CachedVolumeReference : VolumeHeaderBase, ICachedVolumeReference
{
private CachedVolume _cachedVolume;
private bool _locked;
public CachedVolumeReference(CachedVolume cachedVolume)
{
cachedVolume.IncrementReferenceCount();
_cachedVolume = cachedVolume;
_cachedVolume._progressChanged.AddHandler(CachedVolumeOnProgressChanged);
}
public void Dispose()
{
if (_cachedVolume != null)
{
if (_locked) _cachedVolume.Unlock();
_cachedVolume._progressChanged.RemoveHandler(CachedVolumeOnProgressChanged);
_cachedVolume.DecrementReferenceCount();
_cachedVolume = null;
}
}
protected override VolumeHeaderData VolumeHeaderData
{
get { return _cachedVolume._volumeHeaderData; }
}
private void CachedVolumeOnProgressChanged(object sender, EventArgs eventArgs)
{
EventsHelper.Fire(ProgressChanged, this, eventArgs);
}
public Guid Identifier
{
get { return _cachedVolume.Identifier; }
}
public Volume Volume
{
get { return _cachedVolume.Volume; }
}
public event EventHandler ProgressChanged;
public float Progress
{
get { return _cachedVolume.Progress; }
}
public bool IsLoaded
{
get { return _cachedVolume.IsLoaded; }
}
// TODO (CR Apr 2013): API is a bit overloaded; the task provides completion and error info already
// so probably all that is needed is the progress callback argument.
public Task LoadAsync(VolumeLoadProgressCallback onProgress = null, VolumeLoadCompletionCallback onComplete = null, VolumeLoadErrorCallback onError = null)
{
return _cachedVolume.LoadAsync(onProgress, onComplete, onError);
}
public void Load(VolumeLoadProgressCallback callback = null)
{
_cachedVolume.Load(callback);
}
public void Lock()
{
// although the actual cached volume uses counts number of active locks on the data,
// the cached volume reference is intended to be created and disposed frequently
// and each reference should only be held by one entity and not shared
// thus we allow only one lock from each reference instance
// and disposal of reference guarantees the release of that one lock
if (!_locked) _cachedVolume.Lock();
_locked = true;
}
public void Unlock()
{
if (_locked) _cachedVolume.Unlock();
_locked = false;
}
public ICachedVolumeReference CreateReference()
{
return new CachedVolumeReference(_cachedVolume);
}
IVolumeReference IVolumeReference.Clone()
{
return CreateReference();
}
public override int GetHashCode()
{
return 0;
}
private bool Equals(CachedVolumeReference other)
{
return ReferenceEquals(_cachedVolume, other._cachedVolume);
}
public override bool Equals(object obj)
{
return obj is CachedVolumeReference && Equals((CachedVolumeReference) obj);
}
}
#endregion
#region Implementation of ILargeObjectContainer
private readonly LargeObjectContainerData _largeObjectContainerData = new LargeObjectContainerData(Guid.NewGuid()) {RegenerationCost = LargeObjectContainerData.PresetComputedData};
Guid ILargeObjectContainer.Identifier
{
get { return _largeObjectContainerData.Identifier; }
}
public int LargeObjectCount
{
get { return _largeObjectContainerData.LargeObjectCount; }
}
public long BytesHeldCount
{
get { return _largeObjectContainerData.BytesHeldCount; }
}
public DateTime LastAccessTime
{
get { return _largeObjectContainerData.LastAccessTime; }
}
public RegenerationCost RegenerationCost
{
get { return _largeObjectContainerData.RegenerationCost; }
}
public bool IsLocked
{
get { return _largeObjectContainerData.IsLocked; }
}
public void Lock()
{
_largeObjectContainerData.Lock();
}
public void Unlock()
{
_largeObjectContainerData.Unlock();
}
#endregion
}
private struct CacheKey : IEquatable<CacheKey>
{
private readonly Guid _hash;
private readonly long _length;
public CacheKey(IList<Frame> frames)
: this()
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
var firstFrame = frames.FirstOrDefault();
if (firstFrame != null)
{
writer.WriteLine(firstFrame.ParentImageSop.PatientId);
writer.WriteLine(firstFrame.ParentImageSop.PatientsName);
writer.WriteLine(firstFrame.ParentImageSop.StudyInstanceUid);
writer.WriteLine(firstFrame.ParentImageSop.SeriesInstanceUid);
foreach (var f in frames)
writer.WriteLine("{0}:{1}", f.SopInstanceUid, f.FrameNumber);
}
_length = stream.Length;
stream.Position = 0;
_hash = HashUtilities.ComputeHashGuid(stream);
}
}
public Guid Guid
{
get { return _hash; }
}
public override int GetHashCode()
{
return 0x3351E935 ^ _hash.GetHashCode();
}
public bool Equals(CacheKey other)
{
return _hash.Equals(other._hash) && _length.Equals(other._length);
}
public override bool Equals(object obj)
{
return obj is CacheKey && Equals((CacheKey) obj);
}
public override string ToString()
{
return _hash.ToString();
}
}
}
} | testdoron/ClearCanvas | ImageViewer/Volumes/VolumeCache.cs | C# | gpl-3.0 | 27,676 |
/*!
*
* Super simple wysiwyg editor v0.8.16
* https://summernote.org
*
*
* Copyright 2013- Alan Hong. and other contributors
* summernote may be freely distributed under the MIT license.
*
* Date: 2020-02-19T09:12Z
*
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else {
var a = factory();
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 10);
/******/ })
/************************************************************************/
/******/ ({
/***/ 10:
/***/ (function(module, exports) {
(function ($) {
$.extend($.summernote.lang, {
'ca-ES': {
font: {
bold: 'Negreta',
italic: 'Cursiva',
underline: 'Subratllat',
clear: 'Treure estil de lletra',
height: 'Alçada de línia',
name: 'Font',
strikethrough: 'Ratllat',
subscript: 'Subíndex',
superscript: 'Superíndex',
size: 'Mida de lletra'
},
image: {
image: 'Imatge',
insert: 'Inserir imatge',
resizeFull: 'Redimensionar a mida completa',
resizeHalf: 'Redimensionar a la meitat',
resizeQuarter: 'Redimensionar a un quart',
floatLeft: 'Alinear a l\'esquerra',
floatRight: 'Alinear a la dreta',
floatNone: 'No alinear',
shapeRounded: 'Forma: Arrodonit',
shapeCircle: 'Forma: Cercle',
shapeThumbnail: 'Forma: Marc',
shapeNone: 'Forma: Cap',
dragImageHere: 'Arrossegueu una imatge o text aquí',
dropImage: 'Deixa anar aquí una imatge o un text',
selectFromFiles: 'Seleccioneu des dels arxius',
maximumFileSize: 'Mida màxima de l\'arxiu',
maximumFileSizeError: 'La mida màxima de l\'arxiu s\'ha superat.',
url: 'URL de la imatge',
remove: 'Eliminar imatge',
original: 'Original'
},
video: {
video: 'Vídeo',
videoLink: 'Enllaç del vídeo',
insert: 'Inserir vídeo',
url: 'URL del vídeo?',
providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion o Youku)'
},
link: {
link: 'Enllaç',
insert: 'Inserir enllaç',
unlink: 'Treure enllaç',
edit: 'Editar',
textToDisplay: 'Text per mostrar',
url: 'Cap a quina URL porta l\'enllaç?',
openInNewWindow: 'Obrir en una finestra nova'
},
table: {
table: 'Taula',
addRowAbove: 'Add row above',
addRowBelow: 'Add row below',
addColLeft: 'Add column left',
addColRight: 'Add column right',
delRow: 'Delete row',
delCol: 'Delete column',
delTable: 'Delete table'
},
hr: {
insert: 'Inserir línia horitzontal'
},
style: {
style: 'Estil',
p: 'p',
blockquote: 'Cita',
pre: 'Codi',
h1: 'Títol 1',
h2: 'Títol 2',
h3: 'Títol 3',
h4: 'Títol 4',
h5: 'Títol 5',
h6: 'Títol 6'
},
lists: {
unordered: 'Llista desendreçada',
ordered: 'Llista endreçada'
},
options: {
help: 'Ajut',
fullscreen: 'Pantalla sencera',
codeview: 'Veure codi font'
},
paragraph: {
paragraph: 'Paràgraf',
outdent: 'Menys tabulació',
indent: 'Més tabulació',
left: 'Alinear a l\'esquerra',
center: 'Alinear al mig',
right: 'Alinear a la dreta',
justify: 'Justificar'
},
color: {
recent: 'Últim color',
more: 'Més colors',
background: 'Color de fons',
foreground: 'Color de lletra',
transparent: 'Transparent',
setTransparent: 'Establir transparent',
reset: 'Restablir',
resetToDefault: 'Restablir per defecte'
},
shortcut: {
shortcuts: 'Dreceres de teclat',
close: 'Tancar',
textFormatting: 'Format de text',
action: 'Acció',
paragraphFormatting: 'Format de paràgraf',
documentStyle: 'Estil del document',
extraKeys: 'Tecles adicionals'
},
help: {
'insertParagraph': 'Inserir paràgraf',
'undo': 'Desfer l\'última acció',
'redo': 'Refer l\'última acció',
'tab': 'Tabular',
'untab': 'Eliminar tabulació',
'bold': 'Establir estil negreta',
'italic': 'Establir estil cursiva',
'underline': 'Establir estil subratllat',
'strikethrough': 'Establir estil ratllat',
'removeFormat': 'Netejar estil',
'justifyLeft': 'Alinear a l\'esquerra',
'justifyCenter': 'Alinear al centre',
'justifyRight': 'Alinear a la dreta',
'justifyFull': 'Justificar',
'insertUnorderedList': 'Inserir llista desendreçada',
'insertOrderedList': 'Inserir llista endreçada',
'outdent': 'Reduïr tabulació del paràgraf',
'indent': 'Augmentar tabulació del paràgraf',
'formatPara': 'Canviar l\'estil del bloc com a un paràgraf (etiqueta P)',
'formatH1': 'Canviar l\'estil del bloc com a un H1',
'formatH2': 'Canviar l\'estil del bloc com a un H2',
'formatH3': 'Canviar l\'estil del bloc com a un H3',
'formatH4': 'Canviar l\'estil del bloc com a un H4',
'formatH5': 'Canviar l\'estil del bloc com a un H5',
'formatH6': 'Canviar l\'estil del bloc com a un H6',
'insertHorizontalRule': 'Inserir una línia horitzontal',
'linkDialog.show': 'Mostrar panel d\'enllaços'
},
history: {
undo: 'Desfer',
redo: 'Refer'
},
specialChar: {
specialChar: 'CARÀCTERS ESPECIALS',
select: 'Selecciona caràcters especials'
}
}
});
})(jQuery);
/***/ })
/******/ });
}); | rhomicom-systems-tech-gh/Rhomicom-ERP-Web | self/cs/plugins/summernote/lang/summernote-ca-ES.js | JavaScript | gpl-3.0 | 9,499 |
(function() {var implementors = {};
implementors["dbus"] = [];
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
| servo/doc.servo.org | implementors/dbus/objpath/trait.PropertyROHandler.js | JavaScript | mpl-2.0 | 281 |
/*
Built by: build_media_element_js.rake
from https://github.com/johndyer/mediaelement.git
revision: ceeb1a7f41b2557c4f6a865cee5564c82039201d
YOU SHOULDN'T EDIT ME DIRECTLY
*/
define(['jquery'], function (jQuery){
/*!
*
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2014, John Dyer (http://j.hn)
* License: MIT
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.16.4';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube', 'application/x-mpegURL']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube', 'audio/youtube', 'audio/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo', 'video/x-vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
codePath = '',
testname = '',
slashPos,
filenamePos,
scriptUrl,
scriptPath,
scriptFilename,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
// go through all <script> tags
for (; i < il; i++) {
scriptUrl = scripts[i].src;
slashPos = scriptUrl.lastIndexOf('/');
if (slashPos > -1) {
scriptFilename = scriptUrl.substring(slashPos + 1);
scriptPath = scriptUrl.substring(0, slashPos + 1);
} else {
scriptFilename = scriptUrl;
scriptPath = '';
}
// see if any <script> tags have a file name that matches the
for (j = 0; j < jl; j++) {
testname = scriptNames[j];
filenamePos = scriptFilename.indexOf(testname);
if (filenamePos > -1) {
codePath = scriptPath;
break;
}
}
// if we found a path, then break and return it
if (codePath !== '') {
break;
}
}
// send the best path back
return codePath;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && /object|embed/i.test(obj.nodeName)) {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isBustedNativeHTTPS = (location.protocol === 'https:' && (ua.match(/android [12]\./) !== null || ua.match(/macintosh.* version.* safari/) !== null));
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1 || nav.appName.toLowerCase().match(/trident/gi) !== null);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isChromium = (ua.match(/chromium/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit && !t.isIE;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window); // && window.ontouchstart != null); // this breaks iOS 7
// borrowed from Modernizr
t.svg = !! document.createElementNS &&
!! document.createElementNS('http://www.w3.org/2000/svg','svg').createSVGRect;
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// Fix for IE9 on Windows 7N / Windows 7KN (Media Player not installer)
try{
v.canPlayType("video/mp4");
}catch(e){
t.supportsMediaTag = false;
}
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// W3C
t.hasNativeFullscreen = (typeof v.requestFullscreen !== 'undefined');
// webkit/firefox/IE11+
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasMsNativeFullScreen = (typeof v.msRequestFullscreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen || t.hasMsNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
// Enabled?
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = document.mozFullScreenEnabled;
} else if (t.hasMsNativeFullScreen) {
t.nativeFullScreenEnabled = document.msFullscreenEnabled;
}
if (t.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = '';
if (t.hasWebkitNativeFullScreen) {
t.fullScreenEventName = 'webkitfullscreenchange';
} else if (t.hasMozNativeFullScreen) {
t.fullScreenEventName = 'mozfullscreenchange';
} else if (t.hasMsNativeFullScreen) {
t.fullScreenEventName = 'MSFullscreenChange';
}
t.isFullScreen = function() {
if (t.hasMozNativeFullScreen) {
return d.mozFullScreen;
} else if (t.hasWebkitNativeFullScreen) {
return d.webkitIsFullScreen;
} else if (t.hasMsNativeFullScreen) {
return d.msFullscreenElement !== null;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
} else if (t.hasMsNativeFullScreen) {
el.msRequestFullscreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
} else if (t.hasMsNativeFullScreen) {
document.msExitFullscreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
break;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
this.attributes = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return 'probably';
}
}
}
}
return '';
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(Math.floor(x),Math.floor(y),visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
break;
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if (this.pluginElement && this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (var i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(this, args);
}
}
},
// end: fake events
// fake DOM attribute methods
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
mejs.MediaPluginBridge.unregisterPluginElement(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
unregisterPluginElement: function (id) {
delete this.pluginMediaElements[id];
delete this.htmlMediaElements[id];
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
if(!pluginMediaElement){
return;
}
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// use plugin for browsers that have trouble with Basic Authentication on HTTPS sites
httpsBasicAuthSite: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// enabled pseudo-streaming (seek) on .mp4 files
enablePseudoStreaming: false,
// start query parameter sent to server for pseudo-streaming
pseudoStreamingStartQueryParam: 'start',
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy,
media;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
media = n.getAttribute('media');
if (!media || !window.matchMedia || (window.matchMedia && window.matchMedia(media).matches)) {
mediaFiles.push({type:type, url:src});
}
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// special case for Chromium to specify natively supported video codecs (i.e. WebM and Theora)
if (mejs.MediaFeatures.isChromium) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(webm|ogv|ogg)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native') && !(mejs.MediaFeatures.isBustedNativeHTTPS && options.httpsBasicAuthSite === true)) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (mediaFiles[i].type == "video/m3u8" || htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== ''
// special case for m4a supported by detecting mp4 support
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/m4a/,'mp4')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
url = url.split('?')[0];
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
return (/(mp4|m4v|ogg|ogv|m3u8|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
case 'm4a':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
if (options.customError) {
errorContainer.innerHTML = options.customError;
} else {
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>' + mejs.i18n.t('Download File') + '</span></a>';
}
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() !== 'body' && node.parentNode != null) {
if (node.parentNode.tagName.toLowerCase() === 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.pluginWidth > 0) ? options.pluginWidth : (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.pluginHeight > 0) ? options.pluginHeight : (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'jsinitfunction=' + "mejs.MediaPluginBridge.initPlugin",
'jscallbackfunction=' + "mejs.MediaPluginBridge.fireEvent",
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height,
'pseudostreamstart=' + options.pseudoStreamingStartQueryParam];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (options.enablePseudoStreaming) {
initVars.push('pseudostreaming=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '" class="mejs-shim">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '" class="mejs-shim">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'<param name="scale" value="default" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '" ' +
'scale="default"' +
'class="mejs-shim"></embed>';
}
break;
case 'youtube':
var videoId;
// youtu.be url from share button
if (playback.url.lastIndexOf("youtu.be") != -1) {
videoId = playback.url.substr(playback.url.lastIndexOf('/')+1);
if (videoId.indexOf('?') != -1) {
videoId = videoId.substr(0, videoId.indexOf('?'));
}
}
else {
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
}
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
var player_id = pluginid + "_player";
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML ='<iframe src="//player.vimeo.com/video/' + pluginMediaElement.vimeoid + '?api=1&portrait=0&byline=0&title=0&player_id=' + player_id + '" width="' + width +'" height="' + height +'" frameborder="0" class="mejs-shim" id="' + player_id + '" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
if (typeof($f) == 'function') { // froogaloop available
var player = $f(container.childNodes[0]);
player.addEvent('ready', function() {
player.playVideo = function() {
player.api( 'play' );
}
player.stopVideo = function() {
player.api( 'unload' );
}
player.pauseVideo = function() {
player.api( 'pause' );
}
player.seekTo = function( seconds ) {
player.api( 'seekTo', seconds );
}
player.setVolume = function( volume ) {
player.api( 'setVolume', volume );
}
player.setMuted = function( muted ) {
if( muted ) {
player.lastVolume = player.api( 'getVolume' );
player.api( 'setVolume', 0 );
} else {
player.api( 'setVolume', player.lastVolume );
delete player.lastVolume;
}
}
function createEvent(player, pluginMediaElement, eventName, e) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (eventName == 'timeupdate') {
pluginMediaElement.currentTime = obj.currentTime = e.seconds;
pluginMediaElement.duration = obj.duration = e.duration;
}
pluginMediaElement.dispatchEvent(obj.type, obj);
}
player.addEvent('play', function() {
createEvent(player, pluginMediaElement, 'play');
createEvent(player, pluginMediaElement, 'playing');
});
player.addEvent('pause', function() {
createEvent(player, pluginMediaElement, 'pause');
});
player.addEvent('finish', function() {
createEvent(player, pluginMediaElement, 'ended');
});
player.addEvent('playProgress', function(e) {
createEvent(player, pluginMediaElement, 'timeupdate', e);
});
pluginMediaElement.pluginElement = container;
pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(pluginid);
});
}
else {
console.warn("You need to include froogaloop for vimeo to work");
}
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// prevent browser from autoplaying when using a plugin
htmlMediaElement.removeAttribute('autoplay');
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; " class="mejs-shim">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = '//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '" class="mejs-shim">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; " class="mejs-shim">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback';
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'canplay');
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
/*
* Adds Internationalization and localization to mediaelement.
*
* This file does not contain translations, you have to add them manually.
* The schema is always the same: me-i18n-locale-[IETF-language-tag].js
*
* Examples are provided both for german and chinese translation.
*
*
* What is the concept beyond i18n?
* http://en.wikipedia.org/wiki/Internationalization_and_localization
*
* What langcode should i use?
* http://en.wikipedia.org/wiki/IETF_language_tag
* https://tools.ietf.org/html/rfc5646
*
*
* License?
*
* The i18n file uses methods from the Drupal project (drupal.js):
* - i18n.methods.t() (modified)
* - i18n.methods.checkPlain() (full copy)
*
* The Drupal project is (like mediaelementjs) licensed under GPLv2.
* - http://drupal.org/licensing/faq/#q1
* - https://github.com/johndyer/mediaelement
* - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
*
* @author
* Tim Latz (latz.tim@gmail.com)
*
*
* @params
* - context - document, iframe ..
* - exports - CommonJS, window ..
*
*/
;(function(context, exports, undefined) {
"use strict";
var i18n = {
"locale": {
// Ensure previous values aren't overwritten.
"language" : (exports.i18n && exports.i18n.locale.language) || '',
"strings" : (exports.i18n && exports.i18n.locale.strings) || {}
},
"ietf_lang_regex" : /^(x\-)?[a-z]{2,}(\-\w{2,})?(\-\w{2,})?$/,
"methods" : {}
};
// start i18n
/**
* Get language, fallback to browser's language if empty
*
* IETF: RFC 5646, https://tools.ietf.org/html/rfc5646
* Examples: en, zh-CN, cmn-Hans-CN, sr-Latn-RS, es-419, x-private
*/
i18n.getLanguage = function () {
var language = i18n.locale.language || window.navigator.userLanguage || window.navigator.language;
return i18n.ietf_lang_regex.exec(language) ? language : null;
//(WAS: convert to iso 639-1 (2-letters, lower case))
//return language.substr(0, 2).toLowerCase();
};
// i18n fixes for compatibility with WordPress
if ( typeof mejsL10n != 'undefined' ) {
i18n.locale.language = mejsL10n.language;
}
/**
* Encode special characters in a plain-text string for display as HTML.
*/
i18n.methods.checkPlain = function (str) {
var character, regex,
replace = {
'&': '&',
'"': '"',
'<': '<',
'>': '>'
};
str = String(str);
for (character in replace) {
if (replace.hasOwnProperty(character)) {
regex = new RegExp(character, 'g');
str = str.replace(regex, replace[character]);
}
}
return str;
};
/**
* Translate strings to the page language or a given language.
*
*
* @param str
* A string containing the English string to translate.
*
* @param options
* - 'context' (defaults to the default context): The context the source string
* belongs to.
*
* @return
* The translated string, escaped via i18n.methods.checkPlain()
*/
i18n.methods.t = function (str, options) {
// Fetch the localized version of the string.
if (i18n.locale.strings && i18n.locale.strings[options.context] && i18n.locale.strings[options.context][str]) {
str = i18n.locale.strings[options.context][str];
}
return i18n.methods.checkPlain(str);
};
/**
* Wrapper for i18n.methods.t()
*
* @see i18n.methods.t()
* @throws InvalidArgumentException
*/
i18n.t = function(str, options) {
if (typeof str === 'string' && str.length > 0) {
// check every time due language can change for
// different reasons (translation, lang switcher ..)
var language = i18n.getLanguage();
options = options || {
"context" : language
};
return i18n.methods.t(str, options);
}
else {
throw {
"name" : 'InvalidArgumentException',
"message" : 'First argument is either not a string or empty.'
};
}
};
// end i18n
exports.i18n = i18n;
}(document, mejs));
// i18n fixes for compatibility with WordPress
;(function(exports, undefined) {
"use strict";
if ( typeof mejsL10n != 'undefined' ) {
exports[mejsL10n.language] = mejsL10n.strings;
}
}(mejs.i18n.locale.strings));
/*!
*
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2013, John Dyer (http://j.hn/)
* License: MIT
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// When the video is ended, we can show the poster.
showPosterWhenEnded: false,
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// set dimensions via JS instead of CSS
setDimensions: true,
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// rewind to beginning when media ends
autoRewind: true,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// Display the video control
hideVideoControlsOnLoad: false,
// Enable click video element to toggle play/pause
clickToPlayPause: true,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
player.play();
} else {
player.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
player.container.find('.mejs-volume-slider').css('display','block');
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
player.container.find('.mejs-volume-slider').css('display','block');
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // F
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
},
{
keys: [77], // M
action: function(player, media) {
player.container.find('.mejs-volume-slider').css('display','block');
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = {};
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// add to player array (for focus events)
mejs.players[t.id] = t;
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.play();
}
} else if (mf.isAndroid && t.options.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
var videoPlayerTitle = t.isVideo ?
mejs.i18n.t('Video Player') : mejs.i18n.t('Audio Player');
// insert description for screen readers
$('<span class="mejs-offscreen">' + videoPlayerTitle + '</span>').insertBefore(t.$media);
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container ' + (mejs.MediaFeatures.svg ? 'svg' : 'no-svg') +
'" tabindex="0" role="application" aria-label="' + videoPlayerTitle + '">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media)
.focus(function ( e ) {
if( !t.controlsAreVisible ) {
t.showControls(true);
var playButton = t.container.find('.mejs-playpause-button > button');
playButton.focus();
}
});
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0];
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.width;
meOptions.pluginHeight = t.height;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
if (typeof(t.container) != 'undefined' && t.controlsAreVisible){
// controls are shown when loaded
t.container.trigger('controlsshown');
}
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {
t.controlsAreVisible = true;
t.container.trigger('controlsshown');
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
t.container.trigger('controlsshown');
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible || t.options.alwaysShowControls || t.keyboardAction)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
t.container.trigger('controlshidden');
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
t.container.trigger('controlshidden');
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created) {
return;
} else {
t.created = true;
}
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// create callback here since it needs access to current
// MediaElement object
t.clickToPlayPauseCallback = function() {
//
if (t.options.clickToPlayPause) {
if (t.media.paused) {
t.play();
} else {
t.pause();
}
}
};
// click to play/pause
t.media.addEventListener('click', t.clickToPlayPauseCallback, false);
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls ) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
if(t.options.hideVideoControlsOnLoad) {
t.hideControls(false);
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
var playerIndex;
// go through all other players
for (playerIndex in mejs.players) {
var p = mejs.players[playerIndex];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
if(t.options.autoRewind) {
try{
t.media.setCurrentTime(0);
// Fixing an Android stock browser bug, where "seeked" isn't fired correctly after ending the video and jumping to the beginning
window.setTimeout(function(){
$(t.container).find('.mejs-overlay-loading').parent().hide();
}, 20);
} catch (exp) {
}
}
t.media.pause();
if (t.setProgressRail) {
t.setProgressRail();
}
if (t.setCurrentRail) {
t.setCurrentRail();
}
if (t.options.loop) {
t.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
t.container.focusout(function (e) {
if( e.relatedTarget ) { //FF is working on supporting focusout https://bugzilla.mozilla.org/show_bug.cgi?id=687787
var $target = $(e.relatedTarget);
if (t.keyboardAction && $target.parents('.mejs-container').length === 0) {
t.keyboardAction = false;
t.hideControls(true);
}
}
});
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
t.globalBind('resize', function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// This is a work-around for a bug in the YouTube iFrame player, which means
// we can't use the play() API for the initial playback on iOS or Android;
// user has to start playback directly by tapping on the iFrame.
if (t.media.pluginType == 'youtube' && ( mf.isiOS || mf.isAndroid ) ) {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
t.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if( !t.options.setDimensions ) {
return false;
}
if (typeof width != 'undefined') {
t.width = width;
}
if (typeof height != 'undefined') {
t.height = height;
}
// detect 100% mode - use currentStyle for IE since css() doesn't return percentages
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%' || (t.$node[0].currentStyle && t.$node[0].currentStyle.maxWidth === '100%')) {
// do we have the native dimensions yet?
var nativeWidth = (function() {
if (t.isVideo) {
if (t.media.videoWidth && t.media.videoWidth > 0) {
return t.media.videoWidth;
} else if (t.media.getAttribute('width') !== null) {
return t.media.getAttribute('width');
} else {
return t.options.defaultVideoWidth;
}
} else {
return t.options.defaultAudioWidth;
}
})();
var nativeHeight = (function() {
if (t.isVideo) {
if (t.media.videoHeight && t.media.videoHeight > 0) {
return t.media.videoHeight;
} else if (t.media.getAttribute('height') !== null) {
return t.media.getAttribute('height');
} else {
return t.options.defaultVideoHeight;
}
} else {
return t.options.defaultAudioHeight;
}
})();
var
parentWidth = t.container.parent().closest(':visible').width(),
parentHeight = t.container.parent().closest(':visible').height(),
newHeight = t.isVideo || !t.options.autosizeProgress ? parseInt(parentWidth * nativeHeight/nativeWidth, 10) : nativeHeight;
// When we use percent, the newHeight can't be calculated so we get the container height
if (isNaN(newHeight)) {
newHeight = parentHeight;
}
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight && parentWidth ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video> or <audio> and shims
t.$media.add(t.container.find('.mejs-shim'))
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
// special case for big play button so it doesn't go over the controls area
var playLayer = t.layers.find('.mejs-overlay-play'),
playButton = playLayer.find('.mejs-overlay-button');
playLayer.height(t.container.height() - t.controls.height());
playButton.css('margin-top', '-' + (playButton.height()/2 - t.controls.height()/2).toString() + 'px' );
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings(),
lastControl = others.last(),
lastControlPosition = null;
// skip calculation if hidden
if (!t.container.is(':visible') || !rail.length || !rail.is(':visible')) {
return;
}
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'), 10);
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
var $this = $(this);
if ($this.css('position') != 'absolute' && $this.is(':visible')) {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// resize the rail,
// but then check if the last control (say, the fullscreen button) got pushed down
// this often happens when zoomed
do {
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (lastControl.css('position') != 'absolute') {
lastControlPosition = lastControl.position();
railWidth--;
}
} while (lastControlPosition !== null && lastControlPosition.top > 0 && railWidth > 0);
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if ( posterUrl ) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
if(player.options.showPosterWhenEnded && player.options.autoRewind){
media.addEventListener('ended',function() {
poster.show();
}, false);
}
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length === 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
posterDiv.css({'background-image' : 'url(' + url + ')'});
},
buildoverlays: function(player, controls, layers, media) {
var t = this;
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.bind('click', function() { // Removed 'touchstart' due issues on Samsung Android devices where a tap on bigPlay started and immediately stopped the video
if (t.options.clickToPlayPause) {
if (media.paused) {
media.play();
}
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
// Firing the 'canplay' event after a timeout which isn't getting fired on some Android 4.1 devices (https://github.com/johndyer/mediaelement/issues/1305)
if (mejs.MediaFeatures.isAndroid) {
media.canplayTimeout = window.setTimeout(
function() {
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent('canplay', true, true);
return media.dispatchEvent(evt);
}
}, 300
);
}
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
clearTimeout(media.canplayTimeout); // Clear timeout inside 'loadeddata' to prevent 'canplay' to fire twice
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
media.addEventListener('keydown', function(e) {
t.onkeydown(player, media, e);
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
t.container.keydown(function () {
t.keyboardAction = true;
});
// listen for key presses
t.globalBind('keydown', function(e) {
return t.onkeydown(player, media, e);
});
// check if someone clicked outside a player region, then kill its focus
t.globalBind('click', function(event) {
player.hasFocus = $(event.target).closest('.mejs-container').length !== 0;
});
},
onkeydown: function(player, media, e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i = 0, il = player.options.keyActions.length; i < il; i++) {
var keyAction = player.options.keyActions[i];
for (var j = 0, jl = keyAction.keys.length; j < jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
if (typeof(e.preventDefault) == "function") e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: (track.attr('srclang')) ? track.attr('srclang').toLowerCase() : '',
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.load();
this.media.play();
},
pause: function() {
try {
this.media.pause();
} catch (e) {}
},
load: function() {
if (!this.isLoaded) {
this.media.load();
}
this.isLoaded = true;
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this, featureIndex, feature;
// invoke features cleanup
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['clean' + feature]) {
try {
t['clean' + feature](t);
} catch (e) {
// TODO: report control error
//throw e;
//
//
}
}
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$media.prop('controls', true);
// detach events from the video
// TODO: detach event listeners better than this;
// also detach ONLY the events attached by this plugin!
t.$node.clone().insertBefore(t.container).show();
t.$node.remove();
} else {
t.$node.insertBefore(t.container);
}
if (t.media.pluginType !== 'native') {
t.media.remove();
}
// Remove the player from the mejs.players object so that pauseOtherPlayers doesn't blow up when trying to pause a non existance flash api.
delete mejs.players[t.id];
if (typeof t.container == 'object') {
t.container.remove();
}
t.globalUnbind();
delete t.node.player;
},
rebuildtracks: function(){
var t = this;
t.findTracks();
t.buildtracks(t, t.controls, t.layers, t.media);
}
};
(function(){
var rwindow = /^((after|before)print|(before)?unload|hashchange|message|o(ff|n)line|page(hide|show)|popstate|resize|storage)\b/;
function splitEvents(events, id) {
// add player ID as an event namespace so it's easier to unbind them all later
var ret = {d: [], w: []};
$.each((events || '').split(' '), function(k, v){
var eventname = v + '.' + id;
if (eventname.indexOf('.') === 0) {
ret.d.push(eventname);
ret.w.push(eventname);
}
else {
ret[rwindow.test(v) ? 'w' : 'd'].push(eventname);
}
});
ret.d = ret.d.join(' ');
ret.w = ret.w.join(' ');
return ret;
}
mejs.MediaElementPlayer.prototype.globalBind = function(events, data, callback) {
var t = this;
events = splitEvents(events, t.id);
if (events.d) $(document).bind(events.d, data, callback);
if (events.w) $(window).bind(events.w, data, callback);
};
mejs.MediaElementPlayer.prototype.globalUnbind = function(events, callback) {
var t = this;
events = splitEvents(events, t.id);
if (events.d) $(document).unbind(events.d, callback);
if (events.w) $(window).unbind(events.w, callback);
};
})();
// turn into jQuery plugin
if (typeof $ != 'undefined') {
$.fn.mediaelementplayer = function (options) {
if (options === false) {
this.each(function () {
var player = $(this).data('mediaelementplayer');
if (player) {
player.remove();
}
$(this).removeData('mediaelementplayer');
});
}
else {
this.each(function () {
$(this).data('mediaelementplayer', new mejs.MediaElementPlayer(this, options));
});
}
return this;
};
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
}
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playText: mejs.i18n.t('Play'),
pauseText: mejs.i18n.t('Pause')
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
op = t.options,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + op.playText + '" aria-label="' + op.playText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
}),
play_btn = play.find('button');
function togglePlayPause(which) {
if ('play' === which) {
play.removeClass('mejs-play').addClass('mejs-pause');
play_btn.attr({
'title': op.pauseText,
'aria-label': op.pauseText
});
} else {
play.removeClass('mejs-pause').addClass('mejs-play');
play_btn.attr({
'title': op.playText,
'aria-label': op.playText
});
}
};
togglePlayPause('pse');
media.addEventListener('play',function() {
togglePlayPause('play');
}, false);
media.addEventListener('playing',function() {
togglePlayPause('play');
}, false);
media.addEventListener('pause',function() {
togglePlayPause('pse');
}, false);
media.addEventListener('paused',function() {
togglePlayPause('pse');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '" aria-label="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
media.pause();
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
progessHelpText: mejs.i18n.t(
'Use Left/Right Arrow keys to advance one second, Up/Down arrows to advance ten seconds.')
});
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">' +
'<span class="mejs-time-total mejs-time-slider">' +
//'<span class="mejs-offscreen">' + this.options.progessHelpText + '</span>' +
'<span class="mejs-time-buffering"></span>' +
'<span class="mejs-time-loaded"></span>' +
'<span class="mejs-time-current"></span>' +
'<span class="mejs-time-handle"></span>' +
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>' +
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
slider = controls.find('.mejs-time-slider'),
handleMouseMove = function (e) {
var offset = total.offset(),
width = total.outerWidth(true),
percentage = 0,
newTime = 0,
pos = 0,
x;
// mouse or touch position relative to the object
if (e.originalEvent.changedTouches) {
x = e.originalEvent.changedTouches[0].pageX;
}else{
x = e.pageX;
}
if (media.duration) {
if (x < offset.left) {
x = offset.left;
} else if (x > width + offset.left) {
x = width + offset.left;
}
pos = x - offset.left;
percentage = (pos / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown && newTime !== media.currentTime) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false,
lastKeyPressTime = 0,
startedPaused = false,
autoRewindInitial = player.options.autoRewind;
// Accessibility for slider
var updateSlider = function (e) {
var seconds = media.currentTime,
timeSliderText = mejs.i18n.t('Time Slider'),
time = mejs.Utility.secondsToTimeCode(seconds),
duration = media.duration;
slider.attr({
'aria-label': timeSliderText,
'aria-valuemin': 0,
'aria-valuemax': duration,
'aria-valuenow': seconds,
'aria-valuetext': time,
'role': 'slider',
'tabindex': 0
});
};
var restartPlayer = function () {
var now = new Date();
if (now - lastKeyPressTime >= 1000) {
media.play();
}
};
slider.bind('focus', function (e) {
player.options.autoRewind = false;
});
slider.bind('blur', function (e) {
player.options.autoRewind = autoRewindInitial;
});
slider.bind('keydown', function (e) {
if ((new Date() - lastKeyPressTime) >= 1000) {
startedPaused = media.paused;
}
var keyCode = e.keyCode,
duration = media.duration,
seekTime = media.currentTime;
switch (keyCode) {
case 37: // left
seekTime -= 1;
break;
case 39: // Right
seekTime += 1;
break;
case 38: // Up
seekTime += Math.floor(duration * 0.1);
break;
case 40: // Down
seekTime -= Math.floor(duration * 0.1);
break;
case 36: // Home
seekTime = 0;
break;
case 35: // end
seekTime = duration;
break;
case 10: // enter
media.paused ? media.play() : media.pause();
return;
case 13: // space
media.paused ? media.play() : media.pause();
return;
default:
return;
}
seekTime = seekTime < 0 ? 0 : (seekTime >= duration ? duration : Math.floor(seekTime));
lastKeyPressTime = new Date();
if (!startedPaused) {
media.pause();
}
if (seekTime < media.duration && !startedPaused) {
setTimeout(restartPlayer, 1100);
}
media.setCurrentTime(seekTime);
e.preventDefault();
e.stopPropagation();
return false;
});
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown touchstart', function (e) {
// only handle left clicks or touch
if (e.which === 1 || e.which === 0) {
mouseIsDown = true;
handleMouseMove(e);
t.globalBind('mousemove.dur touchmove.dur', function(e) {
handleMouseMove(e);
});
t.globalBind('mouseup.dur touchend.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
t.globalUnbind('.dur');
});
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
t.globalBind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
t.globalUnbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
updateSlider(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e !== undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal !== undefined && target.bytesTotal > 0 && target.bufferedBytes !== undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total !== 0) {
percent = e.loaded / e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime !== undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = Math.round(t.total.width() * t.media.currentTime / t.media.duration),
handlePos = newWidth - Math.round(t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: '<span> | </span>'
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time" role="timer" aria-live="off">' +
'<span class="mejs-currenttime">' +
(player.options.alwaysShowHours ? '00:' : '') +
(player.options.showTimecodeFrameCount? '00:00:00':'00:00') +
'</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
//Toggle the long video class if the video is longer than an hour.
t.container.toggleClass("mejs-long-video", t.media.duration > 3600);
if (t.durationD && (t.options.duration > 0 || t.media.duration)) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.options.duration > 0 ? t.options.duration : t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: mejs.i18n.t('Mute Toggle'),
allyVolumeControlText: mejs.i18n.t('Use Up/Down Arrow keys to increase or decrease volume.'),
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if ((mejs.MediaFeatures.isAndroid || mejs.MediaFeatures.isiOS) && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">' +
'<button type="button" aria-controls="' + t.id +
'" title="' + t.options.muteText +
'" aria-label="' + t.options.muteText +
'"></button>'+
'</div>' +
'<a href="javascript:void(0);" class="mejs-horizontal-volume-slider">' + // outer background
'<span class="mejs-offscreen">' + t.options.allyVolumeControlText + '</span>' +
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</a>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id +
'" title="' + t.options.muteText +
'" aria-label="' + t.options.muteText +
'"></button>'+
'<a href="javascript:void(0);" class="mejs-volume-slider">'+ // outer background
'<span class="mejs-offscreen">' + t.options.allyVolumeControlText + '</span>' +
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</a>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry == 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide();
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume === 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// top/left of full size volume slider background
var totalPosition = volumeTotal.position();
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', Math.round(totalPosition.top + newTop - (volumeHandle.height() / 2)));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', Math.round(totalPosition.left + newLeft - (volumeHandle.width() / 2)));
// rezize the current part of the volume bar
volumeCurrent.width( Math.round(newLeft) );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode === 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top === 0 || totalOffset.left === 0) {
return;
}
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume === 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
var updateVolumeSlider = function (e) {
var volume = Math.floor(media.volume*100);
volumeSlider.attr({
'aria-label': mejs.i18n.t('volumeSlider'),
'aria-valuemin': 0,
'aria-valuemax': 100,
'aria-valuenow': volume,
'aria-valuetext': volume+'%',
'role': 'slider',
'tabindex': 0
});
};
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
t.globalBind('mousemove.vol', function(e) {
handleVolumeMove(e);
});
t.globalBind('mouseup.vol', function () {
mouseIsDown = false;
t.globalUnbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
})
.bind('keydown', function (e) {
var keyCode = e.keyCode;
var volume = media.volume;
switch (keyCode) {
case 38: // Up
volume += 0.1;
break;
case 40: // Down
volume = volume - 0.1;
break;
default:
return true;
}
mouseIsDown = false;
positionVolumeHandle(volume);
media.setVolume(volume);
return false;
})
.bind('blur', function () {
volumeSlider.hide();
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
//Keyboard input
mute.find('button').bind('focus', function () {
volumeSlider.show();
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
updateVolumeSlider(e);
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// mutes the media and sets the volume icon muted if the initial volume is set to 0
if (player.options.startVolume === 0) {
media.setMuted(true);
}
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: mejs.i18n.t('Fullscreen')
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var func = function(e) {
if (player.isFullScreen) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
}
};
player.globalBind(mejs.MediaFeatures.fullScreenEventName, func);
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '" aria-label="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
for (var i in hoverDivs) {
hoverDivs[i].hide();
}
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// prevent clicks from pausing video
t.media.removeEventListener('click', t.clickToPlayPauseCallback);
// store for later
fullscreenIsDisabled = false;
}
},
hoverDivs = {},
hoverDivNames = ['top', 'left', 'right', 'bottom'],
i, len,
positionHoverDivs = function() {
var fullScreenBtnOffsetLeft = fullscreenBtn.offset().left - t.container.offset().left,
fullScreenBtnOffsetTop = fullscreenBtn.offset().top - t.container.offset().top,
fullScreenBtnWidth = fullscreenBtn.outerWidth(true),
fullScreenBtnHeight = fullscreenBtn.outerHeight(true),
containerWidth = t.container.width(),
containerHeight = t.container.height();
for (i in hoverDivs) {
hoverDivs[i].css({position: 'absolute', top: 0, left: 0}); //, backgroundColor: '#f00'});
}
// over video, but not controls
hoverDivs['top']
.width( containerWidth )
.height( fullScreenBtnOffsetTop );
// over controls, but not the fullscreen button
hoverDivs['left']
.width( fullScreenBtnOffsetLeft )
.height( fullScreenBtnHeight )
.css({top: fullScreenBtnOffsetTop});
// after the fullscreen button
hoverDivs['right']
.width( containerWidth - fullScreenBtnOffsetLeft - fullScreenBtnWidth )
.height( fullScreenBtnHeight )
.css({top: fullScreenBtnOffsetTop,
left: fullScreenBtnOffsetLeft + fullScreenBtnWidth});
// under the fullscreen button
hoverDivs['bottom']
.width( containerWidth )
.height( containerHeight - fullScreenBtnHeight - fullScreenBtnOffsetTop )
.css({top: fullScreenBtnOffsetTop + fullScreenBtnHeight});
};
t.globalBind('resize', function() {
positionHoverDivs();
});
for (i = 0, len = hoverDivNames.length; i < len; i++) {
hoverDivs[hoverDivNames[i]] = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls).hide();
}
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn.on('mouseover',function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// restore click-to-play
t.media.addEventListener('click', t.clickToPlayPauseCallback);
// show the divs that will restore things
for (i in hoverDivs) {
hoverDivs[i].show();
}
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
t.isFullScreen = !t.isFullScreen;
// don't allow plugin click to pause video - messes with
// plugin's controls
if (t.isFullScreen) {
t.media.removeEventListener('click', t.clickToPlayPauseCallback);
} else {
t.media.addEventListener('click', t.clickToPlayPauseCallback);
}
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
t.globalBind('mousemove', function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.on('mouseover', function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.on('mouseout', function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
t.globalBind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
cleanfullscreen: function(player) {
player.exitFullScreen();
},
containerSizeTimeout: null,
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// set it to not show scroll bars so 100% will work
$(document.documentElement).addClass('mejs-fullscreen');
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
var zoomMultiplier = window["devicePixelRatio"] || 1;
// Use a percent error margin since devicePixelRatio is a float and not exact.
var percentErrorMargin = 0.002; // 0.2%
var windowWidth = zoomMultiplier * $(window).width();
var screenWidth = screen.width;
var absDiff = Math.abs(screenWidth - windowWidth);
var marginError = screenWidth * percentErrorMargin;
// check if the video is suddenly not really fullscreen
if (absDiff > marginError) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.containerSizeTimeout = setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.media.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('.mejs-shim')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
t.container.find('.mejs-captions-text').css('font-size', screen.width / t.width * 1.00 * 100 + '%');
t.container.find('.mejs-captions-position').css('bottom', '45px');
},
exitFullScreen: function() {
var t = this;
// Prevent container from attempting to stretch a second time
clearTimeout(t.containerSizeTimeout);
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
$(document.documentElement).removeClass('mejs-fullscreen');
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.media.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('.mejs-shim')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
t.container.find('.mejs-captions-text').css('font-size','');
t.container.find('.mejs-captions-position').css('bottom', '');
}
});
})(mejs.$);
//
// mep-feature-tracks.js with instructure customizations
//
// to see the diff, run:
//
// upstream_url='https://raw.githubusercontent.com/johndyer/mediaelement/743f4465231dc20e6f9e96a5cb8b9d5299ceddd3/src/js/mep-feature-tracks.js'
// diff -bu \
// <(curl -s "${upstream_url}") \
// public/javascripts/mediaelement/mep-feature-tracks-instructure.js
//
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: mejs.i18n.t('Captions/Subtitles'),
// option to remove the [cc] button when no <track kind="subtitles"> are present
hideCaptionsButtonWhenEmpty: true,
// If true and we only have one track, change captions to popup
toggleCaptionsButtonWhenOnlyOne: false,
// #id or .class
slidesSelector: ''
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
// INSTRUCTURE added code (the '&& !player.options.can_add_captions' part)
if (player.tracks.length == 0 && !player.options.can_add_captions)
return;
var t = this,
i,
options = '';
if (t.domNode.textTracks) { // if browser will do native captions, prefer mejs captions, loop through tracks and hide
for (var i = t.domNode.textTracks.length - 1; i >= 0; i--) {
t.domNode.textTracks[i].mode = "hidden";
}
}
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position mejs-captions-position-hover"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '" aria-label="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">' + mejs.i18n.t('None') +'</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls);
var subtitleCount = 0;
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
subtitleCount++;
}
}
// if only one language then just make the button a toggle
if (t.options.toggleCaptionsButtonWhenOnlyOne && subtitleCount == 1){
// click
player.captionsButton.on('click',function() {
if (player.selectedTrack == null) {
var lang = player.tracks[0].srclang;
} else {
var lang = 'none';
}
player.setTrack(lang);
});
} else {
// hover
player.captionsButton.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.on('click','input[type=radio]',function() {
lang = this.value;
player.setTrack(lang);
});
}
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('controlsshown', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('controlshidden', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
// INSTRUCTURE added third src argument
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label, player.tracks[i].src);
}
}
// INSTRUCTURE added code
if (player.options.can_add_captions) player.addUploadTrackButton();
// start loading tracks
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
if (player.options.slidesSelector != '') {
player.slidesContainer = $(player.options.slidesSelector);
media.addEventListener('timeupdate',function(e) {
player.displaySlides();
}, false);
}
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
setTrack: function(lang){
var t = this,
i;
if (lang == 'none') {
t.selectedTrack = null;
t.captionsButton.removeClass('mejs-captions-enabled');
} else {
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].srclang == lang) {
if (t.selectedTrack == null)
t.captionsButton.addClass('mejs-captions-enabled');
t.selectedTrack = t.tracks[i];
t.captions.attr('lang', t.selectedTrack.srclang);
t.displayCaptions();
break;
}
}
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
t.checkForTracks();
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters') {
t.media.addEventListener('play', function(e) {
if (t.media.duration > 0) {
t.displayChapters(track);
}
}, false);
}
if (track.kind == 'slides') {
t.setupSlides(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
// INSTRUCTURE added code
addUploadTrackButton: function() {
var t = this;
$('<a href="#" style="color:white">Upload subtitles</a>')
.appendTo(t.captionsButton.find('ul'))
.wrap('<li>')
.click(function(e){
e.preventDefault();
require(['compiled/widget/UploadMediaTrackForm'], function(UploadMediaTrackForm){
new UploadMediaTrackForm(t.options.mediaCommentId, t.media.src);
});
});
t.adjustLanguageBox();
},
// INSTRUCTURE added src argument
addTrackButton: function(lang, label, src) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
// INSTRUCTURE added code
var deleteButtonHtml = '';
if (t.options.can_add_captions) {
deleteButtonHtml = '<a href="#" data-remove="li" data-confirm="Are you sure you want to delete this track?" data-url="' + src + '">×</a>';
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
// INSTRUCTURE added code
deleteButtonHtml +
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
checkForTracks: function() {
var
t = this,
hasSubtitles = false;
// check if any subtitles
if (t.options.hideCaptionsButtonWhenEmpty) {
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'subtitles') {
hasSubtitles = true;
break;
}
}
// INSTRUCTURE added code (second half of conditional)
if (!hasSubtitles && !t.options.can_add_captions) {
t.captionsButton.hide();
t.setControlsSize();
}
}
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
setupSlides: function(track) {
var t = this;
t.slides = track;
t.slides.entries.imgs = [t.slides.entries.text.length];
t.showSlide(0);
},
showSlide: function(index) {
if (typeof this.tracks == 'undefined' || typeof this.slidesContainer == 'undefined') {
return;
}
var t = this,
url = t.slides.entries.text[index],
img = t.slides.entries.imgs[index];
if (typeof img == 'undefined' || typeof img.fadeIn == 'undefined') {
t.slides.entries.imgs[index] = img = $('<img src="' + url + '">')
.on('load', function() {
img.appendTo(t.slidesContainer)
.hide()
.fadeIn()
.siblings(':visible')
.fadeOut();
});
} else {
if (!img.is(':visible') && !img.is(':animated')) {
//
img.fadeIn()
.siblings(':visible')
.fadeOut();
}
}
},
displaySlides: function() {
if (typeof this.slides == 'undefined')
return;
var
t = this,
slides = t.slides,
i;
for (i=0; i<slides.entries.times.length; i++) {
if (t.media.currentTime >= slides.entries.times[i].start && t.media.currentTime <= slides.entries.times[i].stop){
t.showSlide(i);
return; // exit out if one is visible;
}
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
//
// Playback speed control is based on code from an as-yet-unmerged pull request to mediaelement.js
// See: https://github.com/matthillman/mediaelement/commit/e9efc9473ca38c240b712a11ba4c035651c204d4
// And: https://github.com/johndyer/mediaelement/pull/1249
//
(function($) {
// Speed
$.extend(mejs.MepDefaults, {
// INSTRUCTURE CUSTOMIZATION: adjust default available speeds
speeds: ['2.00', '1.50', '1.00', '0.75', '0.50'],
defaultSpeed: '1.00'
});
$.extend(MediaElementPlayer.prototype, {
// INSTRUCTURE CUSTOMIZATION - pulling latest definition of isIE from ME.js master with IE11 fixes
isIE: function() {
return (window.navigator.appName.match(/microsoft/gi) !== null) || (window.navigator.userAgent.match(/trident/gi) !== null);
},
buildspeed: function(player, controls, layers, media) {
// INSTRUCTURE CUSTOMIZATION: enable playback speed controls for both audio and video
// if (!player.isVideo)
// return;
var t = this;
if (t.media.pluginType !== 'native') { return; }
var s = '<div class="mejs-button mejs-speed-button"><button type="button">'+t.options.defaultSpeed+'x</button><div class="mejs-speed-selector"><ul>';
var i, ss;
if ($.inArray(t.options.defaultSpeed, t.options.speeds) === -1) {
t.options.speeds.push(t.options.defaultSpeed);
}
t.options.speeds.sort(function(a, b) {
return parseFloat(b) - parseFloat(a);
});
for (i = 0; i < t.options.speeds.length; i++) {
s += '<li>';
if (t.options.speeds[i] === t.options.defaultSpeed) {
s += '<label class="mejs-speed-selected">'+ t.options.speeds[i] + 'x';
s += '<input type="radio" name="speed" value="' + t.options.speeds[i] + '" checked=true />';
} else {
s += '<label>'+ t.options.speeds[i] + 'x';
s += '<input type="radio" name="speed" value="' + t.options.speeds[i] + '" />';
}
s += '</label></li>';
}
s += '</ul></div></div>';
player.speedButton = $(s).appendTo(controls);
player.playbackspeed = t.options.defaultSpeed;
player.$media.on('loadedmetadata', function() {
media.playbackRate = parseFloat(player.playbackspeed);
});
player.speedButton.on('click', 'input[type=radio]', function() {
player.playbackspeed = $(this).attr('value');
media.playbackRate = parseFloat(player.playbackspeed);
player.speedButton.find('button').text(player.playbackspeed + 'x');
player.speedButton.find('.mejs-speed-selected').removeClass('mejs-speed-selected');
player.speedButton.find('input[type=radio]:checked').parent().addClass('mejs-speed-selected');
//
// INSTRUCTURE CUSTOMIZATION - IE fixes
//
if (t.isIE()) {
// After playback completes, IE will reset the rate to the
// defaultPlaybackRate of 1.00 (with the UI still reflecting the
// selected value) unless we set defaultPlaybackRate as well.
media.defaultPlaybackRate = media.playbackRate;
// Internet Explorer fires a 'waiting' event in addition to the
// 'ratechange' event when the playback speed is changed, even though
// the HTML5 standard says not to. >_<
//
// Even worse, the 'waiting' state does not resolve with any other
// event that would indicate that we are done waiting, like 'playing'
// or 'seeked', so we are left with nothing to hook on but ye olde
// arbitrary point in the future.
$(media).one('waiting', function() {
setTimeout(function() {
layers.find('.mejs-overlay-loading').parent().hide();
controls.find('.mejs-time-buffering').hide();
}, 500);
});
}
});
ss = player.speedButton.find('.mejs-speed-selector');
ss.height(this.speedButton.find('.mejs-speed-selector ul').outerHeight(true) + player.speedButton.find('.mejs-speed-translations').outerHeight(true));
ss.css('top', (-1 * ss.height()) + 'px');
}
});
})(mejs.$);
// Source Chooser Plugin
(function($) {
$.extend(mejs.MepDefaults, {
sourcechooserText: 'Source Chooser'
});
$.extend(MediaElementPlayer.prototype, {
buildsourcechooser: function(player, controls, layers, media) {
if (!player.isVideo) { return; }
var t = this;
player.sourcechooserButton =
$('<div class="mejs-button mejs-sourcechooser-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.sourcechooserText + '" aria-label="' + t.options.sourcechooserText + '"></button>'+
'<div class="mejs-sourcechooser-selector">'+
'<ul>'+
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-sourcechooser-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-sourcechooser-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.on('click', 'input[type=radio]', function() {
if (media.currentSrc === this.value) { return; }
var src = this.value;
var currentTime = media.currentTime;
var wasPlaying = !media.paused;
$(media).one('loadedmetadata', function() {
media.setCurrentTime(currentTime);
});
$(media).one('canplay', function() {
if (wasPlaying) {
media.play();
}
});
media.setSrc(src);
media.load();
});
// add to list
for (var i in this.node.children) {
var src = this.node.children[i];
if (src.nodeName === 'SOURCE' && (media.canPlayType(src.type) === 'probably' || media.canPlayType(src.type) === 'maybe')) {
player.addSourceButton(src.src, src.title, src.type, media.src === src.src);
}
}
},
addSourceButton: function(src, label, type, isCurrent) {
var t = this;
if (label === '' || label === undefined) {
label = src;
}
type = type.split('/')[1];
t.sourcechooserButton.find('ul').append(
$('<li>'+
'<label>' +
'<input type="radio" name="' + t.id + '_sourcechooser" value="' + src + '" ' + (isCurrent ? 'checked="checked"' : '') + ' />' +
label + ' (' + type + ')</label>' +
'</li>')
);
t.adjustSourcechooserBox();
},
adjustSourcechooserBox: function() {
var t = this;
// adjust the size of the outer box
t.sourcechooserButton.find('.mejs-sourcechooser-selector').height(
t.sourcechooserButton.find('.mejs-sourcechooser-selector ul').outerHeight(true)
);
}
});
})(mejs.$);
/*
* Google Analytics Plugin
* Requires
*
*/
(function($) {
$.extend(mejs.MepDefaults, {
googleAnalyticsTitle: '',
googleAnalyticsCategory: 'Videos',
googleAnalyticsEventPlay: 'Play',
googleAnalyticsEventPause: 'Pause',
googleAnalyticsEventEnded: 'Ended',
googleAnalyticsEventTime: 'Time'
});
$.extend(MediaElementPlayer.prototype, {
buildgoogleanalytics: function(player, controls, layers, media) {
media.addEventListener('play', function() {
if (typeof _gaq != 'undefined') {
_gaq.push(['_trackEvent',
player.options.googleAnalyticsCategory,
player.options.googleAnalyticsEventPlay,
(player.options.googleAnalyticsTitle === '') ? player.currentSrc : player.options.googleAnalyticsTitle
]);
}
}, false);
media.addEventListener('pause', function() {
if (typeof _gaq != 'undefined') {
_gaq.push(['_trackEvent',
player.options.googleAnalyticsCategory,
player.options.googleAnalyticsEventPause,
(player.options.googleAnalyticsTitle === '') ? player.currentSrc : player.options.googleAnalyticsTitle
]);
}
}, false);
media.addEventListener('ended', function() {
if (typeof _gaq != 'undefined') {
_gaq.push(['_trackEvent',
player.options.googleAnalyticsCategory,
player.options.googleAnalyticsEventEnded,
(player.options.googleAnalyticsTitle === '') ? player.currentSrc : player.options.googleAnalyticsTitle
]);
}
}, false);
/*
media.addEventListener('timeupdate', function() {
if (typeof _gaq != 'undefined') {
_gaq.push(['_trackEvent',
player.options.googleAnalyticsCategory,
player.options.googleAnalyticsEventEnded,
player.options.googleAnalyticsTime,
(player.options.googleAnalyticsTitle === '') ? player.currentSrc : player.options.googleAnalyticsTitle,
player.currentTime
]);
}
}, true);
*/
}
});
})(mejs.$);
return mejs;
});
| shidao-fm/canvas-lms | public/javascripts/vendor/mediaelement-and-player.js | JavaScript | agpl-3.0 | 158,652 |
// CloudCoder - a web-based pedagogical programming environment
// Copyright (C) 2011-2012, Jaime Spacco <jspacco@knox.edu>
// Copyright (C) 2011-2012, David H. Hovemeyer <david.hovemeyer@gmail.com>
// Copyright (C) 2014, York College of Pennsylvania
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package org.cloudcoder.app.client.view;
import org.cloudcoder.app.client.model.Session;
import org.cloudcoder.app.client.page.SessionObserver;
import org.cloudcoder.app.shared.model.Problem;
import org.cloudcoder.app.shared.util.Publisher;
import org.cloudcoder.app.shared.util.Subscriber;
import org.cloudcoder.app.shared.util.SubscriptionRegistrar;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.ResizeComposite;
/**
* View to display the problem description.
*
* @author David Hovemeyer
*/
public class ProblemDescriptionView extends ResizeComposite implements SessionObserver, Subscriber {
/** Preferred width of the ProblemDescriptionView. */
public static final double DEFAULT_WIDTH_PX = 400.0;
private HTML problemDescriptionHtml;
public ProblemDescriptionView() {
LayoutPanel layoutPanel = new LayoutPanel();
problemDescriptionHtml = new HTML("", true);
layoutPanel.add(problemDescriptionHtml);
problemDescriptionHtml.setStyleName("cc-problemDescription");
layoutPanel.setWidgetLeftRight(problemDescriptionHtml, 0.0, Unit.PX, 0.0, Unit.PX);
layoutPanel.setWidgetTopBottom(problemDescriptionHtml, 0.0, Unit.PX, 0.0, Unit.PX);
initWidget(layoutPanel);
}
public void activate(Session session, SubscriptionRegistrar subscriptionRegistrar) {
session.subscribe(Session.Event.ADDED_OBJECT, this, subscriptionRegistrar);
Problem problem = session.get(Problem.class);
if (problem != null) {
displayProblemDescription(problem);
}
}
@Override
public void eventOccurred(Object key, Publisher publisher, Object hint) {
if (key == Session.Event.ADDED_OBJECT && hint instanceof Problem) {
Problem problem = (Problem) hint;
displayProblemDescription(problem);
}
}
public void displayProblemDescription(Problem problem) {
// Note: if the problem description contains HTML markup, it will
// be rendered. This is intentional, since it allows a greater degree
// of control over formatting that just plain text would allow.
StringBuilder buf = new StringBuilder();
String description = problem.getDescription();
// Add the description as specified in the problem.
buf.append(description);
// Add author information.
buf.append("<div class=\"cc-authorInfo\">Author: <span class=\"cc-authorName\">");
String authorName = problem.getAuthorName();
String authorWebsite = problem.getAuthorWebsite();
if (!authorWebsite.trim().equals("")) {
// Format author name as link to author website
buf.append("<a href=\"");
buf.append(new SafeHtmlBuilder().appendEscaped(authorWebsite).toSafeHtml().asString());
buf.append("\">");
buf.append(new SafeHtmlBuilder().appendEscaped(authorName).toSafeHtml().asString());
buf.append("</a>");
} else {
// No author website
buf.append(new SafeHtmlBuilder().appendEscaped(authorName).toSafeHtml().asString());
}
// Add license information.
buf.append("</span><br>License: <span class=\"cc-problemLicense\"><a href=\"");
buf.append(problem.getLicense().getUrl());
buf.append("\">");
buf.append(problem.getLicense().getName());
buf.append("</a></span>");
buf.append("</span>");
buf.append("</div>");
problemDescriptionHtml.setHTML(buf.toString());
}
}
| cloudcoderdotorg/CloudCoder | CloudCoder/src/org/cloudcoder/app/client/view/ProblemDescriptionView.java | Java | agpl-3.0 | 4,321 |
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace NHibernate.Cfg.MappingSchema
{
public partial class HbmOneToOne : AbstractDecoratable, IEntityPropertyMapping, IFormulasMapping, IRelationship
{
#region Implementation of IEntityPropertyMapping
public string Name
{
get { return name; }
}
public string Access
{
get { return access; }
}
public bool OptimisticLock
{
get { return true; }
}
#endregion
#region Overrides of AbstractDecoratable
protected override HbmMeta[] Metadatas
{
get { return meta ?? Array.Empty<HbmMeta>(); }
}
#endregion
#region Implementation of IFormulasMapping
[XmlIgnore]
public IEnumerable<HbmFormula> Formulas
{
get { return formula ?? AsFormulas(); }
}
private IEnumerable<HbmFormula> AsFormulas()
{
if (string.IsNullOrEmpty(formula1))
{
yield break;
}
else
{
yield return new HbmFormula { Text = new[] { formula1 } };
}
}
#endregion
#region Implementation of IRelationship
public string EntityName
{
get { return entityname; }
}
public string Class
{
get { return @class; }
}
public HbmNotFoundMode NotFoundMode
{
get { return HbmNotFoundMode.Exception; }
}
#endregion
public HbmLaziness? Lazy
{
get { return lazySpecified ? lazy : (HbmLaziness?)null; }
}
public bool IsLazyProperty
{
get { return Lazy == HbmLaziness.Proxy; }
}
}
}
| RogerKratz/nhibernate-core | src/NHibernate/Cfg/MappingSchema/HbmOneToOne.cs | C# | lgpl-2.1 | 1,466 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.permission;
import org.apache.commons.lang.StringUtils;
import org.picocontainer.annotations.Nullable;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.util.RubyUtils;
import java.util.List;
import java.util.Map;
public class ApplyPermissionTemplateQuery {
private static final String TEMPLATE_KEY = "template_key";
private static final String COMPONENTS_KEY = "components";
private final String templateKey;
private List<String> selectedComponents;
private ApplyPermissionTemplateQuery(@Nullable String templateKey) {
this.templateKey = templateKey;
}
public static ApplyPermissionTemplateQuery buildFromParams(Map<String, Object> params) {
ApplyPermissionTemplateQuery query = new ApplyPermissionTemplateQuery((String)params.get(TEMPLATE_KEY));
query.setSelectedComponents(RubyUtils.toStrings(params.get(COMPONENTS_KEY)));
return query;
}
public String getTemplateKey() {
return templateKey;
}
public List<String> getSelectedComponents() {
return selectedComponents;
}
public void validate() {
if(StringUtils.isBlank(templateKey)) {
throw new BadRequestException("Permission template is mandatory");
}
if(selectedComponents == null || selectedComponents.isEmpty()) {
throw new BadRequestException("Please provide at least one entry to which the permission template should be applied");
}
}
private void setSelectedComponents(List<String> selectedComponents) {
this.selectedComponents = selectedComponents;
}
}
| julien-sobczak/sonarqube | server/sonar-server/src/main/java/org/sonar/server/permission/ApplyPermissionTemplateQuery.java | Java | lgpl-3.0 | 2,452 |
/*
* $Id: InvalidPathException.java 471754 2006-11-06 14:55:09Z husted $
*
* 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.struts.chain.commands;
/**
* <p>Exception thrown when no mapping can be found for the specified
* path.</p>
*
* @version $Rev: 471754 $ $Date: 2005-11-05 21:44:59 -0500 (Sat, 05 Nov 2005)
* $
*/
public class InvalidPathException extends Exception {
/**
* Field for Path property.
*/
private String path;
/**
* <p> Default, no-argument constructor. </p>
*/
public InvalidPathException() {
super();
}
/**
* <p> Constructor to inject message and path upon instantiation. </p>
*
* @param message The error or warning message.
* @param path The invalid path.
*/
public InvalidPathException(String message, String path) {
super(message);
this.path = path;
}
/**
* <p> Return the invalid path causing the exception. </p>
*
* @return The invalid path causing the exception.
*/
public String getPath() {
return path;
}
}
| lbndev/sonarqube | tests/upgrade/projects/struts-1.3.9-diet/core/src/main/java/org/apache/struts/chain/commands/InvalidPathException.java | Java | lgpl-3.0 | 1,876 |
// Todo: make autodate an option in the CiteTemplate object, not a preference
// Global object
if (typeof CiteTB == 'undefined') {
var CiteTB = {
"Templates" : {}, // All templates
"Options" : {}, // Global options
"UserOptions" : {}, // User options
"DefaultOptions" : {}, // Script defaults
"ErrorChecks" : {} // Error check functions
};
}
// only load on edit, unless its a user JS/CSS page
if ((wgAction == 'edit' || wgAction == 'submit') && !((wgNamespaceNumber == 2 || wgNamespaceNumber == 4) &&
(wgPageName.indexOf('.js') != -1 || wgPageName.indexOf('.css') != -1 ))) {
appendCSS(".cite-form-td {"+
"height: 0 !important;"+
"padding: 0.1em !important;"+
"}");
// Default options, these mainly exist so the script won't break if a new option is added
CiteTB.DefaultOptions = {
"date format" : "<year>-<zmonth>-<zdate>",
"autodate fields" : [],
"months" : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
"modal" : true,
"autoparse" : false,
"expandtemplates": false
};
// Get an option - user settings override global which override defaults
CiteTB.getOption = function(opt) {
if (CiteTB.UserOptions[opt] != undefined) {
return CiteTB.UserOptions[opt];
} else if (CiteTB.Options[opt] != undefined) {
return CiteTB.Options[opt];
}
return CiteTB.DefaultOptions[opt];
}
CiteTB.init = function() {
/* Main stuff, build the actual toolbar structure
* 1. get the template list, make the dropdown list and set up the template dialog boxes
* 2. actually build the toolbar:
* * A section for cites
* ** dropdown for the templates (previously defined)
* ** button for named refs with a dialog box
* ** button for errorcheck
* 3. add the whole thing to the main toolbar
*/
if (typeof $j('div[rel=cites]')[0] != 'undefined') { // Mystery IE bug workaround
return;
}
$j('head').trigger('reftoolbarbase');
var $target = $j('#wpTextbox1');
var temlist = {};
var d = new Date();
var start = d.getTime();
for (var t in CiteTB.Templates) {
var tem = CiteTB.Templates[t];
sform = CiteTB.escStr(tem.shortform);
var actionobj = {
type: 'dialog',
module: 'cite-dialog-'+sform
};
var dialogobj = {};
dialogobj['cite-dialog-'+sform] = {
resizeme: false,
titleMsg: 'cite-dialog-'+sform,
id: 'citetoolbar-'+sform,
init: function() {},
html: tem.getInitial(),
dialog: {
width:675,
open: function() {
$j(this).html(CiteTB.getOpenTemplate().getForm());
$j('.cite-prev-parse').bind( 'click', CiteTB.prevParseClick);
},
beforeclose: function() {
CiteTB.resetForm();
},
buttons: {
'cite-form-submit': function() {
$j.wikiEditor.modules.toolbar.fn.doAction( $j(this).data( 'context' ), {
type: 'encapsulate',
options: {
peri: ' '
}
}, $j(this) );
var ref = CiteTB.getRef(false, true);
$j(this).dialog( 'close' );
$j.wikiEditor.modules.toolbar.fn.doAction( $j(this).data( 'context' ), {
type: 'encapsulate',
options: {
pre: ref
}
}, $j(this) );
},
'cite-form-showhide': CiteTB.showHideExtra,
'cite-refpreview': function() {
var ref = CiteTB.getRef(false, false);
var template = CiteTB.getOpenTemplate();
var div = $j("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.find('.cite-preview-label').show();
div.find('.cite-ref-preview').text(ref).show();
if (CiteTB.getOption('autoparse')) {
CiteTB.prevParseClick();
} else {
div.find('.cite-prev-parse').show();
div.find('.cite-prev-parsed-label').hide();
div.find('.cite-preview-parsed').html('');
}
},
'wikieditor-toolbar-tool-link-cancel': function() {
$j(this).dialog( 'close' );
},
'cite-form-reset': function() {
CiteTB.resetForm();
}
}
}
};
$target.wikiEditor('addDialog', dialogobj);
if (!CiteTB.getOption('modal')) {
//$j('#citetoolbar-'+sform).dialog('option', 'modal', false);
}
temlist[sform] = {label: tem.templatename, action: actionobj };
}
var refsection = {
'sections': {
'cites': {
type: 'toolbar',
labelMsg: 'cite-section-label',
groups: {
'template': {
tools: {
'template': {
type: 'select',
labelMsg: 'cite-template-list',
list: temlist
}
}
},
'namedrefs': {
labelMsg: 'cite-named-refs-label',
tools: {
'nrefs': {
type: 'button',
action: {
type: 'dialog',
module: 'cite-toolbar-namedrefs'
},
icon: '//upload.wikimedia.org/wikipedia/commons/thumb/b/be/Nuvola_clipboard_lined.svg/22px-Nuvola_clipboard_lined.svg.png',
section: 'cites',
group: 'namedrefs',
labelMsg: 'cite-named-refs-button'
}
}
},
'errorcheck': {
labelMsg: 'cite-errorcheck-label',
tools: {
'echeck': {
type: 'button',
action: {
type: 'dialog',
module: 'cite-toolbar-errorcheck'
},
icon: '//upload.wikimedia.org/wikipedia/commons/thumb/a/a3/Nuvola_apps_korganizer-NO.png/22px-Nuvola_apps_korganizer-NO.png',
section: 'cites',
group: 'errorcheck',
labelMsg: 'cite-errorcheck-button'
}
}
}
}
}
}
};
var defaultdialogs = {
'cite-toolbar-errorcheck': {
titleMsg: 'cite-errorcheck-label',
id: 'citetoolbar-errorcheck',
resizeme: false,
init: function() {},
html: '<div id="cite-namedref-loading">'+
'<img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />'+
' '+mw.usability.getMsg('cite-loading')+'</div>',
dialog: {
width:550,
open: function() {
CiteTB.loadRefs();
},
buttons: {
'cite-errorcheck-submit': function() {
var errorchecks = $j("input[name='cite-err-test']:checked");
var errors = [];
for (var i=0; i<errorchecks.length; i++) {
errors = errors.concat(CiteTB.ErrorChecks[$j(errorchecks[i]).val()].run());
}
CiteTB.displayErrors(errors);
$j(this).dialog( 'close' );
},
'wikieditor-toolbar-tool-link-cancel': function() {
$j(this).dialog( 'close' );
}
}
}
},
'cite-toolbar-namedrefs': {
titleMsg: 'cite-named-refs-title',
resizeme: false,
id: 'citetoolbar-namedrefs',
html: '<div id="cite-namedref-loading">'+
'<img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />'+
' '+mw.usability.getMsg('cite-loading')+'</div>',
init: function() {},
dialog: {
width: 550,
open: function() {
CiteTB.loadRefs();
},
buttons: {
'cite-form-submit': function() {
var refname = $j("#cite-namedref-select").val();
if (refname == '') {
return;
}
$j.wikiEditor.modules.toolbar.fn.doAction( $j(this).data( 'context' ), {
type: 'encapsulate',
options: {
peri: ' '
}
}, $j(this) );
$j(this).dialog( 'close' );
$j.wikiEditor.modules.toolbar.fn.doAction( $j(this).data( 'context' ), {
type: 'encapsulate',
options: {
pre: CiteTB.getNamedRef(refname, true)
}
}, $j(this) );
},
'wikieditor-toolbar-tool-link-cancel': function() {
$j(this).dialog( 'close' );
}
}
}
}
};
$target.wikiEditor('addDialog', defaultdialogs);
$j('#citetoolbar-namedrefs').unbind('dialogopen');
if (!CiteTB.getOption('modal')) {
//$j('#citetoolbar-namedrefs').dialog('option', 'modal', false);
//$j('#citetoolbar-errorcheck').dialog('option', 'modal', false);
appendCSS(".ui-widget-overlay {"+
"display:none !important;"+
"}");
}
$target.wikiEditor('addToToolbar', refsection);
}
// Load local data - messages, cite templates, etc.
$j(document).ready( function() {
switch( wgUserLanguage ) {
case 'es': // Spanish
var RefToolbarMessages = importScript('MediaWiki:RefToolbarMessages-es.js');
break;
default: // English
var RefToolbarMessages = importScript('MediaWiki:RefToolbarMessages-en.js');
}
});
// Setup the main object
CiteTB.mainRefList = [];
CiteTB.refsLoaded = false;
// REF FUNCTIONS
// Actually assemble a ref from user input
CiteTB.getRef = function(inneronly, forinsert) {
var template = CiteTB.getOpenTemplate();
var templatename = template.templatename;
var res = '';
var refobj = {'shorttag':false};
if (!inneronly) {
var group = $j('#cite-'+CiteTB.escStr(template.shortform)+'-group').val();
var refname = $j('#cite-'+CiteTB.escStr(template.shortform)+'-name').val();
res += '<ref';
if (refname) {
refname = $j.trim(refname);
res+=' name='+CiteTB.getQuotedString(refname);
refobj.refname = refname;
}
if (group) {
group = $j.trim(group);
res+=' group='+CiteTB.getQuotedString(group);
refobj.refgroup = group;
}
res+='>';
}
var content ='{{'+templatename;
for( var i=0; i<template.basic.length; i++ ) {
var fieldname = template.basic[i].field;
var field = $j('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldname).val();
if (field) {
content+='|'+fieldname+'=';
content+= $j.trim(field.replace("|", "{{!}}"));
}
}
if ($j('#cite-form-status').val() != 'closed') {
for( var i=0; i<template.extra.length; i++ ) {
var fieldname = template.extra[i].field;
var field = $j('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldname).val();
if (field) {
content+='|'+fieldname+'=';
content+= $j.trim(field.replace("|", "{{!}}"));
}
}
}
content+= '}}';
res+=content;
refobj.content = content;
if (!inneronly) {
res+= '</ref>';
}
if (forinsert) {
CiteTB.mainRefList.push(refobj);
}
return res;
}
// Make a reference to a named ref
CiteTB.getNamedRef = function(refname, forinsert) {
var inner = 'name=';
if (forinsert) {
CiteTB.mainRefList.push( {'shorttag':true, 'refname':refname} );
}
return '<ref name='+CiteTB.getQuotedString(refname)+' />';
}
// Function to load the ref list
CiteTB.loadRefs = function() {
if (CiteTB.refsLoaded) {
return;
}
CiteTB.getPageText(CiteTB.loadRefsInternal);
}
// Function that actually loads the list from the page text
CiteTB.loadRefsInternal = function(text) {
// What this does: extract first name/group extract second name/group shorttag inner content
var refsregex = /< *ref(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ '"\/\>]*?)) *)? *(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ '"\/\>]*?)) *)? *(?:\/ *>|>((?:.|\n)*?)< *\/ *ref *>)/gim
// This should work regardless of the quoting used for names/groups and for linebreaks in the inner content
while (true) {
var ref = refsregex.exec(text);
if (ref == null) {
break;
}
var refobj = {};
if (ref[9]) { // Content + short tag check
//alert('"'+ref[9]+'"');
refobj['content'] = ref[9];
refobj['shorttag'] = false;
} else {
refobj['shorttag'] = true;
}
if (ref[1] != '') { // First name/group
if (ref[2]) {
refobj['ref'+ref[1]] = ref[2];
} else if (ref[3]) {
refobj['ref'+ref[1]] = ref[3];
} else {
refobj['ref'+ref[1]] = ref[4];
}
}
if (ref[5] != '') { // Second name/group
if (ref[6]) {
refobj['ref'+ref[5]] = ref[6];
} else if (ref[7]) {
refobj['ref'+ref[5]] = ref[7];
} else {
refobj['ref'+ref[5]] = ref[8];
}
}
CiteTB.mainRefList.push(refobj);
}
CiteTB.refsLoaded = true;
CiteTB.setupErrorCheck();
CiteTB.setupNamedRefs()
}
// AJAX FUNCTIONS
// Parse some wikitext and hand it off to a callback function
CiteTB.parse = function(text, callback) {
$j.post( wgServer+wgScriptPath+'/api.php',
{action:'parse', title:wgPageName, text:text, prop:'text', format:'json'},
function(data) {
var html = data['parse']['text']['*'];
callback(html);
},
'json'
);
}
// Use the API to expand templates on some text
CiteTB.expandtemplates = function(text, callback) {
$j.post( wgServer+wgScriptPath+'/api.php',
{action:'expandtemplates', title:wgPageName, text:text, format:'json'},
function(data) {
var restext = data['expandtemplates']['*'];
callback(restext);
},
'json'
);
}
// Function to get the page text
CiteTB.getPageText = function(callback) {
var section = $j("input[name='wpSection']").val();
if ( section != '' ) {
var postdata = {action:'query', prop:'revisions', rvprop:'content', pageids:wgArticleId, format:'json'};
if (CiteTB.getOption('expandtemplates')) {
postdata['rvexpandtemplates'] = '1';
}
$j.get( wgServer+wgScriptPath+'/api.php',
postdata,
function(data) {
var pagetext = data['query']['pages'][wgArticleId.toString()]['revisions'][0]['*'];
callback(pagetext);
},
'json'
);
} else {
if (CiteTB.getOption('expandtemplates')) {
CiteTB.expandtemplates($j('#wpTextbox1').wikiEditor('getContents').text(), callback);
} else {
callback($j('#wpTextbox1').wikiEditor('getContents').text());
}
}
}
// Autofill a template from an ID (ISBN, DOI, PMID)
CiteTB.initAutofill = function() {
var elemid = $j(this).attr('id');
var res = /^cite\-auto\-(.*?)\-(.*)\-(.*)$/.exec(elemid);
var tem = res[1];
var field = res[2];
var autotype = res[3];
var id = $j('#cite-'+tem+'-'+field).val();
if (!id) {
return false;
}
var url = 'http://toolserver.org/~alexz/ref/lookup.php?';
url+=autotype+'='+encodeURIComponent(id);
url+='&template='+encodeURIComponent(tem);
var s = document.createElement('script');
s.setAttribute('src', url);
s.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(s);
return false;
}
// Callback for autofill
//TODO: Autofill the URL, at least for DOI
CiteTB.autoFill = function(data, template, type) {
var cl = 'cite-'+template+'-';
$j('.'+cl+'title').val(data.title);
if ($j('.'+cl+'last1').length != 0) {
for(var i=0; i<data.authors.length; i++) {
if ($j('.'+cl+'last'+(i+1)).length) {
$j('.'+cl+'last'+(i+1)).val(data.authors[i][0]);
$j('.'+cl+'first'+(i+1)).val(data.authors[i][1]);
} else {
var coauthors = [];
for(var j=i; j<data.authors.length; j++) {
coauthors.push(data.authors[j].join(', '));
}
$j('.'+cl+'coauthors').val(coauthors.join(', '));
break;
}
}
} else if($j('.'+cl+'author1').length != 0) {
for(var i=0; i<data.authors.length; i++) {
if ($j('.'+cl+'author'+(i+1)).length) {
$j('.'+cl+'author'+(i+1)).val(data.authors[i].join(', '));
} else {
var coauthors = [];
for(var j=i; j<data.authors.length; j++) {
coauthors.push(data.authors[j].join(', '));
}
$j('.'+cl+'coauthors').val(coauthors.join(', '));
break;
}
}
} else {
var authors = [];
for(var i=0; i<data.authors.length; i++) {
authors.push(data.authors[i].join(', '));
}
$j('.'+cl+'authors').val(authors.join('; '));
}
if (type == 'pmid' || type == 'doi') {
if (type == 'doi') {
var DT = new Date(data.date);
$j('.'+cl+'date').val(CiteTB.formatDate(DT));
} else {
$j('.'+cl+'date').val(data.date);
}
$j('.'+cl+'journal').val(data.journal);
$j('.'+cl+'volume').val(data.volume);
$j('.'+cl+'issue').val(data.issue);
$j('.'+cl+'pages').val(data.pages);
} else if (type == 'isbn') {
$j('.'+cl+'publisher').val(data.publisher);
$j('.'+cl+'location').val(data.location);
$j('.'+cl+'year').val(data.year);
$j('.'+cl+'edition').val(data.edition);
}
}
// FORM DIALOG FUNCTIONS
// fill the accessdate param with the current date
CiteTB.fillAccessdate = function() {
var elemid = $j(this).attr('id');
var res = /^cite\-date\-(.*?)\-(.*)$/.exec(elemid);
var id = res[1];
var field = res[2];
var DT = new Date();
datestr = CiteTB.formatDate(DT);
$j('#cite-'+id+'-'+field).val(datestr);
return false;
}
CiteTB.formatDate = function(DT) {
var datestr = CiteTB.getOption('date format');
var zmonth = '';
var month = DT.getUTCMonth()+1;
if (month < 10) {
zmonth = "0"+month.toString();
} else {
zmonth = month.toString();
}
month = month.toString();
var zdate = '';
var date = DT.getUTCDate();
if (date < 10) {
zdate = "0"+date.toString();
} else {
zdate = date.toString();
}
date = date.toString()
datestr = datestr.replace('<date>', date);
datestr = datestr.replace('<month>', month);
datestr = datestr.replace('<zdate>', zdate);
datestr = datestr.replace('<zmonth>', zmonth);
datestr = datestr.replace('<monthname>', CiteTB.getOption('months')[DT.getUTCMonth()]);
datestr = datestr.replace('<year>', DT.getUTCFullYear().toString());
return datestr;
}
// Function called after the ref list is loaded, to actually set the contents of the named ref dialog
// Until the list is loaded, its just a "Loading" placeholder
CiteTB.setupNamedRefs = function() {
var names = []
for( var i=0; i<CiteTB.mainRefList.length; i++) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname) {
names.push(CiteTB.mainRefList[i]);
}
}
var stuff = $j('<div />')
$j('#citetoolbar-namedrefs').html( stuff );
if (names.length == 0) {
stuff.html(mw.usability.getMsg('cite-no-namedrefs'));
} else {
stuff.html(mw.usability.getMsg('cite-namedrefs-intro'));
var select = $j('<select id="cite-namedref-select">');
select.append($j('<option value="" />').text(mw.usability.getMsg('cite-named-refs-dropdown')));
for(var i=0; i<names.length; i++) {
select.append($j('<option />').text(names[i].refname));
}
stuff.after(select);
select.before('<br />');
var prevlabel = $j('<div id="cite-nref-preview-label" style="display:none;" />').html(mw.usability.getMsg('cite-raw-preview'));
select.after(prevlabel);
prevlabel.before("<br /><br />");
prevlabel.after('<div id="cite-namedref-preview" style="padding:0.5em; font-size:110%" />');
var parselabel = $j('<span id="cite-parsed-label" style="display:none;" />').html(mw.usability.getMsg('cite-parsed-label'));
$j('#cite-namedref-preview').after(parselabel);
parselabel.after('<div id="cite-namedref-parsed" style="padding-bottom:0.5em; font-size:110%" />');
var link = $j('<a href="#" id="cite-nref-parse" style="margin:0 1em 0 1em; display:none; color:darkblue" />');
link.html(mw.usability.getMsg('cite-form-parse'));
$j('#cite-namedref-parsed').after(link);
$j("#cite-namedref-select").bind( 'change', CiteTB.namedRefSelectClick);
$j('#cite-nref-parse').bind( 'click', CiteTB.nrefParseClick);
}
}
// Function to get the errorcheck form HTML
CiteTB.setupErrorCheck = function() {
var form = $j('<div id="cite-errorcheck-heading" />').html(mw.usability.getMsg('cite-errorcheck-heading'));
var ul = $j("<ul id='cite-errcheck-list' />");
for (var t in CiteTB.ErrorChecks) {
test = CiteTB.ErrorChecks[t];
ul.append(test.getRow());
}
form.append(ul);
$j('#citetoolbar-errorcheck').html(form);
}
// Callback function for parsed preview
CiteTB.fillNrefPreview = function(parsed) {
$j('#cite-parsed-label').show();
$j('#cite-namedref-parsed').html(parsed);
}
// Click handler for the named-ref parsed preview
CiteTB.nrefParseClick = function() {
var choice = $j("#cite-namedref-select").val();
if (choice == '') {
$j('#cite-parsed-label').hide();
$j('#cite-namedref-parsed').text('');
return false;
}
$j('#cite-nref-parse').hide();
for( var i=0; i<CiteTB.mainRefList.length; i++) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
CiteTB.parse(CiteTB.mainRefList[i].content, CiteTB.fillNrefPreview);
return false;
}
}
}
// Click handler for the named-ref dropdown
CiteTB.lastnamedrefchoice = '';
CiteTB.namedRefSelectClick = function() {
var choice = $j("#cite-namedref-select").val();
if (CiteTB.lastnamedrefchoice == choice) {
return;
}
CiteTB.lastnamedrefchoice = choice;
$j('#cite-parsed-label').hide();
$j('#cite-namedref-parsed').text('');
if (choice == '') {
$j('#cite-nref-preview-label').hide();
$j('#cite-namedref-preview').text('');
$j('#cite-nref-parse').hide();
return;
}
for( var i=0; i<CiteTB.mainRefList.length; i++) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
$j('#cite-nref-preview-label').show();
$j('#cite-namedref-preview').text(CiteTB.mainRefList[i].content);
if (CiteTB.getOption('autoparse')) {
CiteTB.nrefParseClick();
} else {
$j('#cite-nref-parse').show();
}
}
}
}
// callback function for parsed preview
CiteTB.fillTemplatePreview = function(text) {
var template = CiteTB.getOpenTemplate();
var div = $j("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.find('.cite-prev-parsed-label').show();
div.find('.cite-preview-parsed').html(text);
}
// Click handler for template parsed preview
CiteTB.prevParseClick = function() {
var ref = CiteTB.getRef(true, false);
var template = CiteTB.getOpenTemplate();
var div = $j("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.find('.cite-prev-parse').hide();
CiteTB.parse(ref, CiteTB.fillTemplatePreview);
}
// Show/hide the extra fields in the dialog box
CiteTB.showHideExtra = function() {
var template = CiteTB.getOpenTemplate();
var div = $j("#citetoolbar-"+CiteTB.escStr(template.shortform));
var setting = div.find(".cite-form-status").val();
if ( setting == 'closed' ) {
div.find(".cite-form-status").val('open');
div.find('.cite-extra-fields').show(1, function() {
// jQuery adds "display:block", which screws things up
div.find('.cite-extra-fields').attr('style', 'width:100%; background-color:transparent;');
});
} else {
div.find(".cite-form-status").val('closed')
div.find('.cite-extra-fields').hide();
}
}
// Resets form fields and previews
CiteTB.resetForm = function() {
var template = CiteTB.getOpenTemplate();
var div = $j("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.find('.cite-preview-label').hide();
div.find('.cite-ref-preview').text('').hide();
div.find('.cite-prev-parsed-label').hide();
div.find('.cite-preview-parsed').html('');
div.find('.cite-prev-parse').hide();
var id = CiteTB.escStr(template.shortform);
$j('#citetoolbar-'+id+' input[type=text]').val('');
}
// STRING UTILITY FUNCTIONS
// Returns a string quoted as necessary for name/group attributes
CiteTB.getQuotedString = function(s) {
var sp = /\s/.test(s); // spaces
var sq = /\'/.test(s); // single quotes
var dq = /\"/.test(s); // double quotes
if (!sp && !sq && !dq) { // No quotes necessary
return s;
} else if (!dq) { // Can use double quotes
return '"'+s+'"';
} else if (!sq) { // Can use single quotes
return "'"+s+"'";
} else { // Has double and single quotes
s = s.replace(/\"/g, '\"');
return '"'+s+'"';
}
}
// Fix up strings for output - capitalize first char, replace underscores with spaces
CiteTB.fixStr = function(s) {
s = s.slice(0,1).toUpperCase() + s.slice(1);
s = s.replace('_',' ');
return s;
}
// Escape spaces and quotes for use in HTML classes/ids
CiteTB.escStr = function(s) {
return s.replace(' ', '-').replace("'", "\'").replace('"', '\"');
}
// MISC FUNCTIONS
// Determine which template form is open, and get the template object for it
CiteTB.getOpenTemplate = function() {
var dialogs = $j(".ui-dialog-content.ui-widget-content:visible");
var templatename = $j(dialogs[0]).find(".cite-template").val();
var template = null;
return CiteTB.Templates[templatename];
}
// Display the report for the error checks
CiteTB.displayErrors = function(errors) {
$j('#cite-err-report').remove();
var table = $j('<table id="cite-err-report" style="width:100%; border:1px solid #A9A9A9; background-color:#FFEFD5; padding:0.25em; margin-top:0.5em" />');
$j('#editpage-copywarn').before(table);
var tr1 = $j('<tr style="width:100%" />');
var th1 = $j('<th style="width:60%; font-size:110%" />').html(mw.usability.getMsg('cite-err-report-heading'));
var th2 = $j('<th style="text-align:right; width:40%" />');
im = $j('<img />').attr('src', '//upload.wikimedia.org/wikipedia/commons/thumb/5/55/Gtk-stop.svg/20px-Gtk-stop.svg.png');
im.attr('alt', mw.usability.getMsg('cite-err-report-close')).attr('title', mw.usability.getMsg('cite-err-report-close'));
var ad = $j('<a id="cite-err-check-close" />').attr('href', '#');
ad.append(im);
th2.append(ad);
tr1.append(th1).append(th2);
table.append(tr1);
$j('#cite-err-check-close').bind('click', function() { $j('#cite-err-report').remove(); });
if (errors.length == 0) {
var tr = $j('<tr style="width:100%;" />');
var td = $j('<td style="text-align:center; margin:1.5px;" />').html(mw.usability.getMsg('cite-err-report-empty'));
tr.append(td);
table.append(tr);
return;
}
for(var e in errors) {
var err = errors[e];
var tr = $j('<tr style="width:100%;" />');
var td1 = $j('<td style="border: 1px solid black; margin:1.5px; width:60%" />').html(err.err);
var td2 = $j('<td style="border: 1px solid black; margin:1.5px; width:40%" />').html(mw.usability.getMsg(err.msg));
tr.append(td1).append(td2);
table.append(tr);
}
}
} // End of code loaded only on edit | sakcret/apecc_src | css/jquery-ui/Shitō-ryū - Wikipedia, la enciclopedia libre_files/index(2).php | PHP | lgpl-3.0 | 26,767 |
# coding:utf-8
"""
TokenStream represents a stream of tokens that a parser will consume.
TokenStream can be used to consume tokens, peek ahead, and synchonize to a
delimiter token. The tokens that the token stream operates on are either
compiled regular expressions or strings.
"""
import re
LBRACKET = '<'
AT_SYMBOL = '@'
RBRACKET = '>'
DQUOTE = '"'
BAD_DOMAIN = re.compile(r''' # start or end
^-|-$ # with -
''', re.MULTILINE | re.VERBOSE)
DELIMITER = re.compile(r'''
[,;][,;\s]* # delimiter
''', re.MULTILINE | re.VERBOSE)
WHITESPACE = re.compile(r'''
(\ |\t)+ # whitespace
''', re.MULTILINE | re.VERBOSE)
UNI_WHITE = re.compile(ur'''
[
\u0020\u00a0\u1680\u180e
\u2000-\u200a
\u2028\u202f\u205f\u3000
]*
''', re.MULTILINE | re.VERBOSE | re.UNICODE)
RELAX_ATOM = re.compile(r'''
([^\s<>;,"]+)
''', re.MULTILINE | re.VERBOSE)
ATOM = re.compile(r'''
[A-Za-z0-9!#$%&'*+\-/=?^_`{|}~]+ # atext
''', re.MULTILINE | re.VERBOSE)
DOT_ATOM = re.compile(r'''
[A-Za-z0-9!#$%&'*+\-/=?^_`{|}~]+ # atext
(\.[A-Za-z0-9!#$%&'*+\-/=?^_`{|}~]+)* # (dot atext)*
''', re.MULTILINE | re.VERBOSE)
UNI_ATOM = re.compile(ur'''
([^\s<>;,"]+)
''', re.MULTILINE | re.VERBOSE | re.UNICODE)
UNI_QSTR = re.compile(ur'''
"
(?P<qstr>([^"]+))
"
''', re.MULTILINE | re.VERBOSE | re.UNICODE)
QSTRING = re.compile(r'''
" # dquote
(\s* # whitespace
([\x21\x23-\x5b\x5d-\x7e] # qtext
| # or
\\[\x21-\x7e\t\ ]))* # quoted-pair
\s* # whitespace
" # dquote
''', re.MULTILINE | re.VERBOSE)
URL = re.compile(r'''
(?:http|https)://
[^\s<>{}|\^~\[\]`;,]+
''', re.MULTILINE | re.VERBOSE | re.UNICODE)
class TokenStream(object):
"""
Represents the stream of tokens that the parser will consume. The token
stream can be used to consume tokens, peek ahead, and synchonize to a
delimiter token.
When the strem reaches its end, the position is placed
at one plus the position of the last token.
"""
def __init__(self, stream):
self.position = 0
self.stream = stream
def get_token(self, token, ngroup=None):
"""
Get the next token from the stream and advance the stream. Token can
be either a compiled regex or a string.
"""
# match single character
if isinstance(token, basestring) and len(token) == 1:
if self.peek() == token:
self.position += 1
return token
return None
# match a pattern
match = token.match(self.stream, self.position)
if match:
advance = match.end() - match.start()
self.position += advance
# if we are asking for a named capture, return jus that
if ngroup:
return match.group(ngroup)
# otherwise return the entire capture
return match.group()
return None
def end_of_stream(self):
"""
Check if the end of the stream has been reached, if it has, returns
True, otherwise false.
"""
if self.position >= len(self.stream):
return True
return False
def synchronize(self):
"""
Advances the stream to synchronizes to the delimiter token. Used primarily
in relaxed mode parsing.
"""
start_pos = self.position
end_pos = len(self.stream)
match = DELIMITER.search(self.stream, self.position)
if match:
self.position = match.start()
end_pos = match.start()
else:
self.position = end_pos
skip = self.stream[start_pos:end_pos]
if skip.strip() == '':
return None
return skip
def peek(self, token=None):
"""
Peek at the stream to see what the next token is or peek for a
specific token.
"""
# peek at whats next in the stream
if token is None:
if self.position < len(self.stream):
return self.stream[self.position]
else:
return None
# peek for a specific token
else:
match = token.match(self.stream, self.position)
if match:
return self.stream[match.start():match.end()]
return None
| glyph/flanker | flanker/addresslib/tokenizer.py | Python | apache-2.0 | 5,495 |
/*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2019 Adobe
* %%
* 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.
* #L%
*/
package com.adobe.acs.commons.marketo;
/**
* Model for retrieving the configuration values for the Marketo form component
*/
public interface MarketoForm {
default String getFormId() {
throw new UnsupportedOperationException();
}
default String getHidden() {
throw new UnsupportedOperationException();
}
default String getScript() {
throw new UnsupportedOperationException();
}
default String getSuccessUrl() {
throw new UnsupportedOperationException();
}
default String getValues() {
throw new UnsupportedOperationException();
}
default boolean isEdit() {
throw new UnsupportedOperationException();
}
}
| bstopp/acs-aem-commons | bundle/src/main/java/com/adobe/acs/commons/marketo/MarketoForm.java | Java | apache-2.0 | 1,307 |
/*
* 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.druid.client;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.NonnullPair;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.java.util.http.client.Request;
import org.apache.druid.java.util.http.client.response.ClientResponse;
import org.apache.druid.java.util.http.client.response.HttpResponseHandler;
import org.apache.druid.java.util.http.client.response.HttpResponseHandler.TrafficCop;
import org.apache.druid.query.Query;
import org.apache.druid.query.QueryPlus;
import org.apache.druid.query.QueryRunner;
import org.apache.druid.query.QueryRunnerFactoryConglomerate;
import org.apache.druid.query.ReportTimelineMissingSegmentQueryRunner;
import org.apache.druid.query.SegmentDescriptor;
import org.apache.druid.query.context.ResponseContext;
import org.apache.druid.segment.QueryableIndex;
import org.apache.druid.server.QueryResource;
import org.apache.druid.timeline.DataSegment;
import org.jboss.netty.buffer.HeapChannelBufferFactory;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.joda.time.Duration;
import javax.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* An HTTP client for testing which emulates querying data nodes (historicals or realtime tasks).
*/
public class TestHttpClient implements HttpClient
{
private static final TrafficCop NOOP_TRAFFIC_COP = checkNum -> 0L;
private static final int RESPONSE_CTX_HEADER_LEN_LIMIT = 7 * 1024;
private final Map<URL, SimpleServerManager> servers = new HashMap<>();
private final ObjectMapper objectMapper;
public TestHttpClient(ObjectMapper objectMapper)
{
this.objectMapper = objectMapper;
}
public void addServerAndRunner(DruidServer server, SimpleServerManager serverManager)
{
servers.put(computeUrl(server), serverManager);
}
@Nullable
public SimpleServerManager getServerManager(DruidServer server)
{
return servers.get(computeUrl(server));
}
public Map<URL, SimpleServerManager> getServers()
{
return servers;
}
private static URL computeUrl(DruidServer server)
{
try {
return new URL(StringUtils.format("%s://%s/druid/v2/", server.getScheme(), server.getHost()));
}
catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Override
public <Intermediate, Final> ListenableFuture<Final> go(
Request request,
HttpResponseHandler<Intermediate, Final> handler
)
{
throw new UnsupportedOperationException();
}
@Override
public <Intermediate, Final> ListenableFuture<Final> go(
Request request,
HttpResponseHandler<Intermediate, Final> handler,
Duration readTimeout
)
{
try {
final Query query = objectMapper.readValue(request.getContent().array(), Query.class);
final QueryRunner queryRunner = servers.get(request.getUrl()).getQueryRunner();
if (queryRunner == null) {
throw new ISE("Can't find queryRunner for url[%s]", request.getUrl());
}
final ResponseContext responseContext = ResponseContext.createEmpty();
final Sequence sequence = queryRunner.run(QueryPlus.wrap(query), responseContext);
final byte[] serializedContent;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
objectMapper.writeValue(baos, sequence);
serializedContent = baos.toByteArray();
}
final ResponseContext.SerializationResult serializationResult = responseContext.serializeWith(
objectMapper,
RESPONSE_CTX_HEADER_LEN_LIMIT
);
final HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().add(QueryResource.HEADER_RESPONSE_CONTEXT, serializationResult.getResult());
response.setContent(
HeapChannelBufferFactory.getInstance().getBuffer(serializedContent, 0, serializedContent.length)
);
final ClientResponse<Intermediate> intermClientResponse = handler.handleResponse(response, NOOP_TRAFFIC_COP);
final ClientResponse<Final> finalClientResponse = handler.done(intermClientResponse);
return Futures.immediateFuture(finalClientResponse.getObj());
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* A simple server manager for testing which you can manually drop a segment. Currently used for
* testing {@link org.apache.druid.query.RetryQueryRunner}.
*/
public static class SimpleServerManager
{
private final QueryRunnerFactoryConglomerate conglomerate;
private final DataSegment segment;
private final QueryableIndex queryableIndex;
private final boolean throwQueryError;
private boolean isSegmentDropped = false;
public SimpleServerManager(
QueryRunnerFactoryConglomerate conglomerate,
DataSegment segment,
QueryableIndex queryableIndex,
boolean throwQueryError
)
{
this.conglomerate = conglomerate;
this.segment = segment;
this.queryableIndex = queryableIndex;
this.throwQueryError = throwQueryError;
}
private QueryRunner getQueryRunner()
{
if (throwQueryError) {
return (queryPlus, responseContext) -> {
throw new RuntimeException("Exception for testing");
};
}
if (isSegmentDropped) {
return new ReportTimelineMissingSegmentQueryRunner<>(
new SegmentDescriptor(segment.getInterval(), segment.getVersion(), segment.getId().getPartitionNum())
);
} else {
return new SimpleQueryRunner(conglomerate, segment.getId(), queryableIndex);
}
}
public NonnullPair<DataSegment, QueryableIndex> dropSegment()
{
this.isSegmentDropped = true;
return new NonnullPair<>(segment, queryableIndex);
}
}
}
| gianm/druid | server/src/test/java/org/apache/druid/client/TestHttpClient.java | Java | apache-2.0 | 7,232 |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
/**
* @fileoverview Browser atom for injecting JavaScript into the page under
* test. There is no point in using this atom directly from JavaScript.
* Instead, it is intended to be used in its compiled form when injecting
* script from another language (e.g. C++).
*
* TODO: Add an example
*/
goog.provide('bot.inject');
goog.provide('bot.inject.cache');
goog.require('bot');
goog.require('bot.Error');
goog.require('bot.ErrorCode');
goog.require('bot.json');
/**
* @suppress {extraRequire} Used as a forward declaration which causes
* compilation errors if missing.
*/
goog.require('bot.response.ResponseObject');
goog.require('goog.array');
goog.require('goog.dom.NodeType');
goog.require('goog.object');
goog.require('goog.userAgent');
/**
* Type definition for the WebDriver's JSON wire protocol representation
* of a DOM element.
* @typedef {{ELEMENT: string}}
* @see bot.inject.ELEMENT_KEY
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
*/
bot.inject.JsonElement;
/**
* Type definition for a cached Window object that can be referenced in
* WebDriver's JSON wire protocol. Note, this is a non-standard
* representation.
* @typedef {{WINDOW: string}}
* @see bot.inject.WINDOW_KEY
*/
bot.inject.JsonWindow;
/**
* Key used to identify DOM elements in the WebDriver wire protocol.
* @type {string}
* @const
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
*/
bot.inject.ELEMENT_KEY = 'ELEMENT';
/**
* Key used to identify Window objects in the WebDriver wire protocol.
* @type {string}
* @const
*/
bot.inject.WINDOW_KEY = 'WINDOW';
/**
* Converts an element to a JSON friendly value so that it can be
* stringified for transmission to the injector. Values are modified as
* follows:
* <ul>
* <li>booleans, numbers, strings, and null are returned as is</li>
* <li>undefined values are returned as null</li>
* <li>functions are returned as a string</li>
* <li>each element in an array is recursively processed</li>
* <li>DOM Elements are wrapped in object-literals as dictated by the
* WebDriver wire protocol</li>
* <li>all other objects will be treated as hash-maps, and will be
* recursively processed for any string and number key types (all
* other key types are discarded as they cannot be converted to JSON).
* </ul>
*
* @param {*} value The value to make JSON friendly.
* @return {*} The JSON friendly value.
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
*/
bot.inject.wrapValue = function(value) {
switch (goog.typeOf(value)) {
case 'string':
case 'number':
case 'boolean':
return value;
case 'function':
return value.toString();
case 'array':
return goog.array.map(/**@type {IArrayLike}*/ (value),
bot.inject.wrapValue);
case 'object':
// Since {*} expands to {Object|boolean|number|string|undefined}, the
// JSCompiler complains that it is too broad a type for the remainder of
// this block where {!Object} is expected. Downcast to prevent generating
// a ton of compiler warnings.
value = /**@type {!Object}*/ (value);
// Sniff out DOM elements. We're using duck-typing instead of an
// instanceof check since the instanceof might not always work
// (e.g. if the value originated from another Firefox component)
if (goog.object.containsKey(value, 'nodeType') &&
(value['nodeType'] == goog.dom.NodeType.ELEMENT ||
value['nodeType'] == goog.dom.NodeType.DOCUMENT)) {
var ret = {};
ret[bot.inject.ELEMENT_KEY] =
bot.inject.cache.addElement(/**@type {!Element}*/ (value));
return ret;
}
// Check if this is a Window
if (goog.object.containsKey(value, 'document')) {
var ret = {};
ret[bot.inject.WINDOW_KEY] =
bot.inject.cache.addElement(/**@type{!Window}*/ (value));
return ret;
}
if (goog.isArrayLike(value)) {
return goog.array.map(/**@type {IArrayLike}*/ (value),
bot.inject.wrapValue);
}
var filtered = goog.object.filter(value, function(val, key) {
return goog.isNumber(key) || goog.isString(key);
});
return goog.object.map(filtered, bot.inject.wrapValue);
default: // goog.typeOf(value) == 'undefined' || 'null'
return null;
}
};
/**
* Unwraps any DOM element's encoded in the given {@code value}.
* @param {*} value The value to unwrap.
* @param {Document=} opt_doc The document whose cache to retrieve wrapped
* elements from. Defaults to the current document.
* @return {*} The unwrapped value.
*/
bot.inject.unwrapValue = function(value, opt_doc) {
if (goog.isArray(value)) {
return goog.array.map(/**@type {IArrayLike}*/ (value),
function(v) { return bot.inject.unwrapValue(v, opt_doc); });
} else if (goog.isObject(value)) {
if (typeof value == 'function') {
return value;
}
if (goog.object.containsKey(value, bot.inject.ELEMENT_KEY)) {
return bot.inject.cache.getElement(value[bot.inject.ELEMENT_KEY],
opt_doc);
}
if (goog.object.containsKey(value, bot.inject.WINDOW_KEY)) {
return bot.inject.cache.getElement(value[bot.inject.WINDOW_KEY],
opt_doc);
}
return goog.object.map(value, function(val) {
return bot.inject.unwrapValue(val, opt_doc);
});
}
return value;
};
/**
* Recompiles {@code fn} in the context of another window so that the
* correct symbol table is used when the function is executed. This
* function assumes the {@code fn} can be decompiled to its source using
* {@code Function.prototype.toString} and that it only refers to symbols
* defined in the target window's context.
*
* @param {!(Function|string)} fn Either the function that shold be
* recompiled, or a string defining the body of an anonymous function
* that should be compiled in the target window's context.
* @param {!Window} theWindow The window to recompile the function in.
* @return {!Function} The recompiled function.
* @private
*/
bot.inject.recompileFunction_ = function(fn, theWindow) {
if (goog.isString(fn)) {
try {
return new theWindow['Function'](fn);
} catch (ex) {
// Try to recover if in IE5-quirks mode
// Need to initialize the script engine on the passed-in window
if (goog.userAgent.IE && theWindow.execScript) {
theWindow.execScript(';');
return new theWindow['Function'](fn);
}
throw ex;
}
}
return theWindow == window ? fn : new theWindow['Function'](
'return (' + fn + ').apply(null,arguments);');
};
/**
* Executes an injected script. This function should never be called from
* within JavaScript itself. Instead, it is used from an external source that
* is injecting a script for execution.
*
* <p/>For example, in a WebDriver Java test, one might have:
* <pre><code>
* Object result = ((JavascriptExecutor) driver).executeScript(
* "return arguments[0] + arguments[1];", 1, 2);
* </code></pre>
*
* <p/>Once transmitted to the driver, this command would be injected into the
* page for evaluation as:
* <pre><code>
* bot.inject.executeScript(
* function() {return arguments[0] + arguments[1];},
* [1, 2]);
* </code></pre>
*
* <p/>The details of how this actually gets injected for evaluation is left
* as an implementation detail for clients of this library.
*
* @param {!(Function|string)} fn Either the function to execute, or a string
* defining the body of an anonymous function that should be executed. This
* function should only contain references to symbols defined in the context
* of the target window ({@code opt_window}). Any references to symbols
* defined in this context will likely generate a ReferenceError.
* @param {Array.<*>} args An array of wrapped script arguments, as defined by
* the WebDriver wire protocol.
* @param {boolean=} opt_stringify Whether the result should be returned as a
* serialized JSON string.
* @param {!Window=} opt_window The window in whose context the function should
* be invoked; defaults to the current window.
* @return {!(string|bot.response.ResponseObject)} The response object. If
* opt_stringify is true, the result will be serialized and returned in
* string format.
*/
bot.inject.executeScript = function(fn, args, opt_stringify, opt_window) {
var win = opt_window || bot.getWindow();
var ret;
try {
fn = bot.inject.recompileFunction_(fn, win);
var unwrappedArgs = /**@type {Object}*/ (bot.inject.unwrapValue(args,
win.document));
ret = bot.inject.wrapResponse(fn.apply(null, unwrappedArgs));
} catch (ex) {
ret = bot.inject.wrapError(ex);
}
return opt_stringify ? bot.json.stringify(ret) : ret;
};
/**
* Executes an injected script, which is expected to finish asynchronously
* before the given {@code timeout}. When the script finishes or an error
* occurs, the given {@code onDone} callback will be invoked. This callback
* will have a single argument, a {@link bot.response.ResponseObject} object.
*
* The script signals its completion by invoking a supplied callback given
* as its last argument. The callback may be invoked with a single value.
*
* The script timeout event will be scheduled with the provided window,
* ensuring the timeout is synchronized with that window's event queue.
* Furthermore, asynchronous scripts do not work across new page loads; if an
* "unload" event is fired on the window while an asynchronous script is
* pending, the script will be aborted and an error will be returned.
*
* Like {@code bot.inject.executeScript}, this function should only be called
* from an external source. It handles wrapping and unwrapping of input/output
* values.
*
* @param {(!Function|string)} fn Either the function to execute, or a string
* defining the body of an anonymous function that should be executed. This
* function should only contain references to symbols defined in the context
* of the target window ({@code opt_window}). Any references to symbols
* defined in this context will likely generate a ReferenceError.
* @param {Array.<*>} args An array of wrapped script arguments, as defined by
* the WebDriver wire protocol.
* @param {number} timeout The amount of time, in milliseconds, the script
* should be permitted to run; must be non-negative.
* @param {function(string)|function(!bot.response.ResponseObject)} onDone
* The function to call when the given {@code fn} invokes its callback,
* or when an exception or timeout occurs. This will always be called.
* @param {boolean=} opt_stringify Whether the result should be returned as a
* serialized JSON string.
* @param {!Window=} opt_window The window to synchronize the script with;
* defaults to the current window.
*/
bot.inject.executeAsyncScript = function(fn, args, timeout, onDone,
opt_stringify, opt_window) {
var win = opt_window || window;
var timeoutId;
var responseSent = false;
function sendResponse(status, value) {
if (!responseSent) {
if (win.removeEventListener) {
win.removeEventListener('unload', onunload, true);
} else {
win.detachEvent('onunload', onunload);
}
win.clearTimeout(timeoutId);
if (status != bot.ErrorCode.SUCCESS) {
var err = new bot.Error(status, value.message || value + '');
err.stack = value.stack;
value = bot.inject.wrapError(err);
} else {
value = bot.inject.wrapResponse(value);
}
onDone(opt_stringify ? bot.json.stringify(value) : value);
responseSent = true;
}
}
var sendError = goog.partial(sendResponse, bot.ErrorCode.UNKNOWN_ERROR);
if (win.closed) {
sendError('Unable to execute script; the target window is closed.');
return;
}
fn = bot.inject.recompileFunction_(fn, win);
args = /** @type {Array.<*>} */ (bot.inject.unwrapValue(args, win.document));
args.push(goog.partial(sendResponse, bot.ErrorCode.SUCCESS));
if (win.addEventListener) {
win.addEventListener('unload', onunload, true);
} else {
win.attachEvent('onunload', onunload);
}
var startTime = goog.now();
try {
fn.apply(win, args);
// Register our timeout *after* the function has been invoked. This will
// ensure we don't timeout on a function that invokes its callback after
// a 0-based timeout.
timeoutId = win.setTimeout(function() {
sendResponse(bot.ErrorCode.SCRIPT_TIMEOUT,
Error('Timed out waiting for asyncrhonous script result ' +
'after ' + (goog.now() - startTime) + ' ms'));
}, Math.max(0, timeout));
} catch (ex) {
sendResponse(ex.code || bot.ErrorCode.UNKNOWN_ERROR, ex);
}
function onunload() {
sendResponse(bot.ErrorCode.UNKNOWN_ERROR,
Error('Detected a page unload event; asynchronous script ' +
'execution does not work across page loads.'));
}
};
/**
* Wraps the response to an injected script that executed successfully so it
* can be JSON-ified for transmission to the process that injected this
* script.
* @param {*} value The script result.
* @return {{status:bot.ErrorCode,value:*}} The wrapped value.
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#responses
*/
bot.inject.wrapResponse = function(value) {
return {
'status': bot.ErrorCode.SUCCESS,
'value': bot.inject.wrapValue(value)
};
};
/**
* Wraps a JavaScript error in an object-literal so that it can be JSON-ified
* for transmission to the process that injected this script.
* @param {Error} err The error to wrap.
* @return {{status:bot.ErrorCode,value:*}} The wrapped error object.
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#failed-commands
*/
bot.inject.wrapError = function(err) {
// TODO: Parse stackTrace
return {
'status': goog.object.containsKey(err, 'code') ?
err['code'] : bot.ErrorCode.UNKNOWN_ERROR,
// TODO: Parse stackTrace
'value': {
'message': err.message
}
};
};
/**
* The property key used to store the element cache on the DOCUMENT node
* when it is injected into the page. Since compiling each browser atom results
* in a different symbol table, we must use this known key to access the cache.
* This ensures the same object is used between injections of different atoms.
* @private {string}
* @const
*/
bot.inject.cache.CACHE_KEY_ = '$wdc_';
/**
* The prefix for each key stored in an cache.
* @type {string}
* @const
*/
bot.inject.cache.ELEMENT_KEY_PREFIX = ':wdc:';
/**
* Retrieves the cache object for the given window. Will initialize the cache
* if it does not yet exist.
* @param {Document=} opt_doc The document whose cache to retrieve. Defaults to
* the current document.
* @return {Object.<string, (Element|Window)>} The cache object.
* @private
*/
bot.inject.cache.getCache_ = function(opt_doc) {
var doc = opt_doc || document;
var cache = doc[bot.inject.cache.CACHE_KEY_];
if (!cache) {
cache = doc[bot.inject.cache.CACHE_KEY_] = {};
// Store the counter used for generated IDs in the cache so that it gets
// reset whenever the cache does.
cache.nextId = goog.now();
}
// Sometimes the nextId does not get initialized and returns NaN
// TODO: Generate UID on the fly instead.
if (!cache.nextId) {
cache.nextId = goog.now();
}
return cache;
};
/**
* Adds an element to its ownerDocument's cache.
* @param {(Element|Window)} el The element or Window object to add.
* @return {string} The key generated for the cached element.
*/
bot.inject.cache.addElement = function(el) {
// Check if the element already exists in the cache.
var cache = bot.inject.cache.getCache_(el.ownerDocument);
var id = goog.object.findKey(cache, function(value) {
return value == el;
});
if (!id) {
id = bot.inject.cache.ELEMENT_KEY_PREFIX + cache.nextId++;
cache[id] = el;
}
return id;
};
/**
* Retrieves an element from the cache. Will verify that the element is
* still attached to the DOM before returning.
* @param {string} key The element's key in the cache.
* @param {Document=} opt_doc The document whose cache to retrieve the element
* from. Defaults to the current document.
* @return {Element|Window} The cached element.
*/
bot.inject.cache.getElement = function(key, opt_doc) {
key = decodeURIComponent(key);
var doc = opt_doc || document;
var cache = bot.inject.cache.getCache_(doc);
if (!goog.object.containsKey(cache, key)) {
// Throw STALE_ELEMENT_REFERENCE instead of NO_SUCH_ELEMENT since the
// key may have been defined by a prior document's cache.
throw new bot.Error(bot.ErrorCode.STALE_ELEMENT_REFERENCE,
'Element does not exist in cache');
}
var el = cache[key];
// If this is a Window check if it's closed
if (goog.object.containsKey(el, 'setInterval')) {
if (el.closed) {
delete cache[key];
throw new bot.Error(bot.ErrorCode.NO_SUCH_WINDOW,
'Window has been closed.');
}
return el;
}
// Make sure the element is still attached to the DOM before returning.
var node = el;
while (node) {
if (node == doc.documentElement) {
return el;
}
node = node.parentNode;
}
delete cache[key];
throw new bot.Error(bot.ErrorCode.STALE_ELEMENT_REFERENCE,
'Element is no longer attached to the DOM');
};
| alb-i986/selenium | javascript/atoms/inject.js | JavaScript | apache-2.0 | 18,402 |
<?php
/**
* @file
* Contains Drupal\Core\PathProcessor\PathProcessorDecode.
*/
namespace Drupal\Core\PathProcessor;
use Drupal\Core\Config\ConfigFactory;
use Symfony\Component\HttpFoundation\Request;
/**
* Processes the inbound path by urldecoding it.
*
* Parameters in the URL sometimes represent code-meaningful strings. It is
* therefore useful to always urldecode() those values so that individual
* controllers need not concern themselves with it. This is Drupal-specific
* logic and may not be familiar for developers used to other Symfony-family
* projects.
*
* @todo Revisit whether or not this logic is appropriate for here or if
* controllers should be required to implement this logic themselves. If we
* decide to keep this code, remove this TODO.
*/
class PathProcessorDecode implements InboundPathProcessorInterface {
/**
* Implements Drupal\Core\PathProcessor\InboundPathProcessorInterface::processInbound().
*/
public function processInbound($path, Request $request) {
return urldecode($path);
}
}
| nickopris/musicapp | www/core/lib/Drupal/Core/PathProcessor/PathProcessorDecode.php | PHP | apache-2.0 | 1,055 |
// Copyright 2010-2015 RethinkDB, all rights reserved.
#ifndef CLUSTERING_IMMEDIATE_CONSISTENCY_REPLICA_HPP_
#define CLUSTERING_IMMEDIATE_CONSISTENCY_REPLICA_HPP_
#include "clustering/immediate_consistency/backfill_metadata.hpp"
#include "clustering/immediate_consistency/backfiller.hpp"
#include "concurrency/timestamp_enforcer.hpp"
/* `replica_t` represents a replica of a shard which is currently tracking changes to a
given branch. `local_replicator_t` and `remote_replicator_client_t` construct a
`replica_t` after they finish initializing the state of the `store_t` to match the
ongoing writes from the `primary_dispatcher_t`. `replica_t` takes care of actually
applying those ongoing writes and reads to the `store_t`. It also takes care of providing
backfills to new `remote_replicator_client_t`s that are trying to start up. */
class replica_t : public home_thread_mixin_debug_only_t {
public:
replica_t(
mailbox_manager_t *mailbox_manager,
store_view_t *store,
branch_history_manager_t *bhm,
const branch_id_t &branch_id,
state_timestamp_t timestamp);
replica_bcard_t get_replica_bcard() {
return replica_bcard_t {
synchronize_mailbox.get_address(),
branch_id,
backfiller.get_business_card()
};
}
void do_read(
const read_t &read,
state_timestamp_t token,
signal_t *interruptor,
read_response_t *response_out);
/* Warning: If you interrupt `do_write()`, the `replica_t` will be left in an
undefined state, and you should destroy the `replica_t` soon after. */
void do_write(
const write_t &write,
state_timestamp_t timestamp,
order_token_t order_token,
write_durability_t durability,
signal_t *interruptor,
write_response_t *response_out);
void do_dummy_write(
signal_t *interruptor,
write_response_t *response_out);
private:
void on_synchronize(
signal_t *interruptor,
state_timestamp_t timestamp,
mailbox_t<>::address_t);
mailbox_manager_t *const mailbox_manager;
store_view_t *const store;
branch_id_t const branch_id;
/* A timestamp is completed in `start_enforcer` when the corresponding write has
acquired a token from the store, and in `end_enforcer` when the corresponding write
has completed. */
timestamp_enforcer_t start_enforcer, end_enforcer;
backfiller_t backfiller;
replica_bcard_t::synchronize_mailbox_t synchronize_mailbox;
};
#endif /* CLUSTERING_IMMEDIATE_CONSISTENCY_REPLICA_HPP_ */
| JackieXie168/rethinkdb | src/clustering/immediate_consistency/replica.hpp | C++ | apache-2.0 | 2,615 |
/*
* Copyright 2015 Evgeny Dolganov (evgenij.dolganov@gmail.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package och.util.log;
import static och.util.Util.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import och.util.concurrent.ExecutorsUtil;
import och.util.reflections.ProxyUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class AsyncLogFactory {
public static final Set<String> ASYNC_METHODS = set("debug", "error", "fatal", "info", "trace", "warn");
public static class AsyncHandler implements InvocationHandler {
final ExecutorService executor;
final Log real;
public AsyncHandler(ExecutorService executor, Log real) {
this.executor = executor;
this.real = real;
}
@Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
String name = m.getName();
if( ! ASYNC_METHODS.contains(name)){
return ProxyUtil.invokeReal(real, m, args);
}
//async
executor.submit(()->{
try {
ProxyUtil.invokeReal(real, m, args);
}catch(Throwable t){
t.printStackTrace();
}
});
return null;
}
}
private static final ExecutorService executor = ExecutorsUtil.newSingleThreadExecutor("async-logs-thread");
static {
LogFactory.getLog(AsyncLogFactory.class).info("\n***\nASYNC LOG FACTORY INITED\n***");
}
public static Log createAsyncLog(Log log){
AsyncHandler h = new AsyncHandler(executor, log);
return (Log) ProxyUtil.createProxy(AsyncLogFactory.class, Log.class, h);
}
}
| elw00d/live-chat-engine | common/util/src/och/util/log/AsyncLogFactory.java | Java | apache-2.0 | 2,178 |
/*
* 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.beam.runners.spark.structuredstreaming.aggregators.metrics.sink;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import org.apache.beam.runners.spark.structuredstreaming.SparkStructuredStreamingPipelineOptions;
import org.apache.beam.runners.spark.structuredstreaming.SparkStructuredStreamingRunner;
import org.apache.beam.runners.spark.structuredstreaming.examples.WordCount;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* TODO: add testInStreamingMode() once streaming support will be implemented.
*
* <p>A test that verifies Beam metrics are reported to Spark's metrics sink in both batch and
* streaming modes.
*/
@Ignore("Has been failing since at least c350188ef7a8704c7336f3c20a1ab2144abbcd4a")
@RunWith(JUnit4.class)
public class SparkMetricsSinkTest {
@Rule public ExternalResource inMemoryMetricsSink = new InMemoryMetricsSinkRule();
private static final ImmutableList<String> WORDS =
ImmutableList.of("hi there", "hi", "hi sue bob", "hi sue", "", "bob hi");
private static final ImmutableSet<String> EXPECTED_COUNTS =
ImmutableSet.of("hi: 5", "there: 1", "sue: 2", "bob: 2");
private static Pipeline pipeline;
@BeforeClass
public static void beforeClass() {
SparkStructuredStreamingPipelineOptions options =
PipelineOptionsFactory.create().as(SparkStructuredStreamingPipelineOptions.class);
options.setRunner(SparkStructuredStreamingRunner.class);
options.setTestMode(true);
pipeline = Pipeline.create(options);
}
@Test
public void testInBatchMode() throws Exception {
assertThat(InMemoryMetrics.valueOf("emptyLines"), is(nullValue()));
final PCollection<String> output =
pipeline
.apply(Create.of(WORDS).withCoder(StringUtf8Coder.of()))
.apply(new WordCount.CountWords())
.apply(MapElements.via(new WordCount.FormatAsTextFn()));
PAssert.that(output).containsInAnyOrder(EXPECTED_COUNTS);
pipeline.run();
assertThat(InMemoryMetrics.<Double>valueOf("emptyLines"), is(1d));
}
}
| axbaretto/beam | runners/spark/src/test/java/org/apache/beam/runners/spark/structuredstreaming/aggregators/metrics/sink/SparkMetricsSinkTest.java | Java | apache-2.0 | 3,611 |
/**
* 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.hadoop.mapreduce.v2.hs.webapp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response.Status;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.JobACLsManager;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.TaskCompletionEvent;
import org.apache.hadoop.mapreduce.Counters;
import org.apache.hadoop.mapreduce.JobACL;
import org.apache.hadoop.mapreduce.MRConfig;
import org.apache.hadoop.mapreduce.v2.api.records.AMInfo;
import org.apache.hadoop.mapreduce.v2.api.records.JobId;
import org.apache.hadoop.mapreduce.v2.api.records.JobReport;
import org.apache.hadoop.mapreduce.v2.api.records.JobState;
import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptCompletionEvent;
import org.apache.hadoop.mapreduce.v2.api.records.TaskId;
import org.apache.hadoop.mapreduce.v2.api.records.TaskType;
import org.apache.hadoop.mapreduce.v2.app.job.Job;
import org.apache.hadoop.mapreduce.v2.app.job.Task;
import org.apache.hadoop.mapreduce.v2.hs.HistoryContext;
import org.apache.hadoop.mapreduce.v2.hs.MockHistoryContext;
import org.apache.hadoop.security.GroupMappingServiceProvider;
import org.apache.hadoop.security.Groups;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.webapp.WebApp;
import org.junit.Before;
import org.junit.Test;
public class TestHsWebServicesAcls {
private static String FRIENDLY_USER = "friendly";
private static String ENEMY_USER = "enemy";
private JobConf conf;
private HistoryContext ctx;
private String jobIdStr;
private String taskIdStr;
private String taskAttemptIdStr;
private HsWebServices hsWebServices;
@Before
public void setup() throws IOException {
this.conf = new JobConf();
this.conf.set(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING,
NullGroupsProvider.class.getName());
this.conf.setBoolean(MRConfig.MR_ACLS_ENABLED, true);
Groups.getUserToGroupsMappingService(conf);
this.ctx = buildHistoryContext(this.conf);
WebApp webApp = mock(HsWebApp.class);
when(webApp.name()).thenReturn("hsmockwebapp");
this.hsWebServices = new HsWebServices(ctx, conf, webApp, null);
this.hsWebServices.setResponse(mock(HttpServletResponse.class));
Job job = ctx.getAllJobs().values().iterator().next();
this.jobIdStr = job.getID().toString();
Task task = job.getTasks().values().iterator().next();
this.taskIdStr = task.getID().toString();
this.taskAttemptIdStr =
task.getAttempts().keySet().iterator().next().toString();
}
@Test
public void testGetJobAcls() {
HttpServletRequest hsr = mock(HttpServletRequest.class);
when(hsr.getRemoteUser()).thenReturn(ENEMY_USER);
try {
hsWebServices.getJob(hsr, jobIdStr);
fail("enemy can access job");
} catch (WebApplicationException e) {
assertEquals(Status.UNAUTHORIZED,
Status.fromStatusCode(e.getResponse().getStatus()));
}
when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER);
hsWebServices.getJob(hsr, jobIdStr);
}
@Test
public void testGetJobCountersAcls() {
HttpServletRequest hsr = mock(HttpServletRequest.class);
when(hsr.getRemoteUser()).thenReturn(ENEMY_USER);
try {
hsWebServices.getJobCounters(hsr, jobIdStr);
fail("enemy can access job");
} catch (WebApplicationException e) {
assertEquals(Status.UNAUTHORIZED,
Status.fromStatusCode(e.getResponse().getStatus()));
}
when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER);
hsWebServices.getJobCounters(hsr, jobIdStr);
}
@Test
public void testGetJobConfAcls() {
HttpServletRequest hsr = mock(HttpServletRequest.class);
when(hsr.getRemoteUser()).thenReturn(ENEMY_USER);
try {
hsWebServices.getJobConf(hsr, jobIdStr);
fail("enemy can access job");
} catch (WebApplicationException e) {
assertEquals(Status.UNAUTHORIZED,
Status.fromStatusCode(e.getResponse().getStatus()));
}
when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER);
hsWebServices.getJobConf(hsr, jobIdStr);
}
@Test
public void testGetJobTasksAcls() {
HttpServletRequest hsr = mock(HttpServletRequest.class);
when(hsr.getRemoteUser()).thenReturn(ENEMY_USER);
try {
hsWebServices.getJobTasks(hsr, jobIdStr, "m");
fail("enemy can access job");
} catch (WebApplicationException e) {
assertEquals(Status.UNAUTHORIZED,
Status.fromStatusCode(e.getResponse().getStatus()));
}
when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER);
hsWebServices.getJobTasks(hsr, jobIdStr, "m");
}
@Test
public void testGetJobTaskAcls() {
HttpServletRequest hsr = mock(HttpServletRequest.class);
when(hsr.getRemoteUser()).thenReturn(ENEMY_USER);
try {
hsWebServices.getJobTask(hsr, jobIdStr, this.taskIdStr);
fail("enemy can access job");
} catch (WebApplicationException e) {
assertEquals(Status.UNAUTHORIZED,
Status.fromStatusCode(e.getResponse().getStatus()));
}
when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER);
hsWebServices.getJobTask(hsr, this.jobIdStr, this.taskIdStr);
}
@Test
public void testGetSingleTaskCountersAcls() {
HttpServletRequest hsr = mock(HttpServletRequest.class);
when(hsr.getRemoteUser()).thenReturn(ENEMY_USER);
try {
hsWebServices.getSingleTaskCounters(hsr, this.jobIdStr, this.taskIdStr);
fail("enemy can access job");
} catch (WebApplicationException e) {
assertEquals(Status.UNAUTHORIZED,
Status.fromStatusCode(e.getResponse().getStatus()));
}
when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER);
hsWebServices.getSingleTaskCounters(hsr, this.jobIdStr, this.taskIdStr);
}
@Test
public void testGetJobTaskAttemptsAcls() {
HttpServletRequest hsr = mock(HttpServletRequest.class);
when(hsr.getRemoteUser()).thenReturn(ENEMY_USER);
try {
hsWebServices.getJobTaskAttempts(hsr, this.jobIdStr, this.taskIdStr);
fail("enemy can access job");
} catch (WebApplicationException e) {
assertEquals(Status.UNAUTHORIZED,
Status.fromStatusCode(e.getResponse().getStatus()));
}
when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER);
hsWebServices.getJobTaskAttempts(hsr, this.jobIdStr, this.taskIdStr);
}
@Test
public void testGetJobTaskAttemptIdAcls() {
HttpServletRequest hsr = mock(HttpServletRequest.class);
when(hsr.getRemoteUser()).thenReturn(ENEMY_USER);
try {
hsWebServices.getJobTaskAttemptId(hsr, this.jobIdStr, this.taskIdStr,
this.taskAttemptIdStr);
fail("enemy can access job");
} catch (WebApplicationException e) {
assertEquals(Status.UNAUTHORIZED,
Status.fromStatusCode(e.getResponse().getStatus()));
}
when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER);
hsWebServices.getJobTaskAttemptId(hsr, this.jobIdStr, this.taskIdStr,
this.taskAttemptIdStr);
}
@Test
public void testGetJobTaskAttemptIdCountersAcls() {
HttpServletRequest hsr = mock(HttpServletRequest.class);
when(hsr.getRemoteUser()).thenReturn(ENEMY_USER);
try {
hsWebServices.getJobTaskAttemptIdCounters(hsr, this.jobIdStr,
this.taskIdStr, this.taskAttemptIdStr);
fail("enemy can access job");
} catch (WebApplicationException e) {
assertEquals(Status.UNAUTHORIZED,
Status.fromStatusCode(e.getResponse().getStatus()));
}
when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER);
hsWebServices.getJobTaskAttemptIdCounters(hsr, this.jobIdStr,
this.taskIdStr, this.taskAttemptIdStr);
}
private static HistoryContext buildHistoryContext(final Configuration conf)
throws IOException {
HistoryContext ctx = new MockHistoryContext(1, 1, 1);
Map<JobId, Job> jobs = ctx.getAllJobs();
JobId jobId = jobs.keySet().iterator().next();
Job mockJob = new MockJobForAcls(jobs.get(jobId), conf);
jobs.put(jobId, mockJob);
return ctx;
}
private static class NullGroupsProvider
implements GroupMappingServiceProvider {
@Override
public List<String> getGroups(String user) throws IOException {
return Collections.emptyList();
}
@Override
public void cacheGroupsRefresh() throws IOException {
}
@Override
public void cacheGroupsAdd(List<String> groups) throws IOException {
}
@Override
public Set<String> getGroupsSet(String user) throws IOException {
return Collections.emptySet();
}
}
private static class MockJobForAcls implements Job {
private Job mockJob;
private Configuration conf;
private Map<JobACL, AccessControlList> jobAcls;
private JobACLsManager aclsMgr;
public MockJobForAcls(Job mockJob, Configuration conf) {
this.mockJob = mockJob;
this.conf = conf;
AccessControlList viewAcl = new AccessControlList(FRIENDLY_USER);
this.jobAcls = new HashMap<JobACL, AccessControlList>();
this.jobAcls.put(JobACL.VIEW_JOB, viewAcl);
this.aclsMgr = new JobACLsManager(conf);
}
@Override
public JobId getID() {
return mockJob.getID();
}
@Override
public String getName() {
return mockJob.getName();
}
@Override
public JobState getState() {
return mockJob.getState();
}
@Override
public JobReport getReport() {
return mockJob.getReport();
}
@Override
public Counters getAllCounters() {
return mockJob.getAllCounters();
}
@Override
public Map<TaskId, Task> getTasks() {
return mockJob.getTasks();
}
@Override
public Map<TaskId, Task> getTasks(TaskType taskType) {
return mockJob.getTasks(taskType);
}
@Override
public Task getTask(TaskId taskID) {
return mockJob.getTask(taskID);
}
@Override
public List<String> getDiagnostics() {
return mockJob.getDiagnostics();
}
@Override
public int getTotalMaps() {
return mockJob.getTotalMaps();
}
@Override
public int getTotalReduces() {
return mockJob.getTotalReduces();
}
@Override
public int getCompletedMaps() {
return mockJob.getCompletedMaps();
}
@Override
public int getCompletedReduces() {
return mockJob.getCompletedReduces();
}
@Override
public float getProgress() {
return mockJob.getProgress();
}
@Override
public boolean isUber() {
return mockJob.isUber();
}
@Override
public String getUserName() {
return mockJob.getUserName();
}
@Override
public String getQueueName() {
return mockJob.getQueueName();
}
@Override
public Path getConfFile() {
return new Path("/some/path/to/conf");
}
@Override
public Configuration loadConfFile() throws IOException {
return conf;
}
@Override
public Map<JobACL, AccessControlList> getJobACLs() {
return jobAcls;
}
@Override
public TaskAttemptCompletionEvent[] getTaskAttemptCompletionEvents(
int fromEventId, int maxEvents) {
return mockJob.getTaskAttemptCompletionEvents(fromEventId, maxEvents);
}
@Override
public TaskCompletionEvent[] getMapAttemptCompletionEvents(
int startIndex, int maxEvents) {
return mockJob.getMapAttemptCompletionEvents(startIndex, maxEvents);
}
@Override
public List<AMInfo> getAMInfos() {
return mockJob.getAMInfos();
}
@Override
public boolean checkAccess(UserGroupInformation callerUGI,
JobACL jobOperation) {
return aclsMgr.checkAccess(callerUGI, jobOperation,
this.getUserName(), jobAcls.get(jobOperation));
}
@Override
public void setQueueName(String queueName) {
}
@Override
public void setJobPriority(Priority priority) {
}
@Override
public int getFailedMaps() {
return mockJob.getFailedMaps();
}
@Override
public int getFailedReduces() {
return mockJob.getFailedReduces();
}
@Override
public int getKilledMaps() {
return mockJob.getKilledMaps();
}
@Override
public int getKilledReduces() {
return mockJob.getKilledReduces();
}
}
}
| apurtell/hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/test/java/org/apache/hadoop/mapreduce/v2/hs/webapp/TestHsWebServicesAcls.java | Java | apache-2.0 | 13,711 |
package com.github.dockerjava.api.model;
import static org.apache.commons.lang.StringUtils.isEmpty;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.node.NullNode;
import com.github.dockerjava.api.command.InspectContainerResponse.NetworkSettings;
/**
* A container for port bindings, made available as a {@link Map} via its
* {@link #getBindings()} method.
* <p>
* <i>Note: This is an abstraction used for querying existing port bindings from
* a container configuration.
* It is not to be confused with the {@link PortBinding} abstraction used for
* adding new port bindings to a container.</i>
*
* @see HostConfig#getPortBindings()
* @see NetworkSettings#getPorts()
*/
@JsonDeserialize(using = Ports.Deserializer.class)
@JsonSerialize(using = Ports.Serializer.class)
public class Ports {
private final Map<ExposedPort, Binding[]> ports = new HashMap<ExposedPort, Binding[]>();
/**
* Creates a {@link Ports} object with no {@link PortBinding}s.
* Use {@link #bind(ExposedPort, Binding)} or {@link #add(PortBinding...)}
* to add {@link PortBinding}s.
*/
public Ports() { }
/**
* Creates a {@link Ports} object with an initial {@link PortBinding} for
* the specified {@link ExposedPort} and {@link Binding}.
* Use {@link #bind(ExposedPort, Binding)} or {@link #add(PortBinding...)}
* to add more {@link PortBinding}s.
*/
public Ports(ExposedPort exposedPort, Binding host) {
bind(exposedPort, host);
}
/**
* Adds a new {@link PortBinding} for the specified {@link ExposedPort} and
* {@link Binding} to the current bindings.
*/
public void bind(ExposedPort exposedPort, Binding binding) {
if (ports.containsKey(exposedPort)) {
Binding[] bindings = ports.get(exposedPort);
ports.put(exposedPort, (Binding[]) ArrayUtils.add(bindings, binding));
} else {
ports.put(exposedPort, new Binding[]{binding});
}
}
/**
* Adds the specified {@link PortBinding}(s) to the list of {@link PortBinding}s.
*/
public void add(PortBinding... portBindings) {
for (PortBinding binding : portBindings) {
bind(binding.getExposedPort(), binding.getBinding());
}
}
@Override
public String toString(){
return ports.toString();
}
/**
* Returns the port bindings in the format used by the Docker remote API,
* i.e. the {@link Binding}s grouped by {@link ExposedPort}.
*
* @return the port bindings as a {@link Map} that contains one or more
* {@link Binding}s per {@link ExposedPort}.
*/
public Map<ExposedPort, Binding[]> getBindings(){
return ports;
}
/**
* Creates a {@link Binding} for the given IP address and port number.
*/
public static Binding Binding(String hostIp, Integer hostPort) {
return new Binding(hostIp, hostPort);
}
/**
* Creates a {@link Binding} for the given port number, leaving the
* IP address undefined.
*/
public static Binding Binding(Integer hostPort) {
return new Binding(hostPort);
}
/**
* A {@link Binding} represents a socket on the Docker host that is
* used in a {@link PortBinding}.
* It is characterized by an {@link #getHostIp() IP address} and a
* {@link #getHostPort() port number}.
* Both properties may be <code>null</code> in order to let Docker assign
* them dynamically/using defaults.
*
* @see Ports#bind(ExposedPort, Binding)
* @see ExposedPort
*/
public static class Binding {
private final String hostIp;
private final Integer hostPort;
/**
* Creates a {@link Binding} for the given {@link #getHostIp() IP address}
* and {@link #getHostPort() port number}.
*
* @see Ports#bind(ExposedPort, Binding)
* @see ExposedPort
*/
public Binding(String hostIp, Integer hostPort) {
this.hostIp = isEmpty(hostIp) ? null : hostIp;
this.hostPort = hostPort;
}
/**
* Creates a {@link Binding} for the given {@link #getHostPort() port number},
* leaving the {@link #getHostIp() IP address} undefined.
*
* @see Ports#bind(ExposedPort, Binding)
* @see ExposedPort
*/
public Binding(Integer hostPort) {
this(null, hostPort);
}
/**
* Creates a {@link Binding} for the given {@link #getHostIp() IP address},
* leaving the {@link #getHostPort() port number} undefined.
*/
public Binding(String hostIp) {
this(hostIp, null);
}
/**
* Creates a {@link Binding} with both {@link #getHostIp() IP address} and
* {@link #getHostPort() port number} undefined.
*/
public Binding() {
this(null, null);
}
/**
* @return the IP address on the Docker host.
* May be <code>null</code>, in which case Docker will bind the
* port to all interfaces (<code>0.0.0.0</code>).
*/
public String getHostIp() {
return hostIp;
}
/**
* @return the port number on the Docker host.
* May be <code>null</code>, in which case Docker will dynamically
* assign a port.
*/
public Integer getHostPort() {
return hostPort;
}
/**
* Parses a textual host and port specification (as used by the Docker CLI)
* to a {@link Binding}.
* <p>
* Legal syntax: <code>IP|IP:port|port</code>
*
* @param serialized serialized the specification, e.g.
* <code>127.0.0.1:80</code>
* @return a {@link Binding} matching the specification
* @throws IllegalArgumentException if the specification cannot be parsed
*/
public static Binding parse(String serialized) throws IllegalArgumentException {
try {
if (serialized.isEmpty()) {
return new Binding();
}
String[] parts = serialized.split(":");
switch (parts.length) {
case 2: {
return new Binding(parts[0], Integer.valueOf(parts[1]));
}
case 1: {
return parts[0].contains(".") ? new Binding(parts[0])
: new Binding(Integer.valueOf(parts[0]));
}
default: {
throw new IllegalArgumentException();
}
}
} catch (Exception e) {
throw new IllegalArgumentException("Error parsing Binding '"
+ serialized + "'");
}
}
/**
* Returns a string representation of this {@link Binding} suitable
* for inclusion in a JSON message.
* The format is <code>[IP:]Port</code>, like the argument in {@link #parse(String)}.
*
* @return a string representation of this {@link Binding}
*/
@Override
public String toString() {
if (isEmpty(hostIp)) {
return Integer.toString(hostPort);
} else if (hostPort == null) {
return hostIp;
} else {
return hostIp + ":" + hostPort;
}
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Binding) {
Binding other = (Binding) obj;
return new EqualsBuilder()
.append(hostIp, other.getHostIp())
.append(hostPort, other.getHostPort()).isEquals();
} else
return super.equals(obj);
}
}
public static class Deserializer extends JsonDeserializer<Ports> {
@Override
public Ports deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
Ports out = new Ports();
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext();) {
Map.Entry<String, JsonNode> portNode = it.next();
JsonNode bindingsArray = portNode.getValue();
for (int i = 0; i < bindingsArray.size(); i++) {
JsonNode bindingNode = bindingsArray.get(i);
if (!bindingNode.equals(NullNode.getInstance())) {
String hostIp = bindingNode.get("HostIp").textValue();
int hostPort = bindingNode.get("HostPort").asInt();
out.bind(ExposedPort.parse(portNode.getKey()), new Binding(hostIp, hostPort));
}
}
}
return out;
}
}
public static class Serializer extends JsonSerializer<Ports> {
@Override
public void serialize(Ports portBindings, JsonGenerator jsonGen,
SerializerProvider serProvider) throws IOException, JsonProcessingException {
jsonGen.writeStartObject();
for(Entry<ExposedPort, Binding[]> entry : portBindings.getBindings().entrySet()){
jsonGen.writeFieldName(entry.getKey().toString());
jsonGen.writeStartArray();
for (Binding binding : entry.getValue()) {
jsonGen.writeStartObject();
jsonGen.writeStringField("HostIp", binding.getHostIp() == null ? "" : binding.getHostIp());
jsonGen.writeStringField("HostPort", binding.getHostPort() == null ? "" : binding.getHostPort().toString());
jsonGen.writeEndObject();
}
jsonGen.writeEndArray();
}
jsonGen.writeEndObject();
}
}
}
| netvl/docker-java | src/main/java/com/github/dockerjava/api/model/Ports.java | Java | apache-2.0 | 10,941 |
#
# Author:: Matthew Kent (<mkent@magoazul.com>)
# Copyright:: Copyright (c) 2009 Matthew Kent
# License:: Apache License, Version 2.0
#
# 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.
#
require "ohai/mixin/network_constants"
Ohai.plugin(:Network) do
include Ohai::Mixin::NetworkConstants
provides "network", "network/interfaces"
provides "counters/network", "counters/network/interfaces"
def sigar_encaps_lookup(encap)
return "Loopback" if encap.eql?("Local Loopback")
return "PPP" if encap.eql?("Point-to-Point Protocol")
return "SLIP" if encap.eql?("Serial Line IP")
return "VJSLIP" if encap.eql?("VJ Serial Line IP")
return "IPIP" if encap.eql?("IPIP Tunnel")
return "6to4" if encap.eql?("IPv6-in-IPv4")
encap
end
def fetch_interfaces(sigar)
iface = Mash.new
net_counters = Mash.new
sigar.net_interface_list.each do |cint|
iface[cint] = Mash.new
if cint =~ /^(\w+)(\d+.*)/
iface[cint][:type] = $1
iface[cint][:number] = $2
end
ifconfig = sigar.net_interface_config(cint)
iface[cint][:encapsulation] = sigar_encaps_lookup(ifconfig.type)
iface[cint][:addresses] = Mash.new
# Backwards compat: loopback has no hwaddr
if (ifconfig.flags & Sigar::IFF_LOOPBACK) == 0
iface[cint][:addresses][ifconfig.hwaddr] = { "family" => "lladdr" }
end
if ifconfig.address != "0.0.0.0"
iface[cint][:addresses][ifconfig.address] = { "family" => "inet" }
# Backwards compat: no broadcast on tunnel or loopback dev
if ((ifconfig.flags & Sigar::IFF_POINTOPOINT) == 0) &&
((ifconfig.flags & Sigar::IFF_LOOPBACK) == 0)
iface[cint][:addresses][ifconfig.address]["broadcast"] = ifconfig.broadcast
end
iface[cint][:addresses][ifconfig.address]["netmask"] = ifconfig.netmask
end
if ifconfig.prefix6_length != 0
iface[cint][:addresses][ifconfig.address6] = { "family" => "inet6" }
iface[cint][:addresses][ifconfig.address6]["prefixlen"] = ifconfig.prefix6_length.to_s
iface[cint][:addresses][ifconfig.address6]["scope"] = Sigar.net_scope_to_s(ifconfig.scope6)
end
iface[cint][:flags] = Sigar.net_interface_flags_to_s(ifconfig.flags).split(" ")
iface[cint][:mtu] = ifconfig.mtu.to_s
iface[cint][:queuelen] = ifconfig.tx_queue_len.to_s
net_counters[cint] = Mash.new unless net_counters[cint]
if !cint.include?(":")
ifstat = sigar.net_interface_stat(cint)
net_counters[cint][:rx] = { "packets" => ifstat.rx_packets.to_s, "errors" => ifstat.rx_errors.to_s,
"drop" => ifstat.rx_dropped.to_s, "overrun" => ifstat.rx_overruns.to_s,
"frame" => ifstat.rx_frame.to_s, "bytes" => ifstat.rx_bytes.to_s }
net_counters[cint][:tx] = { "packets" => ifstat.tx_packets.to_s, "errors" => ifstat.tx_errors.to_s,
"drop" => ifstat.tx_dropped.to_s, "overrun" => ifstat.tx_overruns.to_s,
"carrier" => ifstat.tx_carrier.to_s, "collisions" => ifstat.tx_collisions.to_s,
"bytes" => ifstat.tx_bytes.to_s }
end
end
begin
sigar.arp_list.each do |arp|
next unless iface[arp.ifname] # this should never happen
iface[arp.ifname][:arp] = Mash.new unless iface[arp.ifname][:arp]
iface[arp.ifname][:arp][arp.address] = arp.hwaddr
end
rescue
#64-bit AIX for example requires 64-bit caller
end
[iface, net_counters]
end
# sigar-only, from network_route plugin
def flags(flags)
f = ""
if (flags & Sigar::RTF_UP) != 0
f += "U"
end
if (flags & Sigar::RTF_GATEWAY) != 0
f += "G"
end
if (flags & Sigar::RTF_HOST) != 0
f += "H"
end
f
end
collect_data(:hpux) do
require "sigar"
sigar = Sigar.new
network Mash.new unless network
network[:interfaces] = Mash.new unless network[:interfaces]
counters Mash.new unless counters
counters[:network] = Mash.new unless counters[:network]
ninfo = sigar.net_info
network[:default_interface] = ninfo.default_gateway_interface
network[:default_gateway] = ninfo.default_gateway
iface, net_counters = fetch_interfaces(sigar)
counters[:network][:interfaces] = net_counters
network["interfaces"] = iface
end
collect_data(:default) do
require "sigar"
sigar = Sigar.new
network Mash.new unless network
network[:interfaces] = Mash.new unless network[:interfaces]
counters Mash.new unless counters
counters[:network] = Mash.new unless counters[:network]
ninfo = sigar.net_info
network[:default_interface] = ninfo.default_gateway_interface
network[:default_gateway] = ninfo.default_gateway
iface, net_counters = fetch_interfaces(sigar)
counters[:network][:interfaces] = net_counters
network[:interfaces] = iface
sigar.net_route_list.each do |route|
next unless network[:interfaces][route.ifname] # this
# should never happen
network[:interfaces][route.ifname][:route] = Mash.new unless network[:interfaces][route.ifname][:route]
route_data = {}
Ohai::Mixin::NetworkConstants::SIGAR_ROUTE_METHODS.each do |m|
if m == :flags
route_data[m] = flags(route.send(m))
else
route_data[m] = route.send(m)
end
end
network[:interfaces][route.ifname][:route][route.destination] = route_data
end
end
end
| criteo-forks/ohai | lib/ohai/plugins/sigar/network.rb | Ruby | apache-2.0 | 6,094 |
/*
* 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.internal.processors.cache.distributed;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.cache.CacheException;
import javax.cache.processor.MutableEntry;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheEntryProcessor;
import org.apache.ignite.cluster.ClusterTopologyException;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
/**
*
*/
public class IgniteBinaryMetadataUpdateNodeRestartTest extends GridCommonAbstractTest {
/** */
private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
/** */
private static final String ATOMIC_CACHE = "atomicCache";
/** */
private static final String TX_CACHE = "txCache";
/** */
private static final int SRVS = 3;
/** */
private static final int CLIENTS = 1;
/** */
private boolean client;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(IP_FINDER);
((TcpCommunicationSpi)cfg.getCommunicationSpi()).setSharedMemoryPort(-1);
cfg.setMarshaller(null);
CacheConfiguration ccfg1 = cacheConfiguration(TX_CACHE, TRANSACTIONAL);
CacheConfiguration ccfg2 = cacheConfiguration(ATOMIC_CACHE, ATOMIC);
cfg.setCacheConfiguration(ccfg1, ccfg2);
cfg.setClientMode(client);
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
super.beforeTestsStarted();
System.setProperty(IgniteSystemProperties.IGNITE_ENABLE_FORCIBLE_NODE_KILL,"true");
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
stopAllGrids();
System.clearProperty(IgniteSystemProperties.IGNITE_ENABLE_FORCIBLE_NODE_KILL);
super.afterTestsStopped();
}
/**
* @param name Cache name.
* @param atomicityMode Cache atomicity mode.
* @return Cache configuration.
*/
private CacheConfiguration cacheConfiguration(String name, CacheAtomicityMode atomicityMode) {
CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
ccfg.setCacheMode(PARTITIONED);
ccfg.setBackups(1);
ccfg.setWriteSynchronizationMode(FULL_SYNC);
ccfg.setName(name);
ccfg.setAtomicityMode(atomicityMode);
return ccfg;
}
/**
* @throws Exception If failed.
*/
public void testNodeRestart() throws Exception {
for (int i = 0; i < 10; i++) {
log.info("Iteration: " + i);
client = false;
startGridsMultiThreaded(SRVS);
client = true;
startGrid(SRVS);
final AtomicBoolean stop = new AtomicBoolean();
try {
IgniteInternalFuture<?> restartFut = GridTestUtils.runAsync(new Callable<Void>() {
@Override public Void call() throws Exception {
while (!stop.get()) {
log.info("Start node.");
startGrid(SRVS + CLIENTS);
log.info("Stop node.");
stopGrid(SRVS + CLIENTS);
}
return null;
}
}, "restart-thread");
final AtomicInteger idx = new AtomicInteger();
IgniteInternalFuture<?> fut = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
int threadIdx = idx.getAndIncrement();
int node = threadIdx % (SRVS + CLIENTS);
Ignite ignite = ignite(node);
log.info("Started thread: " + ignite.name());
Thread.currentThread().setName("update-thread-" + threadIdx + "-" + ignite.name());
IgniteCache<Object, Object> cache1 = ignite.cache(ATOMIC_CACHE);
IgniteCache<Object, Object> cache2 = ignite.cache(TX_CACHE);
ThreadLocalRandom rnd = ThreadLocalRandom.current();
while (!stop.get()) {
try {
cache1.put(new TestClass1(true), create(rnd.nextInt(20) + 1));
cache1.invoke(new TestClass1(true), new TestEntryProcessor(rnd.nextInt(20) + 1));
cache2.put(new TestClass1(true), create(rnd.nextInt(20) + 1));
cache2.invoke(new TestClass1(true), new TestEntryProcessor(rnd.nextInt(20) + 1));
}
catch (CacheException | IgniteException e) {
log.info("Error: " + e);
if (X.hasCause(e, ClusterTopologyException.class)) {
ClusterTopologyException cause = X.cause(e, ClusterTopologyException.class);
if (cause.retryReadyFuture() != null)
cause.retryReadyFuture().get();
}
}
}
return null;
}
}, 10, "update-thread");
U.sleep(5_000);
stop.set(true);
restartFut.get();
fut.get();
}
finally {
stop.set(true);
stopAllGrids();
}
}
}
/**
* @param id Class ID.
* @return Test class instance.
*/
private static Object create(int id) {
switch (id) {
case 1: return new TestClass1(true);
case 2: return new TestClass2();
case 3: return new TestClass3();
case 4: return new TestClass4();
case 5: return new TestClass5();
case 6: return new TestClass6();
case 7: return new TestClass7();
case 8: return new TestClass8();
case 9: return new TestClass9();
case 10: return new TestClass10();
case 11: return new TestClass11();
case 12: return new TestClass12();
case 13: return new TestClass13();
case 14: return new TestClass14();
case 15: return new TestClass15();
case 16: return new TestClass16();
case 17: return new TestClass17();
case 18: return new TestClass18();
case 19: return new TestClass19();
case 20: return new TestClass20();
}
fail();
return null;
}
/**
*
*/
static class TestEntryProcessor implements CacheEntryProcessor<Object, Object, Object> {
/** */
private int id;
/**
* @param id Value id.
*/
public TestEntryProcessor(int id) {
this.id = id;
}
/** {@inheritDoc} */
@Override public Object process(MutableEntry<Object, Object> entry, Object... args) {
entry.setValue(create(id));
return null;
}
}
/**
*
*/
static class TestClass1 {
/** */
int val;
/**
* @param setVal Set value flag.
*/
public TestClass1(boolean setVal) {
this.val = setVal ? ThreadLocalRandom.current().nextInt(10_000) : 0;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
TestClass1 that = (TestClass1)o;
return val == that.val;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return val;
}
}
/**
*
*/
static class TestClass2 {}
/**
*
*/
static class TestClass3 {}
/**
*
*/
static class TestClass4 {}
/**
*
*/
static class TestClass5 {}
/**
*
*/
static class TestClass6 {}
/**
*
*/
static class TestClass7 {}
/**
*
*/
static class TestClass8 {}
/**
*
*/
static class TestClass9 {}
/**
*
*/
static class TestClass10 {}
/**
*
*/
static class TestClass11 {}
/**
*
*/
static class TestClass12 {}
/**
*
*/
static class TestClass13 {}
/**
*
*/
static class TestClass14 {}
/**
*
*/
static class TestClass15 {}
/**
*
*/
static class TestClass16 {}
/**
*
*/
static class TestClass17 {}
/**
*
*/
static class TestClass18 {}
/**
*
*/
static class TestClass19 {}
/**
*
*/
static class TestClass20 {}
}
| WilliamDo/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteBinaryMetadataUpdateNodeRestartTest.java | Java | apache-2.0 | 11,286 |
/*<license>
Copyright 2004 - $Date$ by PeopleWare n.v..
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
</license>*/
package org.ppwcode.vernacular.resourcebundle_II;
import static org.ppwcode.metainfo_I.License.Type.APACHE_V2;
import java.util.ResourceBundle;
import org.ppwcode.metainfo_I.Copyright;
import org.ppwcode.metainfo_I.License;
import org.ppwcode.metainfo_I.vcs.SvnInfo;
import org.toryt.annotations_I.Basic;
import org.toryt.annotations_I.Expression;
import org.toryt.annotations_I.Invars;
import org.toryt.annotations_I.MethodContract;
/**
* Exception thrown if a applicable {@link ResourceBundle} cannot be found.
*
* @author Jan Dockx
* @author PeopleWare n.v.
*/
@Copyright("2004 - $Date$, PeopleWare n.v.")
@License(APACHE_V2)
@SvnInfo(revision = "$Revision$",
date = "$Date$")
@Invars(@Expression("message == null"))
public class ResourceBundleNotFoundException extends ResourceBundleException {
@MethodContract(post = {
@Expression("basename == _basename"),
@Expression("cause == null")
})
public ResourceBundleNotFoundException(String basename) {
this(basename, null);
}
@MethodContract(post = {
@Expression("basename == _basename"),
@Expression("cause == _cause")
})
public ResourceBundleNotFoundException(String basename, Throwable cause) {
super(cause);
$basename = basename;
}
/* <property name="locale"> */
//------------------------------------------------------------------
@Basic
public final String getBasename() {
return $basename;
}
private String $basename;
/* </property> */
}
| jandppw/ppwcode-recovered-from-google-code | java/vernacular/l10n/dev/d20081116-0032/src/main/java/org/ppwcode/vernacular/resourcebundle_II/ResourceBundleNotFoundException.java | Java | apache-2.0 | 2,084 |
/*
* 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.flink.runtime;
import org.apache.flink.util.FlinkException;
/**
* Indicates that a job is not stoppable.
*/
public class StoppingException extends FlinkException {
private static final long serialVersionUID = -721315728140810694L;
public StoppingException(String msg) {
super(msg);
}
public StoppingException(String message, Throwable cause) {
super(message, cause);
}
}
| zimmermatt/flink | flink-runtime/src/main/java/org/apache/flink/runtime/StoppingException.java | Java | apache-2.0 | 1,213 |
/*
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.
*/
var Q = require('q');
var path = require('path');
var shell = require('shelljs');
var Version = require('./Version');
var events = require('cordova-common').events;
var spawn = require('cordova-common').superspawn.spawn;
function MSBuildTools (version, path) {
this.version = version;
this.path = path;
}
MSBuildTools.prototype.buildProject = function(projFile, buildType, buildarch, otherConfigProperties) {
events.emit('log', 'Building project: ' + projFile);
events.emit('log', '\tConfiguration : ' + buildType);
events.emit('log', '\tPlatform : ' + buildarch);
var args = ['/clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal', '/nologo',
'/p:Configuration=' + buildType,
'/p:Platform=' + buildarch];
if (otherConfigProperties) {
var keys = Object.keys(otherConfigProperties);
keys.forEach(function(key) {
args.push('/p:' + key + '=' + otherConfigProperties[key]);
});
}
return spawn(path.join(this.path, 'msbuild'), [projFile].concat(args), { stdio: 'inherit' });
};
// returns full path to msbuild tools required to build the project and tools version
module.exports.findAvailableVersion = function () {
var versions = ['15.0', '14.0', '12.0', '4.0'];
return Q.all(versions.map(checkMSBuildVersion)).then(function (versions) {
// select first msbuild version available, and resolve promise with it
var msbuildTools = versions[0] || versions[1] || versions[2] || versions[3];
return msbuildTools ? Q.resolve(msbuildTools) : Q.reject('MSBuild tools not found');
});
};
module.exports.findAllAvailableVersions = function () {
var versions = ['15.0', '14.0', '12.0', '4.0'];
events.emit('verbose', 'Searching for available MSBuild versions...');
return Q.all(versions.map(checkMSBuildVersion)).then(function(unprocessedResults) {
return unprocessedResults.filter(function(item) {
return !!item;
});
});
};
function checkMSBuildVersion(version) {
return spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\' + version, '/v', 'MSBuildToolsPath'])
.then(function(output) {
// fetch msbuild path from 'reg' output
var toolsPath = /MSBuildToolsPath\s+REG_SZ\s+(.*)/i.exec(output);
if (toolsPath) {
toolsPath = toolsPath[1];
// CB-9565: Windows 10 invokes .NET Native compiler, which only runs on x86 arch,
// so if we're running an x64 Node, make sure to use x86 tools.
if ((version === '15.0' || version === '14.0') && toolsPath.indexOf('amd64') > -1) {
toolsPath = path.resolve(toolsPath, '..');
}
events.emit('verbose', 'Found MSBuild v' + version + ' at ' + toolsPath);
return new MSBuildTools(version, toolsPath);
}
})
.catch(function (err) {
// if 'reg' exits with error, assume that registry key not found
return;
});
}
/// returns an array of available UAP Versions
function getAvailableUAPVersions() {
/*jshint -W069 */
var programFilesFolder = process.env['ProgramFiles(x86)'] || process.env['ProgramFiles'];
// No Program Files folder found, so we won't be able to find UAP SDK
if (!programFilesFolder) return [];
var uapFolderPath = path.join(programFilesFolder, 'Windows Kits', '10', 'Platforms', 'UAP');
if (!shell.test('-e', uapFolderPath)) {
return []; // No UAP SDK exists on this machine
}
var result = [];
shell.ls(uapFolderPath).filter(function(uapDir) {
return shell.test('-d', path.join(uapFolderPath, uapDir));
}).map(function(folder) {
return Version.tryParse(folder);
}).forEach(function(version, index) {
if (version) {
result.push(version);
}
});
return result;
}
module.exports.getAvailableUAPVersions = getAvailableUAPVersions;
| sgrebnov/cordova-windows | template/cordova/lib/MSBuildTools.js | JavaScript | apache-2.0 | 4,798 |
/*
* 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.yardstick.cache;
import java.util.Map;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.yardstick.cache.model.SampleValue;
/**
* Ignite benchmark that performs transactional put operations.
*/
public class IgnitePutTxBenchmark extends IgniteCacheAbstractBenchmark {
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
int key = nextRandom(args.range());
// Implicit transaction is used.
cache.put(key, new SampleValue(key));
return true;
}
/** {@inheritDoc} */
@Override protected IgniteCache<Integer, Object> cache() {
return ignite().cache("tx");
}
} | dlnufox/ignite | modules/yardstick/src/main/java/org/apache/ignite/yardstick/cache/IgnitePutTxBenchmark.java | Java | apache-2.0 | 1,510 |
/*
* Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.rmi;
/**
* From a server executing on JDK 1.1, a
* <code>ServerRuntimeException</code> is thrown as a result of a
* remote method invocation when a <code>RuntimeException</code> is
* thrown while processing the invocation on the server, either while
* unmarshalling the arguments, executing the remote method itself, or
* marshalling the return value.
*
* A <code>ServerRuntimeException</code> instance contains the original
* <code>RuntimeException</code> that occurred as its cause.
*
* <p>A <code>ServerRuntimeException</code> is not thrown from servers
* executing on the Java 2 platform v1.2 or later versions.
*
* @author Ann Wollrath
* @since JDK1.1
* @deprecated no replacement
*/
@Deprecated
public class ServerRuntimeException extends RemoteException {
/* indicate compatibility with JDK 1.1.x version of class */
private static final long serialVersionUID = 7054464920481467219L;
/**
* Constructs a <code>ServerRuntimeException</code> with the specified
* detail message and nested exception.
*
* @param s the detail message
* @param ex the nested exception
* @deprecated no replacement
* @since JDK1.1
*/
@Deprecated
public ServerRuntimeException(String s, Exception ex) {
super(s, ex);
}
}
| shun634501730/java_source_cn | src_en/java/rmi/ServerRuntimeException.java | Java | apache-2.0 | 1,533 |
package test.jpms.g;
import aQute.bnd.annotation.spi.ServiceProvider;
@ServiceProvider(Cloneable.class)
public class Foo implements Cloneable {}
| psoreide/bnd | biz.aQute.bndlib.tests/test/test/jpms/g/Foo.java | Java | apache-2.0 | 147 |
/*
* Copyright (c) 2014 AsyncHttpClient Project. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient.config;
public final class AsyncHttpClientConfigDefaults {
private AsyncHttpClientConfigDefaults() {
}
public static final String ASYNC_CLIENT_CONFIG_ROOT = "org.asynchttpclient.";
public static int defaultMaxConnections() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "maxConnections");
}
public static int defaultMaxConnectionsPerHost() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "maxConnectionsPerHost");
}
public static int defaultConnectTimeout() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "connectTimeout");
}
public static int defaultPooledConnectionIdleTimeout() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "pooledConnectionIdleTimeout");
}
public static int defaultReadTimeout() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "readTimeout");
}
public static int defaultRequestTimeout() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "requestTimeout");
}
public static int defaultWebSocketTimeout() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "webSocketTimeout");
}
public static int defaultConnectionTTL() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "connectionTTL");
}
public static boolean defaultFollowRedirect() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "followRedirect");
}
public static int defaultMaxRedirects() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "maxRedirects");
}
public static boolean defaultCompressionEnforced() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "compressionEnforced");
}
public static String defaultUserAgent() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getString(ASYNC_CLIENT_CONFIG_ROOT + "userAgent");
}
public static int defaultIoThreadMultiplier() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "ioThreadMultiplier");
}
public static String[] defaultEnabledProtocols() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getStringArray(ASYNC_CLIENT_CONFIG_ROOT + "enabledProtocols");
}
public static boolean defaultUseProxySelector() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "useProxySelector");
}
public static boolean defaultUseProxyProperties() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "useProxyProperties");
}
public static boolean defaultStrict302Handling() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "strict302Handling");
}
public static boolean defaultAllowPoolingConnections() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "allowPoolingConnections");
}
public static int defaultMaxRequestRetry() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "maxRequestRetry");
}
public static boolean defaultAllowPoolingSslConnections() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "allowPoolingSslConnections");
}
public static boolean defaultDisableUrlEncodingForBoundRequests() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "disableUrlEncodingForBoundRequests");
}
public static boolean defaultAcceptAnyCertificate() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "acceptAnyCertificate");
}
public static Integer defaultSslSessionCacheSize() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInteger(ASYNC_CLIENT_CONFIG_ROOT + "sslSessionCacheSize");
}
public static Integer defaultSslSessionTimeout() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInteger(ASYNC_CLIENT_CONFIG_ROOT + "sslSessionTimeout");
}
public static int defaultHttpClientCodecMaxInitialLineLength() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "httpClientCodecMaxInitialLineLength");
}
public static int defaultHttpClientCodecMaxHeaderSize() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "httpClientCodecMaxHeaderSize");
}
public static int defaultHttpClientCodecMaxChunkSize() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "httpClientCodecMaxChunkSize");
}
public static boolean defaultDisableZeroCopy() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "disableZeroCopy");
}
public static long defaultHandshakeTimeout() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getLong(ASYNC_CLIENT_CONFIG_ROOT + "handshakeTimeout");
}
public static int defaultChunkedFileChunkSize() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "chunkedFileChunkSize");
}
public static int defaultWebSocketMaxBufferSize() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "webSocketMaxBufferSize");
}
public static int defaultWebSocketMaxFrameSize() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + "webSocketMaxFrameSize");
}
public static boolean defaultKeepEncodingHeader() {
return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + "keepEncodingHeader");
}
}
| elijah513/async-http-client | api/src/main/java/org/asynchttpclient/config/AsyncHttpClientConfigDefaults.java | Java | apache-2.0 | 7,292 |
/*
* 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.jdbc.impl;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Map;
import org.apache.calcite.avatica.util.Cursor.Accessor;
import org.apache.drill.exec.vector.accessor.SqlAccessor;
import org.apache.drill.jdbc.InvalidCursorStateSqlException;
// TODO: Revisit adding null check for non-primitive types to SqlAccessor's
// contract and classes generated by SqlAccessor template (DRILL-xxxx).
class AvaticaDrillSqlAccessor implements Accessor {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AvaticaDrillSqlAccessor.class);
private final static byte PRIMITIVE_NUM_NULL_VALUE = 0;
private final static boolean BOOLEAN_NULL_VALUE = false;
private SqlAccessor underlyingAccessor;
private DrillCursor cursor;
AvaticaDrillSqlAccessor(SqlAccessor drillSqlAccessor, DrillCursor cursor) {
super();
this.underlyingAccessor = drillSqlAccessor;
this.cursor = cursor;
}
private int getCurrentRecordNumber() throws SQLException {
// WORKAROUND: isBeforeFirst can't be called first here because AvaticaResultSet
// .next() doesn't increment its row field when cursor.next() returns false,
// so in that case row can be left at -1, so isBeforeFirst() returns true
// even though we're not longer before the empty set of rows--and it's all
// private, so we can't get to it to override any of several candidates.
if ( cursor.isAfterLast() ) {
throw new InvalidCursorStateSqlException(
"Result set cursor is already positioned past all rows." );
}
else if ( cursor.isBeforeFirst() ) {
throw new InvalidCursorStateSqlException(
"Result set cursor is positioned before all rows. Call next() first." );
}
else {
return cursor.getCurrentRecordNumber();
}
}
/**
* @see SQLAccessor#getObjectClass()
*/
public Class<?> getObjectClass() {
return underlyingAccessor.getObjectClass();
}
@Override
public boolean wasNull() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber());
}
@Override
public String getString() throws SQLException {
return underlyingAccessor.getString(getCurrentRecordNumber());
}
@Override
public boolean getBoolean() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? BOOLEAN_NULL_VALUE
: underlyingAccessor.getBoolean(getCurrentRecordNumber());
}
@Override
public byte getByte() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getByte(getCurrentRecordNumber());
}
@Override
public short getShort() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getShort(getCurrentRecordNumber());
}
@Override
public int getInt() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getInt(getCurrentRecordNumber());
}
@Override
public long getLong() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getLong(getCurrentRecordNumber());
}
@Override
public float getFloat() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getFloat(getCurrentRecordNumber());
}
@Override
public double getDouble() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getDouble(getCurrentRecordNumber());
}
@Override
public BigDecimal getBigDecimal() throws SQLException {
return underlyingAccessor.getBigDecimal(getCurrentRecordNumber());
}
@Override
public BigDecimal getBigDecimal(int scale) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public byte[] getBytes() throws SQLException {
return underlyingAccessor.getBytes(getCurrentRecordNumber());
}
@Override
public InputStream getAsciiStream() throws SQLException {
return underlyingAccessor.getStream(getCurrentRecordNumber());
}
@Override
public InputStream getUnicodeStream() throws SQLException {
return underlyingAccessor.getStream(getCurrentRecordNumber());
}
@Override
public InputStream getBinaryStream() throws SQLException {
return underlyingAccessor.getStream(getCurrentRecordNumber());
}
@Override
public Object getObject() throws SQLException {
return underlyingAccessor.getObject(getCurrentRecordNumber());
}
@Override
public Reader getCharacterStream() throws SQLException {
return underlyingAccessor.getReader(getCurrentRecordNumber());
}
@Override
public Object getObject(Map<String, Class<?>> map) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Ref getRef() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Blob getBlob() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Clob getClob() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Array getArray() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Date getDate(Calendar calendar) throws SQLException {
return underlyingAccessor.getDate(getCurrentRecordNumber());
}
@Override
public Time getTime(Calendar calendar) throws SQLException {
return underlyingAccessor.getTime(getCurrentRecordNumber());
}
@Override
public Timestamp getTimestamp(Calendar calendar) throws SQLException {
return underlyingAccessor.getTimestamp(getCurrentRecordNumber());
}
@Override
public URL getURL() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public NClob getNClob() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public SQLXML getSQLXML() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public String getNString() throws SQLException {
return underlyingAccessor.getString(getCurrentRecordNumber());
}
@Override
public Reader getNCharacterStream() throws SQLException {
return underlyingAccessor.getReader(getCurrentRecordNumber());
}
@Override
public <T> T getObject(Class<T> type) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
}
| parthchandra/incubator-drill | exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/AvaticaDrillSqlAccessor.java | Java | apache-2.0 | 7,901 |
/*
* 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.sysml.runtime.instructions.mr;
import java.util.ArrayList;
import org.apache.sysml.lops.AppendM.CacheType;
import org.apache.sysml.lops.BinaryM.VectorType;
import org.apache.sysml.runtime.instructions.InstructionUtils;
import org.apache.sysml.runtime.matrix.data.MatrixValue;
import org.apache.sysml.runtime.matrix.data.OperationsOnMatrixValues;
import org.apache.sysml.runtime.matrix.mapred.CachedValueMap;
import org.apache.sysml.runtime.matrix.mapred.DistributedCacheInput;
import org.apache.sysml.runtime.matrix.mapred.IndexedMatrixValue;
import org.apache.sysml.runtime.matrix.mapred.MRBaseForCommonInstructions;
import org.apache.sysml.runtime.matrix.operators.BinaryOperator;
import org.apache.sysml.runtime.matrix.operators.Operator;
public class BinaryMInstruction extends BinaryMRInstructionBase implements IDistributedCacheConsumer {
private VectorType _vectorType = null;
private BinaryMInstruction(Operator op, byte in1, byte in2, CacheType ctype, VectorType vtype, byte out, String istr) {
super(MRType.Binary, op, in1, in2, out);
instString = istr;
_vectorType = vtype;
}
public static BinaryMInstruction parseInstruction ( String str ) {
InstructionUtils.checkNumFields ( str, 5 );
String[] parts = InstructionUtils.getInstructionParts ( str );
byte in1, in2, out;
String opcode = parts[0];
in1 = Byte.parseByte(parts[1]);
in2 = Byte.parseByte(parts[2]);
out = Byte.parseByte(parts[3]);
CacheType ctype = CacheType.valueOf(parts[4]);
VectorType vtype = VectorType.valueOf(parts[5]);
BinaryOperator bop = InstructionUtils.parseExtendedBinaryOperator(opcode);
return new BinaryMInstruction(bop, in1, in2, ctype, vtype, out, str);
}
@Override
public void processInstruction(Class<? extends MatrixValue> valueClass,
CachedValueMap cachedValues, IndexedMatrixValue tempValue, IndexedMatrixValue zeroInput,
int blockRowFactor, int blockColFactor) {
ArrayList<IndexedMatrixValue> blkList = cachedValues.get(input1);
if( blkList == null )
return;
for(IndexedMatrixValue in1 : blkList) {
//allocate space for the output value
//try to avoid coping as much as possible
IndexedMatrixValue out;
if( (output!=input1 && output!=input2) )
out=cachedValues.holdPlace(output, valueClass);
else
out=tempValue;
//get second
DistributedCacheInput dcInput = MRBaseForCommonInstructions.dcValues.get(input2);
IndexedMatrixValue in2 = null;
if( _vectorType == VectorType.COL_VECTOR )
in2 = dcInput.getDataBlock((int)in1.getIndexes().getRowIndex(), 1);
else //_vectorType == VectorType.ROW_VECTOR
in2 = dcInput.getDataBlock(1, (int)in1.getIndexes().getColumnIndex());
//process instruction
out.getIndexes().setIndexes(in1.getIndexes());
OperationsOnMatrixValues.performBinaryIgnoreIndexes(in1.getValue(),
in2.getValue(), out.getValue(), ((BinaryOperator)optr));
//put the output value in the cache
if(out==tempValue)
cachedValues.add(output, out);
}
}
@Override //IDistributedCacheConsumer
public boolean isDistCacheOnlyIndex( String inst, byte index )
{
return (index==input2 && index!=input1);
}
@Override //IDistributedCacheConsumer
public void addDistCacheIndex( String inst, ArrayList<Byte> indexes )
{
indexes.add(input2);
}
}
| deroneriksson/incubator-systemml | src/main/java/org/apache/sysml/runtime/instructions/mr/BinaryMInstruction.java | Java | apache-2.0 | 4,115 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* Agfa-Gevaert AG.
* Portions created by the Initial Developer are Copyright (C) 2002-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* See listed authors below.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chee.usr.ui.usermanagement.role.aet;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxFallbackButton;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.resources.CompressedResourceReference;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.util.ListModel;
import org.dcm4chee.usr.dao.UserAccess;
import org.dcm4chee.usr.model.AETGroup;
import org.dcm4chee.usr.ui.validator.AETGroupValidator;
import org.dcm4chee.usr.util.JNDIUtils;
import org.dcm4chee.web.common.base.BaseWicketApplication;
import org.dcm4chee.web.common.base.BaseWicketPage;
import org.dcm4chee.web.common.markup.BaseForm;
import org.dcm4chee.web.common.secure.SecureSessionCheckPage;
import org.dcm4chee.web.common.util.Auditlog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Robert David <robert.david@agfa.com>
* @version $Revision$ $Date$
* @since Apr. 19, 2011
*/
public class CreateOrEditAETGroupPage extends SecureSessionCheckPage {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(CreateOrEditAETGroupPage.class);
protected ModalWindow window;
public CreateOrEditAETGroupPage(final ModalWindow window, ListModel<AETGroup> allAETGroupnames, AETGroup aetGroup) {
super();
this.window = window;
add(new CreateOrEditAETGroupForm("add-aet-group-form", allAETGroupnames, aetGroup));
add(new WebMarkupContainer("create-aet-group-title").setVisible(aetGroup == null));
add(new WebMarkupContainer("edit-aet-group-title").setVisible(aetGroup != null));
}
private final class CreateOrEditAETGroupForm extends BaseForm {
private static final long serialVersionUID = 1L;
private Model<String> groupname = new Model<String>();
private Model<String> description= new Model<String>();
private TextField<String> groupnameTextField= new TextField<String>("aetgrouplist.add-aet-group-form.groupname.input", groupname);
private TextField<String> descriptionTextField= new TextField<String>("aetgrouplist.add-aet-group-form.description.input", description);
public CreateOrEditAETGroupForm(String id, final ListModel<AETGroup> allAETGroupnames, final AETGroup aetGroup) {
super(id);
((BaseWicketApplication) getApplication()).getInitParameter("UserAccessServiceName");
add(groupnameTextField
.setRequired(true)
.add(new AETGroupValidator(allAETGroupnames, (aetGroup == null ? null : aetGroup.getGroupname())))
);
add(descriptionTextField);
if (aetGroup != null) {
groupnameTextField.setModelObject(aetGroup.getGroupname());
descriptionTextField.setModelObject(aetGroup.getDescription());
}
add(new AjaxFallbackButton("add-aet-group-submit", CreateOrEditAETGroupForm.this) {
private static final long serialVersionUID = 1L;
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
try {
UserAccess userAccess = (UserAccess) JNDIUtils.lookup(UserAccess.JNDI_NAME);
if (aetGroup == null) {
AETGroup newAETGroup = new AETGroup(groupname.getObject());
newAETGroup.setDescription(description.getObject());
userAccess.addAETGroup(newAETGroup);
Auditlog.logSoftwareConfiguration(true, "AEGroup "+newAETGroup+" created.");
} else {
StringBuilder sb = new StringBuilder("AEGroup ").append(aetGroup.getGroupname())
.append(" updated. ");
boolean changed = Auditlog.addChange(sb, false, "group name", aetGroup.getGroupname(), groupname.getObject());
Auditlog.addChange(sb, changed, "description", aetGroup.getDescription(), aetGroup.getDescription());
aetGroup.setGroupname(groupname.getObject());
aetGroup.setDescription(description.getObject());
userAccess.updateAETGroup(aetGroup);
Auditlog.logSoftwareConfiguration(true, sb.toString());
}
allAETGroupnames.setObject(userAccess.getAllAETGroups());
window.close(target);
} catch (final Exception e) {
log.error(this.getClass().toString() + ": " + "onSubmit: " + e.getMessage());
log.debug("Exception: ", e);
}
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
target.addComponent(form);
}
});
}
};
}
| medicayun/medicayundicom | dcm4chee-usr/trunk/dcm4chee-usr-ui/src/main/java/org/dcm4chee/usr/ui/usermanagement/role/aet/CreateOrEditAETGroupPage.java | Java | apache-2.0 | 7,267 |
#
# Author:: Jan Zimmek (<jan.zimmek@web.de>)
# Author:: AJ Christensen (<aj@hjksolutions.com>)
# Copyright:: Copyright (c) 2008 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
require 'spec_helper'
require 'ostruct'
# most of this code has been ripped from init_service_spec.rb
# and is only slightly modified to match "arch" needs.
describe Chef::Provider::Service::Arch, "load_current_resource" do
before(:each) do
@node = Chef::Node.new
@node.automatic_attrs[:command] = {:ps => "ps -ef"}
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
@new_resource = Chef::Resource::Service.new("chef")
@new_resource.pattern("chef")
@new_resource.supports({:status => false})
@provider = Chef::Provider::Service::Arch.new(@new_resource, @run_context)
::File.stub!(:exists?).with("/etc/rc.conf").and_return(true)
::File.stub!(:read).with("/etc/rc.conf").and_return("DAEMONS=(network apache sshd)")
end
describe "when first created" do
it "should set the current resources service name to the new resources service name" do
@provider.stub(:shell_out).and_return(OpenStruct.new(:exitstatus => 0, :stdout => ""))
@provider.load_current_resource
@provider.current_resource.service_name.should == 'chef'
end
end
describe "when the service supports status" do
before do
@new_resource.supports({:status => true})
end
it "should run '/etc/rc.d/service_name status'" do
@provider.should_receive(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(:exitstatus => 0))
@provider.load_current_resource
end
it "should set running to true if the the status command returns 0" do
@provider.stub!(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(:exitstatus => 0))
@provider.load_current_resource
@provider.current_resource.running.should be_true
end
it "should set running to false if the status command returns anything except 0" do
@provider.stub!(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(:exitstatus => 1))
@provider.load_current_resource
@provider.current_resource.running.should be_false
end
it "should set running to false if the status command raises" do
@provider.stub!(:shell_out).with("/etc/rc.d/chef status").and_raise(Mixlib::ShellOut::ShellCommandFailed)
@provider.load_current_resource
@provider.current_resource.running.should be_false
end
end
describe "when a status command has been specified" do
before do
@new_resource.status_command("/etc/rc.d/chefhasmonkeypants status")
end
it "should run the services status command if one has been specified" do
@provider.should_receive(:shell_out).with("/etc/rc.d/chefhasmonkeypants status").and_return(OpenStruct.new(:exitstatus => 0))
@provider.load_current_resource
end
end
it "should raise error if the node has a nil ps attribute and no other means to get status" do
@node.automatic_attrs[:command] = {:ps => nil}
@provider.define_resource_requirements
@provider.action = :start
lambda { @provider.process_resource_requirements }.should raise_error(Chef::Exceptions::Service)
end
it "should raise error if the node has an empty ps attribute and no other means to get status" do
@node.automatic_attrs[:command] = {:ps => ""}
@provider.define_resource_requirements
@provider.action = :start
lambda { @provider.process_resource_requirements }.should raise_error(Chef::Exceptions::Service)
end
it "should fail if file /etc/rc.conf does not exist" do
::File.stub!(:exists?).with("/etc/rc.conf").and_return(false)
lambda { @provider.load_current_resource }.should raise_error(Chef::Exceptions::Service)
end
it "should fail if file /etc/rc.conf does not contain DAEMONS array" do
::File.stub!(:read).with("/etc/rc.conf").and_return("")
lambda { @provider.load_current_resource }.should raise_error(Chef::Exceptions::Service)
end
describe "when discovering service status with ps" do
before do
@stdout = StringIO.new(<<-DEFAULT_PS)
aj 7842 5057 0 21:26 pts/2 00:00:06 vi init.rb
aj 7903 5016 0 21:26 pts/5 00:00:00 /bin/bash
aj 8119 6041 0 21:34 pts/3 00:00:03 vi init_service_spec.rb
DEFAULT_PS
@status = mock("Status", :exitstatus => 0, :stdout => @stdout)
@provider.stub!(:shell_out!).and_return(@status)
@node.automatic_attrs[:command] = {:ps => "ps -ef"}
end
it "determines the service is running when it appears in ps" do
@stdout = StringIO.new(<<-RUNNING_PS)
aj 7842 5057 0 21:26 pts/2 00:00:06 chef
aj 7842 5057 0 21:26 pts/2 00:00:06 poos
RUNNING_PS
@status.stub!(:stdout).and_return(@stdout)
@provider.load_current_resource
@provider.current_resource.running.should be_true
end
it "determines the service is not running when it does not appear in ps" do
@provider.stub!(:shell_out!).and_return(@status)
@provider.load_current_resource
@provider.current_resource.running.should be_false
end
it "should raise an exception if ps fails" do
@provider.stub!(:shell_out!).and_raise(Mixlib::ShellOut::ShellCommandFailed)
@provider.load_current_resource
@provider.action = :start
@provider.define_resource_requirements
lambda { @provider.process_resource_requirements }.should raise_error(Chef::Exceptions::Service)
end
end
it "should return existing entries in DAEMONS array" do
::File.stub!(:read).with("/etc/rc.conf").and_return("DAEMONS=(network !apache ssh)")
@provider.daemons.should == ['network', '!apache', 'ssh']
end
context "when the current service status is known" do
before do
@current_resource = Chef::Resource::Service.new("chef")
@provider.current_resource = @current_resource
end
describe Chef::Provider::Service::Arch, "enable_service" do
# before(:each) do
# @new_resource = mock("Chef::Resource::Service",
# :null_object => true,
# :name => "chef",
# :service_name => "chef",
# :running => false
# )
# @new_resource.stub!(:start_command).and_return(false)
#
# @provider = Chef::Provider::Service::Arch.new(@node, @new_resource)
# Chef::Resource::Service.stub!(:new).and_return(@current_resource)
# end
it "should add chef to DAEMONS array" do
::File.stub!(:read).with("/etc/rc.conf").and_return("DAEMONS=(network)")
@provider.should_receive(:update_daemons).with(['network', 'chef'])
@provider.enable_service()
end
end
describe Chef::Provider::Service::Arch, "disable_service" do
# before(:each) do
# @new_resource = mock("Chef::Resource::Service",
# :null_object => true,
# :name => "chef",
# :service_name => "chef",
# :running => false
# )
# @new_resource.stub!(:start_command).and_return(false)
#
# @provider = Chef::Provider::Service::Arch.new(@node, @new_resource)
# Chef::Resource::Service.stub!(:new).and_return(@current_resource)
# end
it "should remove chef from DAEMONS array" do
::File.stub!(:read).with("/etc/rc.conf").and_return("DAEMONS=(network chef)")
@provider.should_receive(:update_daemons).with(['network', '!chef'])
@provider.disable_service()
end
end
describe Chef::Provider::Service::Arch, "start_service" do
# before(:each) do
# @new_resource = mock("Chef::Resource::Service",
# :null_object => true,
# :name => "chef",
# :service_name => "chef",
# :running => false
# )
# @new_resource.stub!(:start_command).and_return(false)
#
# @provider = Chef::Provider::Service::Arch.new(@node, @new_resource)
# Chef::Resource::Service.stub!(:new).and_return(@current_resource)
# end
it "should call the start command if one is specified" do
@new_resource.stub!(:start_command).and_return("/etc/rc.d/chef startyousillysally")
@provider.should_receive(:shell_out!).with("/etc/rc.d/chef startyousillysally")
@provider.start_service()
end
it "should call '/etc/rc.d/service_name start' if no start command is specified" do
@provider.should_receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} start")
@provider.start_service()
end
end
describe Chef::Provider::Service::Arch, "stop_service" do
# before(:each) do
# @new_resource = mock("Chef::Resource::Service",
# :null_object => true,
# :name => "chef",
# :service_name => "chef",
# :running => false
# )
# @new_resource.stub!(:stop_command).and_return(false)
#
# @provider = Chef::Provider::Service::Arch.new(@node, @new_resource)
# Chef::Resource::Service.stub!(:new).and_return(@current_resource)
# end
it "should call the stop command if one is specified" do
@new_resource.stub!(:stop_command).and_return("/etc/rc.d/chef itoldyoutostop")
@provider.should_receive(:shell_out!).with("/etc/rc.d/chef itoldyoutostop")
@provider.stop_service()
end
it "should call '/etc/rc.d/service_name stop' if no stop command is specified" do
@provider.should_receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} stop")
@provider.stop_service()
end
end
describe Chef::Provider::Service::Arch, "restart_service" do
# before(:each) do
# @new_resource = mock("Chef::Resource::Service",
# :null_object => true,
# :name => "chef",
# :service_name => "chef",
# :running => false
# )
# @new_resource.stub!(:restart_command).and_return(false)
# @new_resource.stub!(:supports).and_return({:restart => false})
#
# @provider = Chef::Provider::Service::Arch.new(@node, @new_resource)
# Chef::Resource::Service.stub!(:new).and_return(@current_resource)
# end
it "should call 'restart' on the service_name if the resource supports it" do
@new_resource.stub!(:supports).and_return({:restart => true})
@provider.should_receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} restart")
@provider.restart_service()
end
it "should call the restart_command if one has been specified" do
@new_resource.stub!(:restart_command).and_return("/etc/rc.d/chef restartinafire")
@provider.should_receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} restartinafire")
@provider.restart_service()
end
it "should just call stop, then start when the resource doesn't support restart and no restart_command is specified" do
@provider.should_receive(:stop_service)
@provider.should_receive(:sleep).with(1)
@provider.should_receive(:start_service)
@provider.restart_service()
end
end
describe Chef::Provider::Service::Arch, "reload_service" do
# before(:each) do
# @new_resource = mock("Chef::Resource::Service",
# :null_object => true,
# :name => "chef",
# :service_name => "chef",
# :running => false
# )
# @new_resource.stub!(:reload_command).and_return(false)
# @new_resource.stub!(:supports).and_return({:reload => false})
#
# @provider = Chef::Provider::Service::Arch.new(@node, @new_resource)
# Chef::Resource::Service.stub!(:new).and_return(@current_resource)
# end
it "should call 'reload' on the service if it supports it" do
@new_resource.stub!(:supports).and_return({:reload => true})
@provider.should_receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} reload")
@provider.reload_service()
end
it "should should run the user specified reload command if one is specified and the service doesn't support reload" do
@new_resource.stub!(:reload_command).and_return("/etc/rc.d/chef lollerpants")
@provider.should_receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} lollerpants")
@provider.reload_service()
end
end
end
end
| luna1x/chef-server | vendor/ruby/1.9.1/gems/chef-11.6.2/spec/unit/provider/service/arch_service_spec.rb | Ruby | apache-2.0 | 13,083 |
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTERPROCESS_DETAIL_WINAPI_WRAPPER_COMMON_HPP
#define BOOST_INTERPROCESS_DETAIL_WINAPI_WRAPPER_COMMON_HPP
#ifndef BOOST_CONFIG_HPP
# include <boost/config.hpp>
#endif
#
#if defined(BOOST_HAS_PRAGMA_ONCE)
# pragma once
#endif
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#include <boost/interprocess/detail/win32_api.hpp>
#include <boost/interprocess/detail/posix_time_types_wrk.hpp>
#include <boost/interprocess/errors.hpp>
#include <boost/interprocess/exceptions.hpp>
#include <limits>
namespace boost {
namespace interprocess {
namespace ipcdetail {
inline bool winapi_wrapper_timed_wait_for_single_object(void *handle, const boost::posix_time::ptime &abs_time);
inline void winapi_wrapper_wait_for_single_object(void *handle)
{
winapi_wrapper_timed_wait_for_single_object(handle, boost::posix_time::pos_infin);
}
inline bool winapi_wrapper_try_wait_for_single_object(void *handle)
{
return winapi_wrapper_timed_wait_for_single_object(handle, boost::posix_time::min_date_time);
}
inline bool winapi_wrapper_timed_wait_for_single_object(void *handle, const boost::posix_time::ptime &abs_time)
{
const boost::posix_time::ptime cur_time = microsec_clock::universal_time();
//Windows uses relative wait times so check for negative waits
//and implement as 0 wait to allow try-semantics as POSIX mandates.
unsigned long time = 0u;
if (abs_time == boost::posix_time::pos_infin){
time = winapi::infinite_time;
}
else if(abs_time > cur_time){
time = (abs_time - cur_time).total_milliseconds();
}
unsigned long ret = winapi::wait_for_single_object(handle, time);
if(ret == winapi::wait_object_0){
return true;
}
else if(ret == winapi::wait_timeout){
return false;
}
else if(ret == winapi::wait_abandoned){ //Special case for orphaned mutexes
winapi::release_mutex(handle);
throw interprocess_exception(owner_dead_error);
}
else{
error_info err = system_error_code();
throw interprocess_exception(err);
}
}
} //namespace ipcdetail {
} //namespace interprocess {
} //namespace boost {
#include <boost/interprocess/detail/config_end.hpp>
#endif //BOOST_INTERPROCESS_DETAIL_WINAPI_WRAPPER_COMMON_HPP
| eProsima/Fast-DDS | thirdparty/boost/include/boost/interprocess/sync/windows/winapi_wrapper_common.hpp | C++ | apache-2.0 | 2,717 |
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/common-operator.h"
#include "src/compiler/graph.h"
#include "src/compiler/js-operator.h"
#include "src/compiler/linkage.h"
#include "src/compiler/node-properties.h"
#include "src/compiler/operator-properties.h"
#include "src/compiler/verifier.h"
#include "src/handles-inl.h"
namespace v8 {
namespace internal {
namespace compiler {
// static
int NodeProperties::PastValueIndex(Node* node) {
return FirstValueIndex(node) + node->op()->ValueInputCount();
}
// static
int NodeProperties::PastContextIndex(Node* node) {
return FirstContextIndex(node) +
OperatorProperties::GetContextInputCount(node->op());
}
// static
int NodeProperties::PastFrameStateIndex(Node* node) {
return FirstFrameStateIndex(node) +
OperatorProperties::GetFrameStateInputCount(node->op());
}
// static
int NodeProperties::PastEffectIndex(Node* node) {
return FirstEffectIndex(node) + node->op()->EffectInputCount();
}
// static
int NodeProperties::PastControlIndex(Node* node) {
return FirstControlIndex(node) + node->op()->ControlInputCount();
}
// static
Node* NodeProperties::GetValueInput(Node* node, int index) {
DCHECK(0 <= index && index < node->op()->ValueInputCount());
return node->InputAt(FirstValueIndex(node) + index);
}
// static
Node* NodeProperties::GetContextInput(Node* node) {
DCHECK(OperatorProperties::HasContextInput(node->op()));
return node->InputAt(FirstContextIndex(node));
}
// static
Node* NodeProperties::GetFrameStateInput(Node* node, int index) {
DCHECK_LT(index, OperatorProperties::GetFrameStateInputCount(node->op()));
return node->InputAt(FirstFrameStateIndex(node) + index);
}
// static
Node* NodeProperties::GetEffectInput(Node* node, int index) {
DCHECK(0 <= index && index < node->op()->EffectInputCount());
return node->InputAt(FirstEffectIndex(node) + index);
}
// static
Node* NodeProperties::GetControlInput(Node* node, int index) {
DCHECK(0 <= index && index < node->op()->ControlInputCount());
return node->InputAt(FirstControlIndex(node) + index);
}
// static
bool NodeProperties::IsValueEdge(Edge edge) {
Node* const node = edge.from();
return IsInputRange(edge, FirstValueIndex(node),
node->op()->ValueInputCount());
}
// static
bool NodeProperties::IsContextEdge(Edge edge) {
Node* const node = edge.from();
return IsInputRange(edge, FirstContextIndex(node),
OperatorProperties::GetContextInputCount(node->op()));
}
// static
bool NodeProperties::IsFrameStateEdge(Edge edge) {
Node* const node = edge.from();
return IsInputRange(edge, FirstFrameStateIndex(node),
OperatorProperties::GetFrameStateInputCount(node->op()));
}
// static
bool NodeProperties::IsEffectEdge(Edge edge) {
Node* const node = edge.from();
return IsInputRange(edge, FirstEffectIndex(node),
node->op()->EffectInputCount());
}
// static
bool NodeProperties::IsControlEdge(Edge edge) {
Node* const node = edge.from();
return IsInputRange(edge, FirstControlIndex(node),
node->op()->ControlInputCount());
}
// static
bool NodeProperties::IsExceptionalCall(Node* node) {
if (node->op()->HasProperty(Operator::kNoThrow)) return false;
for (Edge const edge : node->use_edges()) {
if (!NodeProperties::IsControlEdge(edge)) continue;
if (edge.from()->opcode() == IrOpcode::kIfException) return true;
}
return false;
}
// static
void NodeProperties::ReplaceValueInput(Node* node, Node* value, int index) {
DCHECK(index < node->op()->ValueInputCount());
node->ReplaceInput(FirstValueIndex(node) + index, value);
}
// static
void NodeProperties::ReplaceValueInputs(Node* node, Node* value) {
int value_input_count = node->op()->ValueInputCount();
DCHECK_LE(1, value_input_count);
node->ReplaceInput(0, value);
while (--value_input_count > 0) {
node->RemoveInput(value_input_count);
}
}
// static
void NodeProperties::ReplaceContextInput(Node* node, Node* context) {
node->ReplaceInput(FirstContextIndex(node), context);
}
// static
void NodeProperties::ReplaceControlInput(Node* node, Node* control) {
node->ReplaceInput(FirstControlIndex(node), control);
}
// static
void NodeProperties::ReplaceEffectInput(Node* node, Node* effect, int index) {
DCHECK(index < node->op()->EffectInputCount());
return node->ReplaceInput(FirstEffectIndex(node) + index, effect);
}
// static
void NodeProperties::ReplaceFrameStateInput(Node* node, int index,
Node* frame_state) {
DCHECK_LT(index, OperatorProperties::GetFrameStateInputCount(node->op()));
node->ReplaceInput(FirstFrameStateIndex(node) + index, frame_state);
}
// static
void NodeProperties::RemoveFrameStateInput(Node* node, int index) {
DCHECK_LT(index, OperatorProperties::GetFrameStateInputCount(node->op()));
node->RemoveInput(FirstFrameStateIndex(node) + index);
}
// static
void NodeProperties::RemoveNonValueInputs(Node* node) {
node->TrimInputCount(node->op()->ValueInputCount());
}
// static
void NodeProperties::RemoveValueInputs(Node* node) {
int value_input_count = node->op()->ValueInputCount();
while (--value_input_count >= 0) {
node->RemoveInput(value_input_count);
}
}
void NodeProperties::MergeControlToEnd(Graph* graph,
CommonOperatorBuilder* common,
Node* node) {
graph->end()->AppendInput(graph->zone(), node);
graph->end()->set_op(common->End(graph->end()->InputCount()));
}
// static
void NodeProperties::ReplaceUses(Node* node, Node* value, Node* effect,
Node* success, Node* exception) {
// Requires distinguishing between value, effect and control edges.
for (Edge edge : node->use_edges()) {
if (IsControlEdge(edge)) {
if (edge.from()->opcode() == IrOpcode::kIfSuccess) {
DCHECK_NOT_NULL(success);
edge.UpdateTo(success);
} else if (edge.from()->opcode() == IrOpcode::kIfException) {
DCHECK_NOT_NULL(exception);
edge.UpdateTo(exception);
} else {
UNREACHABLE();
}
} else if (IsEffectEdge(edge)) {
DCHECK_NOT_NULL(effect);
edge.UpdateTo(effect);
} else {
DCHECK_NOT_NULL(value);
edge.UpdateTo(value);
}
}
}
// static
void NodeProperties::ChangeOp(Node* node, const Operator* new_op) {
node->set_op(new_op);
Verifier::VerifyNode(node);
}
// static
Node* NodeProperties::FindProjection(Node* node, size_t projection_index) {
for (auto use : node->uses()) {
if (use->opcode() == IrOpcode::kProjection &&
ProjectionIndexOf(use->op()) == projection_index) {
return use;
}
}
return nullptr;
}
// static
void NodeProperties::CollectControlProjections(Node* node, Node** projections,
size_t projection_count) {
#ifdef DEBUG
DCHECK_LE(static_cast<int>(projection_count), node->UseCount());
std::memset(projections, 0, sizeof(*projections) * projection_count);
#endif
size_t if_value_index = 0;
for (Edge const edge : node->use_edges()) {
if (!IsControlEdge(edge)) continue;
Node* use = edge.from();
size_t index;
switch (use->opcode()) {
case IrOpcode::kIfTrue:
DCHECK_EQ(IrOpcode::kBranch, node->opcode());
index = 0;
break;
case IrOpcode::kIfFalse:
DCHECK_EQ(IrOpcode::kBranch, node->opcode());
index = 1;
break;
case IrOpcode::kIfSuccess:
DCHECK(!node->op()->HasProperty(Operator::kNoThrow));
index = 0;
break;
case IrOpcode::kIfException:
DCHECK(!node->op()->HasProperty(Operator::kNoThrow));
index = 1;
break;
case IrOpcode::kIfValue:
DCHECK_EQ(IrOpcode::kSwitch, node->opcode());
index = if_value_index++;
break;
case IrOpcode::kIfDefault:
DCHECK_EQ(IrOpcode::kSwitch, node->opcode());
index = projection_count - 1;
break;
default:
continue;
}
DCHECK_LT(if_value_index, projection_count);
DCHECK_LT(index, projection_count);
DCHECK_NULL(projections[index]);
projections[index] = use;
}
#ifdef DEBUG
for (size_t index = 0; index < projection_count; ++index) {
DCHECK_NOT_NULL(projections[index]);
}
#endif
}
// static
MaybeHandle<Context> NodeProperties::GetSpecializationContext(
Node* node, MaybeHandle<Context> context) {
switch (node->opcode()) {
case IrOpcode::kHeapConstant:
return Handle<Context>::cast(OpParameter<Handle<HeapObject>>(node));
case IrOpcode::kParameter: {
Node* const start = NodeProperties::GetValueInput(node, 0);
DCHECK_EQ(IrOpcode::kStart, start->opcode());
int const index = ParameterIndexOf(node->op());
// The context is always the last parameter to a JavaScript function, and
// {Parameter} indices start at -1, so value outputs of {Start} look like
// this: closure, receiver, param0, ..., paramN, context.
if (index == start->op()->ValueOutputCount() - 2) {
return context;
}
break;
}
default:
break;
}
return MaybeHandle<Context>();
}
// static
MaybeHandle<Context> NodeProperties::GetSpecializationNativeContext(
Node* node, MaybeHandle<Context> native_context) {
while (true) {
switch (node->opcode()) {
case IrOpcode::kJSLoadContext: {
ContextAccess const& access = ContextAccessOf(node->op());
if (access.index() != Context::NATIVE_CONTEXT_INDEX) {
return MaybeHandle<Context>();
}
// Skip over the intermediate contexts, we're only interested in the
// very last context in the context chain anyway.
node = NodeProperties::GetContextInput(node);
break;
}
case IrOpcode::kJSCreateBlockContext:
case IrOpcode::kJSCreateCatchContext:
case IrOpcode::kJSCreateFunctionContext:
case IrOpcode::kJSCreateModuleContext:
case IrOpcode::kJSCreateScriptContext:
case IrOpcode::kJSCreateWithContext: {
// Skip over the intermediate contexts, we're only interested in the
// very last context in the context chain anyway.
node = NodeProperties::GetContextInput(node);
break;
}
case IrOpcode::kHeapConstant: {
// Extract the native context from the actual {context}.
Handle<Context> context =
Handle<Context>::cast(OpParameter<Handle<HeapObject>>(node));
return handle(context->native_context());
}
case IrOpcode::kOsrValue: {
int const index = OpParameter<int>(node);
if (index == Linkage::kOsrContextSpillSlotIndex) {
return native_context;
}
return MaybeHandle<Context>();
}
case IrOpcode::kParameter: {
Node* const start = NodeProperties::GetValueInput(node, 0);
DCHECK_EQ(IrOpcode::kStart, start->opcode());
int const index = ParameterIndexOf(node->op());
// The context is always the last parameter to a JavaScript function,
// and {Parameter} indices start at -1, so value outputs of {Start}
// look like this: closure, receiver, param0, ..., paramN, context.
if (index == start->op()->ValueOutputCount() - 2) {
return native_context;
}
return MaybeHandle<Context>();
}
default:
return MaybeHandle<Context>();
}
}
}
// static
MaybeHandle<JSGlobalObject> NodeProperties::GetSpecializationGlobalObject(
Node* node, MaybeHandle<Context> native_context) {
Handle<Context> context;
if (GetSpecializationNativeContext(node, native_context).ToHandle(&context)) {
return handle(context->global_object());
}
return MaybeHandle<JSGlobalObject>();
}
// static
Type* NodeProperties::GetTypeOrAny(Node* node) {
return IsTyped(node) ? node->type() : Type::Any();
}
// static
bool NodeProperties::AllValueInputsAreTyped(Node* node) {
int input_count = node->op()->ValueInputCount();
for (int index = 0; index < input_count; ++index) {
if (!IsTyped(GetValueInput(node, index))) return false;
}
return true;
}
// static
bool NodeProperties::IsInputRange(Edge edge, int first, int num) {
if (num == 0) return false;
int const index = edge.index();
return first <= index && index < first + num;
}
} // namespace compiler
} // namespace internal
} // namespace v8
| weolar/miniblink49 | v8_5_1/src/compiler/node-properties.cc | C++ | apache-2.0 | 12,642 |
/**
* Copyright 2007-2016, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.gateway.transport.nio;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.jboss.netty.channel.socket.Worker;
import org.kaazing.gateway.resource.address.Protocol;
import org.kaazing.gateway.resource.address.ResourceAddress;
import org.kaazing.gateway.transport.BridgeAcceptor;
import org.kaazing.gateway.transport.BridgeConnector;
import org.kaazing.gateway.transport.Transport;
import org.kaazing.gateway.transport.nio.internal.NioProtocol;
import org.kaazing.gateway.transport.nio.internal.socket.NioSocketAcceptor;
import org.kaazing.gateway.transport.nio.internal.socket.NioSocketConnector;
import org.kaazing.gateway.transport.nio.internal.socket.TcpExtensionFactory;
public final class TcpTransport extends Transport {
private static final Map<String, Protocol> TCP_PROTOCOLS;
static {
Map<String, Protocol> map = new HashMap<>();
map.put("tcp", NioProtocol.TCP);
TCP_PROTOCOLS = Collections.unmodifiableMap(map);
}
private final BridgeAcceptor acceptor;
private final BridgeConnector connector;
private final TcpExtensionFactory extensionFactory;
TcpTransport(Properties configuration) {
extensionFactory = TcpExtensionFactory.newInstance();
acceptor = new NioSocketAcceptor(configuration, extensionFactory);
connector = new NioSocketConnector(configuration);
}
@Override
public BridgeAcceptor getAcceptor() {
return acceptor;
}
@Override
public BridgeConnector getConnector() {
return connector;
}
@Override
public BridgeAcceptor getAcceptor(ResourceAddress address) {
return acceptor;
}
@Override
public BridgeConnector getConnector(ResourceAddress address) {
return connector;
}
@Override
// Used for resource injection
public Collection<?> getExtensions() {
return extensionFactory.availableExtensions();
}
@Override
public Map<String, Protocol> getProtocols() {
return TCP_PROTOCOLS;
}
public Worker[] getWorkers() {
return ((NioSocketAcceptor) getAcceptor()).getWorkers();
}
}
| a-zuckut/gateway | transport/nio/src/main/java/org/kaazing/gateway/transport/nio/TcpTransport.java | Java | apache-2.0 | 2,867 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from charmhelpers.core import hookenv
from charmhelpers.core import host
from jujubigdata import utils
from charms.layer.apache_bigtop_base import Bigtop
from charms import layer
from subprocess import check_output
class Kafka(object):
"""
This class manages Kafka.
"""
def __init__(self):
self.dist_config = utils.DistConfig(
data=layer.options('apache-bigtop-base'))
def open_ports(self):
for port in self.dist_config.exposed_ports('kafka'):
hookenv.open_port(port)
def close_ports(self):
for port in self.dist_config.exposed_ports('kafka'):
hookenv.close_port(port)
def configure_kafka(self, zk_units, network_interface=None):
# Get ip:port data from our connected zookeepers
zks = []
for unit in zk_units:
ip = utils.resolve_private_address(unit['host'])
zks.append("%s:%s" % (ip, unit['port']))
zks.sort()
zk_connect = ",".join(zks)
service, unit_num = os.environ['JUJU_UNIT_NAME'].split('/', 1)
kafka_port = self.dist_config.port('kafka')
roles = ['kafka-server']
override = {
'kafka::server::broker_id': unit_num,
'kafka::server::port': kafka_port,
'kafka::server::zookeeper_connection_string': zk_connect,
}
if network_interface:
ip = Bigtop().get_ip_for_interface(network_interface)
override['kafka::server::bind_addr'] = ip
bigtop = Bigtop()
bigtop.render_site_yaml(roles=roles, overrides=override)
bigtop.trigger_puppet()
self.set_advertise()
self.restart()
def restart(self):
self.stop()
self.start()
def start(self):
host.service_start('kafka-server')
def stop(self):
host.service_stop('kafka-server')
def set_advertise(self):
short_host = check_output(['hostname', '-s']).decode('utf8').strip()
# Configure server.properties
# NB: We set the advertised.host.name below to our short hostname
# to kafka (admin will still have to expose kafka and ensure the
# external client can resolve the short hostname to our public ip).
kafka_server_conf = '/etc/kafka/conf/server.properties'
utils.re_edit_in_place(kafka_server_conf, {
r'^#?advertised.host.name=.*': 'advertised.host.name=%s' % short_host,
})
| welikecloud/bigtop | bigtop-packages/src/charm/kafka/layer-kafka/lib/charms/layer/bigtop_kafka.py | Python | apache-2.0 | 3,240 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class ConstructorInitializerSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public ConstructorInitializerSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new ConstructorInitializerSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParameters()
{
var markup = @"
class BaseClass
{
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base($$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base($$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", "Summary for BaseClass", null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class BaseClass
{
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base($$2, 3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base($$2, 3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param a", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base(2, $$3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base(2, $$3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestThisInvocation()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() [|: this(2, $$3|]) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParen()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() [|: this(2, $$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(b: 2, a: $$
}";
await VerifyCurrentParameterNameAsync(markup, "a");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerParens()
{
var markup = @"
class Foo
{
public Foo(int a) { }
public Foo() : this($$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0),
new SignatureHelpTestItem("Foo(int a)", string.Empty, string.Empty, currentParameterIndex: 0),
};
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(2,$$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(2, $$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAlways()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateNever()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAdvanced()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateMixed()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public BaseClass(int x)
{ }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public BaseClass(int x, int y)
{ }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret
{
public Secret(int secret)
{
}
}
#endif
class SuperSecret : Secret
{
public SuperSecret(int secret) : base($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret
{
public Secret(int secret)
{
}
}
#endif
#if BAR
class SuperSecret : Secret
{
public SuperSecret(int secret) : base($$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// foo($$";
await TestAsync(markup);
}
[WorkItem(1082601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082601")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithBadParameterList()
{
var markup = @"
class BaseClass
{
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base{$$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems);
}
}
}
| ValentinRueda/roslyn | src/EditorFeatures/CSharpTest/SignatureHelp/ConstructorInitializerSignatureHelpProviderTests.cs | C# | apache-2.0 | 19,018 |
# Copyright 2014 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Scumblr::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
#config.cache_classes = true
# Log error messages when you accidentally call methods on nil.
# config.whiny_nils = true
config.eager_load = false
#config.eager_load = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
#config.action_mailer.default_url_options = { :host => "localhost:3000", :protocol => 'http' }
config.action_mailer.delivery_method = :smtp
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
#config.active_record.mass_assignment_sanitizer = :strict
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
#config.active_record.auto_explain_threshold_in_seconds = 0.5
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
#config.assets.prefix = "/assets_dev"
config.after_initialize do
Bullet.enable = true
Bullet.console = true
Bullet.rails_logger = true
end
end
silence_warnings do
require 'pry'
IRB = Pry
end
Rails.application.routes.default_url_options[:host] = "localhost:3000"
| COLABORATI/Scumblr | config/environments/development.rb | Ruby | apache-2.0 | 2,515 |
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: jmarantz@google.com (Joshua Marantz)
//
// Unit tests for SystemMessageHandler
#include "pagespeed/system/system_message_handler.h"
#include "pagespeed/kernel/base/gtest.h"
#include "pagespeed/kernel/base/mock_timer.h"
#include "pagespeed/kernel/base/scoped_ptr.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_writer.h"
#include "pagespeed/kernel/base/thread_system.h"
#include "pagespeed/kernel/util/platform.h"
namespace net_instaweb {
class SystemMessageHandlerTest : public testing::Test {
protected:
SystemMessageHandlerTest()
: thread_system_(Platform::CreateThreadSystem()),
timer_(thread_system_->NewMutex(), MockTimer::kApr_5_2010_ms),
system_message_handler_(&timer_, thread_system_->NewMutex()),
writer_(&buffer_) {
system_message_handler_.set_buffer(&writer_);
system_message_handler_.SetPidString(1234);
}
void AddMessage(MessageType type, StringPiece msg) {
system_message_handler_.AddMessageToBuffer(type, msg);
}
scoped_ptr<ThreadSystem> thread_system_;
MockTimer timer_;
SystemMessageHandler system_message_handler_;
GoogleString buffer_;
StringWriter writer_;
};
// Tests that multi-line messages are annotated with the type-code for
// each line.
TEST_F(SystemMessageHandlerTest, WrapLongLinesError) {
AddMessage(kError, "Now is the time\nfor all good men\nto come to the aid");
EXPECT_STREQ(
"E[Mon, 05 Apr 2010 18:51:26 GMT] [Error] [1234] Now is the time\n"
"Efor all good men\n"
"Eto come to the aid\n",
buffer_);
}
TEST_F(SystemMessageHandlerTest, WrapLongLinesInfo) {
AddMessage(kInfo, "Now is the time\nfor all good men\nto come to the aid");
EXPECT_STREQ(
"I[Mon, 05 Apr 2010 18:51:26 GMT] [Info] [1234] Now is the time\n"
"Ifor all good men\n"
"Ito come to the aid\n",
buffer_);
}
TEST_F(SystemMessageHandlerTest, WrapLongLinesWarning) {
AddMessage(kWarning, "Now is the time\nfor all good men\nto come to the aid");
EXPECT_STREQ(
"W[Mon, 05 Apr 2010 18:51:26 GMT] [Warning] [1234] Now is the time\n"
"Wfor all good men\n"
"Wto come to the aid\n",
buffer_);
}
} // namespace net_instaweb
| ajayanandgit/mod_pagespeed | pagespeed/system/system_message_handler_test.cc | C++ | apache-2.0 | 2,815 |
/**
* 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.tez.dag.app.dag.event;
import org.apache.tez.dag.api.TaskLocationHint;
import org.apache.tez.dag.records.TezTaskID;
import org.apache.tez.runtime.api.impl.TaskSpec;
public class TaskEventScheduleTask extends TaskEvent {
private final TaskSpec baseTaskSpec;
private final TaskLocationHint locationHint;
public TaskEventScheduleTask(TezTaskID taskId, TaskSpec baseTaskSpec, TaskLocationHint locationHint) {
super(taskId, TaskEventType.T_SCHEDULE);
this.baseTaskSpec = baseTaskSpec;
this.locationHint = locationHint;
}
public TaskSpec getBaseTaskSpec() {
return baseTaskSpec;
}
public TaskLocationHint getTaskLocationHint() {
return locationHint;
}
} | amirsojoodi/tez | tez-dag/src/main/java/org/apache/tez/dag/app/dag/event/TaskEventScheduleTask.java | Java | apache-2.0 | 1,505 |
/**
* This class is generated by jOOQ
*/
package io.cattle.platform.core.model;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = { "http://www.jooq.org", "3.3.0" },
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
@javax.persistence.Entity
@javax.persistence.Table(name = "snapshot_storage_pool_map", schema = "cattle")
public interface SnapshotStoragePoolMap extends java.io.Serializable {
/**
* Setter for <code>cattle.snapshot_storage_pool_map.id</code>.
*/
public void setId(java.lang.Long value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.id</code>.
*/
@javax.persistence.Id
@javax.persistence.Column(name = "id", unique = true, nullable = false, precision = 19)
public java.lang.Long getId();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.name</code>.
*/
public void setName(java.lang.String value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.name</code>.
*/
@javax.persistence.Column(name = "name", length = 255)
public java.lang.String getName();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.kind</code>.
*/
public void setKind(java.lang.String value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.kind</code>.
*/
@javax.persistence.Column(name = "kind", nullable = false, length = 255)
public java.lang.String getKind();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.uuid</code>.
*/
public void setUuid(java.lang.String value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.uuid</code>.
*/
@javax.persistence.Column(name = "uuid", unique = true, nullable = false, length = 128)
public java.lang.String getUuid();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.description</code>.
*/
public void setDescription(java.lang.String value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.description</code>.
*/
@javax.persistence.Column(name = "description", length = 1024)
public java.lang.String getDescription();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.state</code>.
*/
public void setState(java.lang.String value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.state</code>.
*/
@javax.persistence.Column(name = "state", nullable = false, length = 128)
public java.lang.String getState();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.created</code>.
*/
public void setCreated(java.util.Date value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.created</code>.
*/
@javax.persistence.Column(name = "created")
public java.util.Date getCreated();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.removed</code>.
*/
public void setRemoved(java.util.Date value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.removed</code>.
*/
@javax.persistence.Column(name = "removed")
public java.util.Date getRemoved();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.remove_time</code>.
*/
public void setRemoveTime(java.util.Date value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.remove_time</code>.
*/
@javax.persistence.Column(name = "remove_time")
public java.util.Date getRemoveTime();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.data</code>.
*/
public void setData(java.util.Map<String,Object> value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.data</code>.
*/
@javax.persistence.Column(name = "data", length = 16777215)
public java.util.Map<String,Object> getData();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.snapshot_id</code>.
*/
public void setSnapshotId(java.lang.Long value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.snapshot_id</code>.
*/
@javax.persistence.Column(name = "snapshot_id", precision = 19)
public java.lang.Long getSnapshotId();
/**
* Setter for <code>cattle.snapshot_storage_pool_map.storage_pool_id</code>.
*/
public void setStoragePoolId(java.lang.Long value);
/**
* Getter for <code>cattle.snapshot_storage_pool_map.storage_pool_id</code>.
*/
@javax.persistence.Column(name = "storage_pool_id", precision = 19)
public java.lang.Long getStoragePoolId();
// -------------------------------------------------------------------------
// FROM and INTO
// -------------------------------------------------------------------------
/**
* Load data from another generated Record/POJO implementing the common interface SnapshotStoragePoolMap
*/
public void from(io.cattle.platform.core.model.SnapshotStoragePoolMap from);
/**
* Copy data into another generated Record/POJO implementing the common interface SnapshotStoragePoolMap
*/
public <E extends io.cattle.platform.core.model.SnapshotStoragePoolMap> E into(E into);
}
| dx9/cattle | code/iaas/model/src/main/java/io/cattle/platform/core/model/SnapshotStoragePoolMap.java | Java | apache-2.0 | 4,895 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.rootwrap import filters
filterlist = [
# nova/volume/iscsi.py: iscsi_helper '--op' ...
filters.CommandFilter("/usr/sbin/ietadm", "root"),
filters.CommandFilter("/usr/sbin/tgtadm", "root"),
# nova/volume/driver.py: 'vgs', '--noheadings', '-o', 'name'
filters.CommandFilter("/sbin/vgs", "root"),
# nova/volume/driver.py: 'lvcreate', '-L', sizestr, '-n', volume_name,..
# nova/volume/driver.py: 'lvcreate', '-L', ...
filters.CommandFilter("/sbin/lvcreate", "root"),
# nova/volume/driver.py: 'dd', 'if=%s' % srcstr, 'of=%s' % deststr,...
filters.CommandFilter("/bin/dd", "root"),
# nova/volume/driver.py: 'lvremove', '-f', "%s/%s" % ...
filters.CommandFilter("/sbin/lvremove", "root"),
# nova/volume/driver.py: 'lvdisplay', '--noheading', '-C', '-o', 'Attr',..
filters.CommandFilter("/sbin/lvdisplay", "root"),
# nova/volume/driver.py: 'iscsiadm', '-m', 'discovery', '-t',...
# nova/volume/driver.py: 'iscsiadm', '-m', 'node', '-T', ...
filters.CommandFilter("/sbin/iscsiadm", "root"),
]
| gyang/nova | nova/rootwrap/volume.py | Python | apache-2.0 | 1,754 |
# Copyright 2016 gRPC 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.
_BEFORE_IMPORT = tuple(globals())
from grpc import * # pylint: disable=wildcard-import
_AFTER_IMPORT = tuple(globals())
GRPC_ELEMENTS = tuple(
element for element in _AFTER_IMPORT
if element not in _BEFORE_IMPORT and element != '_BEFORE_IMPORT')
| chrisdunelm/grpc | src/python/grpcio_tests/tests/unit/_from_grpc_import_star.py | Python | apache-2.0 | 836 |
/*
* Copyright (c) 2018-2019, Nuvoton Technology Corporation
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cmsis.h"
#include "target_cfg.h"
#include "tfm_secure_api.h"
/* Why rename this file to .cpp from .c
*
* NU_TZ_NSC_REGION_START/NU_TZ_NSC_REGION_SIZE would consist of linker-generated symbols.
* To avoid compile error 'initializer element is not a compile-time constant' with
* 'memory_regions' by emitted by C compiler, we rename this file to .cpp.
*
* With renaming to .cpp, to avoid name mangling for TFM HAL functions by C++ compiler, we
* declare these functions with modifier 'extern "C"'.
*/
/* Check relevant macro has been defined */
#if (! defined(TZ_START_NS))
#error("TZ_START_NS not defined")
#endif
#if (! defined(NU_ROM_START_NS))
#error("NU_ROM_START_NS not defined")
#endif
#if (! defined(NU_ROM_SIZE_NS))
#error("NU_ROM_SIZE_NS not defined")
#endif
#if (! defined(NU_TZ_NSC_REGION_START))
#error("NU_TZ_NSC_REGION_START not defined")
#endif
#if (! defined(NU_TZ_NSC_REGION_SIZE))
#error("NU_TZ_NSC_REGION_SIZE not defined")
#endif
#if (! defined(SCB_AIRCR_SYSRESETREQS_VAL))
#error("SCB_AIRCR_SYSRESETREQS_VAL not defined")
#endif
const struct memory_region_limits memory_regions = {
.non_secure_code_start = TZ_START_NS,
.non_secure_partition_base = NU_ROM_START_NS,
.non_secure_partition_limit = NU_ROM_START_NS + NU_ROM_SIZE_NS - 1,
.veneer_base = NU_TZ_NSC_REGION_START,
.veneer_limit = NU_TZ_NSC_REGION_START + NU_TZ_NSC_REGION_SIZE - 1
};
extern "C" void enable_fault_handlers(void)
{
/* M2351 doesn't implement Main Extension, so BUS, MEM, USG and Secure faults (SCB->SHCSR) are not supported. */
}
extern "C" void system_reset_cfg(void)
{
SCB_Setup();
}
extern "C" void tfm_spm_hal_init_debug(void)
{
/* Configure debug authentication
*
* Support macros: DAUTH_NONE/DAUTH_NS_ONLY/DAUTH_FULL/DAUTH_CHIP_DEFAULT
*
* On Nuvoton's M2351, there's no need to configure debug authentication because
* it depends on input signals.
*/
#warning("Ignore debug authentication option because it depends on input signals")
}
/* Configures all interrupts of non-secure peripherals to target NS state */
extern "C" void nvic_interrupt_target_state_cfg()
{
TZ_NVIC_Setup();
}
/* Enables the interrupts associated to the secure peripherals (plus the isolation
* boundary violation interrupts). */
extern "C" void nvic_interrupt_enable()
{
/* Enable SCU security violation (isolation boundary violation) interrupts */
SCU_ENABLE_INT(NU_SCU_SV_MSAK);
/* FIXME: Enable interrupts of secure peripherals */
}
| mbedmicro/mbed | targets/TARGET_NUVOTON/TARGET_M2351/TARGET_M23_S/TARGET_TFM/target_cfg.cpp | C++ | apache-2.0 | 3,196 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.NotSerializableExceptionWrapper;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.logging.support.LoggerMessageFormat;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardNotFoundException;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.admin.indices.alias.delete.AliasesNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* A base class for all elasticsearch exceptions.
*/
public class ElasticsearchException extends RuntimeException implements ToXContent {
public static final String REST_EXCEPTION_SKIP_CAUSE = "rest.exception.cause.skip";
public static final String REST_EXCEPTION_SKIP_STACK_TRACE = "rest.exception.stacktrace.skip";
public static final boolean REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT = true;
public static final boolean REST_EXCEPTION_SKIP_CAUSE_DEFAULT = false;
private static final String INDEX_HEADER_KEY = "es.index";
private static final String SHARD_HEADER_KEY = "es.shard";
private static final String RESOURCE_HEADER_TYPE_KEY = "es.resource.type";
private static final String RESOURCE_HEADER_ID_KEY = "es.resource.id";
private static final Map<String, Constructor<? extends ElasticsearchException>> MAPPING;
private final Map<String, List<String>> headers = new HashMap<>();
/**
* Construct a <code>ElasticsearchException</code> with the specified detail message.
*
* The message can be parameterized using {@code {}} as placeholders for the given
* arguments
*
* @param msg the detail message
* @param args the arguments for the message
*/
public ElasticsearchException(String msg, Object... args) {
super(LoggerMessageFormat.format(msg, args));
}
/**
* Construct a <code>ElasticsearchException</code> with the specified detail message
* and nested exception.
*
* The message can be parameterized using {@code {}} as placeholders for the given
* arguments
*
* @param msg the detail message
* @param cause the nested exception
* @param args the arguments for the message
*/
public ElasticsearchException(String msg, Throwable cause, Object... args) {
super(LoggerMessageFormat.format(msg, args), cause);
}
public ElasticsearchException(StreamInput in) throws IOException {
super(in.readOptionalString(), in.readThrowable());
readStackTrace(this, in);
int numKeys = in.readVInt();
for (int i = 0; i < numKeys; i++) {
final String key = in.readString();
final int numValues = in.readVInt();
final ArrayList<String> values = new ArrayList<>(numValues);
for (int j = 0; j < numValues; j++) {
values.add(in.readString());
}
headers.put(key, values);
}
}
/**
* Adds a new header with the given key.
* This method will replace existing header if a header with the same key already exists
*/
public void addHeader(String key, String... value) {
this.headers.put(key, Arrays.asList(value));
}
/**
* Adds a new header with the given key.
* This method will replace existing header if a header with the same key already exists
*/
public void addHeader(String key, List<String> value) {
this.headers.put(key, value);
}
/**
* Returns a set of all header keys on this exception
*/
public Set<String> getHeaderKeys() {
return headers.keySet();
}
/**
* Returns the list of header values for the given key or {@code null} if not header for the
* given key exists.
*/
public List<String> getHeader(String key) {
return headers.get(key);
}
/**
* Returns the rest status code associated with this exception.
*/
public RestStatus status() {
Throwable cause = unwrapCause();
if (cause == this) {
return RestStatus.INTERNAL_SERVER_ERROR;
} else {
return ExceptionsHelper.status(cause);
}
}
/**
* Unwraps the actual cause from the exception for cases when the exception is a
* {@link ElasticsearchWrapperException}.
*
* @see org.elasticsearch.ExceptionsHelper#unwrapCause(Throwable)
*/
public Throwable unwrapCause() {
return ExceptionsHelper.unwrapCause(this);
}
/**
* Return the detail message, including the message from the nested exception
* if there is one.
*/
public String getDetailedMessage() {
if (getCause() != null) {
StringBuilder sb = new StringBuilder();
sb.append(toString()).append("; ");
if (getCause() instanceof ElasticsearchException) {
sb.append(((ElasticsearchException) getCause()).getDetailedMessage());
} else {
sb.append(getCause());
}
return sb.toString();
} else {
return super.toString();
}
}
/**
* Retrieve the innermost cause of this exception, if none, returns the current exception.
*/
public Throwable getRootCause() {
Throwable rootCause = this;
Throwable cause = getCause();
while (cause != null && cause != rootCause) {
rootCause = cause;
cause = cause.getCause();
}
return rootCause;
}
/**
* Check whether this exception contains an exception of the given type:
* either it is of the given class itself or it contains a nested cause
* of the given type.
*
* @param exType the exception type to look for
* @return whether there is a nested exception of the specified type
*/
public boolean contains(Class exType) {
if (exType == null) {
return false;
}
if (exType.isInstance(this)) {
return true;
}
Throwable cause = getCause();
if (cause == this) {
return false;
}
if (cause instanceof ElasticsearchException) {
return ((ElasticsearchException) cause).contains(exType);
} else {
while (cause != null) {
if (exType.isInstance(cause)) {
return true;
}
if (cause.getCause() == cause) {
break;
}
cause = cause.getCause();
}
return false;
}
}
public void writeTo(StreamOutput out) throws IOException {
out.writeOptionalString(this.getMessage());
out.writeThrowable(this.getCause());
writeStackTraces(this, out);
out.writeVInt(headers.size());
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
out.writeString(entry.getKey());
out.writeVInt(entry.getValue().size());
for (String v : entry.getValue()) {
out.writeString(v);
}
}
}
public static ElasticsearchException readException(StreamInput input, String name) throws IOException {
Constructor<? extends ElasticsearchException> elasticsearchException = MAPPING.get(name);
if (elasticsearchException == null) {
throw new IllegalStateException("unknown exception with name: " + name);
}
try {
return elasticsearchException.newInstance(input);
} catch (InstantiationException|IllegalAccessException|InvocationTargetException e) {
throw new IOException("failed to read exception: [" + name + "]", e);
}
}
/**
* Retruns <code>true</code> iff the given name is a registered for an exception to be read.
*/
public static boolean isRegistered(String name) {
return MAPPING.containsKey(name);
}
static Set<String> getRegisteredKeys() { // for testing
return MAPPING.keySet();
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
Throwable ex = ExceptionsHelper.unwrapCause(this);
if (ex != this) {
toXContent(builder, params, this);
} else {
builder.field("type", getExceptionName());
builder.field("reason", getMessage());
for (String key : headers.keySet()) {
if (key.startsWith("es.")) {
List<String> values = headers.get(key);
xContentHeader(builder, key.substring("es.".length()), values);
}
}
innerToXContent(builder, params);
renderHeader(builder, params);
if (params.paramAsBoolean(REST_EXCEPTION_SKIP_STACK_TRACE, REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT) == false) {
builder.field("stack_trace", ExceptionsHelper.stackTrace(this));
}
}
return builder;
}
/**
* Renders additional per exception information into the xcontent
*/
protected void innerToXContent(XContentBuilder builder, Params params) throws IOException {
causeToXContent(builder, params);
}
/**
* Renders a cause exception as xcontent
*/
protected void causeToXContent(XContentBuilder builder, Params params) throws IOException {
final Throwable cause = getCause();
if (cause != null && params.paramAsBoolean(REST_EXCEPTION_SKIP_CAUSE, REST_EXCEPTION_SKIP_CAUSE_DEFAULT) == false) {
builder.field("caused_by");
builder.startObject();
toXContent(builder, params, cause);
builder.endObject();
}
}
protected final void renderHeader(XContentBuilder builder, Params params) throws IOException {
boolean hasHeader = false;
for (String key : headers.keySet()) {
if (key.startsWith("es.")) {
continue;
}
if (hasHeader == false) {
builder.startObject("header");
hasHeader = true;
}
List<String> values = headers.get(key);
xContentHeader(builder, key, values);
}
if (hasHeader) {
builder.endObject();
}
}
private void xContentHeader(XContentBuilder builder, String key, List<String> values) throws IOException {
if (values != null && values.isEmpty() == false) {
if(values.size() == 1) {
builder.field(key, values.get(0));
} else {
builder.startArray(key);
for (String value : values) {
builder.value(value);
}
builder.endArray();
}
}
}
/**
* Statis toXContent helper method that also renders non {@link org.elasticsearch.ElasticsearchException} instances as XContent.
*/
public static void toXContent(XContentBuilder builder, Params params, Throwable ex) throws IOException {
ex = ExceptionsHelper.unwrapCause(ex);
if (ex instanceof ElasticsearchException) {
((ElasticsearchException) ex).toXContent(builder, params);
} else {
builder.field("type", getExceptionName(ex));
builder.field("reason", ex.getMessage());
if (ex.getCause() != null) {
builder.field("caused_by");
builder.startObject();
toXContent(builder, params, ex.getCause());
builder.endObject();
}
if (params.paramAsBoolean(REST_EXCEPTION_SKIP_STACK_TRACE, REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT) == false) {
builder.field("stack_trace", ExceptionsHelper.stackTrace(ex));
}
}
}
/**
* Returns the root cause of this exception or mupltiple if different shards caused different exceptions
*/
public ElasticsearchException[] guessRootCauses() {
final Throwable cause = getCause();
if (cause != null && cause instanceof ElasticsearchException) {
return ((ElasticsearchException) cause).guessRootCauses();
}
return new ElasticsearchException[] {this};
}
/**
* Returns the root cause of this exception or mupltiple if different shards caused different exceptions.
* If the given exception is not an instance of {@link org.elasticsearch.ElasticsearchException} an empty array
* is returned.
*/
public static ElasticsearchException[] guessRootCauses(Throwable t) {
Throwable ex = ExceptionsHelper.unwrapCause(t);
if (ex instanceof ElasticsearchException) {
return ((ElasticsearchException) ex).guessRootCauses();
}
return new ElasticsearchException[] {new ElasticsearchException(t.getMessage(), t) {
@Override
protected String getExceptionName() {
return getExceptionName(getCause());
}
}};
}
protected String getExceptionName() {
return getExceptionName(this);
}
/**
* Returns a underscore case name for the given exception. This method strips <tt>Elasticsearch</tt> prefixes from exception names.
*/
public static String getExceptionName(Throwable ex) {
String simpleName = ex.getClass().getSimpleName();
if (simpleName.startsWith("Elasticsearch")) {
simpleName = simpleName.substring("Elasticsearch".length());
}
return Strings.toUnderscoreCase(simpleName);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (headers.containsKey(INDEX_HEADER_KEY)) {
builder.append('[').append(getIndex()).append(']');
if (headers.containsKey(SHARD_HEADER_KEY)) {
builder.append('[').append(getShardId()).append(']');
}
builder.append(' ');
}
return builder.append(ExceptionsHelper.detailedMessage(this).trim()).toString();
}
/**
* Deserializes stacktrace elements as well as suppressed exceptions from the given output stream and
* adds it to the given exception.
*/
public static <T extends Throwable> T readStackTrace(T throwable, StreamInput in) throws IOException {
final int stackTraceElements = in.readVInt();
StackTraceElement[] stackTrace = new StackTraceElement[stackTraceElements];
for (int i = 0; i < stackTraceElements; i++) {
final String declaringClasss = in.readString();
final String fileName = in.readOptionalString();
final String methodName = in.readString();
final int lineNumber = in.readVInt();
stackTrace[i] = new StackTraceElement(declaringClasss,methodName, fileName, lineNumber);
}
throwable.setStackTrace(stackTrace);
int numSuppressed = in.readVInt();
for (int i = 0; i < numSuppressed; i++) {
throwable.addSuppressed(in.readThrowable());
}
return throwable;
}
/**
* Serializes the given exceptions stacktrace elements as well as it's suppressed exceptions to the given output stream.
*/
public static <T extends Throwable> T writeStackTraces(T throwable, StreamOutput out) throws IOException {
StackTraceElement[] stackTrace = throwable.getStackTrace();
out.writeVInt(stackTrace.length);
for (StackTraceElement element : stackTrace) {
out.writeString(element.getClassName());
out.writeOptionalString(element.getFileName());
out.writeString(element.getMethodName());
out.writeVInt(element.getLineNumber());
}
Throwable[] suppressed = throwable.getSuppressed();
out.writeVInt(suppressed.length);
for (Throwable t : suppressed) {
out.writeThrowable(t);
}
return throwable;
}
static {
Class<? extends ElasticsearchException>[] exceptions = new Class[]{
org.elasticsearch.common.settings.SettingsException.class,
org.elasticsearch.index.snapshots.IndexShardSnapshotFailedException.class,
org.elasticsearch.index.engine.IndexFailedEngineException.class,
org.elasticsearch.indices.recovery.RecoverFilesRecoveryException.class,
org.elasticsearch.index.translog.TruncatedTranslogException.class,
org.elasticsearch.repositories.RepositoryException.class,
org.elasticsearch.index.engine.DocumentSourceMissingException.class,
org.elasticsearch.index.engine.DocumentMissingException.class,
org.elasticsearch.common.util.concurrent.EsRejectedExecutionException.class,
org.elasticsearch.cluster.routing.RoutingException.class,
org.elasticsearch.common.lucene.Lucene.EarlyTerminationException.class,
org.elasticsearch.indices.InvalidAliasNameException.class,
org.elasticsearch.index.engine.EngineCreationFailureException.class,
org.elasticsearch.index.snapshots.IndexShardRestoreFailedException.class,
org.elasticsearch.script.groovy.GroovyScriptCompilationException.class,
org.elasticsearch.cluster.routing.RoutingValidationException.class,
org.elasticsearch.snapshots.SnapshotMissingException.class,
org.elasticsearch.index.shard.IndexShardRecoveryException.class,
org.elasticsearch.action.search.SearchPhaseExecutionException.class,
org.elasticsearch.common.util.concurrent.UncategorizedExecutionException.class,
org.elasticsearch.index.engine.SnapshotFailedEngineException.class,
org.elasticsearch.action.search.ReduceSearchPhaseException.class,
org.elasticsearch.action.RoutingMissingException.class,
org.elasticsearch.index.engine.DeleteFailedEngineException.class,
org.elasticsearch.indices.recovery.RecoveryFailedException.class,
org.elasticsearch.search.builder.SearchSourceBuilderException.class,
org.elasticsearch.index.engine.RefreshFailedEngineException.class,
org.elasticsearch.index.snapshots.IndexShardSnapshotException.class,
org.elasticsearch.search.query.QueryPhaseExecutionException.class,
org.elasticsearch.cluster.metadata.ProcessClusterEventTimeoutException.class,
org.elasticsearch.index.percolator.PercolatorException.class,
org.elasticsearch.snapshots.ConcurrentSnapshotExecutionException.class,
org.elasticsearch.indices.IndexTemplateAlreadyExistsException.class,
org.elasticsearch.indices.InvalidIndexNameException.class,
org.elasticsearch.indices.recovery.DelayRecoveryException.class,
org.elasticsearch.indices.AliasFilterParsingException.class,
org.elasticsearch.indices.InvalidIndexTemplateException.class,
org.elasticsearch.http.HttpException.class,
org.elasticsearch.index.shard.IndexShardNotRecoveringException.class,
org.elasticsearch.indices.IndexPrimaryShardNotAllocatedException.class,
org.elasticsearch.action.UnavailableShardsException.class,
org.elasticsearch.transport.ActionNotFoundTransportException.class,
org.elasticsearch.index.shard.TranslogRecoveryPerformer.BatchOperationException.class,
org.elasticsearch.ElasticsearchException.class,
org.elasticsearch.index.shard.IndexShardClosedException.class,
org.elasticsearch.client.transport.NoNodeAvailableException.class,
org.elasticsearch.cluster.block.ClusterBlockException.class,
org.elasticsearch.action.FailedNodeException.class,
org.elasticsearch.indices.TypeMissingException.class,
org.elasticsearch.indices.InvalidTypeNameException.class,
org.elasticsearch.transport.netty.SizeHeaderFrameDecoder.HttpOnTransportException.class,
org.elasticsearch.common.util.CancellableThreads.ExecutionCancelledException.class,
org.elasticsearch.snapshots.SnapshotCreationException.class,
org.elasticsearch.script.groovy.GroovyScriptExecutionException.class,
org.elasticsearch.indices.IndexTemplateMissingException.class,
org.elasticsearch.transport.NodeNotConnectedException.class,
org.elasticsearch.index.shard.IndexShardRecoveringException.class,
org.elasticsearch.index.shard.IndexShardStartedException.class,
org.elasticsearch.indices.IndexClosedException.class,
org.elasticsearch.repositories.RepositoryMissingException.class,
org.elasticsearch.search.warmer.IndexWarmerMissingException.class,
org.elasticsearch.percolator.PercolateException.class,
org.elasticsearch.index.engine.EngineException.class,
org.elasticsearch.script.expression.ExpressionScriptExecutionException.class,
org.elasticsearch.action.NoShardAvailableActionException.class,
org.elasticsearch.transport.ReceiveTimeoutTransportException.class,
org.elasticsearch.http.BindHttpException.class,
org.elasticsearch.transport.RemoteTransportException.class,
org.elasticsearch.index.shard.IndexShardRelocatedException.class,
org.elasticsearch.snapshots.InvalidSnapshotNameException.class,
org.elasticsearch.repositories.RepositoryVerificationException.class,
org.elasticsearch.search.SearchException.class,
org.elasticsearch.transport.ActionTransportException.class,
org.elasticsearch.common.settings.NoClassSettingsException.class,
org.elasticsearch.transport.NodeShouldNotConnectException.class,
org.elasticsearch.index.mapper.MapperParsingException.class,
org.elasticsearch.action.support.replication.TransportReplicationAction.RetryOnReplicaException.class,
org.elasticsearch.search.dfs.DfsPhaseExecutionException.class,
org.elasticsearch.index.engine.VersionConflictEngineException.class,
org.elasticsearch.snapshots.SnapshotRestoreException.class,
org.elasticsearch.script.Script.ScriptParseException.class,
org.elasticsearch.ElasticsearchGenerationException.class,
org.elasticsearch.action.TimestampParsingException.class,
org.elasticsearch.action.NoSuchNodeException.class,
org.elasticsearch.transport.BindTransportException.class,
org.elasticsearch.snapshots.SnapshotException.class,
org.elasticsearch.index.mapper.MapperException.class,
org.elasticsearch.transport.TransportException.class,
org.elasticsearch.search.SearchContextException.class,
org.elasticsearch.index.translog.TranslogCorruptedException.class,
org.elasticsearch.transport.TransportSerializationException.class,
org.elasticsearch.cluster.IncompatibleClusterStateVersionException.class,
org.elasticsearch.indices.IndexCreationException.class,
org.elasticsearch.index.mapper.MergeMappingException.class,
org.elasticsearch.transport.NotSerializableTransportException.class,
org.elasticsearch.ElasticsearchTimeoutException.class,
org.elasticsearch.search.SearchContextMissingException.class,
org.elasticsearch.transport.SendRequestTransportException.class,
org.elasticsearch.index.IndexShardAlreadyExistsException.class,
org.elasticsearch.indices.IndexAlreadyExistsException.class,
org.elasticsearch.index.engine.DocumentAlreadyExistsException.class,
org.elasticsearch.transport.ConnectTransportException.class,
org.elasticsearch.gateway.GatewayException.class,
org.elasticsearch.script.ScriptException.class,
org.elasticsearch.script.expression.ExpressionScriptCompilationException.class,
org.elasticsearch.index.shard.IndexShardNotStartedException.class,
org.elasticsearch.index.mapper.StrictDynamicMappingException.class,
org.elasticsearch.index.engine.EngineClosedException.class,
AliasesNotFoundException.class,
org.elasticsearch.transport.ResponseHandlerFailureTransportException.class,
org.elasticsearch.search.SearchParseException.class,
org.elasticsearch.search.fetch.FetchPhaseExecutionException.class,
org.elasticsearch.transport.NodeDisconnectedException.class,
org.elasticsearch.common.breaker.CircuitBreakingException.class,
org.elasticsearch.search.aggregations.AggregationInitializationException.class,
org.elasticsearch.search.aggregations.InvalidAggregationPathException.class,
org.elasticsearch.cluster.routing.IllegalShardRoutingStateException.class,
org.elasticsearch.index.engine.FlushFailedEngineException.class,
org.elasticsearch.index.AlreadyExpiredException.class,
org.elasticsearch.index.translog.TranslogException.class,
org.elasticsearch.index.engine.FlushNotAllowedEngineException.class,
org.elasticsearch.index.engine.RecoveryEngineException.class,
org.elasticsearch.common.blobstore.BlobStoreException.class,
org.elasticsearch.index.snapshots.IndexShardRestoreException.class,
org.elasticsearch.index.query.QueryParsingException.class,
org.elasticsearch.action.support.replication.TransportReplicationAction.RetryOnPrimaryException.class,
org.elasticsearch.index.engine.DeleteByQueryFailedEngineException.class,
org.elasticsearch.discovery.MasterNotDiscoveredException.class,
org.elasticsearch.action.support.broadcast.BroadcastShardOperationFailedException.class,
org.elasticsearch.node.NodeClosedException.class,
org.elasticsearch.search.aggregations.AggregationExecutionException.class,
org.elasticsearch.ElasticsearchParseException.class,
org.elasticsearch.action.PrimaryMissingActionException.class,
org.elasticsearch.index.engine.CreateFailedEngineException.class,
org.elasticsearch.index.shard.IllegalIndexShardStateException.class,
ElasticsearchSecurityException.class,
ResourceNotFoundException.class,
IndexNotFoundException.class,
ShardNotFoundException.class,
NotSerializableExceptionWrapper.class,
Discovery.FailedToCommitClusterStateException.class
};
Map<String, Constructor<? extends ElasticsearchException>> mapping = new HashMap<>(exceptions.length);
for (Class<? extends ElasticsearchException> e : exceptions) {
String name = e.getName();
try {
Constructor<? extends ElasticsearchException> constructor = e.getDeclaredConstructor(StreamInput.class);
if (constructor == null) {
throw new IllegalStateException(name + " has not StreamInput ctor");
}
mapping.put(name, constructor);
} catch (NoSuchMethodException t) {
throw new RuntimeException("failed to register [" + name + "] exception must have a public StreamInput ctor", t);
}
}
MAPPING = Collections.unmodifiableMap(mapping);
}
public String getIndex() {
List<String> index = getHeader(INDEX_HEADER_KEY);
if (index != null && index.isEmpty() == false) {
return index.get(0);
}
return null;
}
public ShardId getShardId() {
List<String> shard = getHeader(SHARD_HEADER_KEY);
if (shard != null && shard.isEmpty() == false) {
return new ShardId(getIndex(), Integer.parseInt(shard.get(0)));
}
return null;
}
public void setIndex(Index index) {
if (index != null) {
addHeader(INDEX_HEADER_KEY, index.getName());
}
}
public void setIndex(String index) {
if (index != null) {
addHeader(INDEX_HEADER_KEY, index);
}
}
public void setShard(ShardId shardId) {
if (shardId != null) {
addHeader(INDEX_HEADER_KEY, shardId.getIndex());
addHeader(SHARD_HEADER_KEY, Integer.toString(shardId.id()));
}
}
public void setResources(String type, String... id) {
assert type != null;
addHeader(RESOURCE_HEADER_ID_KEY, id);
addHeader(RESOURCE_HEADER_TYPE_KEY, type);
}
public List<String> getResourceId() {
return getHeader(RESOURCE_HEADER_ID_KEY);
}
public String getResourceType() {
List<String> header = getHeader(RESOURCE_HEADER_TYPE_KEY);
if (header != null && header.isEmpty() == false) {
assert header.size() == 1;
return header.get(0);
}
return null;
}
public static void renderThrowable(XContentBuilder builder, Params params, Throwable t) throws IOException {
builder.startObject("error");
final ElasticsearchException[] rootCauses = ElasticsearchException.guessRootCauses(t);
builder.field("root_cause");
builder.startArray();
for (ElasticsearchException rootCause : rootCauses){
builder.startObject();
rootCause.toXContent(builder, new ToXContent.DelegatingMapParams(Collections.singletonMap(ElasticsearchException.REST_EXCEPTION_SKIP_CAUSE, "true"), params));
builder.endObject();
}
builder.endArray();
ElasticsearchException.toXContent(builder, params, t);
builder.endObject();
}
}
| springning/elasticsearch | core/src/main/java/org/elasticsearch/ElasticsearchException.java | Java | apache-2.0 | 31,754 |
/*
* 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.reef.wake.time.runtime.event;
import org.apache.reef.wake.EventHandler;
import org.apache.reef.wake.time.event.Alarm;
/**
* An event for client-created alarm.
*/
public final class ClientAlarm extends Alarm {
public ClientAlarm(final long timestamp, final EventHandler<Alarm> handler) {
super(timestamp, handler);
}
}
| yunseong/reef | lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/time/runtime/event/ClientAlarm.java | Java | apache-2.0 | 1,158 |
cask 'adobe-master-collection-cs6' do
version :latest
sha256 :no_check
# This Cask only works for Adobe dmgs containing the deploy folder,
# i.e. the Adobe Collections, not the single Product Installers!
# For correct download URL see links provided at
# https://helpx.adobe.com/x-productkb/policy-pricing/cs6-product-downloads.html
url 'http://trials2.adobe.com/AdobeProducts/STAM/CS6/osx10/MasterCollection_CS6_LS16.dmg',
user_agent: :fake,
cookies: { 'MM_TRIALS' => '1234' }
name 'Adobe CS6 Master Collection' # name must exactly match directory in dmg!
homepage 'https://www.adobe.com/mena_en/products/creativesuite.html'
license :commercial
# staged_path not available in Installer/Uninstall Stanza, workaround by nesting with preflight/postflight
# see https://github.com/caskroom/homebrew-cask/pull/8887
# and https://github.com/caskroom/homebrew-versions/pull/296
preflight do
system '/usr/bin/killall', '-kill', 'SafariNotificationAgent'
system '/usr/bin/sudo', '-E', '--', "#{staged_path}/Adobe CS6 Master Collection/Install.app/Contents/MacOS/Install", '--mode=silent', "--deploymentFile=#{staged_path}/Adobe CS6 Master Collection/deploy/install-en_US.xml"
end
uninstall_preflight do
system '/usr/bin/killall', '-kill', 'SafariNotificationAgent'
system '/usr/bin/sudo', '-E', '--', "#{staged_path}/Adobe CS6 Master Collection/Install.app/Contents/MacOS/Install", '--mode=silent', "--deploymentFile=#{staged_path}/Adobe CS6 Master Collection/deploy/uninstall-en_US.xml"
end
caveats 'Installation or Uninstallation may fail with Exit Code 19 (Conflicting Processes running) if Browsers, Safari Notification Service or SIMBL Services (e.g. Flashlight) are running or Adobe Creative Cloud or any other Adobe Products are already installed. See Logs in /Library/Logs/Adobe/Installers if Installation or Uninstallation fails, to identifify the conflicting processes.'
end
| zerrot/homebrew-versions | Casks/adobe-master-collection-cs6.rb | Ruby | bsd-2-clause | 1,951 |
cask 'fastscripts' do
version '2.6.13'
sha256 '0324cf741f989e9f224259af2b79fcb163fcedcf45e790f8ccb747ffa1971b6c'
url "https://www.red-sweater.com/fastscripts/FastScripts#{version}.zip"
appcast 'https://red-sweater.com/fastscripts/appcast2.php'
name 'FastScripts'
homepage 'https://red-sweater.com/fastscripts/'
app 'FastScripts.app'
end
| chadcatlett/caskroom-homebrew-cask | Casks/fastscripts.rb | Ruby | bsd-2-clause | 353 |
class Jlog < Formula
desc "Pure C message queue with subscribers and publishers for logs"
homepage "https://labs.omniti.com/labs/jlog"
url "https://github.com/omniti-labs/jlog/archive/2.3.0.tar.gz"
sha256 "b8912e8de791701d664965c30357c4bbc68df3206b22f7ea0029e7179b02079a"
head "https://github.com/omniti-labs/jlog.git"
bottle do
cellar :any
sha256 "68d1057ab73d4b1548bbcbfe27e16789d4a2ed66abbe87b49950824287c1c356" => :high_sierra
sha256 "32a6766cb3c60af8e6b47bd80b81362a95e0c27ce57e078f42385af443af49f1" => :sierra
sha256 "b7a9ed90a1f393772747a0c64b60fe07569f963f03f294455cbf569969b3319e" => :el_capitan
sha256 "1479a30b96d3b41eee289a2ffb01ed4d0bb1b45c325bb80c8cc8430f9e7f4052" => :yosemite
end
depends_on "automake" => :build
depends_on "autoconf" => :build
def install
system "autoconf"
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"jlogtest.c").write <<~EOS
#include <stdio.h>
#include <jlog.h>
int main() {
jlog_ctx *ctx;
const char *path = "#{testpath}/jlogexample";
int rv;
// First, ensure that the jlog is created
ctx = jlog_new(path);
if (jlog_ctx_init(ctx) != 0) {
if(jlog_ctx_err(ctx) != JLOG_ERR_CREATE_EXISTS) {
fprintf(stderr, "jlog_ctx_init failed: %d %s\\n", jlog_ctx_err(ctx), jlog_ctx_err_string(ctx));
exit(1);
}
// Make sure it knows about our subscriber(s)
jlog_ctx_add_subscriber(ctx, "one", JLOG_BEGIN);
jlog_ctx_add_subscriber(ctx, "two", JLOG_BEGIN);
}
// Now re-open for writing
jlog_ctx_close(ctx);
ctx = jlog_new(path);
if (jlog_ctx_open_writer(ctx) != 0) {
fprintf(stderr, "jlog_ctx_open_writer failed: %d %s\\n", jlog_ctx_err(ctx), jlog_ctx_err_string(ctx));
exit(0);
}
// Send in some data
rv = jlog_ctx_write(ctx, "hello\\n", strlen("hello\\n"));
if (rv != 0) {
fprintf(stderr, "jlog_ctx_write_message failed: %d %s\\n", jlog_ctx_err(ctx), jlog_ctx_err_string(ctx));
}
jlog_ctx_close(ctx);
}
EOS
system ENV.cc, "jlogtest.c", "-I#{include}", "-L#{lib}", "-ljlog", "-o", "jlogtest"
system testpath/"jlogtest"
end
end
| robohack/homebrew-core | Formula/jlog.rb | Ruby | bsd-2-clause | 2,340 |
class Phyutility < Formula
desc "analyze and modify trees and data matrices"
homepage "http://blackrim.org/programs/phyutility/"
url "https://github.com/blackrim/phyutility/releases/download/v2.7.1/phyutility_2.7.1.tar.gz"
sha256 "3438336abda593cf3043d49910815dc8b8e506e9e44831726407f37a1a7506bc"
# doi "10.1093/bioinformatics/btm619"
# tag "bioinformatics'
bottle :unneeded
def install
libexec.install "phyutility.jar"
bin.write_jar_script libexec/"phyutility.jar", "phyutility"
pkgshare.install "examples", "manual.pdf"
end
def caveats; <<-EOS.undent
The manual and examples are in:
#{opt_pkgshare}
EOS
end
test do
cp Dir[pkgshare/"examples/*"], testpath
system *%W[#{bin}/phyutility -concat -in test.aln test2.aln -out test_new.aln]
compare_file "test_new.aln", "test_all.aln"
end
end
| dpo/homebrew-science | phyutility.rb | Ruby | bsd-2-clause | 856 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.media.ui;
import android.content.Intent;
import android.media.AudioManager;
import android.support.test.InstrumentationRegistry;
import androidx.test.filters.MediumTest;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.FlakyTest;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.ntp.NewTabPage;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.ChromeTabbedActivityTestRule;
import org.chromium.chrome.test.util.NewTabPageTestUtils;
import org.chromium.chrome.test.util.browser.TabLoadObserver;
import org.chromium.components.browser_ui.media.MediaNotificationController;
import org.chromium.components.browser_ui.media.MediaNotificationManager;
import org.chromium.components.embedder_support.util.UrlConstants;
import org.chromium.components.url_formatter.SchemeDisplay;
import org.chromium.components.url_formatter.UrlFormatter;
import org.chromium.content_public.browser.test.util.DOMUtils;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.media.MediaSwitches;
import org.chromium.net.test.EmbeddedTestServer;
import java.util.concurrent.TimeoutException;
/**
* Tests for checking whether the media are paused when unplugging the headset
*/
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({MediaSwitches.AUTOPLAY_NO_GESTURE_REQUIRED_POLICY,
ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public class MediaSessionTest {
@Rule
public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule();
private static final String TEST_PATH = "/content/test/data/media/session/media-session.html";
private static final String VIDEO_ID = "long-video";
private EmbeddedTestServer mTestServer;
@Test
@SmallTest
@FlakyTest
public void testPauseOnHeadsetUnplug() throws IllegalArgumentException, TimeoutException {
mActivityTestRule.startMainActivityWithURL(mTestServer.getURL(TEST_PATH));
Tab tab = mActivityTestRule.getActivity().getActivityTab();
Assert.assertTrue(DOMUtils.isMediaPaused(tab.getWebContents(), VIDEO_ID));
DOMUtils.playMedia(tab.getWebContents(), VIDEO_ID);
DOMUtils.waitForMediaPlay(tab.getWebContents(), VIDEO_ID);
waitForNotificationReady();
simulateHeadsetUnplug();
DOMUtils.waitForMediaPauseBeforeEnd(tab.getWebContents(), VIDEO_ID);
}
/**
* Regression test for crbug.com/1108038.
*
* Makes sure the notification info is updated after a navigation from a native page to a site
* with media.
*/
@Test
@MediumTest
public void mediaSessionUrlUpdatedAfterNativePageNavigation() throws Exception {
mActivityTestRule.startMainActivityWithURL("about:blank");
Tab tab = mActivityTestRule.getActivity().getActivityTab();
mActivityTestRule.loadUrl(UrlConstants.NTP_URL);
NewTabPageTestUtils.waitForNtpLoaded(tab);
Assert.assertTrue(tab.getNativePage() instanceof NewTabPage);
String videoPageUrl = mTestServer.getURL(TEST_PATH);
new TabLoadObserver(tab).fullyLoadUrl(videoPageUrl);
DOMUtils.playMedia(tab.getWebContents(), VIDEO_ID);
DOMUtils.waitForMediaPlay(tab.getWebContents(), VIDEO_ID);
waitForNotificationReady();
TestThreadUtils.runOnUiThreadBlocking(() -> {
MediaNotificationController controller =
MediaNotificationManager.getController(R.id.media_playback_notification);
Assert.assertEquals(UrlFormatter.formatUrlForSecurityDisplay(
videoPageUrl, SchemeDisplay.OMIT_HTTP_AND_HTTPS),
controller.mMediaNotificationInfo.origin);
});
}
@Before
public void setUp() {
mTestServer = EmbeddedTestServer.createAndStartServer(InstrumentationRegistry.getContext());
}
@After
public void tearDown() {
mTestServer.stopAndDestroyServer();
}
private void waitForNotificationReady() {
CriteriaHelper.pollInstrumentationThread(() -> {
return MediaNotificationManager.getController(R.id.media_playback_notification) != null;
});
}
private void simulateHeadsetUnplug() {
Intent i = new Intent(InstrumentationRegistry.getTargetContext(),
ChromeMediaNotificationControllerServices.PlaybackListenerService.class);
i.setAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
InstrumentationRegistry.getContext().startService(i);
}
}
| ric2b/Vivaldi-browser | chromium/chrome/android/javatests/src/org/chromium/chrome/browser/media/ui/MediaSessionTest.java | Java | bsd-3-clause | 5,144 |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using Cosmos.Debug.Common;
namespace Cosmos.Debug.VSDebugEngine.Host {
public abstract class Base {
protected NameValueCollection mParams;
protected bool mUseGDB;
public EventHandler OnShutDown;
public Base(NameValueCollection aParams, bool aUseGDB) {
mParams = aParams;
mUseGDB = aUseGDB;
}
public abstract void Start();
public abstract void Stop();
}
}
| Coder-666/COSMOS | source2/Debug/Cosmos.Debug.VSDebugEngine/Host/Base.cs | C# | bsd-3-clause | 553 |
using System;
using System.Management.Automation;
namespace TestPSSnapIn
{
public class PashTestSnapIn : PSSnapIn
{
public override string Description
{
get { return "Snapin to test Pash's snapin support."; }
}
public override string Name
{
get { return "PashTestSnapIn"; }
}
public override string Vendor
{
get { return "Pash"; }
}
}
}
| WimObiwan/Pash | Source/TestPSSnapIn/PashTestSnapIn.cs | C# | bsd-3-clause | 380 |
package com.openxc.units;
/**
* A Meter is the base unit of length in the SI.
*/
public class Meter extends Quantity<Number> {
private final String TYPE_STRING = "m";
public Meter(Number value) {
super(value);
}
@Override
public String getTypeString() {
return TYPE_STRING;
}
}
| bibhrajit/openxc-androidStudio | openxc/src/com/openxc/units/Meter.java | Java | bsd-3-clause | 323 |
/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
package com.facebook.crypto.benchmarks.cipher;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import com.facebook.crypto.streams.BetterCipherInputStream;
public class BaseCipher {
protected AlgorithmParameterSpec mAlgorithmParameterSpec;
protected String mName;
protected Key mKey;
protected String mProvider;
public BaseCipher(String name, AlgorithmParameterSpec spec, Key key) {
this.mAlgorithmParameterSpec = spec;
this.mName = name;
this.mKey = key;
}
protected void setProvider(String prov) {
mProvider = prov;
}
public InputStream getInputStream(InputStream is) throws NoSuchProviderException,
InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchPaddingException {
return new BetterCipherInputStream(is, getDecrypt());
}
public OutputStream getOutputStream(OutputStream os) throws NoSuchProviderException,
InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchPaddingException {
return new CipherOutputStream(os, getEncrypt());
}
private Cipher getEncrypt()
throws NoSuchPaddingException,
NoSuchAlgorithmException,
InvalidAlgorithmParameterException,
InvalidKeyException,
NoSuchProviderException {
Cipher cipher;
if (mProvider != null) {
cipher = Cipher.getInstance(mName, mProvider);
} else {
cipher = Cipher.getInstance(mName);
}
cipher.init(Cipher.ENCRYPT_MODE, mKey, mAlgorithmParameterSpec);
return cipher;
}
private Cipher getDecrypt()
throws NoSuchPaddingException,
NoSuchAlgorithmException,
InvalidAlgorithmParameterException,
InvalidKeyException,
NoSuchProviderException {
Cipher cipher;
if (mProvider != null) {
cipher = Cipher.getInstance(mName, mProvider);
} else {
cipher = Cipher.getInstance(mName);
}
cipher.init(Cipher.DECRYPT_MODE, mKey, mAlgorithmParameterSpec);
return cipher;
}
}
| hgl888/conceal | benchmarks/src/com/facebook/crypto/benchmarks/cipher/BaseCipher.java | Java | bsd-3-clause | 2,506 |
/*
* Copyright (c) 2011-2015, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include "SystemClass.h"
#include "SubsystemLibrary.h"
#include "VirtualSubsystem.h"
#include "LoggingElementBuilderTemplate.h"
#include <cassert>
#include "PluginLocation.h"
#include "DynamicLibrary.hpp"
#include "Utility.h"
#include "Memory.hpp"
#define base CConfigurableElement
#ifndef PARAMETER_FRAMEWORK_PLUGIN_ENTRYPOINT_V1
#error Missing PARAMETER_FRAMEWORK_PLUGIN_ENTRYPOINT_V1 macro definition
#endif
#define QUOTE(X) #X
#define MACRO_TO_STR(X) QUOTE(X)
const char CSystemClass::entryPointSymbol[] =
MACRO_TO_STR(PARAMETER_FRAMEWORK_PLUGIN_ENTRYPOINT_V1);
using PluginEntryPointV1 = void (*)(CSubsystemLibrary *, core::log::Logger &);
using std::list;
using std::string;
// FIXME: integrate SystemClass to core namespace
using namespace core;
CSystemClass::CSystemClass(log::Logger &logger)
: _pSubsystemLibrary(new CSubsystemLibrary()), _logger(logger)
{
}
CSystemClass::~CSystemClass()
{
delete _pSubsystemLibrary;
// Destroy child subsystems *before* unloading the libraries (otherwise crashes will occur
// as unmapped code will be referenced)
clean();
}
bool CSystemClass::childrenAreDynamic() const
{
return true;
}
string CSystemClass::getKind() const
{
return "SystemClass";
}
bool CSystemClass::getMappingData(const std::string & /*strKey*/,
const std::string *& /*pStrValue*/) const
{
// Although it could make sense to have mapping in the system class,
// just like at subsystem level, it is currently not supported.
return false;
}
string CSystemClass::getFormattedMapping() const
{
return "";
}
bool CSystemClass::loadSubsystems(string &strError, const CSubsystemPlugins *pSubsystemPlugins,
bool bVirtualSubsystemFallback)
{
// Start clean
_pSubsystemLibrary->clean();
typedef TLoggingElementBuilderTemplate<CVirtualSubsystem> VirtualSubsystemBuilder;
// Add virtual subsystem builder
_pSubsystemLibrary->addElementBuilder("Virtual", new VirtualSubsystemBuilder(_logger));
// Set virtual subsytem as builder fallback if required
if (bVirtualSubsystemFallback) {
_pSubsystemLibrary->setDefaultBuilder(
utility::make_unique<VirtualSubsystemBuilder>(_logger));
}
// Add subsystem defined in shared libraries
core::Results errors;
bool bLoadPluginsSuccess = loadSubsystemsFromSharedLibraries(errors, pSubsystemPlugins);
// Fill strError for caller, he has to decide if there is a problem depending on
// bVirtualSubsystemFallback value
strError = utility::asString(errors);
return bLoadPluginsSuccess || bVirtualSubsystemFallback;
}
bool CSystemClass::loadSubsystemsFromSharedLibraries(core::Results &errors,
const CSubsystemPlugins *pSubsystemPlugins)
{
// Plugin list
list<string> lstrPluginFiles;
size_t pluginLocation;
for (pluginLocation = 0; pluginLocation < pSubsystemPlugins->getNbChildren();
pluginLocation++) {
// Get Folder for current Plugin Location
const CPluginLocation *pPluginLocation =
static_cast<const CPluginLocation *>(pSubsystemPlugins->getChild(pluginLocation));
string strFolder(pPluginLocation->getFolder());
if (!strFolder.empty()) {
strFolder += "/";
}
// Iterator on Plugin List:
list<string>::const_iterator it;
const list<string> &pluginList = pPluginLocation->getPluginList();
for (it = pluginList.begin(); it != pluginList.end(); ++it) {
// Fill Plugin files list
lstrPluginFiles.push_back(strFolder + *it);
}
}
// Actually load plugins
while (!lstrPluginFiles.empty()) {
// Because plugins might depend on one another, loading will be done
// as an iteration process that finishes successfully when the remaining
// list of plugins to load gets empty or unsuccessfully if the loading
// process failed to load at least one of them
// Attempt to load the complete list
if (!loadPlugins(lstrPluginFiles, errors)) {
// Unable to load at least one plugin
break;
}
}
if (!lstrPluginFiles.empty()) {
// Unable to load at least one plugin
errors.push_back("Unable to load the following plugins: " +
utility::asString(lstrPluginFiles, ", ") + ".");
return false;
}
return true;
}
// Plugin loading
bool CSystemClass::loadPlugins(list<string> &lstrPluginFiles, core::Results &errors)
{
assert(lstrPluginFiles.size());
bool bAtLeastOneSubsystemPluginSuccessfullyLoaded = false;
auto it = lstrPluginFiles.begin();
while (it != lstrPluginFiles.end()) {
string strPluginFileName = *it;
// Load attempt
try {
auto library = utility::make_unique<DynamicLibrary>(strPluginFileName);
// Load symbol from library
auto subSystemBuilder = library->getSymbol<PluginEntryPointV1>(entryPointSymbol);
// Store libraries handles
_subsystemLibraryHandleList.push_back(std::move(library));
// Fill library
subSystemBuilder(_pSubsystemLibrary, _logger);
} catch (std::exception &e) {
errors.push_back(e.what());
// Next plugin
++it;
continue;
}
// Account for this success
bAtLeastOneSubsystemPluginSuccessfullyLoaded = true;
// Remove successfully loaded plugin from list and select next
lstrPluginFiles.erase(it++);
}
return bAtLeastOneSubsystemPluginSuccessfullyLoaded;
}
const CSubsystemLibrary *CSystemClass::getSubsystemLibrary() const
{
return _pSubsystemLibrary;
}
void CSystemClass::checkForSubsystemsToResync(CSyncerSet &syncerSet, core::Results &infos)
{
size_t uiNbChildren = getNbChildren();
size_t uiChild;
for (uiChild = 0; uiChild < uiNbChildren; uiChild++) {
CSubsystem *pSubsystem = static_cast<CSubsystem *>(getChild(uiChild));
// Collect and consume the need for a resync
if (pSubsystem->needResync(true)) {
infos.push_back("Resynchronizing subsystem: " + pSubsystem->getName());
// get all subsystem syncers
pSubsystem->fillSyncerSet(syncerSet);
}
}
}
void CSystemClass::cleanSubsystemsNeedToResync()
{
size_t uiNbChildren = getNbChildren();
size_t uiChild;
for (uiChild = 0; uiChild < uiNbChildren; uiChild++) {
CSubsystem *pSubsystem = static_cast<CSubsystem *>(getChild(uiChild));
// Consume the need for a resync
pSubsystem->needResync(true);
}
}
| miguelgaio/parameter-framework | parameter/SystemClass.cpp | C++ | bsd-3-clause | 8,364 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/components/local_search_service/shared_structs.h"
#include <utility>
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "chromeos/components/local_search_service/linear_map_search.h"
#include "chromeos/components/string_matching/fuzzy_tokenized_string_match.h"
#include "chromeos/components/string_matching/tokenized_string.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace chromeos {
namespace local_search_service {
local_search_service::Content::Content(const std::string& id,
const std::u16string& content,
double weight)
: id(id), content(content), weight(weight) {}
local_search_service::Content::Content() = default;
local_search_service::Content::Content(const Content& content) = default;
local_search_service::Content::~Content() = default;
Data::Data(const std::string& id,
const std::vector<Content>& contents,
const std::string& locale)
: id(id), contents(contents), locale(locale) {}
Data::Data() = default;
Data::Data(const Data& data) = default;
Data::~Data() = default;
Position::Position() = default;
Position::Position(const Position& position) = default;
Position::Position(const std::string& content_id,
uint32_t start,
uint32_t length)
: content_id(content_id), start(start), length(length) {}
Position::~Position() = default;
Result::Result() = default;
Result::Result(const Result& result) = default;
Result::Result(const std::string& id,
double score,
const std::vector<Position>& positions)
: id(id), score(score), positions(positions) {}
Result::~Result() = default;
WeightedPosition::WeightedPosition() = default;
WeightedPosition::WeightedPosition(const WeightedPosition& weighted_position) =
default;
WeightedPosition::WeightedPosition(double weight, const Position& position)
: weight(weight), position(position) {}
WeightedPosition::~WeightedPosition() = default;
Token::Token() = default;
Token::Token(const std::u16string& text,
const std::vector<WeightedPosition>& pos)
: content(text), positions(pos) {}
Token::Token(const Token& token)
: content(token.content), positions(token.positions) {}
Token::~Token() = default;
} // namespace local_search_service
} // namespace chromeos
| ric2b/Vivaldi-browser | chromium/chromeos/components/local_search_service/shared_structs.cc | C++ | bsd-3-clause | 2,580 |
#
# Specifying JenkinsApi::Client class capabilities
# Author: Kannan Manickam <arangamani.kannan@gmail.com>
#
require File.expand_path('../spec_helper', __FILE__)
require 'yaml'
describe JenkinsApi::Client do
context "Given valid credentials and server information are given" do
before(:all) do
@creds_file = '~/.jenkins_api_client/spec.yml'
# Grabbing just the server IP in a variable so we can check
# for wrong credentials
@server_ip = YAML.load_file(
File.expand_path(@creds_file, __FILE__)
)[:server_ip]
begin
@client = JenkinsApi::Client.new(
YAML.load_file(File.expand_path(@creds_file, __FILE__))
)
rescue Exception => e
puts "WARNING: Credentials are not set properly."
puts e.message
end
end
describe "InstanceMethods" do
describe "#initialize" do
it "Should be able to initialize with valid credentials" do
client1 = JenkinsApi::Client.new(
YAML.load_file(File.expand_path(@creds_file, __FILE__))
)
client1.class.should == JenkinsApi::Client
end
it "Should accept a YAML argument when creating a new client" do
client3 = JenkinsApi::Client.new(
YAML.load_file(File.expand_path(@creds_file, __FILE__))
)
client3.class.should == JenkinsApi::Client
end
it "Should fail if wrong credentials are given" do
client2 = JenkinsApi::Client.new(
:server_ip => @server_ip,
:username => 'stranger',
:password => 'hacked',
:log_location => '/dev/null'
)
expect(
lambda { client2.job.list_all }
).to raise_error(JenkinsApi::Exceptions::Unauthorized)
end
end
describe "#get_jenkins_version" do
it "Should the jenkins version" do
@client.get_jenkins_version.class.should == String
end
end
describe "#get_hudson_version" do
it "Should get the hudson version" do
@client.get_hudson_version.class.should == String
end
end
describe "#exec_script" do
it "Should execute the provided groovy script" do
@client.exec_script('println("hi")').should == "hi\n"
end
end
end
describe "SubClassAccessorMethods" do
describe "#job" do
it "Should return a job object on call" do
@client.job.class.should == JenkinsApi::Client::Job
end
end
describe "#node" do
it "Should return a node object on call" do
@client.node.class.should == JenkinsApi::Client::Node
end
end
describe "#view" do
it "Should return a view object on call" do
@client.view.class.should == JenkinsApi::Client::View
end
end
describe "#system" do
it "Should return a system object on call" do
@client.system.class.should == JenkinsApi::Client::System
end
end
describe "#queue" do
it "Should return a build queue object on call" do
@client.queue.class.should == JenkinsApi::Client::BuildQueue
end
end
end
end
end
| yp-engineering/jenkins_api_client | spec/func_tests/client_spec.rb | Ruby | mit | 3,244 |
module NamespacesHelper
def namespaces_options(selected = :current_user, scope = :default)
groups = current_user.owned_groups.select {|n| n.type == 'Group'}
users = current_user.namespaces.reject {|n| n.type == 'Group'}
group_opts = ["Groups", groups.sort_by(&:human_name).map {|g| [g.human_name, g.id]} ]
users_opts = [ "Users", users.sort_by(&:human_name).map {|u| [u.human_name, u.id]} ]
options = []
options << group_opts
options << users_opts
if selected == :current_user && current_user.namespace
selected = current_user.namespace.id
end
grouped_options_for_select(options, selected)
end
end
| inetfuture/gitlab-tweak | app/helpers/namespaces_helper.rb | Ruby | mit | 652 |
require 'rails/railtie'
module ActiveModel
class Railtie < Rails::Railtie
generators do |app|
app ||= Rails.application # Rails 3.0.x does not yield `app`
Rails::Generators.configure! app.config.generators
require_relative '../generators/controller_override'
end
end
end
module Draper
class Railtie < Rails::Railtie
config.after_initialize do |app|
app.config.paths.add 'app/decorators', eager_load: true
if Rails.env.test?
require 'draper/test_case'
require 'draper/test/rspec_integration' if defined?(RSpec) and RSpec.respond_to?(:configure)
end
end
initializer "draper.setup_action_controller" do |app|
ActiveSupport.on_load :action_controller do
Draper.setup_action_controller self
end
end
initializer "draper.setup_action_mailer" do |app|
ActiveSupport.on_load :action_mailer do
Draper.setup_action_mailer self
end
end
initializer "draper.setup_orm" do |app|
[:active_record, :mongoid].each do |orm|
ActiveSupport.on_load orm do
Draper.setup_orm self
end
end
end
initializer "draper.setup_active_model_serializers" do |app|
ActiveSupport.on_load :active_model_serializers do
if defined?(ActiveModel::ArraySerializerSupport)
Draper::CollectionDecorator.send :include, ActiveModel::ArraySerializerSupport
end
end
end
initializer "draper.minitest-rails_integration" do |app|
ActiveSupport.on_load :minitest do
require "draper/test/minitest_integration"
end
end
console do
require 'action_controller/test_case'
ApplicationController.new.view_context
Draper::ViewContext.build
end
rake_tasks do
Dir[File.join(File.dirname(__FILE__),'tasks/*.rake')].each { |f| load f }
end
end
end
| sho-wtag/catarse-2.0 | vendor/bundle/ruby/2.2.0/gems/draper-2.1.0/lib/draper/railtie.rb | Ruby | mit | 1,885 |
<?php
/**
* jobberbase job board platform
*
* Cache class handles cache operations
*/
class Cache
{
var $cacheDir = null;
var $cacheID = null;
var $cacheTime = null;
var $useCache = null;
/**
* @param $dir folder where cache will be saved
* @param $time (int) time in seconds; if null cache doesn't expire
* @param $use_cache (boolean)
*/
public function __construct($dir, $time = null, $use_cache = true)
{
if (!is_dir($dir)) {
throw new Exception($dir . " doesn't exist");
}
if ($use_cache !== true && $use_cache !== false) {
throw new Exception("\$use_cache is not valid. Must be 'true' or 'false'");
}
if ($time !== null && !is_int($time)) {
throw new Exception("cache time must be null or int");
}
$this->cacheDir = $dir;
$this->cacheTime = $time;
$this->useCache = $use_cache;
$this->setCache();
}
protected function setCache()
{
//Caching options
$options = array('cacheDir' => $this->cacheDir,
'lifeTime' => $this->cacheTime,
'caching' => $this->useCache);
$cache = new Cache_Lite($options);
$this->liteCache = $cache;
}
public function testCache($identifier, $group = 'default')
{
return $this->liteCache->get($identifier, $group);
}
public function saveCache($data, $identifier, $group = 'default')
{
return $this->liteCache->save(serialize($data), $identifier, $group);
}
public function loadCache($identifier, $group = 'default')
{
if ($data = $this->liteCache->get($identifier, $group))
{
return unserialize($data);
}
else
{
return false;
}
}
public function removeCache($identifier, $group = 'default')
{
return $this->liteCache->remove($identifier, $group);
}
public function cleanCache($group = false)
{
return $this->liteCache->clean($group);
}
}
?>
| myusufe/Job | public/_lib/class.Cache.php | PHP | mit | 2,116 |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# 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.
from runonfailure import RunOnFailure
class Select(RunOnFailure):
def get_list_items(self, locator):
"""Returns the values in the list identified by `locator`.
List keywords work on both lists and combo boxes. Key attributes for
lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
return self._selenium.get_select_options(locator)
def get_selected_list_value(self, locator):
"""Returns the value of the selected element from the list identified by `locator`.
Return value is read from `value` attribute of the selected element.
Fails if there are zero or more than one selection.
List keywords work on both lists and combo boxes. Key attributes for
lists are `id` and `name`. See `introduction` for details about
locating elements.
This keyword was added in SeleniumLibrary 2.8.
"""
return self._selenium.get_selected_value(locator)
def get_selected_list_values(self, locator):
"""Returns the values of selected elements (as a list) from the list identified by `locator`.
Fails if there is no selection.
List keywords work on both lists and combo boxes. Key attributes for
lists are `id` and `name`. See `introduction` for details about
locating elements.
This keyword was added in SeleniumLibrary 2.8.
"""
return self._selenium.get_selected_values(locator)
def get_selected_list_label(self, locator):
"""Returns the visible label of the selected element from the list identified by `locator`.
Fails if there are zero or more than one selection.
List keywords work on both lists and combo boxes. Key attributes for
lists are `id` and `name`. See `introduction` for details about
locating elements.
This keyword was added in SeleniumLibrary 2.8.
"""
return self._selenium.get_selected_label(locator)
def get_selected_list_labels(self, locator):
"""Returns the visible labels of selected elements (as a list) from the list identified by `locator`.
Fails if there is no selection.
List keywords work on both lists and combo boxes. Key attributes for
lists are `id` and `name`. See `introduction` for details about
locating elements.
This keyword was added in SeleniumLibrary 2.8.
"""
return self._selenium.get_selected_labels(locator)
def list_selection_should_be(self, locator, *values):
"""Verifies the selection of list identified by `locator` is exactly `*values`.
If you want to test that no option is selected, simply give no `values`.
List keywords work on both lists and combo boxes. Key attributes for
lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
opts = values and 'options [ %s ]' % ' | '.join(values) or 'no options'
self._info("Verifying list '%s' has %s selected." % (locator, opts))
self.page_should_contain_list(locator)
try:
selected_values = self._selenium.get_selected_values(locator)
selected_labels = self._selenium.get_selected_labels(locator)
except Exception, err:
if not values and self._error_contains(err, 'No option selected'):
return
raise
err = "List '%s' should have had selection [ %s ] but it was [ %s ]" \
% (locator, ' | '.join(values), ' | '.join(selected_labels))
for expvalue in values:
if expvalue not in selected_labels + selected_values:
raise AssertionError(err)
for label, value in zip(selected_labels, selected_values):
if label not in values and value not in values:
raise AssertionError(err)
def select_from_list(self, locator, *values):
"""Selects `*values` from list identified by `locator`
If more than one value is given for a single-selection list, the last
value will be selected. If the target list is a multi-selection list,
and `*values` is an empty list, all values of the list will be selected.
List keywords work on both lists and combo boxes. Key attributes for
lists are `id` and `name`. See `introduction` for details about
locating elements.
This keyword does not support waiting for possible page load
automatically. If that is needed, keyword `Wait Until Page Loaded`
can be used after this keyword.
"""
selection = values and "values '%s'" % ', '.join(values) or 'all values'
self._info("Selecting %s from list '%s'." % (selection, locator))
values = list(values)
if len(values) == 0:
values = self._selenium.get_select_options(locator)
if self._is_multiselect_list(locator):
self._select_from_multiselect_list(locator, values)
else:
self._select_from_singleselect_list(locator, values)
def _select_from_multiselect_list(self, locator, selection):
self._call_method_for_list_elements('add_selection', locator, selection)
def _select_from_singleselect_list(self, locator, selection):
self._call_method_for_list_elements('select', locator, selection)
def _is_multiselect_list(self, locator):
try:
self._selenium.get_attribute(locator+'@multiple')
return True
except Exception, err:
if self._error_contains(err, 'attribute: %s@multiple' % locator):
return False
raise
def _call_method_for_list_elements(self, method_name, locator, elements):
method = getattr(self._selenium, method_name)
for elem in elements:
try:
method(locator, elem)
except:
method(locator, 'value=%s' % elem)
def unselect_from_list(self, locator, *values):
"""Unselects given values from list identified by locator.
As a special case, giving empty list as `*selection` will remove all
selections.
List keywords work on both lists and combo boxes. Key attributes for
lists are `id` and `name`. See `introduction` for details about
locating elements.
This keyword does not support waiting for possible page load
automatically. If that is needed, keyword `Wait Until Page Loaded`
can be used after this keyword.
"""
selection = values and "values '%s'" % ', '.join(values) or 'all values'
self._info("Unselecting %s from list '%s'." % (selection, locator))
if not self._is_multiselect_list(locator):
raise RuntimeError("Keyword 'Unselect from list' works only for "
"multiselect lists")
if not values:
self._selenium.remove_all_selections(locator)
else:
self._call_method_for_list_elements('remove_selection', locator,
list(values))
def select_all_from_list(self, locator, wait=''):
"""Selects all values from multi-select list identified by `id`.
Key attributes for lists are `id` and `name`. See `introduction` for
details about locating elements and about `wait` argument.
"""
self._info("Selecting all values from list '%s'." % locator)
selected_items = []
if self._selenium.is_something_selected(locator):
selected_items = self._selenium.get_selected_labels(locator)
for item in self._selenium.get_select_options(locator):
if item not in selected_items:
self._add_to_selection(locator, item)
if wait:
self.wait_until_page_loaded()
def _add_to_selection(self, locator, item):
try:
self._selenium.add_selection(locator, item)
except Exception, err:
if self._error_contains(err, "Not a multi-select"):
raise RuntimeError("Keyword 'Select all from list' works only "
"for multiselect lists.")
raise
def list_should_have_no_selections(self, locator):
"""Verifies list identified by `locator` has no selections.
List keywords work on both lists and combo boxes. Key attributes for
lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
self._info("Verifying list '%s' has no selection." % locator)
if self._selenium.is_something_selected(locator):
selection = ' | '.join(self._selenium.get_selected_labels(locator))
raise AssertionError("List '%s' should have had no selection "
"(selection was [ %s ])" % (locator, selection))
| ktan2020/legacy-automation | win/Lib/site-packages/SeleniumLibrary/select.py | Python | mit | 9,556 |
"""
Support for EnOcean sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.enocean/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_NAME, CONF_ID)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.components import enocean
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'EnOcean sensor'
DEPENDENCIES = ['enocean']
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ID): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup an EnOcean sensor device."""
dev_id = config.get(CONF_ID)
devname = config.get(CONF_NAME)
add_devices([EnOceanSensor(dev_id, devname)])
class EnOceanSensor(enocean.EnOceanDevice, Entity):
"""Representation of an EnOcean sensor device such as a power meter."""
def __init__(self, dev_id, devname):
"""Initialize the EnOcean sensor device."""
enocean.EnOceanDevice.__init__(self)
self.stype = "powersensor"
self.power = None
self.dev_id = dev_id
self.which = -1
self.onoff = -1
self.devname = devname
@property
def name(self):
"""Return the name of the device."""
return 'Power %s' % self.devname
def value_changed(self, value):
"""Update the internal state of the device."""
self.power = value
self.update_ha_state()
@property
def state(self):
"""Return the state of the device."""
return self.power
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return "W"
| Smart-Torvy/torvy-home-assistant | homeassistant/components/sensor/enocean.py | Python | mit | 1,877 |
require 'spec_helper'
describe Coercer::Integer, '#coerced?' do
let(:object) { described_class.new }
it_behaves_like 'Coercible::Coercer#coerced?' do
let(:primitive_value) { 1 }
let(:non_primitive_value) { 1.0 }
end
end
| eprislac/guard-yard | vendor/ruby/2.0.0/gems/coercible-1.0.0/spec/unit/coercible/coercer/integer/coerced_predicate_spec.rb | Ruby | mit | 240 |
/*
Copyright (c) 2014 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package object
// Network should implement the Reference interface.
var _ Reference = Network{}
// Network should implement the NetworkReference interface.
var _ NetworkReference = Network{}
| Tiger66639/jupiter-brain | vendor/src/github.com/vmware/govmomi/object/network_test.go | GO | mit | 778 |
'''tzinfo timezone information for Asia/Manila.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Manila(DstTzInfo):
'''Asia/Manila timezone definition. See datetime.tzinfo for details'''
zone = 'Asia/Manila'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1936,10,31,16,0,0),
d(1937,1,31,15,0,0),
d(1942,4,30,16,0,0),
d(1944,10,31,15,0,0),
d(1954,4,11,16,0,0),
d(1954,6,30,15,0,0),
d(1978,3,21,16,0,0),
d(1978,9,20,15,0,0),
]
_transition_info = [
i(28800,0,'PHT'),
i(32400,3600,'PHST'),
i(28800,0,'PHT'),
i(32400,0,'JST'),
i(28800,0,'PHT'),
i(32400,3600,'PHST'),
i(28800,0,'PHT'),
i(32400,3600,'PHST'),
i(28800,0,'PHT'),
]
Manila = Manila()
| newvem/pytz | pytz/zoneinfo/Asia/Manila.py | Python | mit | 763 |
'''tzinfo timezone information for America/Kentucky/Monticello.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Monticello(DstTzInfo):
'''America/Kentucky/Monticello timezone definition. See datetime.tzinfo for details'''
zone = 'America/Kentucky/Monticello'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1918,3,31,8,0,0),
d(1918,10,27,7,0,0),
d(1919,3,30,8,0,0),
d(1919,10,26,7,0,0),
d(1942,2,9,8,0,0),
d(1945,8,14,23,0,0),
d(1945,9,30,7,0,0),
d(1968,4,28,8,0,0),
d(1968,10,27,7,0,0),
d(1969,4,27,8,0,0),
d(1969,10,26,7,0,0),
d(1970,4,26,8,0,0),
d(1970,10,25,7,0,0),
d(1971,4,25,8,0,0),
d(1971,10,31,7,0,0),
d(1972,4,30,8,0,0),
d(1972,10,29,7,0,0),
d(1973,4,29,8,0,0),
d(1973,10,28,7,0,0),
d(1974,1,6,8,0,0),
d(1974,10,27,7,0,0),
d(1975,2,23,8,0,0),
d(1975,10,26,7,0,0),
d(1976,4,25,8,0,0),
d(1976,10,31,7,0,0),
d(1977,4,24,8,0,0),
d(1977,10,30,7,0,0),
d(1978,4,30,8,0,0),
d(1978,10,29,7,0,0),
d(1979,4,29,8,0,0),
d(1979,10,28,7,0,0),
d(1980,4,27,8,0,0),
d(1980,10,26,7,0,0),
d(1981,4,26,8,0,0),
d(1981,10,25,7,0,0),
d(1982,4,25,8,0,0),
d(1982,10,31,7,0,0),
d(1983,4,24,8,0,0),
d(1983,10,30,7,0,0),
d(1984,4,29,8,0,0),
d(1984,10,28,7,0,0),
d(1985,4,28,8,0,0),
d(1985,10,27,7,0,0),
d(1986,4,27,8,0,0),
d(1986,10,26,7,0,0),
d(1987,4,5,8,0,0),
d(1987,10,25,7,0,0),
d(1988,4,3,8,0,0),
d(1988,10,30,7,0,0),
d(1989,4,2,8,0,0),
d(1989,10,29,7,0,0),
d(1990,4,1,8,0,0),
d(1990,10,28,7,0,0),
d(1991,4,7,8,0,0),
d(1991,10,27,7,0,0),
d(1992,4,5,8,0,0),
d(1992,10,25,7,0,0),
d(1993,4,4,8,0,0),
d(1993,10,31,7,0,0),
d(1994,4,3,8,0,0),
d(1994,10,30,7,0,0),
d(1995,4,2,8,0,0),
d(1995,10,29,7,0,0),
d(1996,4,7,8,0,0),
d(1996,10,27,7,0,0),
d(1997,4,6,8,0,0),
d(1997,10,26,7,0,0),
d(1998,4,5,8,0,0),
d(1998,10,25,7,0,0),
d(1999,4,4,8,0,0),
d(1999,10,31,7,0,0),
d(2000,4,2,8,0,0),
d(2000,10,29,7,0,0),
d(2001,4,1,7,0,0),
d(2001,10,28,6,0,0),
d(2002,4,7,7,0,0),
d(2002,10,27,6,0,0),
d(2003,4,6,7,0,0),
d(2003,10,26,6,0,0),
d(2004,4,4,7,0,0),
d(2004,10,31,6,0,0),
d(2005,4,3,7,0,0),
d(2005,10,30,6,0,0),
d(2006,4,2,7,0,0),
d(2006,10,29,6,0,0),
d(2007,3,11,7,0,0),
d(2007,11,4,6,0,0),
d(2008,3,9,7,0,0),
d(2008,11,2,6,0,0),
d(2009,3,8,7,0,0),
d(2009,11,1,6,0,0),
d(2010,3,14,7,0,0),
d(2010,11,7,6,0,0),
d(2011,3,13,7,0,0),
d(2011,11,6,6,0,0),
d(2012,3,11,7,0,0),
d(2012,11,4,6,0,0),
d(2013,3,10,7,0,0),
d(2013,11,3,6,0,0),
d(2014,3,9,7,0,0),
d(2014,11,2,6,0,0),
d(2015,3,8,7,0,0),
d(2015,11,1,6,0,0),
d(2016,3,13,7,0,0),
d(2016,11,6,6,0,0),
d(2017,3,12,7,0,0),
d(2017,11,5,6,0,0),
d(2018,3,11,7,0,0),
d(2018,11,4,6,0,0),
d(2019,3,10,7,0,0),
d(2019,11,3,6,0,0),
d(2020,3,8,7,0,0),
d(2020,11,1,6,0,0),
d(2021,3,14,7,0,0),
d(2021,11,7,6,0,0),
d(2022,3,13,7,0,0),
d(2022,11,6,6,0,0),
d(2023,3,12,7,0,0),
d(2023,11,5,6,0,0),
d(2024,3,10,7,0,0),
d(2024,11,3,6,0,0),
d(2025,3,9,7,0,0),
d(2025,11,2,6,0,0),
d(2026,3,8,7,0,0),
d(2026,11,1,6,0,0),
d(2027,3,14,7,0,0),
d(2027,11,7,6,0,0),
d(2028,3,12,7,0,0),
d(2028,11,5,6,0,0),
d(2029,3,11,7,0,0),
d(2029,11,4,6,0,0),
d(2030,3,10,7,0,0),
d(2030,11,3,6,0,0),
d(2031,3,9,7,0,0),
d(2031,11,2,6,0,0),
d(2032,3,14,7,0,0),
d(2032,11,7,6,0,0),
d(2033,3,13,7,0,0),
d(2033,11,6,6,0,0),
d(2034,3,12,7,0,0),
d(2034,11,5,6,0,0),
d(2035,3,11,7,0,0),
d(2035,11,4,6,0,0),
d(2036,3,9,7,0,0),
d(2036,11,2,6,0,0),
d(2037,3,8,7,0,0),
d(2037,11,1,6,0,0),
]
_transition_info = [
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CWT'),
i(-18000,3600,'CPT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-21600,0,'CST'),
i(-18000,3600,'CDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
i(-14400,3600,'EDT'),
i(-18000,0,'EST'),
]
Monticello = Monticello()
| newvem/pytz | pytz/zoneinfo/America/Kentucky/Monticello.py | Python | mit | 6,463 |
import { ChangeDetectorRef, ComponentFactoryResolver, ComponentRef, ElementRef, EventEmitter, NgZone, Renderer, ViewContainerRef } from '@angular/core';
import { App } from '../app/app';
import { Config } from '../../config/config';
import { DeepLinker } from '../../navigation/deep-linker';
import { DomController } from '../../platform/dom-controller';
import { GestureController } from '../../gestures/gesture-controller';
import { Keyboard } from '../../platform/keyboard';
import { NavControllerBase } from '../../navigation/nav-controller-base';
import { NavOptions } from '../../navigation/nav-util';
import { Platform } from '../../platform/platform';
import { TabButton } from './tab-button';
import { Tabs } from './tabs';
import { TransitionController } from '../../transitions/transition-controller';
import { ViewController } from '../../navigation/view-controller';
/**
* @name Tab
* @description
* The Tab component, written `<ion-tab>`, is styled based on the mode and should
* be used in conjunction with the [Tabs](../Tabs/) component.
*
* Each `ion-tab` is a declarative component for a [NavController](../../../navigation/NavController/).
* Basically, each tab is a `NavController`. For more information on using
* navigation controllers take a look at the [NavController API Docs](../../../navigation/NavController/).
*
* See the [Tabs API Docs](../Tabs/) for more details on configuring Tabs.
*
* @usage
*
* To add a basic tab, you can use the following markup where the `root` property
* is the page you want to load for that tab, `tabTitle` is the optional text to
* display on the tab, and `tabIcon` is the optional [icon](../../icon/Icon/).
*
* ```html
* <ion-tabs>
* <ion-tab [root]="chatRoot" tabTitle="Chat" tabIcon="chat"></ion-tab>
* </ion-tabs>
* ```
*
* Then, in your class you can set `chatRoot` to an imported class:
*
* ```ts
* import { ChatPage } from '../chat/chat';
*
* export class Tabs {
* // here we'll set the property of chatRoot to
* // the imported class of ChatPage
* chatRoot = ChatPage;
*
* constructor() {
*
* }
* }
* ```
*
* You can also pass some parameters to the root page of the tab through
* `rootParams`. Below we pass `chatParams` to the Chat tab:
*
* ```html
* <ion-tabs>
* <ion-tab [root]="chatRoot" [rootParams]="chatParams" tabTitle="Chat" tabIcon="chat"></ion-tab>
* </ion-tabs>
* ```
*
* ```ts
* export class Tabs {
* chatRoot = ChatPage;
*
* // set some user information on chatParams
* chatParams = {
* user1: "admin",
* user2: "ionic"
* };
*
* constructor() {
*
* }
* }
* ```
*
* And in `ChatPage` you can get the data from `NavParams`:
*
* ```ts
* export class ChatPage {
* constructor(navParams: NavParams) {
* console.log("Passed params", navParams.data);
* }
* }
* ```
*
* Sometimes you may want to call a method instead of navigating to a new
* page. You can use the `(ionSelect)` event to call a method on your class when
* the tab is selected. Below is an example of presenting a modal from one of
* the tabs.
*
* ```html
* <ion-tabs>
* <ion-tab (ionSelect)="chat()" tabTitle="Show Modal"></ion-tab>
* </ion-tabs>
* ```
*
* ```ts
* export class Tabs {
* constructor(public modalCtrl: ModalController) {
*
* }
*
* chat() {
* let modal = this.modalCtrl.create(ChatPage);
* modal.present();
* }
* }
* ```
*
*
* @demo /docs/v2/demos/src/tabs/
* @see {@link /docs/v2/components#tabs Tabs Component Docs}
* @see {@link ../../tabs/Tabs Tabs API Docs}
* @see {@link ../../nav/Nav Nav API Docs}
* @see {@link ../../nav/NavController NavController API Docs}
*/
export declare class Tab extends NavControllerBase {
private _cd;
private linker;
private _dom;
/**
* @private
*/
_isInitial: boolean;
/**
* @private
*/
_isEnabled: boolean;
/**
* @private
*/
_isShown: boolean;
/**
* @private
*/
_tabId: string;
/**
* @private
*/
_btnId: string;
/**
* @private
*/
_loaded: boolean;
/**
* @private
*/
isSelected: boolean;
/**
* @private
*/
btn: TabButton;
/**
* @private
*/
_tabsHideOnSubPages: boolean;
/**
* @input {Page} Set the root page for this tab.
*/
root: any;
/**
* @input {object} Any nav-params to pass to the root page of this tab.
*/
rootParams: any;
/**
* @input {string} The URL path name to represent this tab within the URL.
*/
tabUrlPath: string;
/**
* @input {string} The title of the tab button.
*/
tabTitle: string;
/**
* @input {string} The icon for the tab button.
*/
tabIcon: string;
/**
* @input {string} The badge for the tab button.
*/
tabBadge: string;
/**
* @input {string} The badge color for the tab button.
*/
tabBadgeStyle: string;
/**
* @input {boolean} If true, enable the tab. If false,
* the user cannot interact with this element.
* Default: `true`.
*/
enabled: boolean;
/**
* @input {boolean} If true, the tab button is visible within the
* tabbar. Default: `true`.
*/
show: boolean;
/**
* @input {boolean} If true, swipe to go back is enabled.
*/
swipeBackEnabled: boolean;
/**
* @input {boolean} If true, hide the tabs on child pages.
*/
tabsHideOnSubPages: boolean;
/**
* @output {Tab} Emitted when the current tab is selected.
*/
ionSelect: EventEmitter<Tab>;
constructor(parent: Tabs, app: App, config: Config, plt: Platform, keyboard: Keyboard, elementRef: ElementRef, zone: NgZone, renderer: Renderer, cfr: ComponentFactoryResolver, _cd: ChangeDetectorRef, gestureCtrl: GestureController, transCtrl: TransitionController, linker: DeepLinker, _dom: DomController);
/**
* @private
*/
_vp: ViewContainerRef;
/**
* @private
*/
ngOnInit(): void;
/**
* @private
*/
load(opts: NavOptions, done?: Function): void;
/**
* @private
*/
_viewAttachToDOM(viewCtrl: ViewController, componentRef: ComponentRef<any>, viewport: ViewContainerRef): void;
/**
* @private
*/
setSelected(isSelected: boolean): void;
/**
* @private
*/
readonly index: number;
/**
* @private
*/
updateHref(component: any, data: any): void;
/**
* @private
*/
destroy(): void;
}
| Spect-AR/Spect-AR | node_modules/node_modules/ionic-angular/umd/components/tabs/tab.d.ts | TypeScript | mit | 6,555 |