repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
SerCeMan/intellij-community | platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/GlobalCompilingVisitor.java | 10724 | package com.intellij.structuralsearch.impl.matcher.compiler;
import com.intellij.dupLocator.util.NodeFilter;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.psi.PsiElement;
import com.intellij.structuralsearch.StructuralSearchProfile;
import com.intellij.structuralsearch.StructuralSearchUtil;
import com.intellij.structuralsearch.impl.matcher.filters.CompositeFilter;
import com.intellij.structuralsearch.impl.matcher.filters.LexicalNodesFilter;
import com.intellij.structuralsearch.impl.matcher.handlers.LiteralWithSubstitutionHandler;
import com.intellij.structuralsearch.impl.matcher.handlers.MatchingHandler;
import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler;
import com.intellij.structuralsearch.impl.matcher.predicates.RegExpPredicate;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.intellij.structuralsearch.MatchOptions.INSTANCE_MODIFIER_NAME;
import static com.intellij.structuralsearch.MatchOptions.MODIFIER_ANNOTATION_NAME;
/**
* @author maxim
*/
public class GlobalCompilingVisitor {
@NonNls private static final String SUBSTITUTION_PATTERN_STR = "\\b(__\\$_\\w+)\\b";
private static final Pattern ourSubstitutionPattern = Pattern.compile(SUBSTITUTION_PATTERN_STR);
private static final Set<String> ourReservedWords = new HashSet<String>(Arrays.asList(MODIFIER_ANNOTATION_NAME, INSTANCE_MODIFIER_NAME)) {
{
for (StructuralSearchProfile profile : Extensions.getExtensions(StructuralSearchProfile.EP_NAME)) {
addAll(profile.getReservedWords());
}
}
};
private static final Pattern ourAlternativePattern = Pattern.compile("^\\((.+)\\)$");
@NonNls private static final String WORD_SEARCH_PATTERN_STR = ".*?\\b(.+?)\\b.*?";
private static final Pattern ourWordSearchPattern = Pattern.compile(WORD_SEARCH_PATTERN_STR);
private CompileContext context;
private final ArrayList<PsiElement> myLexicalNodes = new ArrayList<PsiElement>();
private int myCodeBlockLevel;
private static final NodeFilter ourFilter = LexicalNodesFilter.getInstance();
public static NodeFilter getFilter() {
return ourFilter;
}
public void setHandler(PsiElement element, MatchingHandler handler) {
MatchingHandler realHandler = context.getPattern().getHandlerSimple(element);
if (realHandler instanceof SubstitutionHandler) {
((SubstitutionHandler)realHandler).setMatchHandler(handler);
}
else {
// @todo care about composite handler in this case of simple handler!
context.getPattern().setHandler(element, handler);
}
}
public final void handle(PsiElement element) {
if ((!ourFilter.accepts(element) ||
StructuralSearchUtil.isIdentifier(element)) &&
context.getPattern().isRealTypedVar(element) &&
context.getPattern().getHandlerSimple(element) == null
) {
String name = context.getPattern().getTypedVarString(element);
// name is the same for named element (clazz,methods, etc) and token (name of ... itself)
// @todo need fix this
final SubstitutionHandler handler = (SubstitutionHandler)context.getPattern().getHandler(name);
if (handler == null) return;
context.getPattern().setHandler(element, handler);
if (context.getOptions().getVariableConstraint(handler.getName()).isPartOfSearchResults()) {
handler.setTarget(true);
context.getPattern().setTargetNode(element);
}
}
}
public CompileContext getContext() {
return context;
}
public int getCodeBlockLevel() {
return myCodeBlockLevel;
}
public void setCodeBlockLevel(int codeBlockLevel) {
this.myCodeBlockLevel = codeBlockLevel;
}
static void setFilter(MatchingHandler handler, NodeFilter filter) {
if (handler.getFilter() != null &&
handler.getFilter().getClass() != filter.getClass()
) {
// for constructor we will have the same handler for class and method and tokens itselfa
handler.setFilter(
new CompositeFilter(
filter,
handler.getFilter()
)
);
}
else {
handler.setFilter(filter);
}
}
public ArrayList<PsiElement> getLexicalNodes() {
return myLexicalNodes;
}
public void addLexicalNode(PsiElement node) {
myLexicalNodes.add(node);
}
void compile(PsiElement[] elements, CompileContext context) {
myCodeBlockLevel = 0;
this.context = context;
final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(context.getOptions().getFileType());
assert profile != null;
profile.compile(elements, this);
if (context.getPattern().getStrategy() == null) {
System.out.println();
}
}
@Nullable
public MatchingHandler processPatternStringWithFragments(String pattern, OccurenceKind kind) {
return processPatternStringWithFragments(pattern, kind, ourSubstitutionPattern);
}
@Nullable
public MatchingHandler processPatternStringWithFragments(String pattern, OccurenceKind kind, Pattern substitutionPattern) {
String content;
if (kind == OccurenceKind.LITERAL) {
content = pattern.substring(1, pattern.length() - 1);
}
else if (kind == OccurenceKind.COMMENT) {
content = pattern;
}
else {
return null;
}
@NonNls StringBuilder buf = new StringBuilder(content.length());
Matcher matcher = substitutionPattern.matcher(content);
List<SubstitutionHandler> handlers = null;
int start = 0;
String word;
boolean hasLiteralContent = false;
SubstitutionHandler handler = null;
while (matcher.find()) {
if (handlers == null) handlers = new ArrayList<SubstitutionHandler>();
handler = (SubstitutionHandler)getContext().getPattern().getHandler(matcher.group(1));
if (handler != null) handlers.add(handler);
word = content.substring(start, matcher.start());
if (word.length() > 0) {
buf.append(StructuralSearchUtil.shieldSpecialChars(word));
hasLiteralContent = true;
processTokenizedName(word, false, kind);
}
RegExpPredicate predicate = MatchingHandler.getSimpleRegExpPredicate(handler);
if (predicate == null || !predicate.isWholeWords()) {
buf.append("(.*?)");
}
else {
buf.append(".*?\\b(").append(predicate.getRegExp()).append(")\\b.*?");
}
if (isSuitablePredicate(predicate, handler)) {
processTokenizedName(predicate.getRegExp(), false, kind);
}
start = matcher.end();
}
word = content.substring(start, content.length());
if (word.length() > 0) {
hasLiteralContent = true;
buf.append(StructuralSearchUtil.shieldSpecialChars(word));
processTokenizedName(word, false, kind);
}
if (hasLiteralContent) {
if (kind == OccurenceKind.LITERAL) {
buf.insert(0, "[\"']");
buf.append("[\"']");
}
buf.append("$");
}
if (handlers != null) {
return hasLiteralContent ? new LiteralWithSubstitutionHandler(buf.toString(), handlers) : handler;
}
return null;
}
@Contract("null,_ -> false")
static boolean isSuitablePredicate(RegExpPredicate predicate, SubstitutionHandler handler) {
return predicate != null && handler.getMinOccurs() != 0 && predicate.couldBeOptimized();
}
public static void addFilesToSearchForGivenWord(String refname,
boolean endTransaction,
GlobalCompilingVisitor.OccurenceKind kind,
CompileContext compileContext) {
if (!compileContext.getSearchHelper().doOptimizing()) {
return;
}
if (ourReservedWords.contains(refname)) return; // skip our special annotations !!!
boolean addedSomething = false;
if (kind == GlobalCompilingVisitor.OccurenceKind.CODE) {
addedSomething = compileContext.getSearchHelper().addWordToSearchInCode(refname);
}
else if (kind == GlobalCompilingVisitor.OccurenceKind.COMMENT) {
addedSomething = compileContext.getSearchHelper().addWordToSearchInComments(refname);
}
else if (kind == GlobalCompilingVisitor.OccurenceKind.LITERAL) {
addedSomething = compileContext.getSearchHelper().addWordToSearchInLiterals(refname);
}
if (addedSomething && endTransaction) {
compileContext.getSearchHelper().endTransaction();
}
}
public void processTokenizedName(String name, boolean skipComments, GlobalCompilingVisitor.OccurenceKind kind) {
WordTokenizer tokenizer = new WordTokenizer(name);
for (Iterator<String> i = tokenizer.iterator(); i.hasNext();) {
String nextToken = i.next();
if (skipComments &&
(nextToken.equals("/*") || nextToken.equals("/**") || nextToken.equals("*/") || nextToken.equals("*") || nextToken.equals("//"))
) {
continue;
}
Matcher matcher = ourAlternativePattern.matcher(nextToken);
if (matcher.matches()) {
StringTokenizer alternatives = new StringTokenizer(matcher.group(1), "|");
while (alternatives.hasMoreTokens()) {
addFilesToSearchForGivenWord(alternatives.nextToken(), !alternatives.hasMoreTokens(), kind, getContext());
}
}
else {
addFilesToSearchForGivenWord(nextToken, true, kind, getContext());
}
}
}
public enum OccurenceKind {
LITERAL, COMMENT, CODE
}
private static class WordTokenizer {
private final List<String> myWords = new ArrayList<String>();
WordTokenizer(String text) {
final StringTokenizer tokenizer = new StringTokenizer(text);
Matcher matcher = null;
while (tokenizer.hasMoreTokens()) {
String nextToken = tokenizer.nextToken();
if (matcher == null) {
matcher = ourWordSearchPattern.matcher(nextToken);
}
else {
matcher.reset(nextToken);
}
nextToken = (matcher.matches()) ? matcher.group(1) : nextToken;
int lastWordStart = 0;
int i;
for (i = 0; i < nextToken.length(); ++i) {
if (!Character.isJavaIdentifierStart(nextToken.charAt(i))) {
if (i != lastWordStart) {
myWords.add(nextToken.substring(lastWordStart, i));
}
lastWordStart = i + 1;
}
}
if (i != lastWordStart) {
myWords.add(nextToken.substring(lastWordStart, i));
}
}
}
Iterator<String> iterator() {
return myWords.iterator();
}
}
}
| apache-2.0 |
DirtyUnicorns/android_external_chromium-org | chromeos/network/onc/onc_normalizer.cc | 8095 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/network/onc/onc_normalizer.h"
#include <string>
#include "base/logging.h"
#include "base/values.h"
#include "chromeos/network/onc/onc_signature.h"
#include "components/onc/onc_constants.h"
namespace chromeos {
namespace onc {
Normalizer::Normalizer(bool remove_recommended_fields)
: remove_recommended_fields_(remove_recommended_fields) {
}
Normalizer::~Normalizer() {
}
scoped_ptr<base::DictionaryValue> Normalizer::NormalizeObject(
const OncValueSignature* object_signature,
const base::DictionaryValue& onc_object) {
CHECK(object_signature != NULL);
bool error = false;
scoped_ptr<base::DictionaryValue> result =
MapObject(*object_signature, onc_object, &error);
DCHECK(!error);
return result.Pass();
}
scoped_ptr<base::DictionaryValue> Normalizer::MapObject(
const OncValueSignature& signature,
const base::DictionaryValue& onc_object,
bool* error) {
scoped_ptr<base::DictionaryValue> normalized =
Mapper::MapObject(signature, onc_object, error);
if (normalized.get() == NULL)
return scoped_ptr<base::DictionaryValue>();
if (remove_recommended_fields_)
normalized->RemoveWithoutPathExpansion(::onc::kRecommended, NULL);
if (&signature == &kCertificateSignature)
NormalizeCertificate(normalized.get());
else if (&signature == &kEAPSignature)
NormalizeEAP(normalized.get());
else if (&signature == &kEthernetSignature)
NormalizeEthernet(normalized.get());
else if (&signature == &kIPsecSignature)
NormalizeIPsec(normalized.get());
else if (&signature == &kNetworkConfigurationSignature)
NormalizeNetworkConfiguration(normalized.get());
else if (&signature == &kOpenVPNSignature)
NormalizeOpenVPN(normalized.get());
else if (&signature == &kProxySettingsSignature)
NormalizeProxySettings(normalized.get());
else if (&signature == &kVPNSignature)
NormalizeVPN(normalized.get());
else if (&signature == &kWiFiSignature)
NormalizeWiFi(normalized.get());
return normalized.Pass();
}
namespace {
void RemoveEntryUnless(base::DictionaryValue* dict,
const std::string& path,
bool condition) {
if (!condition)
dict->RemoveWithoutPathExpansion(path, NULL);
}
} // namespace
void Normalizer::NormalizeCertificate(base::DictionaryValue* cert) {
using namespace ::onc::certificate;
bool remove = false;
cert->GetBooleanWithoutPathExpansion(::onc::kRemove, &remove);
RemoveEntryUnless(cert, ::onc::certificate::kType, !remove);
std::string type;
cert->GetStringWithoutPathExpansion(::onc::certificate::kType, &type);
RemoveEntryUnless(cert, kPKCS12, type == kClient);
RemoveEntryUnless(cert, kTrustBits, type == kServer || type == kAuthority);
RemoveEntryUnless(cert, kX509, type == kServer || type == kAuthority);
}
void Normalizer::NormalizeEthernet(base::DictionaryValue* ethernet) {
using namespace ::onc::ethernet;
std::string auth;
ethernet->GetStringWithoutPathExpansion(kAuthentication, &auth);
RemoveEntryUnless(ethernet, kEAP, auth == k8021X);
}
void Normalizer::NormalizeEAP(base::DictionaryValue* eap) {
using namespace ::onc::eap;
std::string clientcert_type;
eap->GetStringWithoutPathExpansion(kClientCertType, &clientcert_type);
RemoveEntryUnless(
eap, kClientCertPattern, clientcert_type == ::onc::certificate::kPattern);
RemoveEntryUnless(
eap, kClientCertRef, clientcert_type == ::onc::certificate::kRef);
std::string outer;
eap->GetStringWithoutPathExpansion(kOuter, &outer);
RemoveEntryUnless(eap, kAnonymousIdentity,
outer == kPEAP || outer == kEAP_TTLS);
RemoveEntryUnless(eap, kInner,
outer == kPEAP || outer == kEAP_TTLS || outer == kEAP_FAST);
}
void Normalizer::NormalizeIPsec(base::DictionaryValue* ipsec) {
using namespace ::onc::ipsec;
std::string auth_type;
ipsec->GetStringWithoutPathExpansion(kAuthenticationType, &auth_type);
RemoveEntryUnless(ipsec, ::onc::vpn::kClientCertType, auth_type == kCert);
RemoveEntryUnless(ipsec, kServerCARef, auth_type == kCert);
RemoveEntryUnless(ipsec, kPSK, auth_type == kPSK);
RemoveEntryUnless(ipsec, ::onc::vpn::kSaveCredentials, auth_type == kPSK);
std::string clientcert_type;
ipsec->GetStringWithoutPathExpansion(::onc::vpn::kClientCertType,
&clientcert_type);
RemoveEntryUnless(ipsec,
::onc::vpn::kClientCertPattern,
clientcert_type == ::onc::certificate::kPattern);
RemoveEntryUnless(ipsec,
::onc::vpn::kClientCertRef,
clientcert_type == ::onc::certificate::kRef);
int ike_version = -1;
ipsec->GetIntegerWithoutPathExpansion(kIKEVersion, &ike_version);
RemoveEntryUnless(ipsec, kEAP, ike_version == 2);
RemoveEntryUnless(ipsec, kGroup, ike_version == 1);
RemoveEntryUnless(ipsec, kXAUTH, ike_version == 1);
}
void Normalizer::NormalizeNetworkConfiguration(base::DictionaryValue* network) {
bool remove = false;
network->GetBooleanWithoutPathExpansion(::onc::kRemove, &remove);
if (remove) {
network->RemoveWithoutPathExpansion(::onc::network_config::kIPConfigs,
NULL);
network->RemoveWithoutPathExpansion(::onc::network_config::kName, NULL);
network->RemoveWithoutPathExpansion(::onc::network_config::kNameServers,
NULL);
network->RemoveWithoutPathExpansion(::onc::network_config::kProxySettings,
NULL);
network->RemoveWithoutPathExpansion(::onc::network_config::kSearchDomains,
NULL);
network->RemoveWithoutPathExpansion(::onc::network_config::kType, NULL);
// Fields dependent on kType are removed afterwards, too.
}
std::string type;
network->GetStringWithoutPathExpansion(::onc::network_config::kType, &type);
RemoveEntryUnless(network,
::onc::network_config::kEthernet,
type == ::onc::network_type::kEthernet);
RemoveEntryUnless(
network, ::onc::network_config::kVPN, type == ::onc::network_type::kVPN);
RemoveEntryUnless(network,
::onc::network_config::kWiFi,
type == ::onc::network_type::kWiFi);
}
void Normalizer::NormalizeOpenVPN(base::DictionaryValue* openvpn) {
using namespace ::onc::vpn;
std::string clientcert_type;
openvpn->GetStringWithoutPathExpansion(kClientCertType, &clientcert_type);
RemoveEntryUnless(openvpn,
kClientCertPattern,
clientcert_type == ::onc::certificate::kPattern);
RemoveEntryUnless(
openvpn, kClientCertRef, clientcert_type == ::onc::certificate::kRef);
}
void Normalizer::NormalizeProxySettings(base::DictionaryValue* proxy) {
using namespace ::onc::proxy;
std::string type;
proxy->GetStringWithoutPathExpansion(::onc::proxy::kType, &type);
RemoveEntryUnless(proxy, kManual, type == kManual);
RemoveEntryUnless(proxy, kExcludeDomains, type == kManual);
RemoveEntryUnless(proxy, kPAC, type == kPAC);
}
void Normalizer::NormalizeVPN(base::DictionaryValue* vpn) {
using namespace ::onc::vpn;
std::string type;
vpn->GetStringWithoutPathExpansion(::onc::vpn::kType, &type);
RemoveEntryUnless(vpn, kOpenVPN, type == kOpenVPN);
RemoveEntryUnless(vpn, kIPsec, type == kIPsec || type == kTypeL2TP_IPsec);
RemoveEntryUnless(vpn, kL2TP, type == kTypeL2TP_IPsec);
}
void Normalizer::NormalizeWiFi(base::DictionaryValue* wifi) {
using namespace ::onc::wifi;
std::string security;
wifi->GetStringWithoutPathExpansion(::onc::wifi::kSecurity, &security);
RemoveEntryUnless(wifi, kEAP, security == kWEP_8021X || security == kWPA_EAP);
RemoveEntryUnless(wifi, kPassphrase,
security == kWEP_PSK || security == kWPA_PSK);
}
} // namespace onc
} // namespace chromeos
| bsd-3-clause |
Piicksarn/cdnjs | ajax/libs/jqueryui/1.8.21/i18n/jquery.ui.datepicker-es.min.js | 877 | /*! jQuery UI - v1.8.21 - 2012-06-05
* https://github.com/jquery/jquery-ui
* Includes: jquery.ui.datepicker-es.js
* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
jQuery(function(a){a.datepicker.regional.es={closeText:"Cerrar",prevText:"<Ant",nextText:"Sig>",currentText:"Hoy",monthNames:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],monthNamesShort:["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"],dayNames:["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"],dayNamesShort:["Dom","Lun","Mar","Mié","Juv","Vie","Sáb"],dayNamesMin:["Do","Lu","Ma","Mi","Ju","Vi","Sá"],weekHeader:"Sm",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},a.datepicker.setDefaults(a.datepicker.regional.es)}); | mit |
mattesno1/CouchPotatoServer | libs/CodernityDB/tree_index.py | 107535 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011-2013 Codernity (http://codernity.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.
from index import Index, IndexException, DocIdNotFound, ElemNotFound
import struct
import marshal
import os
import io
import shutil
from storage import IU_Storage
# from ipdb import set_trace
from CodernityDB.env import cdb_environment
from CodernityDB.index import TryReindexException
if cdb_environment.get('rlock_obj'):
from CodernityDB import patch
patch.patch_cache_rr(cdb_environment['rlock_obj'])
from CodernityDB.rr_cache import cache1lvl, cache2lvl
tree_buffer_size = io.DEFAULT_BUFFER_SIZE
cdb_environment['tree_buffer_size'] = tree_buffer_size
MODE_FIRST = 0
MODE_LAST = 1
MOVE_BUFFER_PREV = 0
MOVE_BUFFER_NEXT = 1
class NodeCapacityException(IndexException):
pass
class IU_TreeBasedIndex(Index):
custom_header = 'from CodernityDB.tree_index import TreeBasedIndex'
def __init__(self, db_path, name, key_format='32s', pointer_format='I',
meta_format='32sIIc', node_capacity=10, storage_class=None):
if node_capacity < 3:
raise NodeCapacityException
super(IU_TreeBasedIndex, self).__init__(db_path, name)
self.data_start = self._start_ind + 1
self.node_capacity = node_capacity
self.flag_format = 'c'
self.elements_counter_format = 'h'
self.pointer_format = pointer_format
self.key_format = key_format
self.meta_format = meta_format
self._count_props()
if not storage_class:
storage_class = IU_Storage
if storage_class and not isinstance(storage_class, basestring):
storage_class = storage_class.__name__
self.storage_class = storage_class
self.storage = None
cache = cache1lvl(100)
twolvl_cache = cache2lvl(150)
self._find_key = cache(self._find_key)
self._match_doc_id = cache(self._match_doc_id)
# self._read_single_leaf_record =
# twolvl_cache(self._read_single_leaf_record)
self._find_key_in_leaf = twolvl_cache(self._find_key_in_leaf)
self._read_single_node_key = twolvl_cache(self._read_single_node_key)
self._find_first_key_occurence_in_node = twolvl_cache(
self._find_first_key_occurence_in_node)
self._find_last_key_occurence_in_node = twolvl_cache(
self._find_last_key_occurence_in_node)
self._read_leaf_nr_of_elements = cache(self._read_leaf_nr_of_elements)
self._read_leaf_neighbours = cache(self._read_leaf_neighbours)
self._read_leaf_nr_of_elements_and_neighbours = cache(
self._read_leaf_nr_of_elements_and_neighbours)
self._read_node_nr_of_elements_and_children_flag = cache(
self._read_node_nr_of_elements_and_children_flag)
def _count_props(self):
"""
Counts dynamic properties for tree, such as all complex formats
"""
self.single_leaf_record_format = self.key_format + self.meta_format
self.single_node_record_format = self.pointer_format + \
self.key_format + self.pointer_format
self.node_format = self.elements_counter_format + self.flag_format\
+ self.pointer_format + (self.key_format +
self.pointer_format) * self.node_capacity
self.leaf_format = self.elements_counter_format + self.pointer_format * 2\
+ (self.single_leaf_record_format) * self.node_capacity
self.leaf_heading_format = self.elements_counter_format + \
self.pointer_format * 2
self.node_heading_format = self.elements_counter_format + \
self.flag_format
self.key_size = struct.calcsize('<' + self.key_format)
self.meta_size = struct.calcsize('<' + self.meta_format)
self.single_leaf_record_size = struct.calcsize('<' + self.
single_leaf_record_format)
self.single_node_record_size = struct.calcsize('<' + self.
single_node_record_format)
self.node_size = struct.calcsize('<' + self.node_format)
self.leaf_size = struct.calcsize('<' + self.leaf_format)
self.flag_size = struct.calcsize('<' + self.flag_format)
self.elements_counter_size = struct.calcsize('<' + self.
elements_counter_format)
self.pointer_size = struct.calcsize('<' + self.pointer_format)
self.leaf_heading_size = struct.calcsize(
'<' + self.leaf_heading_format)
self.node_heading_size = struct.calcsize(
'<' + self.node_heading_format)
def create_index(self):
if os.path.isfile(os.path.join(self.db_path, self.name + '_buck')):
raise IndexException('Already exists')
with io.open(os.path.join(self.db_path, self.name + "_buck"), 'w+b') as f:
props = dict(name=self.name,
flag_format=self.flag_format,
pointer_format=self.pointer_format,
elements_counter_format=self.elements_counter_format,
node_capacity=self.node_capacity,
key_format=self.key_format,
meta_format=self.meta_format,
version=self.__version__,
storage_class=self.storage_class)
f.write(marshal.dumps(props))
self.buckets = io.open(os.path.join(self.db_path, self.name +
"_buck"), 'r+b', buffering=0)
self._create_storage()
self.buckets.seek(self._start_ind)
self.buckets.write(struct.pack('<c', 'l'))
self._insert_empty_root()
self.root_flag = 'l'
def destroy(self):
super(IU_TreeBasedIndex, self).destroy()
self._clear_cache()
def open_index(self):
if not os.path.isfile(os.path.join(self.db_path, self.name + '_buck')):
raise IndexException("Doesn't exists")
self.buckets = io.open(
os.path.join(self.db_path, self.name + "_buck"), 'r+b', buffering=0)
self.buckets.seek(self._start_ind)
self.root_flag = struct.unpack('<c', self.buckets.read(1))[0]
self._fix_params()
self._open_storage()
def _insert_empty_root(self):
self.buckets.seek(self.data_start)
root = struct.pack('<' + self.leaf_heading_format,
0,
0,
0)
root += self.single_leaf_record_size * self.node_capacity * '\x00'
self.buckets.write(root)
self.flush()
def insert(self, doc_id, key, start, size, status='o'):
nodes_stack, indexes = self._find_leaf_to_insert(key)
self._insert_new_record_into_leaf(nodes_stack.pop(),
key,
doc_id,
start,
size,
status,
nodes_stack,
indexes)
self._match_doc_id.delete(doc_id)
def _read_leaf_nr_of_elements_and_neighbours(self, leaf_start):
self.buckets.seek(leaf_start)
data = self.buckets.read(
self.elements_counter_size + 2 * self.pointer_size)
nr_of_elements, prev_l, next_l = struct.unpack(
'<' + self.elements_counter_format + 2 * self.pointer_format,
data)
return nr_of_elements, prev_l, next_l
def _read_node_nr_of_elements_and_children_flag(self, start):
self.buckets.seek(start)
data = self.buckets.read(self.elements_counter_size + self.flag_size)
nr_of_elements, children_flag = struct.unpack(
'<' + self.elements_counter_format + self.flag_format,
data)
return nr_of_elements, children_flag
def _read_leaf_nr_of_elements(self, start):
self.buckets.seek(start)
data = self.buckets.read(self.elements_counter_size)
nr_of_elements = struct.unpack(
'<' + self.elements_counter_format, data)
return nr_of_elements[0]
def _read_single_node_key(self, node_start, key_index):
self.buckets.seek(self._calculate_key_position(
node_start, key_index, 'n'))
data = self.buckets.read(self.single_node_record_size)
flag_left, key, pointer_right = struct.unpack(
'<' + self.single_node_record_format, data)
return flag_left, key, pointer_right
def _read_single_leaf_record(self, leaf_start, key_index):
self.buckets.seek(self._calculate_key_position(
leaf_start, key_index, 'l'))
data = self.buckets.read(self.single_leaf_record_size)
key, doc_id, start, size, status = struct.unpack('<' + self.
single_leaf_record_format, data)
return key, doc_id, start, size, status
def _calculate_key_position(self, start, key_index, flag):
"""
Calculates position of key in buckets file
"""
if flag == 'l':
return start + self.leaf_heading_size + key_index * self.single_leaf_record_size
elif flag == 'n':
# returns start position of flag before key[key_index]
return start + self.node_heading_size + key_index * (self.pointer_size + self.key_size)
def _match_doc_id(self, doc_id, key, element_index, leaf_start, nr_of_elements):
curr_key_index = element_index + 1
curr_leaf_start = leaf_start
next_leaf = self._read_leaf_neighbours(leaf_start)[1]
while True:
if curr_key_index < nr_of_elements:
curr_key, curr_doc_id, curr_start, curr_size,\
curr_status = self._read_single_leaf_record(
curr_leaf_start, curr_key_index)
if key != curr_key:
# should't happen, crashes earlier on id index
raise DocIdNotFound
elif doc_id == curr_doc_id and curr_status != 'd':
return curr_leaf_start, nr_of_elements, curr_key_index
else:
curr_key_index = curr_key_index + 1
else: # there are no more elements in current leaf, must jump to next
if not next_leaf: # end of leaf linked list
# should't happen, crashes earlier on id index
raise DocIdNotFound
else:
curr_leaf_start = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
curr_key_index = 0
def _find_existing(self, key, element_index, leaf_start, nr_of_elements):
curr_key_index = element_index + 1
curr_leaf_start = leaf_start
next_leaf = self._read_leaf_neighbours(leaf_start)[1]
while True:
if curr_key_index < nr_of_elements:
curr_key, curr_doc_id, curr_start, curr_size,\
curr_status = self._read_single_leaf_record(
curr_leaf_start, curr_key_index)
if key != curr_key:
raise ElemNotFound
elif curr_status != 'd':
return curr_leaf_start, nr_of_elements, curr_key_index
else:
curr_key_index = curr_key_index + 1
else: # there are no more elements in current leaf, must jump to next
if not next_leaf: # end of leaf linked list
raise ElemNotFound
else:
curr_leaf_start = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
curr_key_index = 0
def _update_element(self, leaf_start, key_index, new_data):
self.buckets.seek(self._calculate_key_position(leaf_start, key_index, 'l')
+ self.key_size)
self.buckets.write(struct.pack('<' + self.meta_format,
*new_data))
# self._read_single_leaf_record.delete(leaf_start_position, key_index)
def _delete_element(self, leaf_start, key_index):
self.buckets.seek(self._calculate_key_position(leaf_start, key_index, 'l')
+ self.single_leaf_record_size - 1)
self.buckets.write(struct.pack('<c', 'd'))
# self._read_single_leaf_record.delete(leaf_start_position, key_index)
def _leaf_linear_key_search(self, key, start, start_index, end_index):
self.buckets.seek(start)
data = self.buckets.read(
(end_index - start_index + 1) * self.single_leaf_record_size)
curr_key = struct.unpack(
'<' + self.key_format, data[:self.key_size])[0]
data = data[self.single_leaf_record_size:]
curr_index = 0
while curr_key != key:
curr_index += 1
curr_key = struct.unpack(
'<' + self.key_format, data[:self.key_size])[0]
data = data[self.single_leaf_record_size:]
return start_index + curr_index
def _node_linear_key_search(self, key, start, start_index, end_index):
self.buckets.seek(start + self.pointer_size)
data = self.buckets.read((end_index - start_index + 1) * (
self.key_size + self.pointer_size))
curr_key = struct.unpack(
'<' + self.key_format, data[:self.key_size])[0]
data = data[self.key_size + self.pointer_size:]
curr_index = 0
while curr_key != key:
curr_index += 1
curr_key = struct.unpack(
'<' + self.key_format, data[:self.key_size])[0]
data = data[self.key_size + self.pointer_size:]
return start_index + curr_index
def _next_buffer(self, buffer_start, buffer_end):
return buffer_end, buffer_end + tree_buffer_size
def _prev_buffer(self, buffer_start, buffer_end):
return buffer_start - tree_buffer_size, buffer_start
def _choose_next_candidate_index_in_leaf(self, leaf_start, candidate_start, buffer_start, buffer_end, imin, imax):
if buffer_start > candidate_start:
move_buffer = MOVE_BUFFER_PREV
elif buffer_end < candidate_start + self.single_leaf_record_size:
move_buffer = MOVE_BUFFER_NEXT
else:
move_buffer = None
return self._calculate_key_position(leaf_start, (imin + imax) / 2, 'l'), (imin + imax) / 2, move_buffer
def _choose_next_candidate_index_in_node(self, node_start, candidate_start, buffer_start, buffer_end, imin, imax):
if buffer_start > candidate_start:
move_buffer = MOVE_BUFFER_PREV
elif buffer_end < candidate_start + self.single_node_record_size:
(self.pointer_size + self.key_size) - 1
move_buffer = MOVE_BUFFER_NEXT
else:
move_buffer = None
return self._calculate_key_position(node_start, (imin + imax) / 2, 'n'), (imin + imax) / 2, move_buffer
def _find_key_in_leaf(self, leaf_start, key, nr_of_elements):
if nr_of_elements == 1:
return self._find_key_in_leaf_with_one_element(key, leaf_start)[-5:]
else:
return self._find_key_in_leaf_using_binary_search(key, leaf_start, nr_of_elements)[-5:]
def _find_key_in_leaf_for_update(self, key, doc_id, leaf_start, nr_of_elements):
if nr_of_elements == 1:
return self._find_key_in_leaf_with_one_element(key, leaf_start, doc_id=doc_id)
else:
return self._find_key_in_leaf_using_binary_search(key, leaf_start, nr_of_elements, mode=MODE_FIRST, doc_id=doc_id)
def _find_index_of_first_key_equal_or_smaller_key(self, key, leaf_start, nr_of_elements):
if nr_of_elements == 1:
return self._find_key_in_leaf_with_one_element(key, leaf_start, mode=MODE_FIRST, return_closest=True)[:2]
else:
return self._find_key_in_leaf_using_binary_search(key, leaf_start, nr_of_elements, mode=MODE_FIRST, return_closest=True)[:2]
def _find_index_of_last_key_equal_or_smaller_key(self, key, leaf_start, nr_of_elements):
if nr_of_elements == 1:
return self._find_key_in_leaf_with_one_element(key, leaf_start, mode=MODE_LAST, return_closest=True)[:2]
else:
return self._find_key_in_leaf_using_binary_search(key, leaf_start, nr_of_elements, mode=MODE_LAST, return_closest=True)[:2]
def _find_index_of_first_key_equal(self, key, leaf_start, nr_of_elements):
if nr_of_elements == 1:
return self._find_key_in_leaf_with_one_element(key, leaf_start, mode=MODE_FIRST)[:2]
else:
return self._find_key_in_leaf_using_binary_search(key, leaf_start, nr_of_elements, mode=MODE_FIRST)[:2]
def _find_key_in_leaf_with_one_element(self, key, leaf_start, doc_id=None, mode=None, return_closest=False):
curr_key, curr_doc_id, curr_start, curr_size,\
curr_status = self._read_single_leaf_record(leaf_start, 0)
if key != curr_key:
if return_closest and curr_status != 'd':
return leaf_start, 0
else:
raise ElemNotFound
else:
if curr_status == 'd':
raise ElemNotFound
elif doc_id is not None and doc_id != curr_doc_id:
# should't happen, crashes earlier on id index
raise DocIdNotFound
else:
return leaf_start, 0, curr_doc_id, curr_key, curr_start, curr_size, curr_status
def _find_key_in_leaf_using_binary_search(self, key, leaf_start, nr_of_elements, doc_id=None, mode=None, return_closest=False):
"""
Binary search implementation used in all get functions
"""
imin, imax = 0, nr_of_elements - 1
buffer_start, buffer_end = self._set_buffer_limits()
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_leaf(leaf_start,
self._calculate_key_position(leaf_start,
(imin + imax) / 2,
'l'),
buffer_start,
buffer_end,
imin, imax)
while imax != imin and imax > imin:
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_start,
candidate_index)
candidate_start = self._calculate_key_position(
leaf_start, candidate_index, 'l')
if key < curr_key:
if move_buffer == MOVE_BUFFER_PREV:
buffer_start, buffer_end = self._prev_buffer(
buffer_start, buffer_end)
else: # if next chosen element is in current buffer, abort moving to other
move_buffer is None
imax = candidate_index - 1
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_leaf(leaf_start,
candidate_start,
buffer_start,
buffer_end,
imin, imax)
elif key == curr_key:
if mode == MODE_LAST:
if move_buffer == MOVE_BUFFER_NEXT:
buffer_start, buffer_end = self._next_buffer(
buffer_start, buffer_end)
else:
move_buffer is None
imin = candidate_index + 1
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_leaf(leaf_start,
candidate_start,
buffer_start,
buffer_end,
imin, imax)
else:
if curr_status == 'o':
break
else:
if move_buffer == MOVE_BUFFER_PREV:
buffer_start, buffer_end = self._prev_buffer(
buffer_start, buffer_end)
else:
move_buffer is None
imax = candidate_index
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_leaf(leaf_start,
candidate_start,
buffer_start,
buffer_end,
imin, imax)
else:
if move_buffer == MOVE_BUFFER_NEXT:
buffer_start, buffer_end = self._next_buffer(
buffer_start, buffer_end)
else:
move_buffer is None
imin = candidate_index + 1
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_leaf(leaf_start,
candidate_start,
buffer_start,
buffer_end,
imin, imax)
if imax > imin:
chosen_key_position = candidate_index
else:
chosen_key_position = imax
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_start,
chosen_key_position)
if key != curr_key:
if return_closest: # useful for find all bigger/smaller methods
return leaf_start, chosen_key_position
else:
raise ElemNotFound
if doc_id and doc_id == curr_doc_id and curr_status == 'o':
return leaf_start, chosen_key_position, curr_doc_id, curr_key, curr_start, curr_size, curr_status
else:
if mode == MODE_FIRST and imin < chosen_key_position: # check if there isn't any element with equal key before chosen one
matching_record_index = self._leaf_linear_key_search(key,
self._calculate_key_position(leaf_start,
imin,
'l'),
imin,
chosen_key_position)
else:
matching_record_index = chosen_key_position
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_start,
matching_record_index)
if curr_status == 'd' and not return_closest:
leaf_start, nr_of_elements, matching_record_index = self._find_existing(key,
matching_record_index,
leaf_start,
nr_of_elements)
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_start,
matching_record_index)
if doc_id is not None and doc_id != curr_doc_id:
leaf_start, nr_of_elements, matching_record_index = self._match_doc_id(doc_id,
key,
matching_record_index,
leaf_start,
nr_of_elements)
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_start,
matching_record_index)
return leaf_start, matching_record_index, curr_doc_id, curr_key, curr_start, curr_size, curr_status
def _find_place_in_leaf(self, key, leaf_start, nr_of_elements):
if nr_of_elements == 1:
return self._find_place_in_leaf_with_one_element(key, leaf_start)
else:
return self._find_place_in_leaf_using_binary_search(key, leaf_start, nr_of_elements)
def _find_place_in_leaf_with_one_element(self, key, leaf_start):
curr_key, curr_doc_id, curr_start, curr_size,\
curr_status = self._read_single_leaf_record(leaf_start, 0)
if curr_status == 'd':
return leaf_start, 0, 0, False, True # leaf start, index of new key position, nr of rec to rewrite, full_leaf flag, on_deleted flag
else:
if key < curr_key:
return leaf_start, 0, 1, False, False
else:
return leaf_start, 1, 0, False, False
def _find_place_in_leaf_using_binary_search(self, key, leaf_start, nr_of_elements):
"""
Binary search implementation used in insert function
"""
imin, imax = 0, nr_of_elements - 1
buffer_start, buffer_end = self._set_buffer_limits()
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_leaf(leaf_start,
self._calculate_key_position(leaf_start,
(imin + imax) / 2,
'l'),
buffer_start,
buffer_end,
imin, imax)
while imax != imin and imax > imin:
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_start,
candidate_index)
candidate_start = self._calculate_key_position(
leaf_start, candidate_index, 'l')
if key < curr_key:
if move_buffer == MOVE_BUFFER_PREV:
buffer_start, buffer_end = self._prev_buffer(
buffer_start, buffer_end)
else: # if next chosen element is in current buffer, abort moving to other
move_buffer is None
imax = candidate_index - 1
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_leaf(leaf_start,
candidate_start,
buffer_start,
buffer_end,
imin, imax)
else:
if move_buffer == MOVE_BUFFER_NEXT:
buffer_start, buffer_end = self._next_buffer(
buffer_start, buffer_end)
else:
move_buffer is None
imin = candidate_index + 1
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_leaf(leaf_start,
candidate_start,
buffer_start,
buffer_end,
imin, imax)
if imax < imin and imin < nr_of_elements:
chosen_key_position = imin
else:
chosen_key_position = imax
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_start,
chosen_key_position)
if curr_status == 'd':
return leaf_start, chosen_key_position, 0, False, True
elif key < curr_key:
if chosen_key_position > 0:
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_start,
chosen_key_position - 1)
if curr_start == 'd':
return leaf_start, chosen_key_position - 1, 0, False, True
else:
return leaf_start, chosen_key_position, nr_of_elements - chosen_key_position, (nr_of_elements == self.node_capacity), False
else:
return leaf_start, chosen_key_position, nr_of_elements - chosen_key_position, (nr_of_elements == self.node_capacity), False
else:
if chosen_key_position < nr_of_elements - 1:
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_start,
chosen_key_position + 1)
if curr_start == 'd':
return leaf_start, chosen_key_position + 1, 0, False, True
else:
return leaf_start, chosen_key_position + 1, nr_of_elements - chosen_key_position - 1, (nr_of_elements == self.node_capacity), False
else:
return leaf_start, chosen_key_position + 1, nr_of_elements - chosen_key_position - 1, (nr_of_elements == self.node_capacity), False
def _set_buffer_limits(self):
pos = self.buckets.tell()
buffer_start = pos - (pos % tree_buffer_size)
return buffer_start, (buffer_start + tree_buffer_size)
def _find_first_key_occurence_in_node(self, node_start, key, nr_of_elements):
if nr_of_elements == 1:
return self._find_key_in_node_with_one_element(key, node_start, mode=MODE_FIRST)
else:
return self._find_key_in_node_using_binary_search(key, node_start, nr_of_elements, mode=MODE_FIRST)
def _find_last_key_occurence_in_node(self, node_start, key, nr_of_elements):
if nr_of_elements == 1:
return self._find_key_in_node_with_one_element(key, node_start, mode=MODE_LAST)
else:
return self._find_key_in_node_using_binary_search(key, node_start, nr_of_elements, mode=MODE_LAST)
def _find_key_in_node_with_one_element(self, key, node_start, mode=None):
l_pointer, curr_key, r_pointer = self._read_single_node_key(
node_start, 0)
if key < curr_key:
return 0, l_pointer
elif key > curr_key:
return 0, r_pointer
else:
if mode == MODE_FIRST:
return 0, l_pointer
elif mode == MODE_LAST:
return 0, r_pointer
else:
raise Exception('Invalid mode declared: set first/last')
def _find_key_in_node_using_binary_search(self, key, node_start, nr_of_elements, mode=None):
imin, imax = 0, nr_of_elements - 1
buffer_start, buffer_end = self._set_buffer_limits()
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_node(node_start,
self._calculate_key_position(node_start,
(imin + imax) / 2,
'n'),
buffer_start,
buffer_end,
imin, imax)
while imax != imin and imax > imin:
l_pointer, curr_key, r_pointer = self._read_single_node_key(
node_start, candidate_index)
candidate_start = self._calculate_key_position(
node_start, candidate_index, 'n')
if key < curr_key:
if move_buffer == MOVE_BUFFER_PREV:
buffer_start, buffer_end = self._prev_buffer(
buffer_start, buffer_end)
else: # if next chosen element is in current buffer, abort moving to other
move_buffer is None
imax = candidate_index - 1
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_node(node_start,
candidate_start,
buffer_start,
buffer_end,
imin, imax)
elif key == curr_key:
if mode == MODE_LAST:
if move_buffer == MOVE_BUFFER_NEXT:
buffer_start, buffer_end = self._next_buffer(
buffer_start, buffer_end)
else:
move_buffer is None
imin = candidate_index + 1
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_node(node_start,
candidate_start,
buffer_start,
buffer_end,
imin, imax)
else:
break
else:
if move_buffer == MOVE_BUFFER_NEXT:
buffer_start, buffer_end = self._next_buffer(
buffer_start, buffer_end)
else:
move_buffer is None
imin = candidate_index + 1
candidate_start, candidate_index, move_buffer = self._choose_next_candidate_index_in_node(node_start,
candidate_start,
buffer_start,
buffer_end,
imin, imax)
if imax > imin:
chosen_key_position = candidate_index
elif imax < imin and imin < nr_of_elements:
chosen_key_position = imin
else:
chosen_key_position = imax
l_pointer, curr_key, r_pointer = self._read_single_node_key(
node_start, chosen_key_position)
if mode == MODE_FIRST and imin < chosen_key_position: # check if there is no elements with equal key before chosen one
matching_record_index = self._node_linear_key_search(key,
self._calculate_key_position(node_start,
imin,
'n'),
imin,
chosen_key_position)
else:
matching_record_index = chosen_key_position
l_pointer, curr_key, r_pointer = self._read_single_node_key(
node_start, matching_record_index)
if key < curr_key:
return matching_record_index, l_pointer
elif key > curr_key:
return matching_record_index, r_pointer
else:
if mode == MODE_FIRST:
return matching_record_index, l_pointer
elif mode == MODE_LAST:
return matching_record_index, r_pointer
else:
raise Exception('Invalid mode declared: first/last')
def _update_leaf_ready_data(self, leaf_start, start_index, new_nr_of_elements, records_to_rewrite):
self.buckets.seek(leaf_start)
self.buckets.write(struct.pack('<h', new_nr_of_elements))
start_position = self._calculate_key_position(
leaf_start, start_index, 'l')
self.buckets.seek(start_position)
self.buckets.write(
struct.pack(
'<' + (new_nr_of_elements - start_index) *
self.single_leaf_record_format,
*records_to_rewrite))
# self._read_single_leaf_record.delete(leaf_start)
self._read_leaf_nr_of_elements.delete(leaf_start)
self._read_leaf_nr_of_elements_and_neighbours.delete(leaf_start)
def _update_leaf(self, leaf_start, new_record_position, nr_of_elements,
nr_of_records_to_rewrite, on_deleted, new_key,
new_doc_id, new_start, new_size, new_status):
if nr_of_records_to_rewrite == 0: # just write at set position
self.buckets.seek(self._calculate_key_position(
leaf_start, new_record_position, 'l'))
self.buckets.write(
struct.pack('<' + self.single_leaf_record_format,
new_key,
new_doc_id,
new_start,
new_size,
new_status))
self.flush()
else: # must read all elems after new one, and rewrite them after new
start = self._calculate_key_position(
leaf_start, new_record_position, 'l')
self.buckets.seek(start)
data = self.buckets.read(nr_of_records_to_rewrite *
self.single_leaf_record_size)
records_to_rewrite = struct.unpack('<' + nr_of_records_to_rewrite *
self.single_leaf_record_format, data)
curr_index = 0
records_to_rewrite = list(records_to_rewrite)
for status in records_to_rewrite[4::5]: # don't write back deleted records, deleting them from list
if status != 'o':
del records_to_rewrite[curr_index * 5:curr_index * 5 + 5]
nr_of_records_to_rewrite -= 1
nr_of_elements -= 1
else:
curr_index += 1
self.buckets.seek(start)
self.buckets.write(
struct.pack(
'<' + (nr_of_records_to_rewrite +
1) * self.single_leaf_record_format,
new_key,
new_doc_id,
new_start,
new_size,
new_status,
*tuple(records_to_rewrite)))
self.flush()
self.buckets.seek(leaf_start)
if not on_deleted: # when new record replaced deleted one, nr of leaf elements stays the same
self.buckets.write(struct.pack('<h', nr_of_elements + 1))
self._read_leaf_nr_of_elements.delete(leaf_start)
self._read_leaf_nr_of_elements_and_neighbours.delete(leaf_start)
self._find_key_in_leaf.delete(leaf_start)
# self._read_single_leaf_record.delete(leaf_start)
def _read_leaf_neighbours(self, leaf_start):
self.buckets.seek(leaf_start + self.elements_counter_size)
neihbours_data = self.buckets.read(2 * self.pointer_size)
prev_l, next_l = struct.unpack(
'<' + 2 * self.pointer_format, neihbours_data)
return prev_l, next_l
def _update_leaf_size_and_pointers(self, leaf_start, new_size, new_prev, new_next):
self.buckets.seek(leaf_start)
self.buckets.write(
struct.pack(
'<' + self.elements_counter_format + 2 * self.pointer_format,
new_size,
new_prev,
new_next))
self._read_leaf_nr_of_elements.delete(leaf_start)
self._read_leaf_neighbours.delete(leaf_start)
self._read_leaf_nr_of_elements_and_neighbours.delete(leaf_start)
def _update_leaf_prev_pointer(self, leaf_start, pointer):
self.buckets.seek(leaf_start + self.elements_counter_size)
self.buckets.write(struct.pack('<' + self.pointer_format,
pointer))
self._read_leaf_neighbours.delete(leaf_start)
self._read_leaf_nr_of_elements_and_neighbours.delete(leaf_start)
def _update_size(self, start, new_size):
self.buckets.seek(start)
self.buckets.write(struct.pack('<' + self.elements_counter_format,
new_size))
self._read_leaf_nr_of_elements.delete(start)
self._read_leaf_nr_of_elements_and_neighbours.delete(start)
def _create_new_root_from_leaf(self, leaf_start, nr_of_records_to_rewrite, new_leaf_size, old_leaf_size, half_size, new_data):
blanks = (self.node_capacity - new_leaf_size) * \
self.single_leaf_record_size * '\x00'
left_leaf_start_position = self.data_start + self.node_size
right_leaf_start_position = self.data_start + \
self.node_size + self.leaf_size
self.buckets.seek(self.data_start + self.leaf_heading_size)
# read old root
data = self.buckets.read(
self.single_leaf_record_size * self.node_capacity)
leaf_data = struct.unpack('<' + self.
single_leaf_record_format * self.node_capacity, data)
# remove deleted records, if succeded abort spliting
if self._update_if_has_deleted(self.data_start, leaf_data, 0, new_data):
return None
# find out key which goes to parent node
if nr_of_records_to_rewrite > new_leaf_size - 1:
key_moved_to_parent_node = leaf_data[(old_leaf_size - 1) * 5]
elif nr_of_records_to_rewrite == new_leaf_size - 1:
key_moved_to_parent_node = new_data[0]
else:
key_moved_to_parent_node = leaf_data[old_leaf_size * 5]
data_to_write = self._prepare_new_root_data(key_moved_to_parent_node,
left_leaf_start_position,
right_leaf_start_position,
'l')
if nr_of_records_to_rewrite > half_size:
# key goes to first half
# prepare left leaf data
left_leaf_data = struct.pack('<' + self.leaf_heading_format + self.single_leaf_record_format
* (self.node_capacity - nr_of_records_to_rewrite),
old_leaf_size,
0,
right_leaf_start_position,
*leaf_data[:-nr_of_records_to_rewrite * 5])
left_leaf_data += struct.pack(
'<' + self.single_leaf_record_format * (
nr_of_records_to_rewrite - new_leaf_size + 1),
new_data[0],
new_data[1],
new_data[2],
new_data[3],
new_data[4],
*leaf_data[-nr_of_records_to_rewrite * 5:(old_leaf_size - 1) * 5])
# prepare right leaf_data
right_leaf_data = struct.pack('<' + self.elements_counter_format + 2 * self.pointer_format +
self.single_leaf_record_format *
new_leaf_size,
new_leaf_size,
left_leaf_start_position,
0,
*leaf_data[-new_leaf_size * 5:])
else:
# key goes to second half
if nr_of_records_to_rewrite:
records_before = leaf_data[old_leaf_size *
5:-nr_of_records_to_rewrite * 5]
records_after = leaf_data[-nr_of_records_to_rewrite * 5:]
else:
records_before = leaf_data[old_leaf_size * 5:]
records_after = []
left_leaf_data = struct.pack(
'<' + self.leaf_heading_format +
self.single_leaf_record_format * old_leaf_size,
old_leaf_size,
0,
right_leaf_start_position,
*leaf_data[:old_leaf_size * 5])
# prepare right leaf_data
right_leaf_data = struct.pack('<' + self.elements_counter_format + 2 * self.pointer_format +
self.single_leaf_record_format * (new_leaf_size -
nr_of_records_to_rewrite - 1),
new_leaf_size,
left_leaf_start_position,
0,
*records_before)
right_leaf_data += struct.pack(
'<' + self.single_leaf_record_format * (
nr_of_records_to_rewrite + 1),
new_data[0],
new_data[1],
new_data[2],
new_data[3],
new_data[4],
*records_after)
left_leaf_data += (self.node_capacity -
old_leaf_size) * self.single_leaf_record_size * '\x00'
right_leaf_data += blanks
data_to_write += left_leaf_data
data_to_write += right_leaf_data
self.buckets.seek(self._start_ind)
self.buckets.write(struct.pack('<c', 'n') + data_to_write)
self.root_flag = 'n'
# self._read_single_leaf_record.delete(leaf_start)
self._find_key_in_leaf.delete(leaf_start)
self._read_leaf_nr_of_elements.delete(leaf_start)
self._read_leaf_nr_of_elements_and_neighbours.delete(leaf_start)
self._read_leaf_neighbours.delete(leaf_start)
return None
def _split_leaf(
self, leaf_start, nr_of_records_to_rewrite, new_key, new_doc_id, new_start, new_size, new_status,
create_new_root=False):
"""
Splits full leaf in two separate ones, first half of records stays on old position,
second half is written as new leaf at the end of file.
"""
half_size = self.node_capacity / 2
if self.node_capacity % 2 == 0:
old_leaf_size = half_size
new_leaf_size = half_size + 1
else:
old_leaf_size = new_leaf_size = half_size + 1
if create_new_root: # leaf is a root
new_data = [new_key, new_doc_id, new_start, new_size, new_status]
self._create_new_root_from_leaf(leaf_start, nr_of_records_to_rewrite, new_leaf_size, old_leaf_size, half_size, new_data)
else:
blanks = (self.node_capacity - new_leaf_size) * \
self.single_leaf_record_size * '\x00'
prev_l, next_l = self._read_leaf_neighbours(leaf_start)
if nr_of_records_to_rewrite > half_size: # insert key into first half of leaf
self.buckets.seek(self._calculate_key_position(leaf_start,
self.node_capacity - nr_of_records_to_rewrite,
'l'))
# read all records with key>new_key
data = self.buckets.read(
nr_of_records_to_rewrite * self.single_leaf_record_size)
records_to_rewrite = struct.unpack(
'<' + nr_of_records_to_rewrite * self.single_leaf_record_format, data)
# remove deleted records, if succeded abort spliting
if self._update_if_has_deleted(leaf_start,
records_to_rewrite,
self.node_capacity -
nr_of_records_to_rewrite,
[new_key, new_doc_id, new_start, new_size, new_status]):
return None
key_moved_to_parent_node = records_to_rewrite[
-new_leaf_size * 5]
# write new leaf at end of file
self.buckets.seek(0, 2) # end of file
new_leaf_start = self.buckets.tell()
# prepare new leaf_data
new_leaf = struct.pack('<' + self.elements_counter_format + 2 * self.pointer_format +
self.single_leaf_record_format *
new_leaf_size,
new_leaf_size,
leaf_start,
next_l,
*records_to_rewrite[-new_leaf_size * 5:])
new_leaf += blanks
# write new leaf
self.buckets.write(new_leaf)
# update old leaf heading
self._update_leaf_size_and_pointers(leaf_start,
old_leaf_size,
prev_l,
new_leaf_start)
# seek position of new key in first half
self.buckets.seek(self._calculate_key_position(leaf_start,
self.node_capacity - nr_of_records_to_rewrite,
'l'))
# write new key and keys after
self.buckets.write(
struct.pack(
'<' + self.single_leaf_record_format *
(nr_of_records_to_rewrite - new_leaf_size + 1),
new_key,
new_doc_id,
new_start,
new_size,
'o',
*records_to_rewrite[:-new_leaf_size * 5]))
if next_l: # when next_l is 0 there is no next leaf to update, avoids writing data at 0 position of file
self._update_leaf_prev_pointer(
next_l, new_leaf_start)
# self._read_single_leaf_record.delete(leaf_start)
self._find_key_in_leaf.delete(leaf_start)
return new_leaf_start, key_moved_to_parent_node
else: # key goes into second half of leaf '
# seek half of the leaf
self.buckets.seek(self._calculate_key_position(
leaf_start, old_leaf_size, 'l'))
data = self.buckets.read(
self.single_leaf_record_size * (new_leaf_size - 1))
records_to_rewrite = struct.unpack('<' + (new_leaf_size - 1) *
self.single_leaf_record_format, data)
# remove deleted records, if succeded abort spliting
if self._update_if_has_deleted(leaf_start,
records_to_rewrite,
old_leaf_size,
[new_key, new_doc_id, new_start, new_size, new_status]):
return None
key_moved_to_parent_node = records_to_rewrite[
-(new_leaf_size - 1) * 5]
if key_moved_to_parent_node > new_key:
key_moved_to_parent_node = new_key
self.buckets.seek(0, 2) # end of file
new_leaf_start = self.buckets.tell()
# prepare new leaf data
index_of_records_split = nr_of_records_to_rewrite * 5
if index_of_records_split:
records_before = records_to_rewrite[
:-index_of_records_split]
records_after = records_to_rewrite[
-index_of_records_split:]
else:
records_before = records_to_rewrite
records_after = []
new_leaf = struct.pack('<' + self.elements_counter_format + 2 * self.pointer_format
+ self.single_leaf_record_format * (new_leaf_size -
nr_of_records_to_rewrite - 1),
new_leaf_size,
leaf_start,
next_l,
*records_before)
new_leaf += struct.pack(
'<' + self.single_leaf_record_format *
(nr_of_records_to_rewrite + 1),
new_key,
new_doc_id,
new_start,
new_size,
'o',
*records_after)
new_leaf += blanks
self.buckets.write(new_leaf)
self._update_leaf_size_and_pointers(leaf_start,
old_leaf_size,
prev_l,
new_leaf_start)
if next_l: # pren next_l is 0 there is no next leaf to update, avoids writing data at 0 position of file
self._update_leaf_prev_pointer(
next_l, new_leaf_start)
# self._read_single_leaf_record.delete(leaf_start)
self._find_key_in_leaf.delete(leaf_start)
return new_leaf_start, key_moved_to_parent_node
def _update_if_has_deleted(self, leaf_start, records_to_rewrite, start_position, new_record_data):
"""
Checks if there are any deleted elements in data to rewrite and prevent from writing then back.
"""
curr_index = 0
nr_of_elements = self.node_capacity
records_to_rewrite = list(records_to_rewrite)
for status in records_to_rewrite[4::5]: # remove deleted from list
if status != 'o':
del records_to_rewrite[curr_index * 5:curr_index * 5 + 5]
nr_of_elements -= 1
else:
curr_index += 1
# if were deleted dont have to split, just update leaf
if nr_of_elements < self.node_capacity:
data_split_index = 0
for key in records_to_rewrite[0::5]:
if key > new_record_data[0]:
break
else:
data_split_index += 1
records_to_rewrite = records_to_rewrite[:data_split_index * 5]\
+ new_record_data\
+ records_to_rewrite[data_split_index * 5:]
self._update_leaf_ready_data(leaf_start,
start_position,
nr_of_elements + 1,
records_to_rewrite),
return True
else: # did not found any deleted records in leaf
return False
def _prepare_new_root_data(self, root_key, left_pointer, right_pointer, children_flag='n'):
new_root = struct.pack(
'<' + self.node_heading_format + self.single_node_record_format,
1,
children_flag,
left_pointer,
root_key,
right_pointer)
new_root += (self.key_size + self.pointer_size) * (self.
node_capacity - 1) * '\x00'
return new_root
def _create_new_root_from_node(self, node_start, children_flag, nr_of_keys_to_rewrite, new_node_size, old_node_size, new_key, new_pointer):
# reading second half of node
self.buckets.seek(self.data_start + self.node_heading_size)
# read all keys with key>new_key
data = self.buckets.read(self.pointer_size + self.
node_capacity * (self.key_size + self.pointer_size))
old_node_data = struct.unpack('<' + self.pointer_format + self.node_capacity *
(self.key_format + self.pointer_format), data)
self.buckets.seek(0, 2) # end of file
new_node_start = self.buckets.tell()
if nr_of_keys_to_rewrite == new_node_size:
key_moved_to_root = new_key
# prepare new nodes data
left_node = struct.pack('<' + self.node_heading_format + self.pointer_format +
old_node_size * (self.
key_format + self.pointer_format),
old_node_size,
children_flag,
*old_node_data[:old_node_size * 2 + 1])
right_node = struct.pack('<' + self.node_heading_format + self.pointer_format +
new_node_size * (self.
key_format + self.pointer_format),
new_node_size,
children_flag,
new_pointer,
*old_node_data[old_node_size * 2 + 1:])
elif nr_of_keys_to_rewrite > new_node_size:
key_moved_to_root = old_node_data[old_node_size * 2 - 1]
# prepare new nodes data
if nr_of_keys_to_rewrite == self.node_capacity:
keys_before = old_node_data[:1]
keys_after = old_node_data[1:old_node_size * 2 - 1]
else:
keys_before = old_node_data[:-nr_of_keys_to_rewrite * 2]
keys_after = old_node_data[-(
nr_of_keys_to_rewrite) * 2:old_node_size * 2 - 1]
left_node = struct.pack('<' + self.node_heading_format + self.pointer_format +
(self.node_capacity - nr_of_keys_to_rewrite) * (self.
key_format + self.pointer_format),
old_node_size,
children_flag,
*keys_before)
left_node += struct.pack(
'<' + (self.key_format + self.pointer_format) *
(nr_of_keys_to_rewrite - new_node_size),
new_key,
new_pointer,
*keys_after)
right_node = struct.pack('<' + self.node_heading_format + self.pointer_format +
new_node_size * (self.
key_format + self.pointer_format),
new_node_size,
children_flag,
*old_node_data[old_node_size * 2:])
else:
# 'inserting key into second half of node and creating new root'
key_moved_to_root = old_node_data[old_node_size * 2 + 1]
# prepare new nodes data
left_node = struct.pack('<' + self.node_heading_format + self.pointer_format +
old_node_size * (self.
key_format + self.pointer_format),
old_node_size,
children_flag,
*old_node_data[:old_node_size * 2 + 1])
if nr_of_keys_to_rewrite:
keys_before = old_node_data[(old_node_size +
1) * 2:-nr_of_keys_to_rewrite * 2]
keys_after = old_node_data[-nr_of_keys_to_rewrite * 2:]
else:
keys_before = old_node_data[(old_node_size + 1) * 2:]
keys_after = []
right_node = struct.pack('<' + self.node_heading_format + self.pointer_format +
(new_node_size - nr_of_keys_to_rewrite - 1) * (self.
key_format + self.pointer_format),
new_node_size,
children_flag,
*keys_before)
right_node += struct.pack(
'<' + (nr_of_keys_to_rewrite + 1) *
(self.key_format + self.pointer_format),
new_key,
new_pointer,
*keys_after)
new_root = self._prepare_new_root_data(key_moved_to_root,
new_node_start,
new_node_start + self.node_size)
left_node += (self.node_capacity - old_node_size) * \
(self.key_size + self.pointer_size) * '\x00'
# adding blanks after new node
right_node += (self.node_capacity - new_node_size) * \
(self.key_size + self.pointer_size) * '\x00'
self.buckets.seek(0, 2)
self.buckets.write(left_node + right_node)
self.buckets.seek(self.data_start)
self.buckets.write(new_root)
self._read_single_node_key.delete(node_start)
self._read_node_nr_of_elements_and_children_flag.delete(node_start)
return None
def _split_node(self, node_start, nr_of_keys_to_rewrite, new_key, new_pointer, children_flag, create_new_root=False):
"""
Splits full node in two separate ones, first half of records stays on old position,
second half is written as new leaf at the end of file.
"""
half_size = self.node_capacity / 2
if self.node_capacity % 2 == 0:
old_node_size = new_node_size = half_size
else:
old_node_size = half_size
new_node_size = half_size + 1
if create_new_root:
self._create_new_root_from_node(node_start, children_flag, nr_of_keys_to_rewrite, new_node_size, old_node_size, new_key, new_pointer)
else:
blanks = (self.node_capacity - new_node_size) * (
self.key_size + self.pointer_size) * '\x00'
if nr_of_keys_to_rewrite == new_node_size: # insert key into first half of node
# reading second half of node
self.buckets.seek(self._calculate_key_position(node_start,
old_node_size,
'n') + self.pointer_size)
# read all keys with key>new_key
data = self.buckets.read(nr_of_keys_to_rewrite *
(self.key_size + self.pointer_size))
old_node_data = struct.unpack('<' + nr_of_keys_to_rewrite *
(self.key_format + self.pointer_format), data)
# write new node at end of file
self.buckets.seek(0, 2)
new_node_start = self.buckets.tell()
# prepare new node_data
new_node = struct.pack('<' + self.node_heading_format + self.pointer_format +
(self.key_format +
self.pointer_format) * new_node_size,
new_node_size,
children_flag,
new_pointer,
*old_node_data)
new_node += blanks
# write new node
self.buckets.write(new_node)
# update old node data
self._update_size(
node_start, old_node_size)
self._read_single_node_key.delete(node_start)
self._read_node_nr_of_elements_and_children_flag.delete(
node_start)
return new_node_start, new_key
elif nr_of_keys_to_rewrite > half_size: # insert key into first half of node
# seek for first key to rewrite
self.buckets.seek(self._calculate_key_position(node_start, self.node_capacity - nr_of_keys_to_rewrite, 'n')
+ self.pointer_size)
# read all keys with key>new_key
data = self.buckets.read(
nr_of_keys_to_rewrite * (self.key_size + self.pointer_size))
old_node_data = struct.unpack(
'<' + nr_of_keys_to_rewrite * (self.key_format + self.pointer_format), data)
key_moved_to_parent_node = old_node_data[-(
new_node_size + 1) * 2]
self.buckets.seek(0, 2)
new_node_start = self.buckets.tell()
# prepare new node_data
new_node = struct.pack('<' + self.node_heading_format +
self.pointer_format + (self.key_format +
self.pointer_format) * new_node_size,
new_node_size,
children_flag,
old_node_data[-new_node_size * 2 - 1],
*old_node_data[-new_node_size * 2:])
new_node += blanks
# write new node
self.buckets.write(new_node)
self._update_size(
node_start, old_node_size)
# seek position of new key in first half
self.buckets.seek(self._calculate_key_position(node_start, self.node_capacity - nr_of_keys_to_rewrite, 'n')
+ self.pointer_size)
# write new key and keys after
self.buckets.write(
struct.pack(
'<' + (self.key_format + self.pointer_format) *
(nr_of_keys_to_rewrite - new_node_size),
new_key,
new_pointer,
*old_node_data[:-(new_node_size + 1) * 2]))
self._read_single_node_key.delete(node_start)
self._read_node_nr_of_elements_and_children_flag.delete(
node_start)
return new_node_start, key_moved_to_parent_node
else: # key goes into second half
# reading second half of node
self.buckets.seek(self._calculate_key_position(node_start,
old_node_size,
'n')
+ self.pointer_size)
data = self.buckets.read(
new_node_size * (self.key_size + self.pointer_size))
old_node_data = struct.unpack('<' + new_node_size *
(self.key_format + self.pointer_format), data)
# find key which goes to parent node
key_moved_to_parent_node = old_node_data[0]
self.buckets.seek(0, 2) # end of file
new_node_start = self.buckets.tell()
index_of_records_split = nr_of_keys_to_rewrite * 2
# prepare new node_data
first_leaf_pointer = old_node_data[1]
old_node_data = old_node_data[2:]
if index_of_records_split:
keys_before = old_node_data[:-index_of_records_split]
keys_after = old_node_data[-index_of_records_split:]
else:
keys_before = old_node_data
keys_after = []
new_node = struct.pack('<' + self.node_heading_format + self.pointer_format +
(self.key_format + self.pointer_format) *
(new_node_size -
nr_of_keys_to_rewrite - 1),
new_node_size,
children_flag,
first_leaf_pointer,
*keys_before)
new_node += struct.pack('<' + (self.key_format + self.pointer_format) *
(nr_of_keys_to_rewrite + 1),
new_key,
new_pointer,
*keys_after)
new_node += blanks
# write new node
self.buckets.write(new_node)
self._update_size(node_start, old_node_size)
self._read_single_node_key.delete(node_start)
self._read_node_nr_of_elements_and_children_flag.delete(
node_start)
return new_node_start, key_moved_to_parent_node
def insert_first_record_into_leaf(self, leaf_start, key, doc_id, start, size, status):
self.buckets.seek(leaf_start)
self.buckets.write(struct.pack('<' + self.elements_counter_format,
1))
self.buckets.seek(leaf_start + self.leaf_heading_size)
self.buckets.write(struct.pack('<' + self.single_leaf_record_format,
key,
doc_id,
start,
size,
status))
# self._read_single_leaf_record.delete(leaf_start)
self._find_key_in_leaf.delete(leaf_start)
self._read_leaf_nr_of_elements.delete(leaf_start)
self._read_leaf_nr_of_elements_and_neighbours.delete(leaf_start)
def _insert_new_record_into_leaf(self, leaf_start, key, doc_id, start, size, status, nodes_stack, indexes):
nr_of_elements = self._read_leaf_nr_of_elements(leaf_start)
if nr_of_elements == 0:
self.insert_first_record_into_leaf(
leaf_start, key, doc_id, start, size, status)
return
leaf_start, new_record_position, nr_of_records_to_rewrite, full_leaf, on_deleted\
= self._find_place_in_leaf(key, leaf_start, nr_of_elements)
if full_leaf:
try: # check if leaf has parent node
leaf_parent_pointer = nodes_stack.pop()
except IndexError: # leaf is a root
leaf_parent_pointer = 0
split_data = self._split_leaf(leaf_start,
nr_of_records_to_rewrite,
key,
doc_id,
start,
size,
status,
create_new_root=(False if leaf_parent_pointer else True))
if split_data is not None: # means that split created new root or replaced split with update_if_has_deleted
new_leaf_start_position, key_moved_to_parent_node = split_data
self._insert_new_key_into_node(leaf_parent_pointer,
key_moved_to_parent_node,
leaf_start,
new_leaf_start_position,
nodes_stack,
indexes)
else: # there is a place for record in leaf
self.buckets.seek(leaf_start)
self._update_leaf(
leaf_start, new_record_position, nr_of_elements, nr_of_records_to_rewrite,
on_deleted, key, doc_id, start, size, status)
def _update_node(self, new_key_position, nr_of_keys_to_rewrite, new_key, new_pointer):
if nr_of_keys_to_rewrite == 0:
self.buckets.seek(new_key_position)
self.buckets.write(
struct.pack('<' + self.key_format + self.pointer_format,
new_key,
new_pointer))
self.flush()
else:
self.buckets.seek(new_key_position)
data = self.buckets.read(nr_of_keys_to_rewrite * (
self.key_size + self.pointer_size))
keys_to_rewrite = struct.unpack(
'<' + nr_of_keys_to_rewrite * (self.key_format + self.pointer_format), data)
self.buckets.seek(new_key_position)
self.buckets.write(
struct.pack(
'<' + (nr_of_keys_to_rewrite + 1) *
(self.key_format + self.pointer_format),
new_key,
new_pointer,
*keys_to_rewrite))
self.flush()
def _insert_new_key_into_node(self, node_start, new_key, old_half_start, new_half_start, nodes_stack, indexes):
parent_key_index = indexes.pop()
nr_of_elements, children_flag = self._read_node_nr_of_elements_and_children_flag(node_start)
parent_prev_pointer = self._read_single_node_key(
node_start, parent_key_index)[0]
if parent_prev_pointer == old_half_start: # splited child was on the left side of his parent key, must write new key before it
new_key_position = self.pointer_size + self._calculate_key_position(node_start, parent_key_index, 'n')
nr_of_keys_to_rewrite = nr_of_elements - parent_key_index
else: # splited child was on the right side of his parent key, must write new key after it
new_key_position = self.pointer_size + self._calculate_key_position(node_start, parent_key_index + 1, 'n')
nr_of_keys_to_rewrite = nr_of_elements - (parent_key_index + 1)
if nr_of_elements == self.node_capacity:
try: # check if node has parent
node_parent_pointer = nodes_stack.pop()
except IndexError: # node is a root
node_parent_pointer = 0
new_data = self._split_node(node_start,
nr_of_keys_to_rewrite,
new_key,
new_half_start,
children_flag,
create_new_root=(False if node_parent_pointer else True))
if new_data: # if not new_data, new root has been created
new_node_start_position, key_moved_to_parent_node = new_data
self._insert_new_key_into_node(node_parent_pointer,
key_moved_to_parent_node,
node_start,
new_node_start_position,
nodes_stack,
indexes)
self._find_first_key_occurence_in_node.delete(node_start)
self._find_last_key_occurence_in_node.delete(node_start)
else: # there is a empty slot for new key in node
self._update_size(node_start, nr_of_elements + 1)
self._update_node(new_key_position,
nr_of_keys_to_rewrite,
new_key,
new_half_start)
self._find_first_key_occurence_in_node.delete(node_start)
self._find_last_key_occurence_in_node.delete(node_start)
self._read_single_node_key.delete(node_start)
self._read_node_nr_of_elements_and_children_flag.delete(node_start)
def _find_leaf_to_insert(self, key):
"""
Traverses tree in search for leaf for insert, remembering parent nodes in path,
looks for last occurence of key if already in tree.
"""
nodes_stack = [self.data_start]
if self.root_flag == 'l':
return nodes_stack, []
else:
nr_of_elements, curr_child_flag = self._read_node_nr_of_elements_and_children_flag(self.data_start)
curr_index, curr_pointer = self._find_last_key_occurence_in_node(
self.data_start, key, nr_of_elements)
nodes_stack.append(curr_pointer)
indexes = [curr_index]
while(curr_child_flag == 'n'):
nr_of_elements, curr_child_flag = self._read_node_nr_of_elements_and_children_flag(curr_pointer)
curr_index, curr_pointer = self._find_last_key_occurence_in_node(curr_pointer, key, nr_of_elements)
nodes_stack.append(curr_pointer)
indexes.append(curr_index)
return nodes_stack, indexes
# nodes stack contains start addreses of nodes directly above leaf with key, indexes match keys adjacent nodes_stack values (as pointers)
# required when inserting new keys in upper tree levels
def _find_leaf_with_last_key_occurence(self, key):
if self.root_flag == 'l':
return self.data_start
else:
nr_of_elements, curr_child_flag = self._read_node_nr_of_elements_and_children_flag(self.data_start)
curr_position = self._find_last_key_occurence_in_node(
self.data_start, key, nr_of_elements)[1]
while(curr_child_flag == 'n'):
nr_of_elements, curr_child_flag = self._read_node_nr_of_elements_and_children_flag(curr_position)
curr_position = self._find_last_key_occurence_in_node(
curr_position, key, nr_of_elements)[1]
return curr_position
def _find_leaf_with_first_key_occurence(self, key):
if self.root_flag == 'l':
return self.data_start
else:
nr_of_elements, curr_child_flag = self._read_node_nr_of_elements_and_children_flag(self.data_start)
curr_position = self._find_first_key_occurence_in_node(
self.data_start, key, nr_of_elements)[1]
while(curr_child_flag == 'n'):
nr_of_elements, curr_child_flag = self._read_node_nr_of_elements_and_children_flag(curr_position)
curr_position = self._find_first_key_occurence_in_node(
curr_position, key, nr_of_elements)[1]
return curr_position
def _find_key(self, key):
containing_leaf_start = self._find_leaf_with_first_key_occurence(key)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(containing_leaf_start)
try:
doc_id, l_key, start, size, status = self._find_key_in_leaf(
containing_leaf_start, key, nr_of_elements)
except ElemNotFound:
if next_leaf:
nr_of_elements = self._read_leaf_nr_of_elements(next_leaf)
else:
raise ElemNotFound
doc_id, l_key, start, size, status = self._find_key_in_leaf(
next_leaf, key, nr_of_elements)
return doc_id, l_key, start, size, status
def _find_key_to_update(self, key, doc_id):
"""
Search tree for key that matches not only given key but also doc_id.
"""
containing_leaf_start = self._find_leaf_with_first_key_occurence(key)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(containing_leaf_start)
try:
leaf_start, record_index, doc_id, l_key, start, size, status = self._find_key_in_leaf_for_update(key,
doc_id,
containing_leaf_start,
nr_of_elements)
except ElemNotFound:
if next_leaf:
nr_of_elements = self._read_leaf_nr_of_elements(next_leaf)
else:
raise TryReindexException()
try:
leaf_start, record_index, doc_id, l_key, start, size, status = self._find_key_in_leaf_for_update(key,
doc_id,
next_leaf,
nr_of_elements)
except ElemNotFound:
raise TryReindexException()
return leaf_start, record_index, doc_id, l_key, start, size, status
def update(self, doc_id, key, u_start=0, u_size=0, u_status='o'):
containing_leaf_start, element_index, old_doc_id, old_key, old_start, old_size, old_status = self._find_key_to_update(key, doc_id)
if u_start:
old_start = u_start
if u_size:
old_size = u_size
if u_status:
old_status = u_status
new_data = (old_doc_id, old_start, old_size, old_status)
self._update_element(containing_leaf_start, element_index, new_data)
self._find_key.delete(key)
self._match_doc_id.delete(doc_id)
self._find_key_in_leaf.delete(containing_leaf_start, key)
return True
def delete(self, doc_id, key, start=0, size=0):
containing_leaf_start, element_index = self._find_key_to_update(
key, doc_id)[:2]
self._delete_element(containing_leaf_start, element_index)
self._find_key.delete(key)
self._match_doc_id.delete(doc_id)
self._find_key_in_leaf.delete(containing_leaf_start, key)
return True
def _find_key_many(self, key, limit=1, offset=0):
leaf_with_key = self._find_leaf_with_first_key_occurence(key)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
try:
leaf_with_key, key_index = self._find_index_of_first_key_equal(
key, leaf_with_key, nr_of_elements)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
except ElemNotFound:
leaf_with_key = next_leaf
key_index = 0
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
while offset:
if key_index < nr_of_elements:
curr_key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_with_key, key_index)
if key == curr_key:
if status != 'd':
offset -= 1
key_index += 1
else:
return
else:
key_index = 0
if next_leaf:
leaf_with_key = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
else:
return
while limit:
if key_index < nr_of_elements:
curr_key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_with_key, key_index)
if key == curr_key:
if status != 'd':
yield doc_id, start, size, status
limit -= 1
key_index += 1
else:
return
else:
key_index = 0
if next_leaf:
leaf_with_key = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
else:
return
def _find_key_smaller(self, key, limit=1, offset=0):
leaf_with_key = self._find_leaf_with_first_key_occurence(key)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
leaf_with_key, key_index = self._find_index_of_first_key_equal_or_smaller_key(key, leaf_with_key, nr_of_elements)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
curr_key = self._read_single_leaf_record(leaf_with_key, key_index)[0]
if curr_key >= key:
key_index -= 1
while offset:
if key_index >= 0:
key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_with_key, key_index)
if status != 'd':
offset -= 1
key_index -= 1
else:
if prev_leaf:
leaf_with_key = prev_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(prev_leaf)
key_index = nr_of_elements - 1
else:
return
while limit:
if key_index >= 0:
key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_with_key, key_index)
if status != 'd':
yield doc_id, key, start, size, status
limit -= 1
key_index -= 1
else:
if prev_leaf:
leaf_with_key = prev_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(prev_leaf)
key_index = nr_of_elements - 1
else:
return
def _find_key_equal_and_smaller(self, key, limit=1, offset=0):
leaf_with_key = self._find_leaf_with_last_key_occurence(key)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
try:
leaf_with_key, key_index = self._find_index_of_last_key_equal_or_smaller_key(key, leaf_with_key, nr_of_elements)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
except ElemNotFound:
leaf_with_key = prev_leaf
key_index = self._read_leaf_nr_of_elements_and_neighbours(
leaf_with_key)[0]
curr_key = self._read_single_leaf_record(leaf_with_key, key_index)[0]
if curr_key > key:
key_index -= 1
while offset:
if key_index >= 0:
key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_with_key, key_index)
if status != 'd':
offset -= 1
key_index -= 1
else:
if prev_leaf:
leaf_with_key = prev_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(prev_leaf)
key_index = nr_of_elements - 1
else:
return
while limit:
if key_index >= 0:
key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_with_key, key_index)
if status != 'd':
yield doc_id, key, start, size, status
limit -= 1
key_index -= 1
else:
if prev_leaf:
leaf_with_key = prev_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(prev_leaf)
key_index = nr_of_elements - 1
else:
return
def _find_key_bigger(self, key, limit=1, offset=0):
leaf_with_key = self._find_leaf_with_last_key_occurence(key)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
try:
leaf_with_key, key_index = self._find_index_of_last_key_equal_or_smaller_key(key, leaf_with_key, nr_of_elements)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
except ElemNotFound:
key_index = 0
curr_key = self._read_single_leaf_record(leaf_with_key, key_index)[0]
if curr_key <= key:
key_index += 1
while offset:
if key_index < nr_of_elements:
curr_key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_with_key, key_index)
if status != 'd':
offset -= 1
key_index += 1
else:
key_index = 0
if next_leaf:
leaf_with_key = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
else:
return
while limit:
if key_index < nr_of_elements:
curr_key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_with_key, key_index)
if status != 'd':
yield doc_id, curr_key, start, size, status
limit -= 1
key_index += 1
else:
key_index = 0
if next_leaf:
leaf_with_key = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
else:
return
def _find_key_equal_and_bigger(self, key, limit=1, offset=0):
leaf_with_key = self._find_leaf_with_first_key_occurence(key)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
leaf_with_key, key_index = self._find_index_of_first_key_equal_or_smaller_key(key, leaf_with_key, nr_of_elements)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
curr_key = self._read_single_leaf_record(leaf_with_key, key_index)[0]
if curr_key < key:
key_index += 1
while offset:
if key_index < nr_of_elements:
curr_key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_with_key, key_index)
if status != 'd':
offset -= 1
key_index += 1
else:
key_index = 0
if next_leaf:
leaf_with_key = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
else:
return
while limit:
if key_index < nr_of_elements:
curr_key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_with_key, key_index)
if status != 'd':
yield doc_id, curr_key, start, size, status
limit -= 1
key_index += 1
else:
key_index = 0
if next_leaf:
leaf_with_key = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
else:
return
def _find_key_between(self, start, end, limit, offset, inclusive_start, inclusive_end):
"""
Returns generator containing all keys withing given interval.
"""
if inclusive_start:
leaf_with_key = self._find_leaf_with_first_key_occurence(start)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
leaf_with_key, key_index = self._find_index_of_first_key_equal_or_smaller_key(start, leaf_with_key, nr_of_elements)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
curr_key = self._read_single_leaf_record(
leaf_with_key, key_index)[0]
if curr_key < start:
key_index += 1
else:
leaf_with_key = self._find_leaf_with_last_key_occurence(start)
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_with_key)
leaf_with_key, key_index = self._find_index_of_last_key_equal_or_smaller_key(start, leaf_with_key, nr_of_elements)
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_with_key, key_index)
if curr_key <= start:
key_index += 1
while offset:
if key_index < nr_of_elements:
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_with_key, key_index)
if curr_status != 'd':
offset -= 1
key_index += 1
else:
key_index = 0
if next_leaf:
leaf_with_key = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
else:
return
while limit:
if key_index < nr_of_elements:
curr_key, curr_doc_id, curr_start, curr_size, curr_status = self._read_single_leaf_record(leaf_with_key, key_index)
if curr_key > end or (curr_key == end and not inclusive_end):
return
elif curr_status != 'd':
yield curr_doc_id, curr_key, curr_start, curr_size, curr_status
limit -= 1
key_index += 1
else:
key_index = 0
if next_leaf:
leaf_with_key = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
else:
return
def get(self, key):
return self._find_key(self.make_key(key))
def get_many(self, key, limit=1, offset=0):
return self._find_key_many(self.make_key(key), limit, offset)
def get_between(self, start, end, limit=1, offset=0, inclusive_start=True, inclusive_end=True):
if start is None:
end = self.make_key(end)
if inclusive_end:
return self._find_key_equal_and_smaller(end, limit, offset)
else:
return self._find_key_smaller(end, limit, offset)
elif end is None:
start = self.make_key(start)
if inclusive_start:
return self._find_key_equal_and_bigger(start, limit, offset)
else:
return self._find_key_bigger(start, limit, offset)
else:
start = self.make_key(start)
end = self.make_key(end)
return self._find_key_between(start, end, limit, offset, inclusive_start, inclusive_end)
def all(self, limit=-1, offset=0):
"""
Traverses linked list of all tree leaves and returns generator containing all elements stored in index.
"""
if self.root_flag == 'n':
leaf_start = self.data_start + self.node_size
else:
leaf_start = self.data_start
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(leaf_start)
key_index = 0
while offset:
if key_index < nr_of_elements:
curr_key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_start, key_index)
if status != 'd':
offset -= 1
key_index += 1
else:
key_index = 0
if next_leaf:
leaf_start = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
else:
return
while limit:
if key_index < nr_of_elements:
curr_key, doc_id, start, size, status = self._read_single_leaf_record(
leaf_start, key_index)
if status != 'd':
yield doc_id, curr_key, start, size, status
limit -= 1
key_index += 1
else:
key_index = 0
if next_leaf:
leaf_start = next_leaf
nr_of_elements, prev_leaf, next_leaf = self._read_leaf_nr_of_elements_and_neighbours(next_leaf)
else:
return
def make_key(self, key):
raise NotImplementedError()
def make_key_value(self, data):
raise NotImplementedError()
def _open_storage(self):
s = globals()[self.storage_class]
if not self.storage:
self.storage = s(self.db_path, self.name)
self.storage.open()
def _create_storage(self):
s = globals()[self.storage_class]
if not self.storage:
self.storage = s(self.db_path, self.name)
self.storage.create()
def compact(self, node_capacity=0):
if not node_capacity:
node_capacity = self.node_capacity
compact_ind = self.__class__(
self.db_path, self.name + '_compact', node_capacity=node_capacity)
compact_ind.create_index()
gen = self.all()
while True:
try:
doc_id, key, start, size, status = gen.next()
except StopIteration:
break
self.storage._f.seek(start)
value = self.storage._f.read(size)
start_ = compact_ind.storage._f.tell()
compact_ind.storage._f.write(value)
compact_ind.insert(doc_id, key, start_, size, status)
compact_ind.close_index()
original_name = self.name
# os.unlink(os.path.join(self.db_path, self.name + "_buck"))
self.close_index()
shutil.move(os.path.join(compact_ind.db_path, compact_ind.
name + "_buck"), os.path.join(self.db_path, self.name + "_buck"))
shutil.move(os.path.join(compact_ind.db_path, compact_ind.
name + "_stor"), os.path.join(self.db_path, self.name + "_stor"))
# self.name = original_name
self.open_index() # reload...
self.name = original_name
self._save_params(dict(name=original_name))
self._fix_params()
self._clear_cache()
return True
def _fix_params(self):
super(IU_TreeBasedIndex, self)._fix_params()
self._count_props()
def _clear_cache(self):
self._find_key.clear()
self._match_doc_id.clear()
# self._read_single_leaf_record.clear()
self._find_key_in_leaf.clear()
self._read_single_node_key.clear()
self._find_first_key_occurence_in_node.clear()
self._find_last_key_occurence_in_node.clear()
self._read_leaf_nr_of_elements.clear()
self._read_leaf_neighbours.clear()
self._read_leaf_nr_of_elements_and_neighbours.clear()
self._read_node_nr_of_elements_and_children_flag.clear()
def close_index(self):
super(IU_TreeBasedIndex, self).close_index()
self._clear_cache()
class IU_MultiTreeBasedIndex(IU_TreeBasedIndex):
"""
Class that allows to index more than one key per database record.
It operates very well on GET/INSERT. It's not optimized for
UPDATE operations (will always readd everything)
"""
def __init__(self, *args, **kwargs):
super(IU_MultiTreeBasedIndex, self).__init__(*args, **kwargs)
def insert(self, doc_id, key, start, size, status='o'):
if isinstance(key, (list, tuple)):
key = set(key)
elif not isinstance(key, set):
key = set([key])
ins = super(IU_MultiTreeBasedIndex, self).insert
for curr_key in key:
ins(doc_id, curr_key, start, size, status)
return True
def update(self, doc_id, key, u_start, u_size, u_status='o'):
if isinstance(key, (list, tuple)):
key = set(key)
elif not isinstance(key, set):
key = set([key])
upd = super(IU_MultiTreeBasedIndex, self).update
for curr_key in key:
upd(doc_id, curr_key, u_start, u_size, u_status)
def delete(self, doc_id, key, start=0, size=0):
if isinstance(key, (list, tuple)):
key = set(key)
elif not isinstance(key, set):
key = set([key])
delete = super(IU_MultiTreeBasedIndex, self).delete
for curr_key in key:
delete(doc_id, curr_key, start, size)
def get(self, key):
return super(IU_MultiTreeBasedIndex, self).get(key)
def make_key_value(self, data):
raise NotImplementedError()
# classes for public use, done in this way because of
# generation static files with indexes (_index directory)
class TreeBasedIndex(IU_TreeBasedIndex):
pass
class MultiTreeBasedIndex(IU_MultiTreeBasedIndex):
"""
It allows to index more than one key for record. (ie. prefix/infix/suffix search mechanizms)
That class is designed to be used in custom indexes.
"""
pass
| gpl-3.0 |
ucare-uchicago/hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/resources/OwnerParam.java | 1404 | /**
* 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.hdfs.web.resources;
/** Owner parameter. */
public class OwnerParam extends StringParam {
/** Parameter name. */
public static final String NAME = "owner";
/** Default parameter value. */
public static final String DEFAULT = "";
private static final Domain DOMAIN = new Domain(NAME, null);
/**
* Constructor.
* @param str a string representation of the parameter value.
*/
public OwnerParam(final String str) {
super(DOMAIN, str == null || str.equals(DEFAULT)? null: str);
}
@Override
public String getName() {
return NAME;
}
}
| apache-2.0 |
savaki/gocd | tools/jruby-1.7.11/lib/ruby/gems/shared/gems/buildr-1.4.22-java/spec/java/doc_spec.rb | 1899 | # 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.
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helpers'))
describe 'Javadoc' do
def sources
@sources ||= (1..3).map { |i| "Test#{i}" }.
each { |name| write "src/main/java/foo/#{name}.java", "package foo; public class #{name}{}" }.
map { |name| "src/main/java/foo/#{name}.java" }
end
it 'should pick -windowtitle from project name by default' do
define 'foo' do
compile.using(:javac)
define 'bar' do
compile.using(:javac)
end
end
project('foo').doc.options[:windowtitle].should eql('foo')
project('foo:bar').doc.options[:windowtitle].should eql('foo:bar')
end
it 'should pick -windowtitle from project description by default, if available' do
desc 'My App'
define 'foo' do
compile.using(:javac)
end
project('foo').doc.options[:windowtitle].should eql('My App')
end
it 'should not override explicit :windowtitle' do
define 'foo' do
compile.using(:javac)
doc.using :windowtitle => 'explicit'
end
project('foo').doc.options[:windowtitle].should eql('explicit')
end
end
| apache-2.0 |
krk/coreclr | tests/src/JIT/HardwareIntrinsics/General/Vector256_1/As.SByte.cs | 11636 | // 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void AsSByte()
{
var test = new VectorAs__AsSByte();
// Validates basic functionality works
test.RunBasicScenario();
// Validates basic functionality works using the generic form, rather than the type-specific form of the method
test.RunGenericScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorAs__AsSByte
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Vector256<SByte> value;
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<byte> byteResult = value.AsByte();
ValidateResult(byteResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<double> doubleResult = value.AsDouble();
ValidateResult(doubleResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<short> shortResult = value.AsInt16();
ValidateResult(shortResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<int> intResult = value.AsInt32();
ValidateResult(intResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<long> longResult = value.AsInt64();
ValidateResult(longResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<sbyte> sbyteResult = value.AsSByte();
ValidateResult(sbyteResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<float> floatResult = value.AsSingle();
ValidateResult(floatResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<ushort> ushortResult = value.AsUInt16();
ValidateResult(ushortResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<uint> uintResult = value.AsUInt32();
ValidateResult(uintResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<ulong> ulongResult = value.AsUInt64();
ValidateResult(ulongResult, value);
}
public void RunGenericScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario));
Vector256<SByte> value;
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<byte> byteResult = value.As<SByte, byte>();
ValidateResult(byteResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<double> doubleResult = value.As<SByte, double>();
ValidateResult(doubleResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<short> shortResult = value.As<SByte, short>();
ValidateResult(shortResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<int> intResult = value.As<SByte, int>();
ValidateResult(intResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<long> longResult = value.As<SByte, long>();
ValidateResult(longResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<sbyte> sbyteResult = value.As<SByte, sbyte>();
ValidateResult(sbyteResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<float> floatResult = value.As<SByte, float>();
ValidateResult(floatResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<ushort> ushortResult = value.As<SByte, ushort>();
ValidateResult(ushortResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<uint> uintResult = value.As<SByte, uint>();
ValidateResult(uintResult, value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
Vector256<ulong> ulongResult = value.As<SByte, ulong>();
ValidateResult(ulongResult, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Vector256<SByte> value;
value = Vector256.Create(TestLibrary.Generator.GetSByte());
object byteResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsByte))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<byte>)(byteResult), value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
object doubleResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsDouble))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<double>)(doubleResult), value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
object shortResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsInt16))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<short>)(shortResult), value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
object intResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsInt32))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<int>)(intResult), value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
object longResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsInt64))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<long>)(longResult), value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
object sbyteResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsSByte))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<sbyte>)(sbyteResult), value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
object floatResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsSingle))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<float>)(floatResult), value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
object ushortResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsUInt16))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<ushort>)(ushortResult), value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
object uintResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsUInt32))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<uint>)(uintResult), value);
value = Vector256.Create(TestLibrary.Generator.GetSByte());
object ulongResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsUInt64))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<ulong>)(ulongResult), value);
}
private void ValidateResult<T>(Vector256<T> result, Vector256<SByte> value, [CallerMemberName] string method = "")
where T : struct
{
SByte[] resultElements = new SByte[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result);
SByte[] valueElements = new SByte[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref valueElements[0]), value);
ValidateResult(resultElements, valueElements, typeof(T), method);
}
private void ValidateResult(SByte[] resultElements, SByte[] valueElements, Type targetType, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < ElementCount; i++)
{
if (resultElements[i] != valueElements[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte>.As{targetType.Name}: {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| mit |
XieXianbin/openjdk | jaxp/src/com/sun/org/apache/xpath/internal/axes/SubContextList.java | 1593 | /*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: SubContextList.java,v 1.1.2.1 2005/08/01 01:30:28 jeffsuttor Exp $
*/
package com.sun.org.apache.xpath.internal.axes;
import com.sun.org.apache.xpath.internal.XPathContext;
/**
* A class that implements this interface is a sub context node list, meaning it
* is a node list for a location path step for a predicate.
* @xsl.usage advanced
*/
public interface SubContextList
{
/**
* Get the number of nodes in the node list, which, in the XSLT 1 based
* counting system, is the last index position.
*
*
* @param xctxt The XPath runtime context.
*
* @return the number of nodes in the node list.
*/
public int getLastPos(XPathContext xctxt);
/**
* Get the current sub-context position.
*
* @param xctxt The XPath runtime context.
*
* @return The position of the current node in the list.
*/
public int getProximityPosition(XPathContext xctxt);
}
| gpl-2.0 |
ftomassetti/intellij-community | plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/FxmlReferencesContributor.java | 12533 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.javaFX.fxml.refs;
import com.intellij.openapi.util.TextRange;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.patterns.XmlAttributeValuePattern;
import com.intellij.patterns.XmlPatterns;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.JavaClassReferenceProvider;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlProcessingInstruction;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xml.XmlElementDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.javaFX.fxml.FxmlConstants;
import org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory;
import org.jetbrains.plugins.javaFX.fxml.JavaFxPsiUtil;
import static com.intellij.patterns.PlatformPatterns.virtualFile;
import static com.intellij.patterns.StandardPatterns.string;
/**
* User: anna
* Date: 1/14/13
*/
public class FxmlReferencesContributor extends PsiReferenceContributor {
public static final JavaClassReferenceProvider CLASS_REFERENCE_PROVIDER = new JavaClassReferenceProvider();
@Override
public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
final XmlAttributeValuePattern attributeValueInFxml = XmlPatterns.xmlAttributeValue().inVirtualFile(
virtualFile().withExtension(JavaFxFileTypeFactory.FXML_EXTENSION));
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withParent(XmlPatterns.xmlAttribute().withName(FxmlConstants.FX_CONTROLLER))
.and(attributeValueInFxml),
CLASS_REFERENCE_PROVIDER);
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue()
.withParent(XmlPatterns.xmlAttribute().withName("type")
.withParent(XmlPatterns.xmlTag().withName(FxmlConstants.FX_ROOT)))
.and(attributeValueInFxml),
new MyJavaClassReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlTag().inVirtualFile(virtualFile().withExtension(JavaFxFileTypeFactory.FXML_EXTENSION)),
new MyJavaClassReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withParent(XmlPatterns.xmlAttribute().withName(FxmlConstants.FX_ID))
.and(attributeValueInFxml),
new JavaFxFieldIdReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withParent(XmlPatterns.xmlAttribute().withName(FxmlConstants.FX_ELEMENT_SOURCE)
.withParent(XmlPatterns.xmlTag()
.withName(FxmlConstants.FX_INCLUDE)))
.and(attributeValueInFxml),
new JavaFxSourceReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withParent(XmlPatterns.xmlAttribute().withName(FxmlConstants.FX_ELEMENT_SOURCE)
.withParent(XmlPatterns.xmlTag()
.withName(FxmlConstants.FX_SCRIPT)))
.and(attributeValueInFxml),
new JavaFxSourceReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withParent(XmlPatterns.xmlAttribute().withName(FxmlConstants.FX_ELEMENT_SOURCE)
.withParent(XmlPatterns.xmlTag()
.withName(string().oneOf(FxmlConstants.FX_REFERENCE, FxmlConstants.FX_COPY))))
.and(attributeValueInFxml),
new JavaFxComponentIdReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withParent(XmlPatterns.xmlAttribute().withName(FxmlConstants.FX_FACTORY))
.and(attributeValueInFxml),
new JavaFxFactoryReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withValue(string().startsWith("#"))
.and(attributeValueInFxml),
new JavaFxEventHandlerReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withValue(string().startsWith("@")).and(attributeValueInFxml),
new JavaFxLocationReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withValue(string().startsWith("$")).and(attributeValueInFxml),
new JavaFxComponentIdReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withParent(XmlPatterns.xmlAttribute().withName("url")).and(attributeValueInFxml),
new JavaFxLocationReferenceProvider(false, "png"));
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withParent(XmlPatterns.xmlAttribute().withName(FxmlConstants.STYLESHEETS)).and(attributeValueInFxml),
new JavaFxLocationReferenceProvider(true, "css"));
registrar.registerReferenceProvider(PlatformPatterns.psiElement(XmlProcessingInstruction.class).inVirtualFile(virtualFile().withExtension(JavaFxFileTypeFactory.FXML_EXTENSION)),
new ImportReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().and(attributeValueInFxml),
new JavaFxColorReferenceProvider());
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue()
.withParent(XmlPatterns.xmlAttribute().withName(FxmlConstants.FX_VALUE)
.withParent(XmlPatterns.xmlTag().withParent(XmlPatterns.xmlTag().withName(FxmlConstants.STYLESHEETS))))
.and(attributeValueInFxml),
new JavaFxLocationReferenceProvider(true, "css"));
}
private static class MyJavaClassReferenceProvider extends JavaClassReferenceProvider {
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element) {
String name = element instanceof XmlAttributeValue ? ((XmlAttributeValue)element).getValue()
: ((XmlTag)element).getName();
return getReferencesByString(name, element, 1);
}
@NotNull
@Override
public PsiReference[] getReferencesByString(String str,
@NotNull final PsiElement position,
int offsetInPosition) {
if (str.length() == 0) return PsiReference.EMPTY_ARRAY;
final PsiReference[] references = super.getReferencesByString(str, position, offsetInPosition);
final int offset = position instanceof XmlTag ? 1 : 0;
if (references.length <= offset) return PsiReference.EMPTY_ARRAY;
final PsiReference[] results = new PsiReference[references.length - offset];
for (int i = 0; i < results.length; i++) {
results[i] = new JavaClassReferenceWrapper(references[i], position);
}
return results;
}
private static class JavaClassReferenceWrapper implements PsiReference {
private final PsiReference myReference;
private final PsiElement myPosition;
public JavaClassReferenceWrapper(PsiReference reference, PsiElement position) {
myReference = reference;
myPosition = position;
}
@Override
public PsiElement getElement() {
return myReference.getElement();
}
@Override
public TextRange getRangeInElement() {
return myReference.getRangeInElement();
}
@Nullable
@Override
public PsiElement resolve() {
final PsiElement resolve = myReference.resolve();
if (resolve != null) {
return resolve;
}
return getReferencedClass();
}
private PsiElement getReferencedClass() {
if (myPosition instanceof XmlTag) {
final XmlElementDescriptor descriptor = ((XmlTag)myPosition).getDescriptor();
if (descriptor != null) {
final PsiElement declaration = descriptor.getDeclaration();
if (declaration instanceof PsiMethod &&
((PsiMethod)declaration).hasModifierProperty(PsiModifier.STATIC)) {
final PsiClass containingClass = ((PsiMethod)declaration).getContainingClass();
if (containingClass != null && myReference.getCanonicalText().equals(containingClass.getName())) {
return containingClass;
}
}
}
}
else if (myPosition instanceof XmlAttributeValue) {
return JavaFxPsiUtil.findPsiClass(((XmlAttributeValue)myPosition).getValue(), myPosition);
}
return null;
}
@NotNull
public String getCanonicalText() {
return myReference.getCanonicalText();
}
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
String oldText = getOldName();
final TextRange range = getRangeInElement();
final String newText =
oldText.substring(0, range.getStartOffset() - 1) + newElementName + oldText.substring(range.getEndOffset() - 1);
return setNewName(newText);
}
public PsiElement bindToElement(@NotNull PsiElement element)
throws IncorrectOperationException {
String oldText = getOldName();
final TextRange range = getRangeInElement();
final String newText = (element instanceof PsiPackage ? ((PsiPackage)element).getQualifiedName() : ((PsiClass)element).getName()) +
oldText.substring(range.getEndOffset() - 1);
return setNewName(newText);
}
private PsiElement setNewName(String newText) {
if (myPosition instanceof XmlTag) {
return ((XmlTag)myPosition).setName(newText);
}
else {
final XmlElementFactory xmlElementFactory = XmlElementFactory.getInstance(myPosition.getProject());
final XmlAttribute xmlAttribute = xmlElementFactory.createXmlAttribute("attributeName", newText);
final XmlAttributeValue valueElement = xmlAttribute.getValueElement();
assert valueElement != null;
return myPosition.replace(valueElement);
}
}
private String getOldName() {
return myPosition instanceof XmlTag ? ((XmlTag)myPosition).getName() : ((XmlAttributeValue)myPosition).getValue();
}
public boolean isReferenceTo(PsiElement element) {
return myReference.isReferenceTo(element) || getReferencedClass() == element;
}
@NotNull
public Object[] getVariants() {
return myReference.getVariants();
}
public boolean isSoft() {
return true;
}
}
}
}
| apache-2.0 |
girving/tensorflow | tensorflow/contrib/framework/python/ops/__init__.py | 1524 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A module containing TensorFlow ops whose API may change in the future."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# TODO(ptucker): Add these to tf.contrib.variables?
# pylint: disable=wildcard-import
from tensorflow.contrib.framework.python.ops.arg_scope import *
from tensorflow.contrib.framework.python.ops.checkpoint_ops import *
from tensorflow.contrib.framework.python.ops.critical_section_ops import *
from tensorflow.contrib.framework.python.ops.ops import *
from tensorflow.contrib.framework.python.ops.prettyprint_ops import *
from tensorflow.contrib.framework.python.ops.script_ops import *
from tensorflow.contrib.framework.python.ops.sort_ops import *
from tensorflow.contrib.framework.python.ops.variables import *
# pylint: enable=wildcard-import
| apache-2.0 |
joone/chromium-crosswalk | chrome/browser/supervised_user/legacy/supervised_user_pref_mapping_service.cc | 3180 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/supervised_user/legacy/supervised_user_pref_mapping_service.h"
#include "base/bind.h"
#include "base/prefs/pref_service.h"
#include "base/values.h"
#include "chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service.h"
#include "chrome/browser/supervised_user/supervised_user_constants.h"
#include "chrome/common/pref_names.h"
const int kNoAvatar = -1;
SupervisedUserPrefMappingService::SupervisedUserPrefMappingService(
PrefService* prefs,
SupervisedUserSharedSettingsService* shared_settings)
: prefs_(prefs),
shared_settings_(shared_settings),
supervised_user_id_(prefs->GetString(prefs::kSupervisedUserId)),
weak_ptr_factory_(this) {}
SupervisedUserPrefMappingService::~SupervisedUserPrefMappingService() {}
void SupervisedUserPrefMappingService::Init() {
subscription_ = shared_settings_->Subscribe(
base::Bind(&SupervisedUserPrefMappingService::OnSharedSettingChanged,
weak_ptr_factory_.GetWeakPtr()));
pref_change_registrar_.Init(prefs_);
pref_change_registrar_.Add(
prefs::kProfileAvatarIndex,
base::Bind(&SupervisedUserPrefMappingService::OnAvatarChanged,
weak_ptr_factory_.GetWeakPtr()));
// Check if we need to update the shared setting with the avatar index.
// Otherwise we update the user pref in case we missed a notification.
if (GetChromeAvatarIndex() == kNoAvatar) {
OnAvatarChanged();
} else {
OnSharedSettingChanged(supervised_user_id_,
supervised_users::kChromeAvatarIndex);
}
}
void SupervisedUserPrefMappingService::OnAvatarChanged() {
int new_avatar_index = prefs_->GetInteger(prefs::kProfileAvatarIndex);
if (new_avatar_index < 0)
return;
// First check if the avatar index is a new value.
if (GetChromeAvatarIndex() == new_avatar_index)
return;
// If yes, update the shared settings value.
shared_settings_->SetValue(supervised_user_id_,
supervised_users::kChromeAvatarIndex,
base::FundamentalValue(new_avatar_index));
}
void SupervisedUserPrefMappingService::OnSharedSettingChanged(
const std::string& su_id,
const std::string& key) {
DCHECK_EQ(su_id, supervised_user_id_);
if (key != supervised_users::kChromeAvatarIndex)
return;
const base::Value* value = shared_settings_->GetValue(su_id, key);
int avatar_index;
bool success = value->GetAsInteger(&avatar_index);
DCHECK(success);
prefs_->SetInteger(prefs::kProfileAvatarIndex, avatar_index);
}
void SupervisedUserPrefMappingService::Shutdown() {
subscription_.reset();
}
int SupervisedUserPrefMappingService::GetChromeAvatarIndex() {
const base::Value* value = shared_settings_->GetValue(
supervised_user_id_, supervised_users::kChromeAvatarIndex);
if (!value)
return kNoAvatar;
int current_avatar_index;
bool success = value->GetAsInteger(¤t_avatar_index);
DCHECK(success);
return current_avatar_index;
}
| bsd-3-clause |
HKMOpen/actor-platform | actor-apps/core/src/main/java/im/actor/core/api/rpc/ResponseSendAuthCodeObsolete.java | 1876 | package im.actor.core.api.rpc;
/*
* Generated by the Actor API Scheme generator. DO NOT EDIT!
*/
import im.actor.runtime.bser.*;
import im.actor.runtime.collections.*;
import static im.actor.runtime.bser.Utils.*;
import im.actor.core.network.parser.*;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import com.google.j2objc.annotations.ObjectiveCName;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import im.actor.core.api.*;
public class ResponseSendAuthCodeObsolete extends Response {
public static final int HEADER = 0x2;
public static ResponseSendAuthCodeObsolete fromBytes(byte[] data) throws IOException {
return Bser.parse(new ResponseSendAuthCodeObsolete(), data);
}
private String smsHash;
private boolean isRegistered;
public ResponseSendAuthCodeObsolete(@NotNull String smsHash, boolean isRegistered) {
this.smsHash = smsHash;
this.isRegistered = isRegistered;
}
public ResponseSendAuthCodeObsolete() {
}
@NotNull
public String getSmsHash() {
return this.smsHash;
}
public boolean isRegistered() {
return this.isRegistered;
}
@Override
public void parse(BserValues values) throws IOException {
this.smsHash = values.getString(1);
this.isRegistered = values.getBool(2);
}
@Override
public void serialize(BserWriter writer) throws IOException {
if (this.smsHash == null) {
throw new IOException();
}
writer.writeString(1, this.smsHash);
writer.writeBool(2, this.isRegistered);
}
@Override
public String toString() {
String res = "tuple SendAuthCodeObsolete{";
res += "}";
return res;
}
@Override
public int getHeaderKey() {
return HEADER;
}
}
| mit |
froala/cdnjs | ajax/libs/raven.js/3.5.1/plugins/ember.js | 2043 | /*! Raven.js 3.5.1 (bef9fa7) | github.com/getsentry/raven-js */
/*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright 2016 Matt Robenolt and other contributors
* Released under the BSD license
* https://github.com/getsentry/raven-js/blob/master/LICENSE
*
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g=(g.Raven||(g.Raven = {}));g=(g.Plugins||(g.Plugins = {}));g.Ember = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Ember.js plugin
*
* Patches event handler callbacks and ajax callbacks.
*/
'use strict';
function emberPlugin(Raven, Ember) {
Ember = Ember || window.Ember;
// quit if Ember isn't on the page
if (!Ember) return;
var _oldOnError = Ember.onerror;
Ember.onerror = function EmberOnError(error) {
Raven.captureException(error);
if (typeof _oldOnError === 'function') {
_oldOnError.call(this, error);
}
};
Ember.RSVP.on('error', function (reason) {
if (reason instanceof Error) {
Raven.captureException(reason, {extra: {context: 'Unhandled Promise error detected'}});
} else {
Raven.captureMessage('Unhandled Promise error detected', {extra: {reason: reason}});
}
});
}
module.exports = emberPlugin;
},{}]},{},[1])(1)
}); | mit |
risatya/smartlogicpro | vendor/laravel/framework/src/Illuminate/Foundation/MigrationPublisher.php | 2657 | <?php namespace Illuminate\Foundation;
use Carbon\Carbon;
use Illuminate\Filesystem\Filesystem;
class MigrationPublisher {
/**
* A cache of migrations at a given destination.
*
* @var array
*/
protected $existing = array();
/**
* Create a new migration publisher instance.
*
* @param \Illuminate\Filesystem\Filesystem $files
* @return void
*/
public function __construct(Filesystem $files)
{
$this->files = $files;
}
/**
* Publish the given package's migrations.
*
* @param string $source
* @param string $destination
* @return array
*/
public function publish($source, $destination)
{
$add = 0;
$published = array();
foreach ($this->getFreshMigrations($source, $destination) as $file)
{
$add++;
$newName = $this->getNewMigrationName($file, $add);
$this->files->copy(
$file, $newName = $destination.'/'.$newName
);
$published[] = $newName;
}
return $published;
}
/**
* Get the fresh migrations for the source.
*
* @param string $source
* @param string $destination
* @return array
*/
protected function getFreshMigrations($source, $destination)
{
$me = $this;
return array_filter($this->getPackageMigrations($source), function($file) use ($me, $destination)
{
return ! $me->migrationExists($file, $destination);
});
}
/**
* Determine if the migration is already published.
*
* @param string $migration
* @return bool
*/
public function migrationExists($migration, $destination)
{
$existing = $this->getExistingMigrationNames($destination);
return in_array(substr(basename($migration), 18), $existing);
}
/**
* Get the existing migration names from the destination.
*
* @param string $destination
* @return array
*/
public function getExistingMigrationNames($destination)
{
if (isset($this->existing[$destination])) return $this->existing[$destination];
return $this->existing[$destination] = array_map(function($file)
{
return substr(basename($file), 18);
}, $this->files->files($destination));
}
/**
* Get the file list from the source directory.
*
* @param string $source
* @return array
*/
protected function getPackageMigrations($source)
{
$files = array_filter($this->files->files($source), function($file)
{
return ! starts_with($file, '.');
});
sort($files);
return $files;
}
/**
* Get the new migration name.
*
* @param string $file
* @param int $add
* @return string
*/
protected function getNewMigrationName($file, $add)
{
return Carbon::now()->addSeconds($add)->format('Y_m_d_His').substr(basename($file), 17);
}
}
| mit |
mknecht/learn-geo | node_modules/browserify/node_modules/buffer/test/base64-newline.js | 1059 | var B = require('../').Buffer
var test = require('tape')
var data = [
'',
''
]
test('base64 strings with newlines / invalid charaters', function (t) {
// newline in utf8 -- should not be an issue
t.equal(
new B('LS0tCnRpdGxlOiBUaHJlZSBkYXNoZXMgbWFya3MgdGhlIHNwb3QKdGFnczoK', 'base64').toString('utf8'),
'---\ntitle: Three dashes marks the spot\ntags:\n'
)
// newline in base64 -- should get stripped
t.equal(
new B('LS0tCnRpdGxlOiBUaHJlZSBkYXNoZXMgbWFya3MgdGhlIHNwb3QKdGFnczoK\nICAtIHlhbWwKICAtIGZyb250LW1hdHRlcgogIC0gZGFzaGVzCmV4cGFuZWQt', 'base64').toString('utf8'),
'---\ntitle: Three dashes marks the spot\ntags:\n - yaml\n - front-matter\n - dashes\nexpaned-'
)
// tab characters in base64 - should get stripped
t.equal(
new B('LS0tCnRpdGxlOiBUaHJlZSBkYXNoZXMgbWFya3MgdGhlIHNwb3QKdGFnczoK\t\t\t\tICAtIHlhbWwKICAtIGZyb250LW1hdHRlcgogIC0gZGFzaGVzCmV4cGFuZWQt', 'base64').toString('utf8'),
'---\ntitle: Three dashes marks the spot\ntags:\n - yaml\n - front-matter\n - dashes\nexpaned-'
)
t.end()
})
| mit |
EmptyChaos/dolphin | Externals/wxWidgets3/src/common/menucmn.cpp | 31521 | ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/menucmn.cpp
// Purpose: wxMenu and wxMenuBar methods common to all ports
// Author: Vadim Zeitlin
// Modified by:
// Created: 26.10.99
// Copyright: (c) wxWidgets team
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_MENUS
#ifndef WX_PRECOMP
#include "wx/intl.h"
#include "wx/log.h"
#include "wx/menu.h"
#include "wx/frame.h"
#endif
#include "wx/stockitem.h"
// ----------------------------------------------------------------------------
// template lists
// ----------------------------------------------------------------------------
#include "wx/listimpl.cpp"
WX_DEFINE_LIST(wxMenuList)
WX_DEFINE_LIST(wxMenuItemList)
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// XTI for wxMenu(Bar)
// ----------------------------------------------------------------------------
wxDEFINE_FLAGS( wxMenuStyle )
wxBEGIN_FLAGS( wxMenuStyle )
wxFLAGS_MEMBER(wxMENU_TEAROFF)
wxEND_FLAGS( wxMenuStyle )
wxIMPLEMENT_DYNAMIC_CLASS_XTI(wxMenu, wxEvtHandler, "wx/menu.h");
wxCOLLECTION_TYPE_INFO( wxMenuItem *, wxMenuItemList ) ;
#if wxUSE_EXTENDED_RTTI
template<> void wxCollectionToVariantArray( wxMenuItemList const &theList,
wxAnyList &value)
{
wxListCollectionToAnyList<wxMenuItemList::compatibility_iterator>( theList, value ) ;
}
#endif
wxBEGIN_PROPERTIES_TABLE(wxMenu)
wxEVENT_PROPERTY( Select, wxEVT_MENU, wxCommandEvent)
wxPROPERTY( Title, wxString, SetTitle, GetTitle, wxString(), \
0 /*flags*/, wxT("Helpstring"), wxT("group") )
wxREADONLY_PROPERTY_FLAGS( MenuStyle, wxMenuStyle, long, GetStyle, \
wxEMPTY_PARAMETER_VALUE, 0 /*flags*/, wxT("Helpstring"), \
wxT("group")) // style
wxPROPERTY_COLLECTION( MenuItems, wxMenuItemList, wxMenuItem*, Append, \
GetMenuItems, 0 /*flags*/, wxT("Helpstring"), wxT("group"))
wxEND_PROPERTIES_TABLE()
wxEMPTY_HANDLERS_TABLE(wxMenu)
wxDIRECT_CONSTRUCTOR_2( wxMenu, wxString, Title, long, MenuStyle )
wxDEFINE_FLAGS( wxMenuBarStyle )
wxBEGIN_FLAGS( wxMenuBarStyle )
wxFLAGS_MEMBER(wxMB_DOCKABLE)
wxEND_FLAGS( wxMenuBarStyle )
#if wxUSE_EXTENDED_RTTI
// the negative id would lead the window (its superclass !) to
// vetoe streaming out otherwise
bool wxMenuBarStreamingCallback( const wxObject *WXUNUSED(object), wxObjectWriter *,
wxObjectWriterCallback *, const wxStringToAnyHashMap & )
{
return true;
}
#endif
wxIMPLEMENT_DYNAMIC_CLASS_XTI_CALLBACK(wxMenuBar, wxWindow, "wx/menu.h", \
wxMenuBarStreamingCallback)
#if wxUSE_EXTENDED_RTTI
WX_DEFINE_LIST( wxMenuInfoHelperList )
wxIMPLEMENT_DYNAMIC_CLASS_XTI(wxMenuInfoHelper, wxObject, "wx/menu.h");
wxBEGIN_PROPERTIES_TABLE(wxMenuInfoHelper)
wxREADONLY_PROPERTY( Menu, wxMenu*, GetMenu, wxEMPTY_PARAMETER_VALUE, \
0 /*flags*/, wxT("Helpstring"), wxT("group"))
wxREADONLY_PROPERTY( Title, wxString, GetTitle, wxString(), \
0 /*flags*/, wxT("Helpstring"), wxT("group"))
wxEND_PROPERTIES_TABLE()
wxEMPTY_HANDLERS_TABLE(wxMenuInfoHelper)
wxCONSTRUCTOR_2( wxMenuInfoHelper, wxMenu*, Menu, wxString, Title )
wxCOLLECTION_TYPE_INFO( wxMenuInfoHelper *, wxMenuInfoHelperList ) ;
template<> void wxCollectionToVariantArray( wxMenuInfoHelperList const &theList,
wxAnyList &value)
{
wxListCollectionToAnyList<wxMenuInfoHelperList::compatibility_iterator>( theList, value ) ;
}
#endif
wxBEGIN_PROPERTIES_TABLE(wxMenuBar)
wxPROPERTY_COLLECTION( MenuInfos, wxMenuInfoHelperList, wxMenuInfoHelper*, AppendMenuInfo, \
GetMenuInfos, 0 /*flags*/, wxT("Helpstring"), wxT("group"))
wxEND_PROPERTIES_TABLE()
wxEMPTY_HANDLERS_TABLE(wxMenuBar)
wxCONSTRUCTOR_DUMMY( wxMenuBar )
#if wxUSE_EXTENDED_RTTI
const wxMenuInfoHelperList& wxMenuBarBase::GetMenuInfos() const
{
wxMenuInfoHelperList* list = const_cast< wxMenuInfoHelperList* > (& m_menuInfos);
WX_CLEAR_LIST( wxMenuInfoHelperList, *list);
for (size_t i = 0 ; i < GetMenuCount(); ++i)
{
wxMenuInfoHelper* info = new wxMenuInfoHelper();
info->Create( GetMenu(i), GetMenuLabel(i));
list->Append(info);
}
return m_menuInfos;
}
#endif
// ----------------------------------------------------------------------------
// XTI for wxMenuItem
// ----------------------------------------------------------------------------
#if wxUSE_EXTENDED_RTTI
bool wxMenuItemStreamingCallback( const wxObject *object, wxObjectWriter *,
wxObjectWriterCallback *, const wxStringToAnyHashMap & )
{
const wxMenuItem * mitem = wx_dynamic_cast(const wxMenuItem*, object);
if ( mitem->GetMenu() && !mitem->GetMenu()->GetTitle().empty() )
{
// we don't stream out the first two items for menus with a title,
// they will be reconstructed
if ( mitem->GetMenu()->FindItemByPosition(0) == mitem ||
mitem->GetMenu()->FindItemByPosition(1) == mitem )
return false;
}
return true;
}
#endif
wxBEGIN_ENUM( wxItemKind )
wxENUM_MEMBER( wxITEM_SEPARATOR )
wxENUM_MEMBER( wxITEM_NORMAL )
wxENUM_MEMBER( wxITEM_CHECK )
wxENUM_MEMBER( wxITEM_RADIO )
wxEND_ENUM( wxItemKind )
wxIMPLEMENT_DYNAMIC_CLASS_XTI_CALLBACK(wxMenuItem, wxObject, "wx/menuitem.h", \
wxMenuItemStreamingCallback)
wxBEGIN_PROPERTIES_TABLE(wxMenuItem)
wxPROPERTY( Parent, wxMenu*, SetMenu, GetMenu, wxEMPTY_PARAMETER_VALUE, \
0 /*flags*/, wxT("Helpstring"), wxT("group") )
wxPROPERTY( Id, int, SetId, GetId, wxEMPTY_PARAMETER_VALUE, \
0 /*flags*/, wxT("Helpstring"), wxT("group") )
wxPROPERTY( ItemLabel, wxString, SetItemLabel, GetItemLabel, wxString(), \
0 /*flags*/, wxT("Helpstring"), wxT("group") )
wxPROPERTY( Help, wxString, SetHelp, GetHelp, wxString(), \
0 /*flags*/, wxT("Helpstring"), wxT("group") )
wxREADONLY_PROPERTY( Kind, wxItemKind, GetKind, wxEMPTY_PARAMETER_VALUE, \
0 /*flags*/, wxT("Helpstring"), wxT("group") )
wxPROPERTY( SubMenu, wxMenu*, SetSubMenu, GetSubMenu, wxEMPTY_PARAMETER_VALUE, \
0 /*flags*/, wxT("Helpstring"), wxT("group") )
wxPROPERTY( Enabled, bool, Enable, IsEnabled, wxAny((bool)true), \
0 /*flags*/, wxT("Helpstring"), wxT("group") )
wxPROPERTY( Checked, bool, Check, IsChecked, wxAny((bool)false), \
0 /*flags*/, wxT("Helpstring"), wxT("group") )
wxPROPERTY( Checkable, bool, SetCheckable, IsCheckable, wxAny((bool)false), \
0 /*flags*/, wxT("Helpstring"), wxT("group") )
wxEND_PROPERTIES_TABLE()
wxEMPTY_HANDLERS_TABLE(wxMenuItem)
wxDIRECT_CONSTRUCTOR_6( wxMenuItem, wxMenu*, Parent, int, Id, wxString, \
Text, wxString, Help, wxItemKind, Kind, wxMenu*, SubMenu )
// ----------------------------------------------------------------------------
// wxMenuItemBase
// ----------------------------------------------------------------------------
wxMenuItemBase::wxMenuItemBase(wxMenu *parentMenu,
int itemid,
const wxString& text,
const wxString& help,
wxItemKind kind,
wxMenu *subMenu)
{
switch ( itemid )
{
case wxID_ANY:
m_id = wxWindow::NewControlId();
break;
case wxID_SEPARATOR:
m_id = wxID_SEPARATOR;
// there is a lot of existing code just doing Append(wxID_SEPARATOR)
// and it makes sense to omit the following optional parameters,
// including the kind one which doesn't default to wxITEM_SEPARATOR,
// of course, so override it here
kind = wxITEM_SEPARATOR;
break;
case wxID_NONE:
// (popup) menu titles in wxMSW use this ID to indicate that
// it's not a real menu item, so we don't want the check below to
// apply to it
m_id = itemid;
break;
default:
// ids are limited to 16 bits under MSW so portable code shouldn't
// use ids outside of this range (negative ids generated by wx are
// fine though)
wxASSERT_MSG( (itemid >= 0 && itemid < SHRT_MAX) ||
(itemid >= wxID_AUTO_LOWEST && itemid <= wxID_AUTO_HIGHEST),
wxS("invalid itemid value") );
m_id = itemid;
}
// notice that parentMenu can be NULL: the item can be attached to the menu
// later with SetMenu()
m_parentMenu = parentMenu;
m_subMenu = subMenu;
m_isEnabled = true;
m_isChecked = false;
m_kind = kind;
SetItemLabel(text);
SetHelp(help);
}
wxMenuItemBase::~wxMenuItemBase()
{
delete m_subMenu;
}
#if wxUSE_ACCEL
wxAcceleratorEntry *wxMenuItemBase::GetAccel() const
{
return wxAcceleratorEntry::Create(GetItemLabel());
}
void wxMenuItemBase::SetAccel(wxAcceleratorEntry *accel)
{
wxString text = m_text.BeforeFirst(wxT('\t'));
if ( accel )
{
text += wxT('\t');
text += accel->ToString();
}
SetItemLabel(text);
}
#endif // wxUSE_ACCEL
void wxMenuItemBase::SetItemLabel(const wxString& str)
{
m_text = str;
if ( m_text.empty() && !IsSeparator() )
{
wxASSERT_MSG( wxIsStockID(GetId()),
wxT("A non-stock menu item with an empty label?") );
m_text = wxGetStockLabel(GetId(), wxSTOCK_WITH_ACCELERATOR |
wxSTOCK_WITH_MNEMONIC);
}
}
void wxMenuItemBase::SetHelp(const wxString& str)
{
m_help = str;
if ( m_help.empty() && !IsSeparator() && wxIsStockID(GetId()) )
{
// get a stock help string
m_help = wxGetStockHelpString(GetId());
}
}
wxString wxMenuItemBase::GetLabelText(const wxString& text)
{
return wxStripMenuCodes(text);
}
#if WXWIN_COMPATIBILITY_2_8
wxString wxMenuItemBase::GetLabelFromText(const wxString& text)
{
return GetLabelText(text);
}
#endif
bool wxMenuBase::ms_locked = true;
// ----------------------------------------------------------------------------
// wxMenu ctor and dtor
// ----------------------------------------------------------------------------
void wxMenuBase::Init(long style)
{
m_menuBar = NULL;
m_menuParent = NULL;
m_invokingWindow = NULL;
m_style = style;
m_clientData = NULL;
m_eventHandler = this;
}
wxMenuBase::~wxMenuBase()
{
WX_CLEAR_LIST(wxMenuItemList, m_items);
}
// ----------------------------------------------------------------------------
// wxMenu item adding/removing
// ----------------------------------------------------------------------------
void wxMenuBase::AddSubMenu(wxMenu *submenu)
{
wxCHECK_RET( submenu, wxT("can't add a NULL submenu") );
submenu->SetParent((wxMenu *)this);
}
wxMenuItem* wxMenuBase::DoAppend(wxMenuItem *item)
{
wxCHECK_MSG( item, NULL, wxT("invalid item in wxMenu::Append()") );
m_items.Append(item);
item->SetMenu((wxMenu*)this);
if ( item->IsSubMenu() )
{
AddSubMenu(item->GetSubMenu());
}
return item;
}
wxMenuItem* wxMenuBase::Insert(size_t pos, wxMenuItem *item)
{
wxCHECK_MSG( item, NULL, wxT("invalid item in wxMenu::Insert") );
if ( pos == GetMenuItemCount() )
{
return DoAppend(item);
}
else
{
wxCHECK_MSG( pos < GetMenuItemCount(), NULL,
wxT("invalid index in wxMenu::Insert") );
return DoInsert(pos, item);
}
}
wxMenuItem* wxMenuBase::DoInsert(size_t pos, wxMenuItem *item)
{
wxCHECK_MSG( item, NULL, wxT("invalid item in wxMenu::Insert()") );
wxMenuItemList::compatibility_iterator node = m_items.Item(pos);
wxCHECK_MSG( node, NULL, wxT("invalid index in wxMenu::Insert()") );
m_items.Insert(node, item);
item->SetMenu((wxMenu*)this);
if ( item->IsSubMenu() )
{
AddSubMenu(item->GetSubMenu());
}
return item;
}
wxMenuItem *wxMenuBase::Remove(wxMenuItem *item)
{
wxCHECK_MSG( item, NULL, wxT("invalid item in wxMenu::Remove") );
wxMenuItemList::compatibility_iterator node = m_items.Find(item);
// if we get here, the item is valid or one of Remove() functions is broken
wxCHECK_MSG( node, NULL, wxT("removing item not in the menu?") );
// call DoRemove() before removing the item from the list of items as the
// existing code in port-specific implementation may rely on the item still
// being there (this is the case for at least wxMSW)
wxMenuItem* const item2 = DoRemove(item);
// we detach the item, but we do delete the list node (i.e. don't call
// DetachNode() here!)
m_items.Erase(node);
return item2;
}
wxMenuItem *wxMenuBase::DoRemove(wxMenuItem *item)
{
item->SetMenu(NULL);
wxMenu *submenu = item->GetSubMenu();
if ( submenu )
{
submenu->SetParent(NULL);
if ( submenu->IsAttached() )
submenu->Detach();
}
return item;
}
bool wxMenuBase::Delete(wxMenuItem *item)
{
wxCHECK_MSG( item, false, wxT("invalid item in wxMenu::Delete") );
return DoDelete(item);
}
bool wxMenuBase::DoDelete(wxMenuItem *item)
{
wxMenuItem *item2 = Remove(item);
wxCHECK_MSG( item2, false, wxT("failed to delete menu item") );
// don't delete the submenu
item2->SetSubMenu(NULL);
delete item2;
return true;
}
bool wxMenuBase::Destroy(wxMenuItem *item)
{
wxCHECK_MSG( item, false, wxT("invalid item in wxMenu::Destroy") );
return DoDestroy(item);
}
bool wxMenuBase::DoDestroy(wxMenuItem *item)
{
wxMenuItem *item2 = Remove(item);
wxCHECK_MSG( item2, false, wxT("failed to delete menu item") );
delete item2;
return true;
}
// ----------------------------------------------------------------------------
// wxMenu searching for items
// ----------------------------------------------------------------------------
// Finds the item id matching the given string, wxNOT_FOUND if not found.
int wxMenuBase::FindItem(const wxString& text) const
{
wxString label = wxMenuItem::GetLabelText(text);
for ( wxMenuItemList::compatibility_iterator node = m_items.GetFirst();
node;
node = node->GetNext() )
{
wxMenuItem *item = node->GetData();
if ( item->IsSubMenu() )
{
int rc = item->GetSubMenu()->FindItem(label);
if ( rc != wxNOT_FOUND )
return rc;
}
// we execute this code for submenus as well to alllow finding them by
// name just like the ordinary items
if ( !item->IsSeparator() )
{
if ( item->GetItemLabelText() == label )
return item->GetId();
}
}
return wxNOT_FOUND;
}
// recursive search for item by id
wxMenuItem *wxMenuBase::FindItem(int itemId, wxMenu **itemMenu) const
{
if ( itemMenu )
*itemMenu = NULL;
wxMenuItem *item = NULL;
for ( wxMenuItemList::compatibility_iterator node = m_items.GetFirst();
node && !item;
node = node->GetNext() )
{
item = node->GetData();
if ( item->GetId() == itemId )
{
if ( itemMenu )
*itemMenu = (wxMenu *)this;
}
else if ( item->IsSubMenu() )
{
item = item->GetSubMenu()->FindItem(itemId, itemMenu);
}
else
{
// don't exit the loop
item = NULL;
}
}
return item;
}
// non recursive search
wxMenuItem *wxMenuBase::FindChildItem(int itemid, size_t *ppos) const
{
wxMenuItem *item = NULL;
wxMenuItemList::compatibility_iterator node = GetMenuItems().GetFirst();
size_t pos;
for ( pos = 0; node; pos++ )
{
if ( node->GetData()->GetId() == itemid )
{
item = node->GetData();
break;
}
node = node->GetNext();
}
if ( ppos )
{
*ppos = item ? pos : (size_t)wxNOT_FOUND;
}
return item;
}
// find by position
wxMenuItem* wxMenuBase::FindItemByPosition(size_t position) const
{
wxCHECK_MSG( position < m_items.GetCount(), NULL,
wxT("wxMenu::FindItemByPosition(): invalid menu index") );
return m_items.Item( position )->GetData();
}
// ----------------------------------------------------------------------------
// wxMenu helpers used by derived classes
// ----------------------------------------------------------------------------
void wxMenuBase::UpdateUI(wxEvtHandler* source)
{
wxWindow * const win = GetWindow();
if ( !source && win )
source = win->GetEventHandler();
if ( !source )
source = GetEventHandler();
if ( !source )
source = this;
wxMenuItemList::compatibility_iterator node = GetMenuItems().GetFirst();
while ( node )
{
wxMenuItem* item = node->GetData();
if ( !item->IsSeparator() )
{
wxWindowID itemid = item->GetId();
wxUpdateUIEvent event(itemid);
event.SetEventObject( this );
if ( source->ProcessEvent(event) )
{
// if anything changed, update the changed attribute
if (event.GetSetText())
SetLabel(itemid, event.GetText());
if (event.GetSetChecked())
Check(itemid, event.GetChecked());
if (event.GetSetEnabled())
Enable(itemid, event.GetEnabled());
}
// recurse to the submenus
if ( item->GetSubMenu() )
item->GetSubMenu()->UpdateUI(source);
}
//else: item is a separator (which doesn't process update UI events)
node = node->GetNext();
}
}
bool wxMenuBase::SendEvent(int itemid, int checked)
{
wxCommandEvent event(wxEVT_MENU, itemid);
event.SetInt(checked);
return DoProcessEvent(this, event, GetWindow());
}
/* static */
bool wxMenuBase::DoProcessEvent(wxMenuBase* menu, wxEvent& event, wxWindow* win)
{
event.SetEventObject(menu);
if ( menu )
{
wxMenuBar* const mb = menu->GetMenuBar();
// Try the menu's event handler first
wxEvtHandler *handler = menu->GetEventHandler();
if ( handler )
{
// Indicate to the event processing code that we're going to pass
// this event to another handler if it's not processed here to
// prevent it from passing the event to wxTheApp: this will be done
// below if we do have the associated window.
if ( win || mb )
event.SetWillBeProcessedAgain();
if ( handler->SafelyProcessEvent(event) )
return true;
}
// If this menu is part of the menu bar, try the event there. this
if ( mb )
{
if ( mb->HandleWindowEvent(event) )
return true;
// If this already propagated it upwards to the window containing
// the menu bar, we don't have to handle it in this window again
// below.
if ( event.ShouldPropagate() )
return false;
}
}
// Try the window the menu was popped up from.
if ( win )
return win->HandleWindowEvent(event);
// Not processed.
return false;
}
/* static */
bool
wxMenuBase::ProcessMenuEvent(wxMenu* menu, wxMenuEvent& event, wxWindow* win)
{
// Try to process the event in the usual places first.
if ( DoProcessEvent(menu, event, win) )
return true;
// But the menu events should also reach the TLW parent if they were not
// processed before so, as it's not a command event and hence doesn't
// bubble up by default, send it there explicitly if not done yet.
wxWindow* const tlw = wxGetTopLevelParent(win);
if ( tlw != win && tlw->HandleWindowEvent(event) )
return true;
return false;
}
// ----------------------------------------------------------------------------
// wxMenu attaching/detaching to/from menu bar
// ----------------------------------------------------------------------------
wxMenuBar* wxMenuBase::GetMenuBar() const
{
if(GetParent())
return GetParent()->GetMenuBar();
return m_menuBar;
}
void wxMenuBase::Attach(wxMenuBarBase *menubar)
{
// use Detach() instead!
wxASSERT_MSG( menubar, wxT("menu can't be attached to NULL menubar") );
// use IsAttached() to prevent this from happening
wxASSERT_MSG( !m_menuBar, wxT("attaching menu twice?") );
m_menuBar = (wxMenuBar *)menubar;
}
void wxMenuBase::Detach()
{
// use IsAttached() to prevent this from happening
wxASSERT_MSG( m_menuBar, wxT("detaching unattached menu?") );
m_menuBar = NULL;
}
// ----------------------------------------------------------------------------
// wxMenu invoking window handling
// ----------------------------------------------------------------------------
void wxMenuBase::SetInvokingWindow(wxWindow *win)
{
wxASSERT_MSG( !GetParent(),
"should only be called for top level popup menus" );
wxASSERT_MSG( !IsAttached(),
"menus attached to menu bar can't have invoking window" );
m_invokingWindow = win;
}
wxWindow *wxMenuBase::GetWindow() const
{
// only the top level menus have non-NULL invoking window or a pointer to
// the menu bar so recurse upwards until we find it
const wxMenuBase *menu = this;
while ( menu->GetParent() )
{
menu = menu->GetParent();
}
return menu->GetMenuBar() ? menu->GetMenuBar()->GetFrame()
: menu->GetInvokingWindow();
}
// ----------------------------------------------------------------------------
// wxMenu functions forwarded to wxMenuItem
// ----------------------------------------------------------------------------
void wxMenuBase::Enable( int itemid, bool enable )
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_RET( item, wxT("wxMenu::Enable: no such item") );
item->Enable(enable);
}
bool wxMenuBase::IsEnabled( int itemid ) const
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_MSG( item, false, wxT("wxMenu::IsEnabled: no such item") );
return item->IsEnabled();
}
void wxMenuBase::Check( int itemid, bool enable )
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_RET( item, wxT("wxMenu::Check: no such item") );
item->Check(enable);
}
bool wxMenuBase::IsChecked( int itemid ) const
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_MSG( item, false, wxT("wxMenu::IsChecked: no such item") );
return item->IsChecked();
}
void wxMenuBase::SetLabel( int itemid, const wxString &label )
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_RET( item, wxT("wxMenu::SetLabel: no such item") );
item->SetItemLabel(label);
}
wxString wxMenuBase::GetLabel( int itemid ) const
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_MSG( item, wxEmptyString, wxT("wxMenu::GetLabel: no such item") );
return item->GetItemLabel();
}
void wxMenuBase::SetHelpString( int itemid, const wxString& helpString )
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_RET( item, wxT("wxMenu::SetHelpString: no such item") );
item->SetHelp( helpString );
}
wxString wxMenuBase::GetHelpString( int itemid ) const
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_MSG( item, wxEmptyString, wxT("wxMenu::GetHelpString: no such item") );
return item->GetHelp();
}
// ----------------------------------------------------------------------------
// wxMenuBarBase ctor and dtor
// ----------------------------------------------------------------------------
wxMenuBarBase::wxMenuBarBase()
{
// not attached yet
m_menuBarFrame = NULL;
}
wxMenuBarBase::~wxMenuBarBase()
{
WX_CLEAR_LIST(wxMenuList, m_menus);
}
// ----------------------------------------------------------------------------
// wxMenuBar item access: the base class versions manage m_menus list, the
// derived class should reflect the changes in the real menubar
// ----------------------------------------------------------------------------
wxMenu *wxMenuBarBase::GetMenu(size_t pos) const
{
wxMenuList::compatibility_iterator node = m_menus.Item(pos);
wxCHECK_MSG( node, NULL, wxT("bad index in wxMenuBar::GetMenu()") );
return node->GetData();
}
bool wxMenuBarBase::Append(wxMenu *menu, const wxString& title)
{
wxCHECK_MSG( menu, false, wxT("can't append NULL menu") );
wxCHECK_MSG( !title.empty(), false, wxT("can't append menu with empty title") );
m_menus.Append(menu);
menu->Attach(this);
return true;
}
bool wxMenuBarBase::Insert(size_t pos, wxMenu *menu,
const wxString& title)
{
if ( pos == m_menus.GetCount() )
{
return wxMenuBarBase::Append(menu, title);
}
else // not at the end
{
wxCHECK_MSG( menu, false, wxT("can't insert NULL menu") );
wxMenuList::compatibility_iterator node = m_menus.Item(pos);
wxCHECK_MSG( node, false, wxT("bad index in wxMenuBar::Insert()") );
m_menus.Insert(node, menu);
menu->Attach(this);
return true;
}
}
wxMenu *wxMenuBarBase::Replace(size_t pos, wxMenu *menu,
const wxString& WXUNUSED(title))
{
wxCHECK_MSG( menu, NULL, wxT("can't insert NULL menu") );
wxMenuList::compatibility_iterator node = m_menus.Item(pos);
wxCHECK_MSG( node, NULL, wxT("bad index in wxMenuBar::Replace()") );
wxMenu *menuOld = node->GetData();
node->SetData(menu);
menu->Attach(this);
menuOld->Detach();
return menuOld;
}
wxMenu *wxMenuBarBase::Remove(size_t pos)
{
wxMenuList::compatibility_iterator node = m_menus.Item(pos);
wxCHECK_MSG( node, NULL, wxT("bad index in wxMenuBar::Remove()") );
wxMenu *menu = node->GetData();
m_menus.Erase(node);
menu->Detach();
return menu;
}
int wxMenuBarBase::FindMenu(const wxString& title) const
{
wxString label = wxMenuItem::GetLabelText(title);
size_t count = GetMenuCount();
for ( size_t i = 0; i < count; i++ )
{
wxString title2 = GetMenuLabel(i);
if ( (title2 == title) ||
(wxMenuItem::GetLabelText(title2) == label) )
{
// found
return (int)i;
}
}
return wxNOT_FOUND;
}
// ----------------------------------------------------------------------------
// wxMenuBar attaching/detaching to/from the frame
// ----------------------------------------------------------------------------
void wxMenuBarBase::Attach(wxFrame *frame)
{
wxASSERT_MSG( !IsAttached(), wxT("menubar already attached!") );
SetParent(frame);
m_menuBarFrame = frame;
}
void wxMenuBarBase::Detach()
{
wxASSERT_MSG( IsAttached(), wxT("detaching unattached menubar") );
m_menuBarFrame = NULL;
SetParent(NULL);
}
// ----------------------------------------------------------------------------
// wxMenuBar searching for items
// ----------------------------------------------------------------------------
wxMenuItem *wxMenuBarBase::FindItem(int itemid, wxMenu **menu) const
{
if ( menu )
*menu = NULL;
wxMenuItem *item = NULL;
size_t count = GetMenuCount(), i;
wxMenuList::const_iterator it;
for ( i = 0, it = m_menus.begin(); !item && (i < count); i++, it++ )
{
item = (*it)->FindItem(itemid, menu);
}
return item;
}
int wxMenuBarBase::FindMenuItem(const wxString& menu, const wxString& item) const
{
wxString label = wxMenuItem::GetLabelText(menu);
int i = 0;
wxMenuList::compatibility_iterator node;
for ( node = m_menus.GetFirst(); node; node = node->GetNext(), i++ )
{
if ( label == wxMenuItem::GetLabelText(GetMenuLabel(i)) )
return node->GetData()->FindItem(item);
}
return wxNOT_FOUND;
}
// ---------------------------------------------------------------------------
// wxMenuBar functions forwarded to wxMenuItem
// ---------------------------------------------------------------------------
void wxMenuBarBase::Enable(int itemid, bool enable)
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_RET( item, wxT("attempt to enable an item which doesn't exist") );
item->Enable(enable);
}
void wxMenuBarBase::Check(int itemid, bool check)
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_RET( item, wxT("attempt to check an item which doesn't exist") );
wxCHECK_RET( item->IsCheckable(), wxT("attempt to check an uncheckable item") );
item->Check(check);
}
bool wxMenuBarBase::IsChecked(int itemid) const
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_MSG( item, false, wxT("wxMenuBar::IsChecked(): no such item") );
return item->IsChecked();
}
bool wxMenuBarBase::IsEnabled(int itemid) const
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_MSG( item, false, wxT("wxMenuBar::IsEnabled(): no such item") );
return item->IsEnabled();
}
void wxMenuBarBase::SetLabel(int itemid, const wxString& label)
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_RET( item, wxT("wxMenuBar::SetLabel(): no such item") );
item->SetItemLabel(label);
}
wxString wxMenuBarBase::GetLabel(int itemid) const
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_MSG( item, wxEmptyString,
wxT("wxMenuBar::GetLabel(): no such item") );
return item->GetItemLabel();
}
void wxMenuBarBase::SetHelpString(int itemid, const wxString& helpString)
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_RET( item, wxT("wxMenuBar::SetHelpString(): no such item") );
item->SetHelp(helpString);
}
wxString wxMenuBarBase::GetHelpString(int itemid) const
{
wxMenuItem *item = FindItem(itemid);
wxCHECK_MSG( item, wxEmptyString,
wxT("wxMenuBar::GetHelpString(): no such item") );
return item->GetHelp();
}
void wxMenuBarBase::UpdateMenus()
{
wxMenu* menu;
int nCount = GetMenuCount();
for (int n = 0; n < nCount; n++)
{
menu = GetMenu( n );
if (menu != NULL)
menu->UpdateUI();
}
}
#if WXWIN_COMPATIBILITY_2_8
// get or change the label of the menu at given position
void wxMenuBarBase::SetLabelTop(size_t pos, const wxString& label)
{
SetMenuLabel(pos, label);
}
wxString wxMenuBarBase::GetLabelTop(size_t pos) const
{
return GetMenuLabelText(pos);
}
#endif
#endif // wxUSE_MENUS
| gpl-2.0 |
LeChuck42/or1k-gcc | libgo/go/path/filepath/path_unix.go | 805 | // Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd
package filepath
import "strings"
// IsAbs returns true if the path is absolute.
func IsAbs(path string) bool {
return strings.HasPrefix(path, "/")
}
// volumeNameLen returns length of the leading volume name on Windows.
// It returns 0 elsewhere.
func volumeNameLen(path string) int {
return 0
}
// HasPrefix exists for historical compatibility and should not be used.
func HasPrefix(p, prefix string) bool {
return strings.HasPrefix(p, prefix)
}
func splitList(path string) []string {
if path == "" {
return []string{}
}
return strings.Split(path, string(ListSeparator))
}
| gpl-2.0 |
davies0422/p1545661Experiment | node_modules/nano/tests/unit/design/view.js | 966 | // Licensed under the Apache License, Version 2.0 (the 'License'); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
'use strict';
var viewDesign = require('../../helpers/unit').unit([
'view',
'view'
]);
viewDesign('alice', 'by_id', {
keys: ['foobar', 'barfoo'],
'include_docs': true
}, {
body: '{"keys":["foobar","barfoo"]}',
headers: {
accept: 'application/json',
'content-type': 'application/json'
},
method: 'POST',
qs: {
'include_docs': true
},
uri: '/mock/_design/alice/_view/by_id'
});
| apache-2.0 |
mathspace/libcloud | libcloud/test/compute/test_vultr.py | 4153 | # 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 sys
import unittest
try:
import simplejson as json
except ImportError:
import json # NOQA
from libcloud.utils.py3 import httplib
from libcloud.compute.drivers.vultr import VultrNodeDriver
from libcloud.test import LibcloudTestCase, MockHttpTestCase
from libcloud.test.file_fixtures import ComputeFileFixtures
from libcloud.test.secrets import VULTR_PARAMS
# class VultrTests(unittest.TestCase, TestCaseMixin):
class VultrTests(LibcloudTestCase):
def setUp(self):
VultrNodeDriver.connectionCls.conn_classes = \
(VultrMockHttp, VultrMockHttp)
VultrMockHttp.type = None
self.driver = VultrNodeDriver(*VULTR_PARAMS)
def test_list_images_success(self):
images = self.driver.list_images()
self.assertTrue(len(images) >= 1)
image = images[0]
self.assertTrue(image.id is not None)
self.assertTrue(image.name is not None)
def test_list_sizes_success(self):
sizes = self.driver.list_sizes()
self.assertTrue(len(sizes) == 22)
size = sizes[0]
self.assertTrue(size.id is not None)
self.assertEqual(size.name, '512 MB RAM,160 GB SATA,1.00 TB BW')
self.assertEqual(size.ram, 512)
size = sizes[21]
self.assertTrue(size.id is not None)
self.assertEqual(size.name, '65536 MB RAM,800 GB SSD,9.00 TB BW')
self.assertEqual(size.ram, 65536)
def test_list_locations_success(self):
locations = self.driver.list_locations()
self.assertTrue(len(locations) >= 1)
location = locations[0]
self.assertEqual(location.id, '1')
self.assertEqual(location.name, 'New Jersey')
def test_list_nodes_success(self):
nodes = self.driver.list_nodes()
self.assertEqual(len(nodes), 2)
self.assertEqual(nodes[0].id, '1')
self.assertEqual(nodes[0].public_ips, ['108.61.206.153'])
def test_reboot_node_success(self):
node = self.driver.list_nodes()[0]
result = self.driver.reboot_node(node)
self.assertTrue(result)
def test_destroy_node_success(self):
node = self.driver.list_nodes()[0]
result = self.driver.destroy_node(node)
self.assertTrue(result)
class VultrMockHttp(MockHttpTestCase):
fixtures = ComputeFileFixtures('vultr')
def _v1_regions_list(self, method, url, body, headers):
body = self.fixtures.load('list_locations.json')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _v1_os_list(self, method, url, body, headers):
body = self.fixtures.load('list_images.json')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _v1_plans_list(self, method, url, body, headers):
body = self.fixtures.load('list_sizes.json')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _v1_server_list(self, method, url, body, headers):
body = self.fixtures.load('list_nodes.json')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _v1_server_destroy(self, method, url, body, headers):
return (httplib.OK, "", {}, httplib.responses[httplib.OK])
def _v1_server_reboot(self, method, url, body, headers):
return (httplib.OK, "", {}, httplib.responses[httplib.OK])
if __name__ == '__main__':
sys.exit(unittest.main())
| apache-2.0 |
kodabb/homebrew | Library/Homebrew/utils.rb | 15766 | require "pathname"
require "exceptions"
require "utils/json"
require "utils/inreplace"
require "utils/popen"
require "utils/fork"
require "utils/git"
require "open-uri"
class Tty
class << self
def tick
# necessary for 1.8.7 unicode handling since many installs are on 1.8.7
@tick ||= ["2714".hex].pack("U*")
end
def cross
# necessary for 1.8.7 unicode handling since many installs are on 1.8.7
@cross ||= ["2718".hex].pack("U*")
end
def strip_ansi(string)
string.gsub(/\033\[\d+(;\d+)*m/, "")
end
def blue
bold 34
end
def white
bold 39
end
def red
underline 31
end
def yellow
underline 33
end
def reset
escape 0
end
def em
underline 39
end
def green
bold 32
end
def gray
bold 30
end
def highlight
bold 39
end
def width
`/usr/bin/tput cols`.strip.to_i
end
def truncate(str)
str.to_s[0, width - 4]
end
private
def color(n)
escape "0;#{n}"
end
def bold(n)
escape "1;#{n}"
end
def underline(n)
escape "4;#{n}"
end
def escape(n)
"\033[#{n}m" if $stdout.tty?
end
end
end
def ohai(title, *sput)
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.blue}==>#{Tty.white} #{title}#{Tty.reset}"
puts sput
end
def oh1(title)
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.green}==>#{Tty.white} #{title}#{Tty.reset}"
end
# Print a warning (do this rarely)
def opoo(warning)
$stderr.puts "#{Tty.yellow}Warning#{Tty.reset}: #{warning}"
end
def onoe(error)
$stderr.puts "#{Tty.red}Error#{Tty.reset}: #{error}"
end
def ofail(error)
onoe error
Homebrew.failed = true
end
def odie(error)
onoe error
exit 1
end
def pretty_installed(f)
if !$stdout.tty?
"#{f}"
elsif ENV["HOMEBREW_NO_EMOJI"]
"#{Tty.highlight}#{Tty.green}#{f} (installed)#{Tty.reset}"
else
"#{Tty.highlight}#{f} #{Tty.green}#{Tty.tick}#{Tty.reset}"
end
end
def pretty_uninstalled(f)
if !$stdout.tty?
"#{f}"
elsif ENV["HOMEBREW_NO_EMOJI"]
"#{Tty.red}#{f} (uninstalled)#{Tty.reset}"
else
"#{f} #{Tty.red}#{Tty.cross}#{Tty.reset}"
end
end
def pretty_duration(s)
s = s.to_i
res = ""
if s > 59
m = s / 60
s %= 60
res = "#{m} minute#{plural m}"
return res if s == 0
res << " "
end
res + "#{s} second#{plural s}"
end
def plural(n, s = "s")
(n == 1) ? "" : s
end
def interactive_shell(f = nil)
unless f.nil?
ENV["HOMEBREW_DEBUG_PREFIX"] = f.prefix
ENV["HOMEBREW_DEBUG_INSTALL"] = f.full_name
end
if ENV["SHELL"].include?("zsh") && ENV["HOME"].start_with?(HOMEBREW_TEMP.resolved_path.to_s)
FileUtils.touch "#{ENV["HOME"]}/.zshrc"
end
Process.wait fork { exec ENV["SHELL"] }
if $?.success?
return
elsif $?.exited?
puts "Aborting due to non-zero exit status"
exit $?.exitstatus
else
raise $?.inspect
end
end
module Homebrew
def self._system(cmd, *args)
pid = fork do
yield if block_given?
args.collect!(&:to_s)
exec(cmd, *args) rescue nil
exit! 1 # never gets here unless exec failed
end
Process.wait(pid)
$?.success?
end
def self.system(cmd, *args)
puts "#{cmd} #{args*" "}" if ARGV.verbose?
_system(cmd, *args)
end
def self.git_origin
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git config --get remote.origin.url 2>/dev/null`.chuzzle }
end
def self.git_head
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git rev-parse --verify -q HEAD 2>/dev/null`.chuzzle }
end
def self.git_short_head
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git rev-parse --short=4 --verify -q HEAD 2>/dev/null`.chuzzle }
end
def self.git_last_commit
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git show -s --format="%cr" HEAD 2>/dev/null`.chuzzle }
end
def self.git_last_commit_date
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git show -s --format="%cd" --date=short HEAD 2>/dev/null`.chuzzle }
end
def self.homebrew_version_string
if pretty_revision = git_short_head
last_commit = git_last_commit_date
"#{HOMEBREW_VERSION} (git revision #{pretty_revision}; last commit #{last_commit})"
else
"#{HOMEBREW_VERSION} (no git repository)"
end
end
def self.install_gem_setup_path!(gem, version = nil, executable = gem)
require "rubygems"
# Add Gem binary directory and (if missing) Ruby binary directory to PATH.
path = ENV["PATH"].split(File::PATH_SEPARATOR)
path.unshift(RUBY_BIN) if which("ruby") != RUBY_PATH
path.unshift("#{Gem.user_dir}/bin")
ENV["PATH"] = path.join(File::PATH_SEPARATOR)
if Gem::Specification.find_all_by_name(gem, version).empty?
ohai "Installing or updating '#{gem}' gem"
install_args = %W[--no-ri --no-rdoc --user-install #{gem}]
install_args << "--version" << version if version
# Do `gem install [...]` without having to spawn a separate process or
# having to find the right `gem` binary for the running Ruby interpreter.
require "rubygems/commands/install_command"
install_cmd = Gem::Commands::InstallCommand.new
install_cmd.handle_options(install_args)
exit_code = 1 # Should not matter as `install_cmd.execute` always throws.
begin
install_cmd.execute
rescue Gem::SystemExitException => e
exit_code = e.exit_code
end
odie "Failed to install/update the '#{gem}' gem." if exit_code != 0
end
unless which executable
odie <<-EOS.undent
The '#{gem}' gem is installed but couldn't find '#{executable}' in the PATH:
#{ENV["PATH"]}
EOS
end
end
end
def with_system_path
old_path = ENV["PATH"]
ENV["PATH"] = "/usr/bin:/bin"
yield
ensure
ENV["PATH"] = old_path
end
def run_as_not_developer(&_block)
old = ENV.delete "HOMEBREW_DEVELOPER"
yield
ensure
ENV["HOMEBREW_DEVELOPER"] = old
end
# Kernel.system but with exceptions
def safe_system(cmd, *args)
Homebrew.system(cmd, *args) || raise(ErrorDuringExecution.new(cmd, args))
end
# prints no output
def quiet_system(cmd, *args)
Homebrew._system(cmd, *args) do
# Redirect output streams to `/dev/null` instead of closing as some programs
# will fail to execute if they can't write to an open stream.
$stdout.reopen("/dev/null")
$stderr.reopen("/dev/null")
end
end
def curl(*args)
brewed_curl = HOMEBREW_PREFIX/"opt/curl/bin/curl"
curl = if MacOS.version <= "10.8" && brewed_curl.exist?
brewed_curl
else
Pathname.new "/usr/bin/curl"
end
raise "#{curl} is not executable" unless curl.exist? && curl.executable?
flags = HOMEBREW_CURL_ARGS
flags = flags.delete("#") if ARGV.verbose?
args = [flags, HOMEBREW_USER_AGENT, *args]
args << "--verbose" if ENV["HOMEBREW_CURL_VERBOSE"]
args << "--silent" if !$stdout.tty? || ENV["TRAVIS"]
safe_system curl, *args
end
def puts_columns(items)
return if items.empty?
unless $stdout.tty?
puts items
return
end
# TTY case: If possible, output using multiple columns.
console_width = Tty.width
console_width = 80 if console_width <= 0
plain_item_lengths = items.map { |s| Tty.strip_ansi(s).length }
max_len = plain_item_lengths.max
col_gap = 2 # number of spaces between columns
gap_str = " " * col_gap
cols = (console_width + col_gap) / (max_len + col_gap)
cols = 1 if cols < 1
rows = (items.size + cols - 1) / cols
cols = (items.size + rows - 1) / rows # avoid empty trailing columns
if cols >= 2
col_width = (console_width + col_gap) / cols - col_gap
items = items.each_with_index.map do |item, index|
item + "".ljust(col_width - plain_item_lengths[index])
end
end
if cols == 1
puts items
else
rows.times do |row_index|
item_indices_for_row = row_index.step(items.size - 1, rows).to_a
puts items.values_at(*item_indices_for_row).join(gap_str)
end
end
end
def which(cmd, path = ENV["PATH"])
path.split(File::PATH_SEPARATOR).each do |p|
begin
pcmd = File.expand_path(cmd, p)
rescue ArgumentError
# File.expand_path will raise an ArgumentError if the path is malformed.
# See https://github.com/Homebrew/homebrew/issues/32789
next
end
return Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd)
end
nil
end
def which_all(cmd, path = ENV["PATH"])
path.split(File::PATH_SEPARATOR).map do |p|
begin
pcmd = File.expand_path(cmd, p)
rescue ArgumentError
# File.expand_path will raise an ArgumentError if the path is malformed.
# See https://github.com/Homebrew/homebrew/issues/32789
next
end
Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd)
end.compact.uniq
end
def which_editor
editor = ENV.values_at("HOMEBREW_EDITOR", "VISUAL", "EDITOR").compact.first
return editor unless editor.nil?
# Find Textmate
editor = "mate" if which "mate"
# Find BBEdit / TextWrangler
editor ||= "edit" if which "edit"
# Find vim
editor ||= "vim" if which "vim"
# Default to standard vim
editor ||= "/usr/bin/vim"
opoo <<-EOS.undent
Using #{editor} because no editor was set in the environment.
This may change in the future, so we recommend setting EDITOR, VISUAL,
or HOMEBREW_EDITOR to your preferred text editor.
EOS
editor
end
def exec_editor(*args)
safe_exec(which_editor, *args)
end
def exec_browser(*args)
browser = ENV["HOMEBREW_BROWSER"] || ENV["BROWSER"] || OS::PATH_OPEN
safe_exec(browser, *args)
end
def safe_exec(cmd, *args)
# This buys us proper argument quoting and evaluation
# of environment variables in the cmd parameter.
exec "/bin/sh", "-c", "#{cmd} \"$@\"", "--", *args
end
# GZips the given paths, and returns the gzipped paths
def gzip(*paths)
paths.collect do |path|
with_system_path { safe_system "gzip", path }
Pathname.new("#{path}.gz")
end
end
# Returns array of architectures that the given command or library is built for.
def archs_for_command(cmd)
cmd = which(cmd) unless Pathname.new(cmd).absolute?
Pathname.new(cmd).archs
end
def ignore_interrupts(opt = nil)
std_trap = trap("INT") do
puts "One sec, just cleaning up" unless opt == :quietly
end
yield
ensure
trap("INT", std_trap)
end
def nostdout
if ARGV.verbose?
yield
else
begin
out = $stdout.dup
$stdout.reopen("/dev/null")
yield
ensure
$stdout.reopen(out)
out.close
end
end
end
def paths
@paths ||= ENV["PATH"].split(File::PATH_SEPARATOR).collect do |p|
begin
File.expand_path(p).chomp("/")
rescue ArgumentError
onoe "The following PATH component is invalid: #{p}"
end
end.uniq.compact
end
# return the shell profile file based on users' preference shell
def shell_profile
case ENV["SHELL"]
when %r{/(ba)?sh} then "~/.bash_profile"
when %r{/zsh} then "~/.zshrc"
when %r{/ksh} then "~/.kshrc"
else "~/.bash_profile"
end
end
module GitHub
extend self
ISSUES_URI = URI.parse("https://api.github.com/search/issues")
Error = Class.new(RuntimeError)
HTTPNotFoundError = Class.new(Error)
class RateLimitExceededError < Error
def initialize(reset, error)
super <<-EOS.undent
GitHub #{error}
Try again in #{pretty_ratelimit_reset(reset)}, or create a personal access token:
#{Tty.em}https://github.com/settings/tokens/new?scopes=&description=Homebrew#{Tty.reset}
and then set the token as: HOMEBREW_GITHUB_API_TOKEN
EOS
end
def pretty_ratelimit_reset(reset)
pretty_duration(Time.at(reset) - Time.now)
end
end
class AuthenticationFailedError < Error
def initialize(error)
super <<-EOS.undent
GitHub #{error}
HOMEBREW_GITHUB_API_TOKEN may be invalid or expired, check:
#{Tty.em}https://github.com/settings/tokens#{Tty.reset}
EOS
end
end
def open(url, &_block)
# This is a no-op if the user is opting out of using the GitHub API.
return if ENV["HOMEBREW_NO_GITHUB_API"]
require "net/https"
headers = {
"User-Agent" => HOMEBREW_USER_AGENT,
"Accept" => "application/vnd.github.v3+json"
}
headers["Authorization"] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN
begin
Kernel.open(url, headers) { |f| yield Utils::JSON.load(f.read) }
rescue OpenURI::HTTPError => e
handle_api_error(e)
rescue EOFError, SocketError, OpenSSL::SSL::SSLError => e
raise Error, "Failed to connect to: #{url}\n#{e.message}", e.backtrace
rescue Utils::JSON::Error => e
raise Error, "Failed to parse JSON response\n#{e.message}", e.backtrace
end
end
def handle_api_error(e)
if e.io.meta.fetch("x-ratelimit-remaining", 1).to_i <= 0
reset = e.io.meta.fetch("x-ratelimit-reset").to_i
error = Utils::JSON.load(e.io.read)["message"]
raise RateLimitExceededError.new(reset, error)
end
case e.io.status.first
when "401", "403"
raise AuthenticationFailedError.new(e.message)
when "404"
raise HTTPNotFoundError, e.message, e.backtrace
else
error = Utils::JSON.load(e.io.read)["message"] rescue nil
raise Error, [e.message, error].compact.join("\n"), e.backtrace
end
end
def issues_matching(query, qualifiers = {})
uri = ISSUES_URI.dup
uri.query = build_query_string(query, qualifiers)
open(uri) { |json| json["items"] }
end
def repository(user, repo)
open(URI.parse("https://api.github.com/repos/#{user}/#{repo}")) { |j| j }
end
def build_query_string(query, qualifiers)
s = "q=#{uri_escape(query)}+"
s << build_search_qualifier_string(qualifiers)
s << "&per_page=100"
end
def build_search_qualifier_string(qualifiers)
{
:repo => "Homebrew/homebrew",
:in => "title"
}.update(qualifiers).map do |qualifier, value|
"#{qualifier}:#{value}"
end.join("+")
end
def uri_escape(query)
if URI.respond_to?(:encode_www_form_component)
URI.encode_www_form_component(query)
else
require "erb"
ERB::Util.url_encode(query)
end
end
def issues_for_formula(name)
issues_matching(name, :state => "open")
end
def print_pull_requests_matching(query)
return [] if ENV["HOMEBREW_NO_GITHUB_API"]
ohai "Searching pull requests..."
open_or_closed_prs = issues_matching(query, :type => "pr")
open_prs = open_or_closed_prs.select { |i| i["state"] == "open" }
if open_prs.any?
puts "Open pull requests:"
prs = open_prs
elsif open_or_closed_prs.any?
puts "Closed pull requests:"
prs = open_or_closed_prs
else
return
end
prs.each { |i| puts "#{i["title"]} (#{i["html_url"]})" }
end
def private_repo?(user, repo)
uri = URI.parse("https://api.github.com/repos/#{user}/#{repo}")
open(uri) { |json| json["private"] }
end
end
def disk_usage_readable(size_in_bytes)
if size_in_bytes >= 1_073_741_824
size = size_in_bytes.to_f / 1_073_741_824
unit = "G"
elsif size_in_bytes >= 1_048_576
size = size_in_bytes.to_f / 1_048_576
unit = "M"
elsif size_in_bytes >= 1_024
size = size_in_bytes.to_f / 1_024
unit = "K"
else
size = size_in_bytes
unit = "B"
end
# avoid trailing zero after decimal point
if (size * 10).to_i % 10 == 0
"#{size.to_i}#{unit}"
else
"#{"%.1f" % size}#{unit}"
end
end
def number_readable(number)
numstr = number.to_i.to_s
(numstr.size - 3).step(1, -3) { |i| numstr.insert(i, ",") }
numstr
end
| bsd-2-clause |
looker/sentry | src/sentry/features/exceptions.py | 125 | from __future__ import absolute_import
__all__ = ['FeatureNotRegistered']
class FeatureNotRegistered(Exception):
pass
| bsd-3-clause |
ckclark/elasticsearch | core/src/main/java/org/elasticsearch/index/query/functionscore/ScoreFunctionBuilders.java | 3722 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.query.functionscore;
import org.elasticsearch.index.query.functionscore.exp.ExponentialDecayFunctionBuilder;
import org.elasticsearch.index.query.functionscore.fieldvaluefactor.FieldValueFactorFunctionBuilder;
import org.elasticsearch.index.query.functionscore.gauss.GaussDecayFunctionBuilder;
import org.elasticsearch.index.query.functionscore.lin.LinearDecayFunctionBuilder;
import org.elasticsearch.index.query.functionscore.random.RandomScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.script.ScriptScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.weight.WeightBuilder;
import org.elasticsearch.script.Script;
public class ScoreFunctionBuilders {
public static ExponentialDecayFunctionBuilder exponentialDecayFunction(String fieldName, Object origin, Object scale) {
return new ExponentialDecayFunctionBuilder(fieldName, origin, scale);
}
public static ExponentialDecayFunctionBuilder exponentialDecayFunction(String fieldName, Object scale) {
return new ExponentialDecayFunctionBuilder(fieldName, null, scale);
}
public static GaussDecayFunctionBuilder gaussDecayFunction(String fieldName, Object origin, Object scale) {
return new GaussDecayFunctionBuilder(fieldName, origin, scale);
}
public static GaussDecayFunctionBuilder gaussDecayFunction(String fieldName, Object scale) {
return new GaussDecayFunctionBuilder(fieldName, null, scale);
}
public static LinearDecayFunctionBuilder linearDecayFunction(String fieldName, Object origin, Object scale) {
return new LinearDecayFunctionBuilder(fieldName, origin, scale);
}
public static LinearDecayFunctionBuilder linearDecayFunction(String fieldName, Object scale) {
return new LinearDecayFunctionBuilder(fieldName, null, scale);
}
public static ScriptScoreFunctionBuilder scriptFunction(Script script) {
return (new ScriptScoreFunctionBuilder(script));
}
public static ScriptScoreFunctionBuilder scriptFunction(String script) {
return (new ScriptScoreFunctionBuilder(new Script(script)));
}
public static RandomScoreFunctionBuilder randomFunction(int seed) {
return (new RandomScoreFunctionBuilder()).seed(seed);
}
public static RandomScoreFunctionBuilder randomFunction(long seed) {
return (new RandomScoreFunctionBuilder()).seed(seed);
}
public static RandomScoreFunctionBuilder randomFunction(String seed) {
return (new RandomScoreFunctionBuilder()).seed(seed);
}
public static WeightBuilder weightFactorFunction(float weight) {
return (WeightBuilder)(new WeightBuilder().setWeight(weight));
}
public static FieldValueFactorFunctionBuilder fieldValueFactorFunction(String fieldName) {
return new FieldValueFactorFunctionBuilder(fieldName);
}
}
| apache-2.0 |
EunBongSong/TizenRT | external/iotivity/iotivity_1.2-rel/service/resource-container/bundle-java-api/src/main/java/org/iotivity/resourcecontainer/bundle/api/BundleActivator.java | 1883 | //******************************************************************
//
// Copyright 2015 Samsung Electronics 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.iotivity.resourcecontainer.bundle.api;
import java.util.List;
/**
* The BundleActivator interface needs to be implemented. A bundle provider
* can directly extend fromt the BaseActivator.
*/
public interface BundleActivator {
/**
* Activates the bundle and creates all resources.
*/
public void activateBundle();
/**
* Deactivates the bundle and destroys all resources.
*/
public void deactivateBundle();
/**
* Registers a single resource instance at the resource container
* @param resource Instance of a BundleResource
*/
public int registerResource(BundleResource resource);
/**
* Unregisters a single resource instance at the resource container
* @param resource Instance of a BundleResource
*/
public void unregisterResource(BundleResource resource);
/**
* List the configuration of the bundle resources.
* @return List of configuration for each resource
*/
public List<ResourceConfig> getConfiguredBundleResources();
}
| apache-2.0 |
denzelsN/pinpoint | bootstrap-core/src/test/java/com/navercorp/pinpoint/bootstrap/config/ProfilableClassFilterTest.java | 2400 | /*
* Copyright 2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.bootstrap.config;
import org.junit.Assert;
import org.junit.Test;
import com.navercorp.pinpoint.bootstrap.config.ProfilableClassFilter;
import java.io.IOException;
public class ProfilableClassFilterTest {
@Test
public void testIsProfilableClassWithNoConfiguration() throws IOException {
ProfilableClassFilter filter = new ProfilableClassFilter("com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpoint.testweb.MyClass");
Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb/controllers/MyController"));
Assert.assertFalse(filter.filter("net/spider/king/wang/Jjang"));
Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb2/controller/MyController"));
Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb2/MyClass"));
}
/**
* <pre>
* configuration is
* profile.package.include=com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpoint.testweb.MyClass
* </pre>
*
* @throws IOException
*/
@Test
public void testIsProfilableClass() throws IOException {
ProfilableClassFilter filter = new ProfilableClassFilter("com.navercorp.pinpoint.testweb.controller.*,com.navercorp.pinpoint.testweb.MyClass");
Assert.assertTrue(filter.filter("com/navercorp/pinpoint/testweb/MyClass"));
Assert.assertTrue(filter.filter("com/navercorp/pinpoint/testweb/controller/MyController"));
Assert.assertTrue(filter.filter("com/navercorp/pinpoint/testweb/controller/customcontroller/MyCustomController"));
Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb/MyUnknownClass"));
Assert.assertFalse(filter.filter("com/navercorp/pinpoint/testweb/controller2/MyController"));
}
} | apache-2.0 |
GiovanniConserva/TestDeploy | venv/Lib/site-packages/django/core/management/__init__.py | 14438 | from __future__ import unicode_literals
import os
import pkgutil
import sys
from collections import OrderedDict, defaultdict
from importlib import import_module
import django
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import (
BaseCommand, CommandError, CommandParser, handle_default_options,
)
from django.core.management.color import color_style
from django.utils import autoreload, lru_cache, six
from django.utils._os import npath, upath
def find_commands(management_dir):
"""
Given a path to a management directory, returns a list of all the command
names that are available.
Returns an empty list if no commands are defined.
"""
command_dir = os.path.join(management_dir, 'commands')
return [name for _, name, is_pkg in pkgutil.iter_modules([npath(command_dir)])
if not is_pkg and not name.startswith('_')]
def load_command_class(app_name, name):
"""
Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate.
"""
module = import_module('%s.management.commands.%s' % (app_name, name))
return module.Command()
@lru_cache.lru_cache(maxsize=None)
def get_commands():
"""
Returns a dictionary mapping command names to their callback applications.
This works by looking for a management.commands package in django.core, and
in each installed application -- if a commands package exists, all commands
in that package are registered.
Core commands are always included. If a settings module has been
specified, user-defined commands will also be included.
The dictionary is in the format {command_name: app_name}. Key-value
pairs from this dictionary can then be used in calls to
load_command_class(app_name, command_name)
If a specific version of a command must be loaded (e.g., with the
startapp command), the instantiated module can be placed in the
dictionary in place of the application name.
The dictionary is cached on the first call and reused on subsequent
calls.
"""
commands = {name: 'django.core' for name in find_commands(upath(__path__[0]))}
if not settings.configured:
return commands
for app_config in reversed(list(apps.get_app_configs())):
path = os.path.join(app_config.path, 'management')
commands.update({name: app_config.name for name in find_commands(path)})
return commands
def call_command(name, *args, **options):
"""
Calls the given command, with the given options and args/kwargs.
This is the primary API you should use for calling specific commands.
Some examples:
call_command('migrate')
call_command('shell', plain=True)
call_command('sqlmigrate', 'myapp')
"""
# Load the command object.
try:
app_name = get_commands()[name]
except KeyError:
raise CommandError("Unknown command: %r" % name)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
command = app_name
else:
command = load_command_class(app_name, name)
# Simulate argument parsing to get the option defaults (see #10080 for details).
parser = command.create_parser('', name)
if command.use_argparse:
# Use the `dest` option name from the parser option
opt_mapping = {sorted(s_opt.option_strings)[0].lstrip('-').replace('-', '_'): s_opt.dest
for s_opt in parser._actions if s_opt.option_strings}
arg_options = {opt_mapping.get(key, key): value for key, value in options.items()}
defaults = parser.parse_args(args=args)
defaults = dict(defaults._get_kwargs(), **arg_options)
# Move positional args out of options to mimic legacy optparse
args = defaults.pop('args', ())
else:
# Legacy optparse method
defaults, _ = parser.parse_args(args=[])
defaults = dict(defaults.__dict__, **options)
if 'skip_checks' not in options:
defaults['skip_checks'] = True
return command.execute(*args, **defaults)
class ManagementUtility(object):
"""
Encapsulates the logic of the django-admin and manage.py utilities.
A ManagementUtility has a number of commands, which can be manipulated
by editing the self.commands dictionary.
"""
def __init__(self, argv=None):
self.argv = argv or sys.argv[:]
self.prog_name = os.path.basename(self.argv[0])
self.settings_exception = None
def main_help_text(self, commands_only=False):
"""
Returns the script's main help text, as a string.
"""
if commands_only:
usage = sorted(get_commands().keys())
else:
usage = [
"",
"Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,
"",
"Available subcommands:",
]
commands_dict = defaultdict(lambda: [])
for name, app in six.iteritems(get_commands()):
if app == 'django.core':
app = 'django'
else:
app = app.rpartition('.')[-1]
commands_dict[app].append(name)
style = color_style()
for app in sorted(commands_dict.keys()):
usage.append("")
usage.append(style.NOTICE("[%s]" % app))
for name in sorted(commands_dict[app]):
usage.append(" %s" % name)
# Output an extra note if settings are not properly configured
if self.settings_exception is not None:
usage.append(style.NOTICE(
"Note that only Django core commands are listed "
"as settings are not properly configured (error: %s)."
% self.settings_exception))
return '\n'.join(usage)
def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
if os.environ.get('DJANGO_SETTINGS_MODULE'):
# If `subcommand` is missing due to misconfigured settings, the
# following line will retrigger an ImproperlyConfigured exception
# (get_commands() swallows the original one) so the user is
# informed about it.
settings.INSTALLED_APPS
else:
sys.stderr.write("No Django settings specified.\n")
sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %
(subcommand, self.prog_name))
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
def autocomplete(self):
"""
Output completion suggestions for BASH.
The output of this function is passed to BASH's `COMREPLY` variable and
treated as completion suggestions. `COMREPLY` expects a space
separated string as the result.
The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used
to get information about the cli input. Please refer to the BASH
man-page for more information about this variables.
Subcommand options are saved as pairs. A pair consists of
the long option string (e.g. '--exclude') and a boolean
value indicating if the option requires arguments. When printing to
stdout, an equal sign is appended to options which require arguments.
Note: If debugging this function, it is recommended to write the debug
output in a separate file. Otherwise the debug output will be treated
and formatted as potential completion suggestions.
"""
# Don't complete if user hasn't sourced bash_completion file.
if 'DJANGO_AUTO_COMPLETE' not in os.environ:
return
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ['COMP_CWORD'])
try:
curr = cwords[cword - 1]
except IndexError:
curr = ''
subcommands = list(get_commands()) + ['help']
options = [('--help', False)]
# subcommand
if cword == 1:
print(' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands))))
# subcommand options
# special case: the 'help' subcommand has no options
elif cwords[0] in subcommands and cwords[0] != 'help':
subcommand_cls = self.fetch_command(cwords[0])
# special case: add the names of installed apps to options
if cwords[0] in ('dumpdata', 'sqlmigrate', 'sqlsequencereset', 'test'):
try:
app_configs = apps.get_app_configs()
# Get the last part of the dotted path as the app name.
options.extend((app_config.label, 0) for app_config in app_configs)
except ImportError:
# Fail silently if DJANGO_SETTINGS_MODULE isn't set. The
# user will find out once they execute the command.
pass
parser = subcommand_cls.create_parser('', cwords[0])
if subcommand_cls.use_argparse:
options.extend((sorted(s_opt.option_strings)[0], s_opt.nargs != 0) for s_opt in
parser._actions if s_opt.option_strings)
else:
options.extend((s_opt.get_opt_string(), s_opt.nargs != 0) for s_opt in
parser.option_list)
# filter out previously specified options from available options
prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
options = [opt for opt in options if opt[0] not in prev_opts]
# filter options by current input
options = sorted((k, v) for k, v in options if k.startswith(curr))
for option in options:
opt_label = option[0]
# append '=' to options which require args
if option[1]:
opt_label += '='
print(opt_label)
sys.exit(1)
def execute(self):
"""
Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it.
"""
try:
subcommand = self.argv[1]
except IndexError:
subcommand = 'help' # Display help if no arguments were given.
# Preprocess options to extract --settings and --pythonpath.
# These options could affect the commands that are available, so they
# must be processed early.
parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
parser.add_argument('--settings')
parser.add_argument('--pythonpath')
parser.add_argument('args', nargs='*') # catch-all
try:
options, args = parser.parse_known_args(self.argv[2:])
handle_default_options(options)
except CommandError:
pass # Ignore any option errors at this point.
no_settings_commands = [
'help', 'version', '--help', '--version', '-h',
'compilemessages', 'makemessages',
'startapp', 'startproject',
]
try:
settings.INSTALLED_APPS
except ImproperlyConfigured as exc:
self.settings_exception = exc
# A handful of built-in management commands work without settings.
# Load the default settings -- where INSTALLED_APPS is empty.
if subcommand in no_settings_commands:
settings.configure()
if settings.configured:
# Start the auto-reloading dev server even if the code is broken.
# The hardcoded condition is a code smell but we can't rely on a
# flag on the command class because we haven't located it yet.
if subcommand == 'runserver' and '--noreload' not in self.argv:
try:
autoreload.check_errors(django.setup)()
except Exception:
# The exception will be raised later in the child process
# started by the autoreloader. Pretend it didn't happen by
# loading an empty list of applications.
apps.all_models = defaultdict(OrderedDict)
apps.app_configs = OrderedDict()
apps.apps_ready = apps.models_ready = apps.ready = True
# In all other cases, django.setup() is required to succeed.
else:
django.setup()
self.autocomplete()
if subcommand == 'help':
if '--commands' in args:
sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
elif len(options.args) < 1:
sys.stdout.write(self.main_help_text() + '\n')
else:
self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
# Special-cases: We want 'django-admin --version' and
# 'django-admin --help' to work, for backwards compatibility.
elif subcommand == 'version' or self.argv[1:] == ['--version']:
sys.stdout.write(django.get_version() + '\n')
elif self.argv[1:] in (['--help'], ['-h']):
sys.stdout.write(self.main_help_text() + '\n')
else:
self.fetch_command(subcommand).run_from_argv(self.argv)
def execute_from_command_line(argv=None):
"""
A simple method that runs a ManagementUtility.
"""
utility = ManagementUtility(argv)
utility.execute()
| bsd-3-clause |
AndreiMariusSili/EnactusMVC | vendor/react/promise/tests/CancellationQueueTest.php | 2474 | <?php
namespace React\Promise;
class CancellationQueueTest extends TestCase
{
/** @test */
public function acceptsSimpleCancellableThenable()
{
$p = new SimpleTestCancellableThenable();
$cancellationQueue = new CancellationQueue();
$cancellationQueue->enqueue($p);
$cancellationQueue();
$this->assertTrue($p->cancelCalled);
}
/** @test */
public function ignoresSimpleCancellable()
{
$p = new SimpleTestCancellable();
$cancellationQueue = new CancellationQueue();
$cancellationQueue->enqueue($p);
$cancellationQueue();
$this->assertFalse($p->cancelCalled);
}
/** @test */
public function callsCancelOnPromisesEnqueuedBeforeStart()
{
$d1 = $this->getCancellableDeferred();
$d2 = $this->getCancellableDeferred();
$cancellationQueue = new CancellationQueue();
$cancellationQueue->enqueue($d1->promise());
$cancellationQueue->enqueue($d2->promise());
$cancellationQueue();
}
/** @test */
public function callsCancelOnPromisesEnqueuedAfterStart()
{
$d1 = $this->getCancellableDeferred();
$d2 = $this->getCancellableDeferred();
$cancellationQueue = new CancellationQueue();
$cancellationQueue();
$cancellationQueue->enqueue($d2->promise());
$cancellationQueue->enqueue($d1->promise());
}
/** @test */
public function doesNotCallCancelTwiceWhenStartedTwice()
{
$d = $this->getCancellableDeferred();
$cancellationQueue = new CancellationQueue();
$cancellationQueue->enqueue($d->promise());
$cancellationQueue();
$cancellationQueue();
}
/** @test */
public function rethrowsExceptionsThrownFromCancel()
{
$this->setExpectedException('\Exception', 'test');
$mock = $this->getMock('React\Promise\CancellablePromiseInterface');
$mock
->expects($this->once())
->method('cancel')
->will($this->throwException(new \Exception('test')));
$cancellationQueue = new CancellationQueue();
$cancellationQueue->enqueue($mock);
$cancellationQueue();
}
private function getCancellableDeferred()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke');
return new Deferred($mock);
}
}
| mit |
wout/cdnjs | ajax/libs/datepick/3.5.2/js/jquery.datepick-fr.js | 1476 | /* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood@virginbroadband.com.au) and Stéphane Nahmani (sholby@sholby.net). */
(function($) {
$.datepick.regional['fr'] = {
clearText: 'Effacer', clearStatus: 'Effacer la date sélectionnée',
closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
prevText: '<Préc', prevStatus: 'Voir le mois précédent',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Courant', currentStatus: 'Voir le mois courant',
monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
'Jul','Aoû','Sep','Oct','Nov','Déc'],
monthStatus: 'Voir un autre mois', yearStatus: 'Voir une autre année',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: '\'Choisir\' le DD d MM',
dateFormat: 'dd/mm/yy', firstDay: 1,
initStatus: 'Choisir la date', isRTL: false,
showMonthAfterYear: false, yearSuffix: ''};
$.datepick.setDefaults($.datepick.regional['fr']);
})(jQuery);
| mit |
jannishuebl/rubyspec | core/process/wait_spec.rb | 2886 | require File.expand_path('../../../spec_helper', __FILE__)
describe "Process.wait" do
before :all do
begin
Process.waitall
rescue NotImplementedError
end
end
it "raises an Errno::ECHILD if there are no child processes" do
lambda { Process.wait }.should raise_error(Errno::ECHILD)
end
platform_is_not :windows do
it "returns its childs pid" do
pid = Process.fork { Process.exit! }
Process.wait.should == pid
end
it "sets $? to a Process::Status" do
pid = Process.fork { Process.exit! }
Process.wait
$?.should be_kind_of(Process::Status)
$?.pid.should == pid
end
it "waits for any child process if no pid is given" do
pid = Process.fork { Process.exit! }
Process.wait.should == pid
lambda { Process.kill(0, pid) }.should raise_error(Errno::ESRCH)
end
it "waits for a specific child if a pid is given" do
pid1 = Process.fork { Process.exit! }
pid2 = Process.fork { Process.exit! }
Process.wait(pid2).should == pid2
Process.wait(pid1).should == pid1
lambda { Process.kill(0, pid1) }.should raise_error(Errno::ESRCH)
lambda { Process.kill(0, pid2) }.should raise_error(Errno::ESRCH)
end
it "coerces the pid to an Integer" do
pid1 = Process.fork { Process.exit! }
Process.wait(mock_int(pid1)).should == pid1
lambda { Process.kill(0, pid1) }.should raise_error(Errno::ESRCH)
end
# This spec is probably system-dependent.
it "waits for a child whose process group ID is that of the calling process" do
read, write = IO.pipe
pid1 = Process.fork {
read.close
Process.setpgid(0, 0)
write << 1
write.close
Process.exit!
}
Process.setpgid(0, 0)
ppid = Process.pid
pid2 = Process.fork {
read.close
Process.setpgid(0, ppid);
write << 2
write.close
Process.exit!
}
write.close
read.read(1)
read.read(1) # to give children a chance to set their process groups
read.close
Process.wait(0).should == pid2
Process.wait.should == pid1
end
# This spec is probably system-dependent.
it "doesn't block if no child is available when WNOHANG is used" do
pid = Process.fork do
Signal.trap("TERM") { Process.exit! }
10.times { sleep(1) }
Process.exit!
end
Process.wait(pid, Process::WNOHANG).should be_nil
# sleep slightly to allow the child to at least start up and
# setup it's TERM handler
sleep 0.25
Process.kill("TERM", pid)
Process.wait.should == pid
end
it "always accepts flags=0" do
pid = Process.fork { Process.exit! }
Process.wait(-1, 0).should == pid
lambda { Process.kill(0, pid) }.should raise_error(Errno::ESRCH)
end
end
end
| mit |
FMCalisto/FMCalisto.github.io | node_modules/rxjs/operators/startWith.d.ts | 894 | import { IScheduler } from '../Scheduler';
import { MonoTypeOperatorFunction } from '../interfaces';
export declare function startWith<T>(v1: T, scheduler?: IScheduler): MonoTypeOperatorFunction<T>;
export declare function startWith<T>(v1: T, v2: T, scheduler?: IScheduler): MonoTypeOperatorFunction<T>;
export declare function startWith<T>(v1: T, v2: T, v3: T, scheduler?: IScheduler): MonoTypeOperatorFunction<T>;
export declare function startWith<T>(v1: T, v2: T, v3: T, v4: T, scheduler?: IScheduler): MonoTypeOperatorFunction<T>;
export declare function startWith<T>(v1: T, v2: T, v3: T, v4: T, v5: T, scheduler?: IScheduler): MonoTypeOperatorFunction<T>;
export declare function startWith<T>(v1: T, v2: T, v3: T, v4: T, v5: T, v6: T, scheduler?: IScheduler): MonoTypeOperatorFunction<T>;
export declare function startWith<T>(...array: Array<T | IScheduler>): MonoTypeOperatorFunction<T>;
| mit |
smrq/DefinitelyTyped | types/imgur-rest-api/index.d.ts | 5766 | // Type definitions for Imgur REST API 3.0
// Project: https://api.imgur.com/
// Definitions by: Luke William Westby <http://github.com/lukewestby>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace ImgurRestApi {
interface Response<T> {
data: any; //T|Error;
status: number;
success: boolean;
}
interface Account {
id: number;
url: string;
bio: string;
reputation: number;
created: number;
pro_expiration: any; //number|boolean;
}
interface AccountSettings {
email: string;
high_quality: boolean;
public_images: boolean;
album_privacy: string;
pro_expiration: any; //number|boolean;
accepted_gallery_terms: boolean;
active_emails: Array<string>;
messaging_enabled: boolean;
blocked_users: Array<BlockedUser>;
}
interface Album {
id: string;
title: string;
description: string;
datetime: number;
cover: string;
cover_width: number;
cover_height: number;
account_url?: string;
account_id?: number;
privacy: string;
layout: string;
views: number;
link: string;
favorite: boolean;
nsfw?: boolean;
section: string;
order: number;
deletehash?: string;
images_count: number;
images: Array<Image>;
}
interface BlockedUser {
blocked_id: number;
blocked_url: string;
}
interface Comment {
id: number;
image_id: string;
comment: string;
author: string;
author_id: number;
on_album: boolean;
album_cover: string;
ups: number;
downs: number;
points: number;
datetime: number;
parent_id: number;
deleted: boolean;
vote?: string;
children: Array<Comment>
}
interface Conversation {
id: number;
last_message_preview: string;
datetime: number;
with_account_id: number;
with_account: string;
message_count: number;
messages?: Array<Message>;
done?: boolean;
page?: number;
}
interface CustomGallery {
account_url: string;
link: string;
tags: Array<string>
item_count: number;
items: Array<GalleryItem>;
}
interface GalleryItem {
id: string;
title: string;
description: string;
datetime: number;
account_url?: string;
account_id?: number;
ups: number;
downs: number;
score: number;
is_album: boolean;
views: number;
link: string;
vote?: string;
favorite: boolean;
nsfw?: boolean;
comment_count: number;
topic: string;
topic_id: number;
}
interface GalleryAlbum extends GalleryItem {
cover: string;
cover_width: number;
cover_height: number;
privacy: string;
layout: string;
images_count: number;
images: Array<Image>;
}
interface GalleryImage extends GalleryItem {
type: string;
animated: boolean;
width: number;
height: number;
size: number;
bandwidth: number;
deletehash?: string;
gifv?: string;
mp4?: string;
webm?: string;
looping?: boolean;
section: string;
}
interface GalleryProfile {
total_gallery_comments: number;
total_gallery_favorites: number;
total_gallery_submissions: number;
trophies: Array<Trophy>;
}
interface Trophy {
id: number;
name: string;
name_clean: string;
description: string;
data: string;
data_link: string;
datetime: number;
image: string;
}
interface Image {
id: string;
title: string;
description: string;
datetime: number;
type: string;
animated: boolean;
width: number;
height: number;
size: number;
views: number;
bandwidth: number;
deletehash?: string;
name?: string;
section: string;
link: string;
gifv?: string;
mp4?: string;
webm?: string;
looping?: boolean;
vote?: string;
favorite: boolean;
nsfw?: boolean;
account_url?: string;
account_id?: number;
}
interface MemeMetadata {
meme_name: string;
top_text: string;
bottom_text: string;
bg_image: string;
}
interface Message {
id: number;
from: string;
account_id: number;
sender_id: number;
body: string;
conversation_id: number;
datetime: number;
}
interface Notification<T> {
id: number;
account_id: number;
viewed: boolean;
content: T;
}
interface AccountNotifications {
replies: Array<Notification<Comment>>;
messages: Array<Notification<Conversation>>;
}
interface Tag {
name: string;
followers: number;
total_items: number;
following?: boolean;
items: Array<GalleryItem>
}
interface TagVote {
ups: number;
downs: number;
name: string;
author: string;
}
interface Topic {
id: number;
name: string;
description: string;
}
interface Vote {
ups: number;
downs: number;
}
interface Error {
error: string;
request: string;
method: string;
}
}
| mit |
githubmoros/myclinicsoft | vendor/google/apiclient-services/src/Google/Service/Storage/ComposeRequest.php | 1764 | <?php
/*
* 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.
*/
class Google_Service_Storage_ComposeRequest extends Google_Collection
{
protected $collection_key = 'sourceObjects';
protected $destinationType = 'Google_Service_Storage_StorageObject';
protected $destinationDataType = '';
public $kind;
protected $sourceObjectsType = 'Google_Service_Storage_ComposeRequestSourceObjects';
protected $sourceObjectsDataType = 'array';
/**
* @param Google_Service_Storage_StorageObject
*/
public function setDestination(Google_Service_Storage_StorageObject $destination)
{
$this->destination = $destination;
}
/**
* @return Google_Service_Storage_StorageObject
*/
public function getDestination()
{
return $this->destination;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
/**
* @param Google_Service_Storage_ComposeRequestSourceObjects
*/
public function setSourceObjects($sourceObjects)
{
$this->sourceObjects = $sourceObjects;
}
/**
* @return Google_Service_Storage_ComposeRequestSourceObjects
*/
public function getSourceObjects()
{
return $this->sourceObjects;
}
}
| mit |
gu1lhermematos/BOXFACIL | includes/javascript/dojo/dojox/atom/widget/nls/el/PeopleEditor.js | 139 | ({"add":"Προσθήκη","addAuthor":"Προσθήκη συντάκτη","addContributor":"Προσθήκη συνεισφέροντα"}) | gpl-3.0 |
blakeembrey/TypeScript | tests/cases/conformance/types/thisType/fluentClasses.ts | 248 | class A {
foo() {
return this;
}
}
class B extends A {
bar() {
return this;
}
}
class C extends B {
baz() {
return this;
}
}
var c: C;
var z = c.foo().bar().baz(); // Fluent pattern
| apache-2.0 |
victor-gonzalez/AliPhysics | PWGPP/AD/trending/DrawTrendingADQA.C | 71024 | #if !defined(__CINT__) || defined(__MAKECINT__)
#include <TError.h>
#include <TROOT.h>
#include <TKey.h>
#include <TH2.h>
#include <TF1.h>
#include <TH1.h>
#include <TFile.h>
#include <TCanvas.h>
#include <TPad.h>
#include <TStyle.h>
#include <TGrid.h>
#include <TGridResult.h>
#include <TEnv.h>
#include <TLegend.h>
#include <TMath.h>
#include <TSpectrum.h>
#include <TTree.h>
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliGRPObject.h"
#include "AliTriggerInput.h"
#include "AliTriggerConfiguration.h"
#endif
Int_t DrawTrendingADQA(TString mergedTrendFile ="trending.root",Bool_t showLumi = kFALSE)
{
Int_t badrun=0;
Int_t goodrun=0;
if(!mergedTrendFile)
{
printf("Cannot open merged trend file with AD QA");
return 1;
}
char outfilename[200]="ProductionQA.hist.root";
TString plotDir(".");
TFile *treandFile = TFile::Open(mergedTrendFile.Data());
if(!treandFile)
{
Printf("ERROR: trending file not found. Exiting ...\n");
return -1;
}
TTree*ttree=(TTree*)treandFile->Get("trending");
if(!ttree)
{
printf("Invalid trending tree");
return 2;
}
//----------------------Take trending tree------------------------------------
Int_t runNumber=0; Int_t fillNumber=0;
Int_t adReady=0,invalidInput=0,qaNotFound=0,adActive=0,adQANotfound=0,noEntries=0;
Int_t LHCstate = -1; Float_t runTime = 0;
Float_t meanTotalChargeADA = -1024, meanTotalChargeADC = -1024;
Float_t meanChargeChannelTime[16];
Float_t meanTimeADA = -1024, meanTimeADC = -1024;
Float_t meanTimeSigmaADA = -1024, meanTimeSigmaADC = -1024;
Float_t meanTimeErrADA = -1024, meanTimeErrADC = -1024;
Float_t meanTimeSigmaErrADA = -1024, meanTimeSigmaErrADC = -1024;
Float_t rateUBA = -1024, rateUBC = -1024, rateUGA = -1024, rateUGC = -1024;
Float_t rateADAND = -1024, rateADOR = -1024, rateErr = -1024;
Float_t rateRatioADV0AND = -1024, rateRatioADV0OR = -1024;
Float_t saturationADA = -1024, saturationADC = -1024;
Float_t MPV[16], MPVErr[16];
Float_t meanPedestal[32],widthPedestal[32];
Float_t slewingChi2ADA = -1024, slewingChi2ADC = -1024;
Float_t ratePhysADAND = -1024, ratePhysADOR = -1024;
Float_t ratePhysBBA = -1024, ratePhysBBC = -1024;
Float_t ratePhysBGA = -1024, ratePhysBGC = -1024;
Float_t channelTimeMean[16], channelTimeSigma[16];
Float_t flagNoTimeFraction[16];
Float_t thresholdData[16], thresholdOCDB[16];
Float_t integratedChargeChannel[16];
Float_t triggerChargeChannel[16];
Float_t tailChargeChannel[16];
Float_t integratedChargeChannel_Weighted[16];
Float_t triggerChargeChannel_Weighted[16];
Float_t tailChargeChannel_Weighted[16];
ttree->SetBranchAddress("adReady",&adReady);
ttree->SetBranchAddress("invalidInput",&invalidInput);
ttree->SetBranchAddress("qaNotFound",&qaNotFound);
ttree->SetBranchAddress("adActive",&adActive);
ttree->SetBranchAddress("adQANotfound",&adQANotfound);
ttree->SetBranchAddress("noEntries",&noEntries);
ttree->SetBranchAddress("run",&runNumber);
ttree->SetBranchAddress("fill",&fillNumber);
ttree->SetBranchAddress("LHCstate",&LHCstate);
ttree->SetBranchAddress("runTime",&runTime);
ttree->SetBranchAddress("meanTotalChargeADA",&meanTotalChargeADA);
ttree->SetBranchAddress("meanTotalChargeADC",&meanTotalChargeADC);
ttree->SetBranchAddress("meanChargeChannelTime", &meanChargeChannelTime[0]);
ttree->SetBranchAddress("meanTimeADA",&meanTimeADA);
ttree->SetBranchAddress("meanTimeADC",&meanTimeADC);
ttree->SetBranchAddress("meanTimeErrADA",&meanTimeErrADA);
ttree->SetBranchAddress("meanTimeErrADC",&meanTimeErrADC);
ttree->SetBranchAddress("meanTimeSigmaADA",&meanTimeSigmaADA);
ttree->SetBranchAddress("meanTimeSigmaADC",&meanTimeSigmaADC);
ttree->SetBranchAddress("meanTimeSigmaErrADA",&meanTimeSigmaErrADA);
ttree->SetBranchAddress("meanTimeSigmaErrADC",&meanTimeSigmaErrADC);
ttree->SetBranchAddress("rateUBA",&rateUBA);
ttree->SetBranchAddress("rateUBC",&rateUBC);
ttree->SetBranchAddress("rateUGA",&rateUGA);
ttree->SetBranchAddress("rateUGC",&rateUGC);
ttree->SetBranchAddress("rateADAND",&rateADAND);
ttree->SetBranchAddress("rateADOR",&rateADOR);
ttree->SetBranchAddress("rateRatioADV0AND",&rateRatioADV0AND);
ttree->SetBranchAddress("rateRatioADV0OR",&rateRatioADV0OR);
ttree->SetBranchAddress("rateErr",&rateErr);
ttree->SetBranchAddress("MPV",&MPV);
ttree->SetBranchAddress("MPVErr",&MPVErr);
ttree->SetBranchAddress("meanPedestal",&meanPedestal);
ttree->SetBranchAddress("widthPedestal",&widthPedestal);
ttree->SetBranchAddress("slewingChi2ADA",&slewingChi2ADA);
ttree->SetBranchAddress("slewingChi2ADC",&slewingChi2ADC);
ttree->SetBranchAddress("saturationADA",&saturationADA);
ttree->SetBranchAddress("saturationADC",&saturationADC);
ttree->SetBranchAddress("ratePhysADAND",&ratePhysADAND);
ttree->SetBranchAddress("ratePhysADOR",&ratePhysADOR);
ttree->SetBranchAddress("ratePhysBBA",&ratePhysBBA);
ttree->SetBranchAddress("ratePhysBBC",&ratePhysBBC);
ttree->SetBranchAddress("ratePhysBGA",&ratePhysBGA);
ttree->SetBranchAddress("ratePhysBGC",&ratePhysBGC);
ttree->SetBranchAddress("channelTimeMean", &channelTimeMean[0]);
ttree->SetBranchAddress("channelTimeSigma", &channelTimeSigma[0]);
ttree->SetBranchAddress("flagNoTimeFraction", &flagNoTimeFraction[0]);
ttree->SetBranchAddress("thresholdData", &thresholdData[0]);
ttree->SetBranchAddress("thresholdOCDB", &thresholdOCDB[0]);
ttree->SetBranchAddress("integratedChargeChannel", &integratedChargeChannel[0]);
ttree->SetBranchAddress("triggerChargeChannel", &triggerChargeChannel[0]);
ttree->SetBranchAddress("tailChargeChannel", &tailChargeChannel[0]);
ttree->SetBranchAddress("integratedChargeChannel_Weighted", &integratedChargeChannel_Weighted[0]);
ttree->SetBranchAddress("triggerChargeChannel_Weighted", &triggerChargeChannel_Weighted[0]);
ttree->SetBranchAddress("tailChargeChannel_Weighted", &tailChargeChannel_Weighted[0]);
//----------------------Make trending histos------------------------------------
ttree->GetEntry(0);
Int_t nRuns=ttree->GetEntries();
TList fListHist;
TH1I *hADready= new TH1I("hADready","Run with higt voltage off",0,0,1);
TH1I *hInvalidInput= new TH1I("hInvalidInput","run with invalid input",0,0,1);
TH1I *hQANotFound= new TH1I("hQANotFound","QA not found",0,0,1);
TH1I *hADactive= new TH1I("hADactive","AD not active",0,0,1);
TH1I *hADqaNotfound= new TH1I("hADqaNotfound","AD QA not found",0,0,1);
TH1I *hNoEntries= new TH1I("hNoEntries","no entries in qa file",0,0,1);
TH1F *hRunTime = new TH1F("hRunTime","Run duration;;Time (min)",nRuns,-0.5,nRuns-0.5);
TH1I *hLHCstate = new TH1I("hLHCstate","LHC state;;State",nRuns,-0.5,nRuns-0.5);
TH1I *hNEvents = new TH1I("hNEvents","Number of events;;Number of events",nRuns,-0.5,nRuns-0.5);
TH1I *hFillNumber = new TH1I("hFillNumber","Fill number;;Fill",nRuns,-0.5,nRuns-0.5);
TH1F *hMeanTotalChargeADA = new TH1F("hMeanTotalChargeADA","Mean total charge;;Charge (ADC counts)",nRuns,-0.5,nRuns-0.5);
TH1F *hMeanTotalChargeADC = new TH1F("hMeanTotalChargeADC","Mean total charge;;Charge (ADC counts)",nRuns,-0.5,nRuns-0.5);
TH2F *hMeanChargeChannelTime = new TH2F("hMeanChargeChannelTime","Mean charge per channel with time;Channel;Charge (ADC counts)",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH1F *hMeanTimeADA = new TH1F("hMeanTimeADA","Mean time;;Time (ns)",nRuns,-0.5,nRuns-0.5);
TH1F *hMeanTimeADC = new TH1F("hMeanTimeADC","Mean time;;Time (ns)",nRuns,-0.5,nRuns-0.5);
TH1F *hMeanTimeSigmaADA = new TH1F("hMeanTimeSigmaADA","Mean time Sigma;;#sigma (ns)",nRuns,-0.5,nRuns-0.5);
TH1F *hMeanTimeSigmaADC = new TH1F("hMeanTimeSigmaADC","Mean time Sigma;;#sigma (ns)",nRuns,-0.5,nRuns-0.5);
TH1F *hRateUBA = new TH1F("hRateUBA","Mean trigger rate UB;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRateUBC = new TH1F("hRateUBC","Mean trigger rate UB;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRateUGA = new TH1F("hRateUGA","Mean trigger rate UG;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRateUGC = new TH1F("hRateUGC","Mean trigger rate UG;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRateADAND = new TH1F("hRateADAND","Mean trigger rate AD;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRateADOR = new TH1F("hRateADOR","Mean trigger rate AD;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRatioVZEROADAND = new TH1F("hRatioVZEROADAND","Trigger rate ratio VZERO/AD",nRuns,-0.5,nRuns-0.5);
TH1F *hRatioVZEROADOR = new TH1F("hRatioVZEROADOR","Trigger rate ratio VZERO/AD",nRuns,-0.5,nRuns-0.5);
TH2F *hMPV = new TH2F("hMPV","MIP position per channel;Channel;MPV (ADC counts)",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH2F *hMeanPedestal = new TH2F("hMeanPedestal","Pedestal mean per channel;;Pedestal (ADC counts)",32,-0.5,31.5,nRuns,-0.5,nRuns-0.5);
TH2F *hWidthPedestal = new TH2F("hWidthPedestal","Pedestal width per channel;;Width (ADC counts)",32,-0.5,31.5,nRuns,-0.5,nRuns-0.5);
TH1F *hSlewingChi2ADA = new TH1F("hSlewingChi2ADA","Time slewing Chi2;;Chi2",nRuns,-0.5,nRuns-0.5);
TH1F *hSlewingChi2ADC = new TH1F("hSlewingChi2ADC","Time slewing Chi2;;Chi2",nRuns,-0.5,nRuns-0.5);
TH1F *hSaturationADA = new TH1F("hSaturationADA","Saturation;;Saturation",nRuns,-0.5,nRuns-0.5);
TH1F *hSaturationADC = new TH1F("hSaturationADC","Saturation;;Saturation",nRuns,-0.5,nRuns-0.5);
TH2F *hChannelTimeMean = new TH2F("hChannelTimeMean","Mean time per channel;Channel;Time (ns)",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH2F *hChannelTimeSigma = new TH2F("hChannelTimeSigma","Time resolution per channel;Channel;Time (ns)",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH1F *hRatePhysADAND = new TH1F("hRatePhysADAND","Physics selection rate AD;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRatePhysADOR = new TH1F("hRatePhysADOR","Physics selection rate AD;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRatePhysBBA = new TH1F("hRatePhysBBA","Physics selection rate BB;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRatePhysBBC = new TH1F("hRatePhysBBC","Physics selection rate BB;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRatePhysBGA = new TH1F("hRatePhysBGA","Physics selection rate BG;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH1F *hRatePhysBGC = new TH1F("hRatePhysBGC","Physics selection rate BG;;Trigger rate",nRuns,-0.5,nRuns-0.5);
TH2F *hFlagNoTime = new TH2F("hFlagNoTime","Fraction of events with BB/BG flag but not time;Channel;Fraction",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH2F *hThresholdData = new TH2F("hThresholdData","Threshold from data fit;Channel;Threshold",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH2F *hThresholdOCDB = new TH2F("hThresholdOCDB","Threshold from OCDB;Channel;Threshold",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH2F *hTriggerChargeChannel = new TH2F("hTriggerChargeChannel","Mean trigger charge per channel;Channel;Charge (ADC counts)",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH2F *hTailChargeChannel = new TH2F("hTailChargeChannel","Mean tail charge per channel;Channel;Charge (ADC counts)",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH2F *hIntegratedChargeChannel = new TH2F("hIntegratedChargeChannel","Mean integrated charge per channel;Channel;Charge (ADC counts)",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH2F *hTriggerChargeChannel_Weighted = new TH2F("hTriggerChargeChannel_Weighted","Mean trigger charge per channel;Channel;Charge (ADC counts)",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH2F *hTailChargeChannel_Weighted = new TH2F("hTailChargeChannel_Weighted","Mean tail charge per channel;Channel;Charge (ADC counts)",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
TH2F *hIntegratedChargeChannel_Weighted = new TH2F("hIntegratedChargeChannel_Weighted","Mean integrated charge per channel;Channel;Charge (ADC counts)",16,-0.5,15.5,nRuns,-0.5,nRuns-0.5);
char ChannelInt[10];
for(Int_t iPM=0; iPM<16; iPM++){
for(Int_t iInt=0; iInt<2; iInt++){
sprintf(ChannelInt,"Ch %d Int%d",iPM,iInt);
hMeanPedestal->GetXaxis()->SetBinLabel(1+iPM+16*iInt,ChannelInt);
hWidthPedestal->GetXaxis()->SetBinLabel(1+iPM+16*iInt,ChannelInt);
}
}
fListHist.Add(hRunTime);
fListHist.Add(hLHCstate);
fListHist.Add(hNEvents);
fListHist.Add(hFillNumber);
fListHist.Add(hMeanTotalChargeADA);
fListHist.Add(hMeanTotalChargeADC);
fListHist.Add(hMeanChargeChannelTime);
fListHist.Add(hMeanTimeADA);
fListHist.Add(hMeanTimeADC);
fListHist.Add(hMeanTimeSigmaADA);
fListHist.Add(hMeanTimeSigmaADC);
fListHist.Add(hRateUBA);
fListHist.Add(hRateUBC);
fListHist.Add(hRateUGA);
fListHist.Add(hRateUGC);
fListHist.Add(hRateADAND);
fListHist.Add(hRateADOR);
fListHist.Add(hRatioVZEROADAND);
fListHist.Add(hRatioVZEROADOR);
fListHist.Add(hMPV);
fListHist.Add(hMeanPedestal);
fListHist.Add(hWidthPedestal);
fListHist.Add(hSlewingChi2ADA);
fListHist.Add(hSlewingChi2ADC);
fListHist.Add(hSaturationADA);
fListHist.Add(hSaturationADC);
fListHist.Add(hChannelTimeMean);
fListHist.Add(hChannelTimeSigma);
fListHist.Add(hRatePhysADAND);
fListHist.Add(hRatePhysADOR);
fListHist.Add(hRatePhysBBA);
fListHist.Add(hRatePhysBBC);
fListHist.Add(hRatePhysBGA);
fListHist.Add(hRatePhysBGC);
fListHist.Add(hFlagNoTime);
fListHist.Add(hThresholdData);
fListHist.Add(hThresholdOCDB);
fListHist.Add(hTriggerChargeChannel);
fListHist.Add(hTailChargeChannel);
fListHist.Add(hIntegratedChargeChannel);
fListHist.Add(hTriggerChargeChannel_Weighted);
fListHist.Add(hTailChargeChannel_Weighted);
fListHist.Add(hIntegratedChargeChannel_Weighted);
if(showLumi){
TFile *treandFileEVS = TFile::Open("trendingEVS.root");
TTree *ttreeEVS=(TTree*)treandFileEVS->Get("trending");
Int_t runEVS = 0;
Double_t muEVS = 0;
Double_t lumi_seenEVS = 0;
Double_t interactionRateEVS = 0;
ttreeEVS->SetBranchAddress("run",&runEVS);
ttreeEVS->SetBranchAddress("mu",&muEVS);
ttreeEVS->SetBranchAddress("interactionRate",&interactionRateEVS);
ttreeEVS->SetBranchAddress("lumi_seen",&lumi_seenEVS);
Double_t lumi[1000];
Double_t lumiInt[1000];
lumiInt[0] = 0.0;
ttreeEVS->GetEntry(0);
Int_t nRunsEVS=ttreeEVS->GetEntries();
UInt_t EVSruns[1000];
for(Int_t irunEVS=0;irunEVS<nRunsEVS;irunEVS++) { ttreeEVS->GetEntry(irunEVS); EVSruns[irunEVS] = runEVS;}
Double_t channelBins[17];
for(Int_t ichannel = 0; ichannel<17; ichannel++ )channelBins[ichannel] = -0.5 + ichannel;
TH1F *hFillNumberLumi = new TH1F("hFillNumberLumi","Fill number;;Fill",nRuns,-0.5,nRuns-0.5);
TH1F *hLumiSeen = new TH1F("hLumiSeen","Lumi seen;;Lumi",nRuns,-0.5,nRuns-0.5);
TH1F *hLumiIntegrated = new TH1F("hLumiIntegrated","Lumi integrated;;Lumi",nRuns,-0.5,nRuns-0.5);
}
//----------------------Loop over runs in tree------------------------------------
char runlabel[6];
for(Int_t irun=0;irun<nRuns;irun++){
ttree->GetEntry(irun);
sprintf(runlabel,"%i",runNumber);
if(showLumi){
Bool_t foundEVS = kFALSE;
Int_t irunFound = 0;
for(Int_t irunEVS=0;irunEVS<nRunsEVS;irunEVS++){
if(runNumber == EVSruns[irunEVS]){
irunFound = irunEVS;
foundEVS = kTRUE;
break;
}
}
if(!foundEVS) continue;
ttreeEVS->GetEntry(irunFound);
}
//----------------------Bad runs------------------------------------
if(invalidInput==1 || qaNotFound==1 || adActive==1 || adQANotfound==1 || noEntries==1){
hInvalidInput->SetBins(badrun+1,0,badrun+1);
hInvalidInput->GetXaxis()->SetBinLabel(badrun+1,runlabel);
hQANotFound->SetBins(badrun+1,0,badrun+1);
hQANotFound->GetXaxis()->SetBinLabel(badrun+1,runlabel);
hADactive->SetBins(badrun+1,0,badrun+1);
hADactive->GetXaxis()->SetBinLabel(badrun+1,runlabel);
hADqaNotfound->SetBins(badrun+1,0,badrun+1);
hADqaNotfound->GetXaxis()->SetBinLabel(badrun+1,runlabel);
hNoEntries->SetBins(badrun+1,0,badrun+1);
hNoEntries->GetXaxis()->SetBinLabel(badrun+1,runlabel);
hADready->SetBins(badrun,0,badrun);
hADready->GetXaxis()->SetBinLabel(badrun,runlabel);
if(adReady==1) hADready->SetBinContent(badrun,adReady);
}
if(invalidInput==1){
hInvalidInput->SetBinContent(badrun+1,invalidInput);
badrun++;
}
else if(qaNotFound==1){
hQANotFound->SetBinContent(badrun+1,qaNotFound);
badrun++;
}
else if(adActive==1){
hADactive->SetBinContent(badrun+1,adActive);
badrun++;
}
else if(adQANotfound==1){
hADqaNotfound->SetBinContent(badrun+1,adQANotfound);
badrun++;
}
else if(noEntries==1){
hNoEntries->SetBinContent(badrun+1,noEntries);
badrun++;
}
//----------------------Good runs------------------------------------
else
{
if(showLumi){
lumi[goodrun] = lumi_seenEVS;
lumiInt[goodrun+1] = lumi_seenEVS;
for(Int_t pastrun = 0; pastrun<goodrun; pastrun++)lumiInt[goodrun+1] += lumi[pastrun];
hFillNumberLumi->SetBins(goodrun+1,lumiInt);
hFillNumberLumi->SetBinContent(goodrun+1,fillNumber);
hLumiSeen->SetBins(goodrun+1,0,goodrun+1);
hLumiSeen->SetBinContent(goodrun+1,lumi_seenEVS);
hLumiSeen->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hLumiIntegrated->SetBins(goodrun+1,0,goodrun+1);
hLumiIntegrated->SetBinContent(goodrun+1,lumiInt[goodrun+1]);
hLumiIntegrated->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
}
hFillNumber->SetBins(goodrun+1,0,goodrun+1);
hFillNumber->SetBinContent(goodrun+1,fillNumber);
hFillNumber->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRunTime->SetBins(goodrun+1,0,goodrun+1);
hRunTime->SetBinContent(goodrun+1,runTime);
hRunTime->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hLHCstate->SetBins(goodrun+1,0,goodrun+1);
hLHCstate->SetBinContent(goodrun+1,LHCstate);
hLHCstate->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hNEvents->SetBins(goodrun+1,0,goodrun+1);
hNEvents->SetBinContent(goodrun+1,(Int_t)2*TMath::Power(rateErr,-2));
hNEvents->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hMeanTotalChargeADA->SetBins(goodrun+1,0,goodrun+1);
hMeanTotalChargeADA->SetBinContent(goodrun+1,meanTotalChargeADA);
hMeanTotalChargeADA->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hMeanTotalChargeADC->SetBins(goodrun+1,0,goodrun+1);
hMeanTotalChargeADC->SetBinContent(goodrun+1,meanTotalChargeADC);
hMeanTotalChargeADC->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hMeanChargeChannelTime->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hMeanChargeChannelTime->SetBinContent(i+1,goodrun+1,meanChargeChannelTime[i]);
hMeanChargeChannelTime->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
if(LHCstate == 3){ //Gain mon only for Stable beams runs
if(showLumi){
hTriggerChargeChannel->SetBins(17,channelBins,goodrun+1,lumiInt);
for(Int_t i=0; i<16; i++) hTriggerChargeChannel->SetBinContent(i+1,goodrun+1,triggerChargeChannel[i]/MPV[i]);
hTriggerChargeChannel->GetXaxis()->SetTitle("Integrated lumi [#mub]");
hTailChargeChannel->SetBins(17,channelBins,goodrun+1,lumiInt);
for(Int_t i=0; i<16; i++) hTailChargeChannel->SetBinContent(i+1,goodrun+1,tailChargeChannel[i]/MPV[i]);
hTailChargeChannel->GetXaxis()->SetTitle("Integrated lumi [#mub]");
hIntegratedChargeChannel->SetBins(17,channelBins,goodrun+1,lumiInt);
for(Int_t i=0; i<16; i++) hIntegratedChargeChannel->SetBinContent(i+1,goodrun+1,integratedChargeChannel[i]/MPV[i]);
hIntegratedChargeChannel->GetXaxis()->SetTitle("Integrated lumi [#mub]");
hTriggerChargeChannel_Weighted->SetBins(17,channelBins,goodrun+1,lumiInt);
for(Int_t i=0; i<16; i++) hTriggerChargeChannel_Weighted->SetBinContent(i+1,goodrun+1,triggerChargeChannel_Weighted[i]/MPV[i]);
hTriggerChargeChannel_Weighted->GetXaxis()->SetTitle("Integrated lumi [#mub]");
hTailChargeChannel_Weighted->SetBins(17,channelBins,goodrun+1,lumiInt);
for(Int_t i=0; i<16; i++) hTailChargeChannel_Weighted->SetBinContent(i+1,goodrun+1,tailChargeChannel_Weighted[i]/MPV[i]);
hTailChargeChannel_Weighted->GetXaxis()->SetTitle("Integrated lumi [#mub]");
hIntegratedChargeChannel_Weighted->SetBins(17,channelBins,goodrun+1,lumiInt);
for(Int_t i=0; i<16; i++) hIntegratedChargeChannel_Weighted->SetBinContent(i+1,goodrun+1,integratedChargeChannel_Weighted[i]/MPV[i]);
hIntegratedChargeChannel_Weighted->GetXaxis()->SetTitle("Integrated lumi [#mub]");
}
else{
hTriggerChargeChannel->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hTriggerChargeChannel->SetBinContent(i+1,goodrun+1,triggerChargeChannel[i]/MPV[i]);
hTriggerChargeChannel->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hTailChargeChannel->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hTailChargeChannel->SetBinContent(i+1,goodrun+1,tailChargeChannel[i]/MPV[i]);
hTailChargeChannel->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hIntegratedChargeChannel->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hIntegratedChargeChannel->SetBinContent(i+1,goodrun+1,integratedChargeChannel[i]/MPV[i]);
hIntegratedChargeChannel->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hTriggerChargeChannel_Weighted->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hTriggerChargeChannel_Weighted->SetBinContent(i+1,goodrun+1,triggerChargeChannel_Weighted[i]/MPV[i]);
hTriggerChargeChannel_Weighted->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hTailChargeChannel_Weighted->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hTailChargeChannel_Weighted->SetBinContent(i+1,goodrun+1,tailChargeChannel_Weighted[i]/MPV[i]);
hTailChargeChannel_Weighted->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hIntegratedChargeChannel_Weighted->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hIntegratedChargeChannel_Weighted->SetBinContent(i+1,goodrun+1,integratedChargeChannel_Weighted[i]/MPV[i]);
hIntegratedChargeChannel_Weighted->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
}
}
hMeanTimeADA->SetBins(goodrun+1,0,goodrun+1);
hMeanTimeADA->SetBinContent(goodrun+1,meanTimeADA);
hMeanTimeADA->SetBinError(goodrun+1,meanTimeErrADA);
hMeanTimeADA->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hMeanTimeADC->SetBins(goodrun+1,0,goodrun+1);
hMeanTimeADC->SetBinContent(goodrun+1,meanTimeADC);
hMeanTimeADC->SetBinError(goodrun+1,meanTimeErrADC);
hMeanTimeADC->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hMeanTimeSigmaADA->SetBins(goodrun+1,0,goodrun+1);
hMeanTimeSigmaADA->SetBinContent(goodrun+1,meanTimeSigmaADA);
hMeanTimeSigmaADA->SetBinError(goodrun+1,meanTimeSigmaErrADA);
hMeanTimeSigmaADA->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hMeanTimeSigmaADC->SetBins(goodrun+1,0,goodrun+1);
hMeanTimeSigmaADC->SetBinContent(goodrun+1,meanTimeSigmaADC);
hMeanTimeSigmaADC->SetBinError(goodrun+1,meanTimeSigmaErrADC);
hMeanTimeSigmaADC->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRateUBA->SetBins(goodrun+1,0,goodrun+1);
hRateUBA->SetBinContent(goodrun+1,rateUBA);
if(rateUBA!=0)hRateUBA->SetBinError(goodrun+1,rateErr/rateUBA);
hRateUBA->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRateUBC->SetBins(goodrun+1,0,goodrun+1);
hRateUBC->SetBinContent(goodrun+1,rateUBC);
if(rateUBC!=0)hRateUBC->SetBinError(goodrun+1,rateErr/rateUBC);
hRateUBC->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRateUGA->SetBins(goodrun+1,0,goodrun+1);
hRateUGA->SetBinContent(goodrun+1,rateUGA);
if(rateUGA!=0)hRateUGA->SetBinError(goodrun+1,rateErr/rateUGA);
hRateUGA->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRateUGC->SetBins(goodrun+1,0,goodrun+1);
hRateUGC->SetBinContent(goodrun+1,rateUGC);
if(rateUGC!=0)hRateUGC->SetBinError(goodrun+1,rateErr/rateUGC);
hRateUGC->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRateADAND->SetBins(goodrun+1,0,goodrun+1);
hRateADAND->SetBinContent(goodrun+1,rateADAND);
if(rateADAND!=0)hRateADAND->SetBinError(goodrun+1,rateErr/rateADAND);
hRateADAND->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRateADOR->SetBins(goodrun+1,0,goodrun+1);
hRateADOR->SetBinContent(goodrun+1,rateADOR);
if(rateADOR!=0)hRateADOR->SetBinError(goodrun+1,rateErr/rateADOR);
hRateADOR->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRatioVZEROADAND->SetBins(goodrun+1,0,goodrun+1);
hRatioVZEROADAND->SetBinContent(goodrun+1,rateRatioADV0AND);
if(rateRatioADV0AND!=0)hRatioVZEROADAND->SetBinError(goodrun+1,rateErr/rateRatioADV0AND);
hRatioVZEROADAND->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRatioVZEROADOR->SetBins(goodrun+1,0,goodrun+1);
hRatioVZEROADOR->SetBinContent(goodrun+1,rateRatioADV0OR);
if(rateRatioADV0OR!=0)hRatioVZEROADOR->SetBinError(goodrun+1,rateErr/rateRatioADV0OR);
hRatioVZEROADOR->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRatePhysADAND->SetBins(goodrun+1,0,goodrun+1);
hRatePhysADAND->SetBinContent(goodrun+1,rateADAND);
if(ratePhysADAND!=0)hRatePhysADAND->SetBinError(goodrun+1,rateErr/ratePhysADAND);
hRatePhysADAND->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRatePhysADOR->SetBins(goodrun+1,0,goodrun+1);
hRatePhysADOR->SetBinContent(goodrun+1,ratePhysADOR);
if(ratePhysADOR!=0)hRatePhysADOR->SetBinError(goodrun+1,rateErr/ratePhysADOR);
hRatePhysADOR->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRatePhysBBA->SetBins(goodrun+1,0,goodrun+1);
hRatePhysBBA->SetBinContent(goodrun+1,ratePhysBBA);
if(ratePhysBBA!=0)hRatePhysBBA->SetBinError(goodrun+1,rateErr/ratePhysBBA);
hRatePhysBBA->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRatePhysBBC->SetBins(goodrun+1,0,goodrun+1);
hRatePhysBBC->SetBinContent(goodrun+1,ratePhysBBC);
if(ratePhysBBC!=0)hRatePhysBBC->SetBinError(goodrun+1,rateErr/ratePhysBBC);
hRatePhysBBC->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRatePhysBGA->SetBins(goodrun+1,0,goodrun+1);
hRatePhysBGA->SetBinContent(goodrun+1,ratePhysBGA);
if(ratePhysBGA!=0)hRatePhysBGA->SetBinError(goodrun+1,rateErr/ratePhysBGA);
hRatePhysBGA->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hRatePhysBGC->SetBins(goodrun+1,0,goodrun+1);
hRatePhysBGC->SetBinContent(goodrun+1,ratePhysBGC);
if(ratePhysBGC!=0)hRatePhysBGC->SetBinError(goodrun+1,rateErr/ratePhysBGC);
hRatePhysBGC->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hMPV->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++){
hMPV->SetBinContent(i+1,goodrun+1,MPV[i]);
hMPV->SetBinError(i+1,goodrun+1,MPVErr[i]);
}
hMPV->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hMeanPedestal->SetBins(32,-0.5,31.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<32; i++)hMeanPedestal->SetBinContent(i+1,goodrun+1,meanPedestal[i]);
hMeanPedestal->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hWidthPedestal->SetBins(32,-0.5,31.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<32; i++)hWidthPedestal->SetBinContent(i+1,goodrun+1,widthPedestal[i]);
hWidthPedestal->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hSlewingChi2ADA->SetBins(goodrun+1,0,goodrun+1);
hSlewingChi2ADA->SetBinContent(goodrun+1,slewingChi2ADA);
hSlewingChi2ADA->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hSlewingChi2ADC->SetBins(goodrun+1,0,goodrun+1);
hSlewingChi2ADC->SetBinContent(goodrun+1,slewingChi2ADC);
hSlewingChi2ADC->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hSaturationADA->SetBins(goodrun+1,0,goodrun+1);
hSaturationADA->SetBinContent(goodrun+1,saturationADA);
hSaturationADA->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hSaturationADC->SetBins(goodrun+1,0,goodrun+1);
hSaturationADC->SetBinContent(goodrun+1,saturationADC);
hSaturationADC->GetXaxis()->SetBinLabel(goodrun+1,runlabel);
hChannelTimeMean->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hChannelTimeMean->SetBinContent(i+1,goodrun+1,channelTimeMean[i]);
hChannelTimeMean->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hChannelTimeSigma->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hChannelTimeSigma->SetBinContent(i+1,goodrun+1,channelTimeSigma[i]);
hChannelTimeSigma->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hFlagNoTime->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hFlagNoTime->SetBinContent(i+1,goodrun+1,flagNoTimeFraction[i]);
hFlagNoTime->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hThresholdData->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hThresholdData->SetBinContent(i+1,goodrun+1,thresholdData[i]);
hThresholdData->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
hThresholdOCDB->SetBins(16,-0.5,15.5,goodrun+1,0,goodrun+1);
for(Int_t i=0; i<16; i++) hThresholdOCDB->SetBinContent(i+1,goodrun+1,thresholdOCDB[i]);
hThresholdOCDB->GetYaxis()->SetBinLabel(goodrun+1,runlabel);
goodrun++;
}
}
TFile*fout=new TFile(outfilename,"recreate");
fout->cd();
fListHist.Write();
fout->Close();
//----------------------Print trending plots------------------------------------
int maxRun =runNumber;
ttree->GetEntry(0);
int minRun = runNumber;
myOptions();
gROOT->ForceStyle();
TDatime now;
int iDate = now.GetDate();
int iYear=iDate/10000;
int iMonth=(iDate%10000)/100;
int iDay=iDate%100;
char* cMonth[12]={"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"};
char cStamp1[25],cStamp2[25];
sprintf(cStamp1,"%i %s %i",iDay, cMonth[iMonth-1], iYear);
sprintf(cStamp2,"%i/%.2d/%i",iDay, iMonth, iYear);
TCanvas *c1 = new TCanvas("MeanTotalCharge"," ",800,400);
c1->Draw();
c1->cd();
TPad *myPad1 = new TPad("myPad1", "The pad",0,0,1,1);
myPadSetUp(myPad1,0.15,0.1,0.04,0.15);
myPad1->SetGridy();
myPad1->Draw();
myPad1->cd();
myHistSetUp(hMeanTotalChargeADA);
myHistSetUp(hMeanTotalChargeADC);
hMeanTotalChargeADA->SetMarkerColor(kBlue);
hMeanTotalChargeADC->SetMarkerColor(kRed);
hMeanTotalChargeADA->SetMarkerStyle(kFullCircle);
hMeanTotalChargeADC->SetMarkerStyle(kFullCircle);
myScaleSetUp(hMeanTotalChargeADA,hMeanTotalChargeADC);
hMeanTotalChargeADA->Draw("P");
hMeanTotalChargeADC->Draw("Psame");
AddFillSeparationLines(hFillNumber);
TLegend *myLegend1 = new TLegend(0.70,0.67,0.97,0.82);
myLegendSetUp(myLegend1,0.04,1);
myLegend1->AddEntry(hMeanTotalChargeADA,"ADA","p");
myLegend1->AddEntry(hMeanTotalChargeADC,"ADC","p");
myLegend1->Draw();
c1->Print(Form("%s/QA_Resume_%d_%d.pdf(",plotDir.Data(),minRun,maxRun));
TH1D *hChannelSlice;
TH1D *hChannelSliceBlue;
TH1D *hChannelSliceRed;
Int_t fitStatus;
TF1 *linFitBlue = new TF1("linFitBlue","pol1",0,10e6);
linFitBlue->SetLineWidth(1);
linFitBlue->SetLineStyle(kDashed);
linFitBlue->SetLineColor(kBlue);
TF1 *linFitRed = new TF1("linFitRed","pol1",0,10e6);
linFitRed->SetLineWidth(1);
linFitRed->SetLineStyle(kDashed);
linFitRed->SetLineColor(kRed);
TH1F *hFitIntegrated = new TH1F("hFitIntegrated","Slope/Offset of linear fit",16,-0.5,15.5);
hFitIntegrated->GetXaxis()->SetTitle("Channel");
hFitIntegrated->SetMarkerStyle(kOpenSquare);
hFitIntegrated->SetMarkerColor(kRed);
TH1F *hFitIntegrated_Weighted = new TH1F("hFitIntegrated_Weighted","Slope/Offset of linear fit",16,-0.5,15.5);
hFitIntegrated_Weighted->GetXaxis()->SetTitle("Channel");
hFitIntegrated_Weighted->SetMarkerStyle(kFullCircle);
hFitIntegrated_Weighted->SetMarkerColor(kRed);
TCanvas *c101 = new TCanvas("Integrated Charge channel"," ",6000,600);
c101->Draw();
c101->cd();
TPad *myPad101 = new TPad("myPad101", "The pad",0,0,1,1);
myPad101->Draw();
myPadSetUp(myPad101,0.04,0.10,0.02,0.20);
myPad101->cd();
for(Int_t i = 0; i<16; i++){
gPad->SetGridy();
hChannelSliceBlue = hIntegratedChargeChannel->ProjectionY("hChannelSliceBlue",i+1,i+1);
hChannelSliceRed = hIntegratedChargeChannel_Weighted->ProjectionY("hChannelSliceRed",i+1,i+1);
hChannelSliceBlue->SetLineColor(kBlue);
hChannelSliceRed->SetLineColor(kRed);
fitStatus = hChannelSliceBlue->Fit(linFitBlue);
if(fitStatus ==0 && linFitBlue->GetParameter(0) != 0 && linFitBlue->GetParameter(1) != 0){
hFitIntegrated->SetBinContent(i+1,linFitBlue->GetParameter(1)/linFitBlue->GetParameter(0));
hFitIntegrated->SetBinError(i+1,linFitBlue->GetParameter(1)/linFitBlue->GetParameter(0) * (linFitBlue->GetParError(1)/linFitBlue->GetParameter(1)+linFitBlue->GetParError(0)/linFitBlue->GetParameter(0)));
}
fitStatus = hChannelSliceRed->Fit(linFitRed);
if(fitStatus ==0 && linFitRed->GetParameter(0) != 0 && linFitRed->GetParameter(1) != 0){
hFitIntegrated_Weighted->SetBinContent(i+1,linFitRed->GetParameter(1)/linFitRed->GetParameter(0));
hFitIntegrated_Weighted->SetBinError(i+1,linFitRed->GetParameter(1)/linFitRed->GetParameter(0) * (linFitRed->GetParError(1)/linFitRed->GetParameter(1)+linFitRed->GetParError(0)/linFitRed->GetParameter(0)));
}
myHistSetUp(hChannelSliceBlue);
hChannelSliceBlue->SetLineWidth(1);
myScaleSetUp(hChannelSliceBlue,hChannelSliceRed);
hChannelSliceBlue->SetTitle(Form("Quantile of integrated charge channel %d",i));
if(showLumi) hChannelSliceBlue->GetXaxis()->SetTitle("Integrated lumi [1/#mub]");
else hChannelSliceBlue->GetXaxis()->SetTitle("");
hChannelSliceBlue->GetXaxis()->SetLabelSize(0.05);
hChannelSliceBlue->GetYaxis()->SetTitle("Quantile 0.95");
hChannelSliceBlue->GetYaxis()->SetTitleOffset(0.3);
hChannelSliceBlue->DrawCopy("HIST");
hChannelSliceRed->DrawCopy("HISTsame");
linFitBlue->Draw("same");
linFitRed->Draw("same");
if(showLumi)AddFillSeparationLines(hFillNumberLumi);
else AddFillSeparationLines(hFillNumber);
if(i == 0)c101->Print(Form("%s/GainMon_%d_%d.pdf(",plotDir.Data(),minRun,maxRun));
else c101->Print(Form("%s/GainMon_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
}
TH1F *hFitTrigger = new TH1F("hFitTrigger","Slope/Offset of linear fit",16,-0.5,15.5);
hFitTrigger->GetXaxis()->SetTitle("Channel");
hFitTrigger->SetMarkerStyle(kOpenSquare);
hFitTrigger->SetMarkerColor(kBlue);
TH1F *hFitTrigger_Weighted = new TH1F("hFitTrigger_Weighted","Slope/Offset of linear fit",16,-0.5,15.5);
hFitTrigger_Weighted->GetXaxis()->SetTitle("Channel");
hFitTrigger_Weighted->SetMarkerStyle(kFullCircle);
hFitTrigger_Weighted->SetMarkerColor(kBlue);
TCanvas *c102 = new TCanvas("Trigger charge channel"," ",6000,600);
c102->Draw();
c102->cd();
TPad *myPad102 = new TPad("myPad102", "The pad",0,0,1,1);
myPad102->Draw();
myPadSetUp(myPad102,0.04,0.10,0.02,0.20);
myPad102->cd();
for(Int_t i = 0; i<16; i++){
gPad->SetGridy();
hChannelSliceBlue = hTriggerChargeChannel->ProjectionY("hChannelSliceBlue",i+1,i+1);
hChannelSliceRed = hTriggerChargeChannel_Weighted->ProjectionY("hChannelSliceRed",i+1,i+1);
hChannelSliceBlue->SetLineColor(kBlue);
hChannelSliceRed->SetLineColor(kRed);
fitStatus = hChannelSliceBlue->Fit(linFitBlue);
if(fitStatus ==0 && linFitBlue->GetParameter(0) != 0 && linFitBlue->GetParameter(1) != 0){
hFitTrigger->SetBinContent(i+1,linFitBlue->GetParameter(1)/linFitBlue->GetParameter(0));
hFitTrigger->SetBinError(i+1,linFitBlue->GetParameter(1)/linFitBlue->GetParameter(0) * (linFitBlue->GetParError(1)/linFitBlue->GetParameter(1)+linFitBlue->GetParError(0)/linFitBlue->GetParameter(0)));
}
fitStatus = hChannelSliceRed->Fit(linFitRed);
if(fitStatus ==0 && linFitRed->GetParameter(0) != 0 && linFitRed->GetParameter(1) != 0){
hFitTrigger_Weighted->SetBinContent(i+1,linFitRed->GetParameter(1)/linFitRed->GetParameter(0));
hFitTrigger_Weighted->SetBinError(i+1,linFitRed->GetParameter(1)/linFitRed->GetParameter(0) * (linFitRed->GetParError(1)/linFitRed->GetParameter(1)+linFitRed->GetParError(0)/linFitRed->GetParameter(0)));
}
myHistSetUp(hChannelSliceBlue);
hChannelSliceBlue->SetLineWidth(1);
myScaleSetUp(hChannelSliceBlue,hChannelSliceRed);
hChannelSliceBlue->SetTitle(Form("Quantile of trigger charge channel %d",i));
if(showLumi) hChannelSliceBlue->GetXaxis()->SetTitle("Integrated lumi [1/#mub]");
else hChannelSliceBlue->GetXaxis()->SetTitle("");
hChannelSliceBlue->GetXaxis()->SetLabelSize(0.05);
hChannelSliceBlue->GetYaxis()->SetTitle("Quantile 0.95");
hChannelSliceBlue->GetYaxis()->SetTitleOffset(0.3);
hChannelSliceBlue->DrawCopy("HIST");
hChannelSliceRed->DrawCopy("HISTsame");
linFitBlue->Draw("same");
linFitRed->Draw("same");
if(showLumi)AddFillSeparationLines(hFillNumberLumi);
else AddFillSeparationLines(hFillNumber);
c102->Print(Form("%s/GainMon_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
}
TH1F *hFitTail = new TH1F("hFitTail","Slope/Offset of linear fit",16,-0.5,15.5);
hFitTail->GetXaxis()->SetTitle("Channel");
hFitTail->SetMarkerStyle(kOpenSquare);
hFitTail->SetMarkerColor(kGreen);
TH1F *hFitTail_Weighted = new TH1F("hFitTail_Weighted","Slope/Offset of linear fit",16,-0.5,15.5);
hFitTail_Weighted->GetXaxis()->SetTitle("Channel");
hFitTail_Weighted->SetMarkerStyle(kFullCircle);
hFitTail_Weighted->SetMarkerColor(kGreen);
TCanvas *c103 = new TCanvas("Tail charge channel"," ",6000,600);
c103->Draw();
c103->cd();
TPad *myPad103 = new TPad("myPad103", "The pad",0,0,1,1);
myPad103->Draw();
myPadSetUp(myPad103,0.04,0.10,0.02,0.20);
myPad103->cd();
for(Int_t i = 0; i<16; i++){
gPad->SetGridy();
hChannelSliceBlue = hTailChargeChannel->ProjectionY("hChannelSliceBlue",i+1,i+1);
hChannelSliceRed = hTailChargeChannel_Weighted->ProjectionY("hChannelSliceRed",i+1,i+1);
hChannelSliceBlue->SetLineColor(kBlue);
hChannelSliceRed->SetLineColor(kRed);
hChannelSliceBlue->Fit(linFitBlue);
fitStatus = hChannelSliceBlue->Fit(linFitBlue);
if(fitStatus ==0 && linFitBlue->GetParameter(0) != 0 && linFitBlue->GetParameter(1) != 0){
hFitTail->SetBinContent(i+1,linFitBlue->GetParameter(1)/linFitBlue->GetParameter(0));
hFitTail->SetBinError(i+1,linFitBlue->GetParameter(1)/linFitBlue->GetParameter(0) * (linFitBlue->GetParError(1)/linFitBlue->GetParameter(1)+linFitBlue->GetParError(0)/linFitBlue->GetParameter(0)));
}
fitStatus = hChannelSliceRed->Fit(linFitRed);
if(fitStatus ==0 && linFitRed->GetParameter(0) != 0 && linFitRed->GetParameter(1) != 0){
hFitTail_Weighted->SetBinContent(i+1,linFitRed->GetParameter(1)/linFitRed->GetParameter(0));
hFitTail_Weighted->SetBinError(i+1,linFitRed->GetParameter(1)/linFitRed->GetParameter(0) * (linFitRed->GetParError(1)/linFitRed->GetParameter(1)+linFitRed->GetParError(0)/linFitRed->GetParameter(0)));
}
myHistSetUp(hChannelSliceBlue);
hChannelSliceBlue->SetLineWidth(1);
myScaleSetUp(hChannelSliceBlue,hChannelSliceRed);
hChannelSliceBlue->SetTitle(Form("Quantile of tail charge channel %d",i));
if(showLumi) hChannelSliceBlue->GetXaxis()->SetTitle("Integrated lumi [1/#mub]");
else hChannelSliceBlue->GetXaxis()->SetTitle("");
hChannelSliceBlue->GetXaxis()->SetLabelSize(0.05);
hChannelSliceBlue->GetYaxis()->SetTitle("Quantile 0.95");
hChannelSliceBlue->GetYaxis()->SetTitleOffset(0.3);
hChannelSliceBlue->DrawCopy("HIST");
hChannelSliceRed->DrawCopy("HISTsame");
linFitBlue->Draw("same");
linFitRed->Draw("same");
if(showLumi)AddFillSeparationLines(hFillNumberLumi);
else AddFillSeparationLines(hFillNumber);
c103->Print(Form("%s/GainMon_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
}
TF1 *constFitADA_Int = new TF1("constFitADA_Int","pol0",7.9,15.5);
constFitADA_Int->SetLineWidth(2);
constFitADA_Int->SetLineStyle(kDashed);
constFitADA_Int->SetLineColor(kRed);
TF1 *constFitADC_Int = new TF1("constFitADC_Int","pol0",-0.1,7.5);
constFitADC_Int->SetLineWidth(2);
constFitADC_Int->SetLineStyle(kDashed);
constFitADC_Int->SetLineColor(kRed);
TF1 *constFitADA_IntW = new TF1("constFitADA_IntW","pol0",7.9,15.5);
constFitADA_IntW->SetLineWidth(2);
constFitADA_IntW->SetLineStyle(kSolid);
constFitADA_IntW->SetLineColor(kRed);
TF1 *constFitADC_IntW = new TF1("constFitADC_IntW","pol0",-0.1,7.5);
constFitADC_IntW->SetLineWidth(2);
constFitADC_IntW->SetLineStyle(kSolid);
constFitADC_IntW->SetLineColor(kRed);
TF1 *constFitADA_Trg = new TF1("constFitADA_Trg","pol0",7.9,15.5);
constFitADA_Trg->SetLineWidth(2);
constFitADA_Trg->SetLineStyle(kDashed);
constFitADA_Trg->SetLineColor(kBlue);
TF1 *constFitADC_Trg = new TF1("constFitADC_Trg","pol0",-0.1,7.5);
constFitADC_Trg->SetLineWidth(2);
constFitADC_Trg->SetLineStyle(kDashed);
constFitADC_Trg->SetLineColor(kBlue);
TF1 *constFitADA_TrgW = new TF1("constFitADA_TrgW","pol0",7.9,15.5);
constFitADA_TrgW->SetLineWidth(2);
constFitADA_TrgW->SetLineStyle(kSolid);
constFitADA_TrgW->SetLineColor(kBlue);
TF1 *constFitADC_TrgW = new TF1("constFitADC_TrgW","pol0",-0.1,7.5);
constFitADC_TrgW->SetLineWidth(2);
constFitADC_TrgW->SetLineStyle(kSolid);
constFitADC_TrgW->SetLineColor(kBlue);
TF1 *constFitADA_Tail = new TF1("constFitADA_Tail","pol0",7.9,15.5);
constFitADA_Tail->SetLineWidth(2);
constFitADA_Tail->SetLineStyle(kDashed);
constFitADA_Tail->SetLineColor(kGreen);
TF1 *constFitADC_Tail = new TF1("constFitADC_Tail","pol0",-0.1,7.5);
constFitADC_Tail->SetLineWidth(2);
constFitADC_Tail->SetLineStyle(kDashed);
constFitADC_Tail->SetLineColor(kGreen);
TF1 *constFitADA_TailW = new TF1("constFitADA_TailW","pol0",7.9,15.5);
constFitADA_TailW->SetLineWidth(2);
constFitADA_TailW->SetLineStyle(kSolid);
constFitADA_TailW->SetLineColor(kGreen);
TF1 *constFitADC_TailW = new TF1("constFitADC_TailW","pol0",-0.1,7.5);
constFitADC_TailW->SetLineWidth(2);
constFitADC_TailW->SetLineStyle(kSolid);
constFitADC_TailW->SetLineColor(kGreen);
hFitIntegrated->Fit(constFitADA_Int,"R");
hFitIntegrated->Fit(constFitADC_Int,"R");
hFitIntegrated_Weighted->Fit(constFitADA_IntW,"R");
hFitIntegrated_Weighted->Fit(constFitADC_IntW,"R");
hFitTrigger->Fit(constFitADA_Trg,"R");
hFitTrigger->Fit(constFitADC_Trg,"R");
hFitTrigger_Weighted->Fit(constFitADA_TrgW,"R");
hFitTrigger_Weighted->Fit(constFitADC_TrgW,"R");
hFitTail->Fit(constFitADA_Tail,"R");
hFitTail->Fit(constFitADC_Tail,"R");
hFitTail_Weighted->Fit(constFitADA_TailW,"R");
hFitTail_Weighted->Fit(constFitADC_TailW,"R");
TCanvas *c104 = new TCanvas("Slopes"," ",800,400);
c104->Draw();
c104->cd();
TPad *myPad104 = new TPad("myPad104", "The pad",0,0,1,1);
myPadSetUp(myPad104,0.15,0.1,0.04,0.15);
myPad104->SetGridy();
myPad104->Draw();
myPad104->cd();
myHistSetUp(hFitIntegrated);
//hFitIntegrated->GetYaxis()->SetRangeUser(-70e-9,0.0);
//hFitIntegrated->GetYaxis()->SetRangeUser(-0.0020,0.0);
hFitIntegrated->Draw("E");
hFitIntegrated_Weighted->Draw("Esame");
hFitTrigger->Draw("Esame");
hFitTrigger_Weighted->Draw("Esame");
hFitTail->Draw("Esame");
hFitTail_Weighted->Draw("Esame");
constFitADA_Int->Draw("same");
constFitADC_Int->Draw("same");
constFitADA_IntW->Draw("same");
constFitADC_IntW->Draw("same");
constFitADA_Trg->Draw("same");
constFitADC_Trg->Draw("same");
constFitADA_TrgW->Draw("same");
constFitADC_TrgW->Draw("same");
constFitADA_Tail->Draw("same");
constFitADC_Tail->Draw("same");
constFitADA_TailW->Draw("same");
constFitADC_TailW->Draw("same");
TLegend *myLegend01 = new TLegend(0.70,0.17,0.97,0.52);
myLegendSetUp(myLegend01,0.04,1);
myLegend01->AddEntry(hFitIntegrated,"Integrated charge","p");
myLegend01->AddEntry(hFitIntegrated_Weighted,"Integrated charge weighted","p");
myLegend01->AddEntry(hFitTrigger,"Trigger charge","p");
myLegend01->AddEntry(hFitTrigger_Weighted,"Trigger charge weighted","p");
myLegend01->AddEntry(hFitTail,"Tail charge","p");
myLegend01->AddEntry(hFitTail_Weighted,"Tail charge weighted","p");
myLegend01->Draw();
TLegend *myLegend02 = new TLegend(0.70,0.17,0.97,0.52);
myLegendSetUp(myLegend02,0.04,1);
//myLegend2->SetFillStyle(kSolid);
myLegend02->AddEntry(constFitADA_Int," ","l");
myLegend02->AddEntry(constFitADA_IntW," ","l");
myLegend02->AddEntry(constFitADA_Trg," ","l");
myLegend02->AddEntry(constFitADA_TrgW," ","l");
myLegend02->AddEntry(constFitADA_Tail," ","l");
myLegend02->AddEntry(constFitADA_TailW," ","l");
myLegend02->Draw();
c104->Print(Form("%s/GainMon_%d_%d.pdf)",plotDir.Data(),minRun,maxRun));
TCanvas *c2 = new TCanvas("MeanTime"," ",800,400);
c2->Draw();
c2->cd();
TPad *myPad2 = new TPad("myPad2", "The pad",0,0,1,1);
myPadSetUp(myPad2,0.15,0.1,0.04,0.15);
myPad2->SetGridy();
myPad2->Draw();
myPad2->cd();
myHistSetUp(hMeanTimeADA);
myHistSetUp(hMeanTimeADC);
hMeanTimeADA->SetMarkerColor(kBlue);
hMeanTimeADC->SetMarkerColor(kRed);
hMeanTimeADA->SetMarkerStyle(kFullCircle);
hMeanTimeADC->SetMarkerStyle(kFullCircle);
//myScaleSetUp(hMeanTimeADA,hMeanTimeADC);
hMeanTimeADA->GetYaxis()->SetRangeUser(50,70);
hMeanTimeADA->Draw("E");
hMeanTimeADC->Draw("Esame");
AddFillSeparationLines(hFillNumber);
myLegend1->Draw();
c2->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c3 = new TCanvas("MeanTimeSigma"," ",800,400);
c3->Draw();
c3->cd();
TPad *myPad3 = new TPad("myPad3", "The pad",0,0,1,1);
myPadSetUp(myPad3,0.15,0.1,0.04,0.15);
myPad3->SetGridy();
myPad3->Draw();
myPad3->cd();
myHistSetUp(hMeanTimeSigmaADA);
myHistSetUp(hMeanTimeSigmaADC);
hMeanTimeSigmaADA->SetMarkerColor(kBlue);
hMeanTimeSigmaADC->SetMarkerColor(kRed);
hMeanTimeSigmaADA->SetMarkerStyle(kFullCircle);
hMeanTimeSigmaADC->SetMarkerStyle(kFullCircle);
//myScaleSetUp(hMeanTimeSigmaADA,hMeanTimeSigmaADC);
hMeanTimeSigmaADA->GetYaxis()->SetRangeUser(0.1,1.0);
hMeanTimeSigmaADA->Draw("E");
hMeanTimeSigmaADC->Draw("Esame");
AddFillSeparationLines(hFillNumber);
myLegend1->Draw();
c3->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c21 = new TCanvas("ChannelTime"," ",800,400);
c21->Draw();
c21->cd();
TPad *myPad21 = new TPad("myPad21", "The pad",0,0,1,1);
myPadSetUp(myPad21,0.15,0.1,0.04,0.15);
myPad21->SetGridy();
myPad21->Draw();
myPad21->cd();
myHistSetUp(hChannelTimeMean);
hChannelTimeMean->Draw("COLZTEXT");
c21->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c22 = new TCanvas("Channel time 1D"," ",1200,800);
c22->Draw();
c22->cd();
TPad *myPad22 = new TPad("myPad22", "The pad",0,0,1,1);
myPad22->Divide(4,4);
myPad22->Draw();
for(Int_t i = 0; i<16; i++){
myPadSetUp(myPad22->cd(i+1),0.15,0.00,0.05,0.15);
myPad22->cd(i+1);
gPad->SetGridy();
hChannelSlice = hChannelTimeMean->ProjectionY("hChannelSlice",i+1,i+1);
myHistSetUp(hChannelSlice);
hChannelSlice->SetMarkerStyle(kFullCircle);
hChannelSlice->SetMarkerSize(0.5);
hChannelSlice->GetXaxis()->SetTitle("");
hChannelSlice->GetYaxis()->SetTitle("Time mean (ns)");
hChannelSlice->SetTitle(Form("Mean time channel %d",i));
if(i<8)hChannelSlice->GetYaxis()->SetRangeUser(62,68);
else hChannelSlice->GetYaxis()->SetRangeUser(53,59);
hChannelSlice->DrawCopy("P");
AddFillSeparationLines(hFillNumber);
}
c22->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c31 = new TCanvas("ChannelSigma"," ",800,400);
c31->Draw();
c31->cd();
TPad *myPad31 = new TPad("myPad31", "The pad",0,0,1,1);
myPadSetUp(myPad31,0.15,0.1,0.04,0.15);
myPad31->SetGridy();
myPad31->Draw();
myPad31->cd();
myHistSetUp(hChannelTimeSigma);
hChannelTimeSigma->Draw("COLZTEXT");
c31->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c32 = new TCanvas("Channel sigma 1D"," ",1200,800);
c32->Draw();
c32->cd();
TPad *myPad32 = new TPad("myPad32", "The pad",0,0,1,1);
myPad32->Divide(4,4);
myPad32->Draw();
for(Int_t i = 0; i<16; i++){
myPadSetUp(myPad32->cd(i+1),0.15,0.00,0.05,0.15);
myPad32->cd(i+1);
gPad->SetGridy();
hChannelSlice = hChannelTimeSigma->ProjectionY("hChannelSlice",i+1,i+1);
myHistSetUp(hChannelSlice);
hChannelSlice->SetMarkerStyle(kFullCircle);
hChannelSlice->SetMarkerSize(0.5);
hChannelSlice->GetXaxis()->SetTitle("");
hChannelSlice->GetYaxis()->SetTitle("Time resolution (ns)");
hChannelSlice->SetTitle(Form("Time resolution channel %d",i));
hChannelSlice->GetYaxis()->SetRangeUser(0.1,1.1);
hChannelSlice->DrawCopy("P");
AddFillSeparationLines(hFillNumber);
}
c32->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c4 = new TCanvas("Rate UB"," ",800,400);
c4->Draw();
c4->cd();
TPad *myPad4 = new TPad("myPad4", "The pad",0,0,1,1);
myPadSetUp(myPad4,0.15,0.1,0.04,0.15);
myPad4->SetGridy();
myPad4->Draw();
myPad4->cd();
myHistSetUp(hRateUBA);
myHistSetUp(hRateUBC);
hRateUBA->SetMarkerColor(kBlue);
hRateUBC->SetMarkerColor(kRed);
hRateUBA->SetMarkerStyle(kFullCircle);
hRateUBC->SetMarkerStyle(kFullCircle);
hRateUBA->GetYaxis()->SetRangeUser(0,1.4);
hRateUBA->Draw("E");
hRateUBC->Draw("Esame");
AddFillSeparationLines(hFillNumber);
myLegend1->Draw();
c4->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c41 = new TCanvas("Physics selection rate BB"," ",800,400);
c41->Draw();
c41->cd();
TPad *myPad41 = new TPad("myPad41", "The pad",0,0,1,1);
myPadSetUp(myPad41,0.15,0.1,0.04,0.15);
myPad41->SetGridy();
myPad41->Draw();
myPad41->cd();
myHistSetUp(hRatePhysBBA);
myHistSetUp(hRatePhysBBC);
hRatePhysBBA->SetMarkerColor(kBlue);
hRatePhysBBC->SetMarkerColor(kRed);
hRatePhysBBA->SetMarkerStyle(kFullCircle);
hRatePhysBBC->SetMarkerStyle(kFullCircle);
hRatePhysBBA->GetYaxis()->SetRangeUser(0,1.4);
hRatePhysBBA->Draw("E");
hRatePhysBBC->Draw("Esame");
AddFillSeparationLines(hFillNumber);
myLegend1->Draw();
c41->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c5 = new TCanvas("Rate UG"," ",800,400);
c5->Draw();
c5->cd();
TPad *myPad5 = new TPad("myPad5", "The pad",0,0,1,1);
myPadSetUp(myPad5,0.15,0.1,0.04,0.15);
myPad5->SetGridy();
myPad5->Draw();
myPad5->cd();
myHistSetUp(hRateUGA);
myHistSetUp(hRateUGC);
hRateUGA->SetMarkerColor(kBlue);
hRateUGC->SetMarkerColor(kRed);
hRateUGA->SetMarkerStyle(kFullCircle);
hRateUGC->SetMarkerStyle(kFullCircle);
myScaleSetUp(hRateUGA,hRateUGC);
hRateUGA->Draw("E");
hRateUGC->Draw("Esame");
AddFillSeparationLines(hFillNumber);
myLegend1->Draw();
c5->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c51 = new TCanvas("Physics selection rate BG"," ",800,400);
c51->Draw();
c51->cd();
TPad *myPad51 = new TPad("myPad51", "The pad",0,0,1,1);
myPadSetUp(myPad51,0.15,0.1,0.04,0.15);
myPad51->SetGridy();
myPad51->Draw();
myPad51->cd();
myHistSetUp(hRatePhysBGA);
myHistSetUp(hRatePhysBGC);
hRatePhysBGA->SetMarkerColor(kBlue);
hRatePhysBGC->SetMarkerColor(kRed);
hRatePhysBGA->SetMarkerStyle(kFullCircle);
hRatePhysBGC->SetMarkerStyle(kFullCircle);
myScaleSetUp(hRatePhysBGA,hRatePhysBGC);
hRatePhysBGA->Draw("E");
hRatePhysBGC->Draw("Esame");
AddFillSeparationLines(hFillNumber);
myLegend1->Draw();
c51->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c6 = new TCanvas("Rate AD"," ",800,400);
c6->Draw();
c6->cd();
TPad *myPad6 = new TPad("myPad6", "The pad",0,0,1,1);
myPadSetUp(myPad6,0.15,0.1,0.04,0.15);
myPad6->SetGridy();
myPad6->Draw();
myPad6->cd();
myHistSetUp(hRateADAND);
myHistSetUp(hRateADOR);
hRateADAND->SetMarkerColor(kBlue);
hRateADOR->SetMarkerColor(kRed);
hRateADAND->SetMarkerStyle(kFullCircle);
hRateADOR->SetMarkerStyle(kFullCircle);
hRateADAND->GetYaxis()->SetRangeUser(0,1.4);
hRateADAND->Draw("E");
hRateADOR->Draw("Esame");
AddFillSeparationLines(hFillNumber);
TLegend *myLegend2 = new TLegend(0.70,0.67,0.97,0.82);
myLegendSetUp(myLegend2,0.04,1);
myLegend2->AddEntry(hRateADAND,"ADAND","p");
myLegend2->AddEntry(hRateADOR,"ADOR","p");
myLegend2->Draw();
c6->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c61 = new TCanvas("Physics selection rate AD"," ",800,400);
c61->Draw();
c61->cd();
TPad *myPad61 = new TPad("myPad61", "The pad",0,0,1,1);
myPadSetUp(myPad61,0.15,0.1,0.04,0.15);
myPad61->SetGridy();
myPad61->Draw();
myPad61->cd();
myHistSetUp(hRatePhysADAND);
myHistSetUp(hRatePhysADOR);
hRatePhysADAND->SetMarkerColor(kBlue);
hRatePhysADOR->SetMarkerColor(kRed);
hRatePhysADAND->SetMarkerStyle(kFullCircle);
hRatePhysADOR->SetMarkerStyle(kFullCircle);
hRatePhysADAND->GetYaxis()->SetRangeUser(0,1.4);
hRatePhysADAND->Draw("E");
hRatePhysADOR->Draw("Esame");
AddFillSeparationLines(hFillNumber);
myLegend2->Draw();
c61->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c11 = new TCanvas("Rate VZERO_AD"," ",800,400);
c11->Draw();
c11->cd();
TPad *myPad11 = new TPad("myPad11", "The pad",0,0,1,1);
myPadSetUp(myPad11,0.15,0.1,0.04,0.15);
myPad11->SetGridy();
myPad11->Draw();
myPad11->cd();
myHistSetUp(hRatioVZEROADAND);
myHistSetUp(hRatioVZEROADOR);
hRatioVZEROADAND->SetMarkerColor(kBlue);
hRatioVZEROADOR->SetMarkerColor(kRed);
hRatioVZEROADAND->SetMarkerStyle(kFullCircle);
hRatioVZEROADOR->SetMarkerStyle(kFullCircle);
myScaleSetUp(hRatioVZEROADAND,hRatioVZEROADOR);
hRatioVZEROADAND->Draw("E");
hRatioVZEROADOR->Draw("Esame");
AddFillSeparationLines(hFillNumber);
TLegend *myLegend3 = new TLegend(0.70,0.67,0.97,0.82);
myLegendSetUp(myLegend3,0.04,1);
myLegend3->AddEntry(hRatioVZEROADAND,"VZERO_AND/AD_AND","p");
myLegend3->AddEntry(hRatioVZEROADOR,"VZERO_OR/AD_OR","p");
myLegend3->Draw();
c11->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c15 = new TCanvas("FlagNoTime"," ",800,400);
c15->Draw();
c15->cd();
TPad *myPad15 = new TPad("myPad15", "The pad",0,0,1,1);
myPadSetUp(myPad15,0.15,0.1,0.04,0.15);
myPad15->SetGridy();
myPad15->Draw();
myPad15->cd();
myHistSetUp(hFlagNoTime);
if(hFlagNoTime->Integral()!=0)hFlagNoTime->Draw("COLZTEXT");
c15->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c151 = new TCanvas("FlagNoTime 1D"," ",1200,800);
c151->Draw();
c151->cd();
TPad *myPad151 = new TPad("myPad151", "The pad",0,0,1,1);
myPad151->Divide(4,4);
myPad151->Draw();
for(Int_t i = 0; i<16; i++){
myPadSetUp(myPad151->cd(i+1),0.15,0.10,0.05,0.15);
myPad151->cd(i+1);
gPad->SetGridy();
hChannelSlice = hFlagNoTime->ProjectionY("hChannelSlice",i+1,i+1);
myHistSetUp(hChannelSlice);
hChannelSlice->SetLineWidth(1);
myScaleSetUp(hChannelSlice);
hChannelSlice->GetXaxis()->SetTitle("");
hChannelSlice->GetYaxis()->SetTitle("Fraction with flag but no time");
hChannelSlice->SetTitle(Form("Flag but no time fraction channel %d",i));
//hChannelSlice->GetYaxis()->SetRangeUser(2,30);
hChannelSlice->DrawCopy("HIST");
}
c151->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c7 = new TCanvas("MPV"," ",800,400);
c7->Draw();
c7->cd();
TPad *myPad7 = new TPad("myPad7", "The pad",0,0,1,1);
myPadSetUp(myPad7,0.15,0.1,0.04,0.15);
myPad7->SetGridy();
myPad7->Draw();
myPad7->cd();
myHistSetUp(hMPV);
if(hMPV->Integral()!=0)hMPV->Draw("COLZTEXT");
c7->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c71 = new TCanvas("MPV 1D"," ",1200,800);
c71->Draw();
c71->cd();
TPad *myPad71 = new TPad("myPad71", "The pad",0,0,1,1);
myPad71->Divide(4,4);
myPad71->Draw();
for(Int_t i = 0; i<16; i++){
myPadSetUp(myPad71->cd(i+1),0.15,0.00,0.05,0.15);
myPad71->cd(i+1);
gPad->SetGridy();
hChannelSlice = hMPV->ProjectionY("hChannelSlice",i+1,i+1,"e");
for(Int_t j = 0; j<hChannelSlice->GetNbinsX(); j++)hChannelSlice->SetBinError(j+1,hMPV->GetBinError(i+1,j+1));
myHistSetUp(hChannelSlice);
hChannelSlice->SetLineWidth(1);
myScaleSetUp(hChannelSlice);
hChannelSlice->GetXaxis()->SetTitle("");
hChannelSlice->GetYaxis()->SetTitle("MPV (ADC counts)");
hChannelSlice->SetTitle(Form("MPV channel %d",i));
hChannelSlice->GetYaxis()->SetRangeUser(0,17);
hChannelSlice->SetMarkerStyle(kFullCircle);
hChannelSlice->DrawCopy("E");
}
c71->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c13 = new TCanvas("SlewingChi2"," ",800,400);
c13->Draw();
c13->cd();
TPad *myPad13 = new TPad("myPad13", "The pad",0,0,1,1);
myPadSetUp(myPad13,0.15,0.1,0.04,0.15);
myPad13->SetGridy();
myPad13->Draw();
myPad13->cd();
myHistSetUp(hSlewingChi2ADA);
myHistSetUp(hSlewingChi2ADC);
hSlewingChi2ADA->SetMarkerColor(kBlue);
hSlewingChi2ADC->SetMarkerColor(kRed);
hSlewingChi2ADA->SetMarkerStyle(kFullCircle);
hSlewingChi2ADC->SetMarkerStyle(kFullCircle);
//myScaleSetUp(hSlewingChi2ADA,hSlewingChi2ADC);
hSlewingChi2ADA->GetYaxis()->SetRangeUser(-0.1,1);
hSlewingChi2ADA->SetTitle("Average deviation from time of flight");
hSlewingChi2ADA->GetYaxis()->SetTitle("Mean |#Delta| [ns]");
hSlewingChi2ADA->Draw("P");
hSlewingChi2ADC->Draw("Psame");
AddFillSeparationLines(hFillNumber);
myLegend1->Draw();
c13->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c14 = new TCanvas("Saturation"," ",800,400);
c14->Draw();
c14->cd();
TPad *myPad14 = new TPad("myPad14", "The pad",0,0,1,1);
myPadSetUp(myPad14,0.15,0.1,0.04,0.15);
myPad14->SetGridy();
myPad14->Draw();
myPad14->cd();
myHistSetUp(hSaturationADA);
myHistSetUp(hSaturationADC);
hSaturationADA->SetMarkerColor(kBlue);
hSaturationADC->SetMarkerColor(kRed);
hSaturationADA->SetMarkerStyle(kFullCircle);
hSaturationADC->SetMarkerStyle(kFullCircle);
myScaleSetUp(hSaturationADA,hSaturationADC);
hSaturationADA->GetYaxis()->SetRange(0,hSaturationADA->GetYaxis()->GetLast());
hSaturationADA->Draw("P");
hSaturationADC->Draw("Psame");
AddFillSeparationLines(hFillNumber);
myLegend1->Draw();
c14->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
if(hADready->GetEntries())
{
TCanvas * cBad1 = new TCanvas("cBad1","");
cBad1->cd();
hADready->Draw();
cBad1->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
}
if(hInvalidInput->GetEntries())
{
TCanvas * cBad2 = new TCanvas("cBad2","");
cBad2->cd();
hInvalidInput->Draw();
cBad2->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
}
if(hQANotFound->GetEntries())
{
TCanvas * cBad3 = new TCanvas("cBad3","");
cBad3->cd();
hQANotFound->Draw();
cBad3->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
}
if(hADactive->GetEntries())
{
TCanvas * cBad4 = new TCanvas("cBad4","");
cBad4->cd();
hADactive->Draw();
cBad4->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
}
if(hADqaNotfound->GetEntries())
{
TCanvas * cBad5 = new TCanvas("cBad5","");
cBad5->cd();
hADqaNotfound->Draw();
cBad5->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
}
if(hNoEntries->GetEntries())
{
TCanvas * cBad6 = new TCanvas("cBad6","");
cBad6->cd();
hNoEntries->Draw();
cBad6->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
}
TCanvas *c16 = new TCanvas("Thresholds"," ",1200,800);
c16->Draw();
c16->cd();
TPad *myPad16 = new TPad("myPad16", "The pad",0,0,1,1);
myPad16->Divide(4,4);
myPad16->Draw();
TH1D *hChannelSliceBlue;
TH1D *hChannelSliceRed;
for(Int_t i = 0; i<16; i++){
myPadSetUp(myPad16->cd(i+1),0.15,0.00,0.05,0.15);
myPad16->cd(i+1);
gPad->SetGridy();
hChannelSliceRed = hThresholdData->ProjectionY("hChannelSliceRed",i+1,i+1);
myHistSetUp(hChannelSliceRed);
hChannelSliceRed->SetLineWidth(1);
hChannelSliceRed->SetLineColor(kRed);
hChannelSliceRed->GetXaxis()->SetTitle("");
hChannelSliceRed->GetYaxis()->SetTitle("Threshold [ADC counts]");
hChannelSliceRed->SetTitle(Form("Threshold, channel %d",i));
hChannelSliceBlue = hThresholdOCDB->ProjectionY("hChannelSliceBlue",i+1,i+1);
myHistSetUp(hChannelSliceBlue);
hChannelSliceBlue->SetLineWidth(1);
hChannelSliceBlue->SetLineColor(kBlue);
myScaleSetUp(hChannelSliceRed,hChannelSliceBlue);
hChannelSliceRed->DrawCopy("HIST");
hChannelSliceBlue->DrawCopy("HISTSAME");
TLegend *myLegend4 = new TLegend(0.36,0.62,0.62,0.84);
myLegendSetUp(myLegend4,0.08,1);
myLegend4->AddEntry(hChannelSliceRed,"Data","l");
myLegend4->AddEntry(hChannelSliceBlue,"OCDB","l");
myLegend4->Draw();
}
c16->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c8 = new TCanvas("Pedestal mean"," ",1200,400);
c8->Draw();
c8->cd();
TPad *myPad8 = new TPad("myPad8", "The pad",0,0,1,1);
myPadSetUp(myPad8,0.15,0.1,0.04,0.15);
myPad8->SetGridy();
myPad8->Draw();
myPad8->cd();
myHistSetUp(hMeanPedestal);
if(hMeanPedestal->Integral()!=0)hMeanPedestal->Draw("COLZTEXT");
c8->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c81 = new TCanvas("Pedestal mean 1D Int0"," ",1200,800);
c81->Draw();
c81->cd();
TPad *myPad81 = new TPad("myPad81", "The pad",0,0,1,1);
myPad81->Divide(4,4);
myPad81->Draw();
for(Int_t i = 0; i<16; i++){
myPadSetUp(myPad81->cd(i+1),0.15,0.00,0.05,0.15);
myPad81->cd(i+1);
gPad->SetGridy();
hChannelSlice = hMeanPedestal->ProjectionY("hChannelSlice",i+1,i+1);
myHistSetUp(hChannelSlice);
hChannelSlice->SetLineWidth(1);
hChannelSlice->GetXaxis()->SetTitle("");
hChannelSlice->GetYaxis()->SetTitle("Pedestal mean");
myScaleSetUp(hChannelSlice);
hChannelSlice->SetTitle(Form("Pedestal mean channel %d, Int0",i));
hChannelSlice->DrawCopy("HIST");
AddFillSeparationLines(hFillNumber);
}
c81->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c82 = new TCanvas("Pedestal mean 1D Int1"," ",1200,800);
c82->Draw();
c82->cd();
TPad *myPad82 = new TPad("myPad82", "The pad",0,0,1,1);
myPad82->Divide(4,4);
myPad82->Draw();
for(Int_t i = 0; i<16; i++){
myPadSetUp(myPad82->cd(i+1),0.15,0.00,0.05,0.15);
myPad82->cd(i+1);
gPad->SetGridy();
hChannelSlice = hMeanPedestal->ProjectionY("hChannelSlice",i+17,i+17);
myHistSetUp(hChannelSlice);
hChannelSlice->SetLineWidth(1);
hChannelSlice->GetXaxis()->SetTitle("");
hChannelSlice->GetYaxis()->SetTitle("Pedestal mean");
myScaleSetUp(hChannelSlice);
hChannelSlice->SetTitle(Form("Pedestal mean channel %d, Int1",i));
hChannelSlice->DrawCopy("HIST");
AddFillSeparationLines(hFillNumber);
}
c82->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c9 = new TCanvas("Pedestal width"," ",1200,400);
c9->Draw();
c9->cd();
TPad *myPad9 = new TPad("myPad9", "The pad",0,0,1,1);
myPadSetUp(myPad9,0.15,0.1,0.04,0.15);
myPad9->SetGridy();
myPad9->Draw();
myPad9->cd();
myHistSetUp(hWidthPedestal);
if(hWidthPedestal->Integral()!=0)hWidthPedestal->Draw("COLZTEXT");
c9->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c91 = new TCanvas("Pedestal width 1D Int0"," ",1200,800);
c91->Draw();
c91->cd();
TPad *myPad91 = new TPad("myPad91", "The pad",0,0,1,1);
myPad91->Divide(4,4);
myPad91->Draw();
for(Int_t i = 0; i<16; i++){
myPadSetUp(myPad91->cd(i+1),0.15,0.00,0.05,0.15);
myPad91->cd(i+1);
gPad->SetGridy();
hChannelSlice = hWidthPedestal->ProjectionY("hChannelSlice",i+1,i+1);
myHistSetUp(hChannelSlice);
hChannelSlice->SetLineWidth(1);
hChannelSlice->GetXaxis()->SetTitle("");
hChannelSlice->GetYaxis()->SetTitle("Pedestal width");
myScaleSetUp(hChannelSlice);
hChannelSlice->SetTitle(Form("Pedestal width channel %d, Int0",i));
hChannelSlice->DrawCopy("HIST");
AddFillSeparationLines(hFillNumber);
}
c91->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c92 = new TCanvas("Pedestal width 1D Int1"," ",1200,800);
c92->Draw();
c92->cd();
TPad *myPad92 = new TPad("myPad92", "The pad",0,0,1,1);
myPad92->Divide(4,4);
myPad92->Draw();
for(Int_t i = 0; i<16; i++){
myPadSetUp(myPad92->cd(i+1),0.15,0.00,0.05,0.15);
myPad92->cd(i+1);
gPad->SetGridy();
hChannelSlice = hWidthPedestal->ProjectionY("hChannelSlice",i+17,i+17);
myHistSetUp(hChannelSlice);
hChannelSlice->SetLineWidth(1);
hChannelSlice->GetXaxis()->SetTitle("");
hChannelSlice->GetYaxis()->SetTitle("Pedestal width");
myScaleSetUp(hChannelSlice);
hChannelSlice->SetTitle(Form("Pedestal width channel %d, Int1",i));
hChannelSlice->DrawCopy("HIST");
AddFillSeparationLines(hFillNumber);
}
c92->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c10 = new TCanvas("Run time"," ",800,400);
c10->Draw();
c10->cd();
TPad *myPad10 = new TPad("myPad10", "The pad",0,0,1,1);
myPadSetUp(myPad10,0.15,0.1,0.04,0.15);
myPad10->SetGridy();
myPad10->Draw();
myPad10->cd();
myHistSetUp(hRunTime);
hRunTime->SetMarkerStyle(kFullCircle);
hRunTime->Draw("P");
c10->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c11 = new TCanvas("LHC state"," ",800,400);
c11->Draw();
c11->cd();
TPad *myPad11 = new TPad("myPad11", "The pad",0,0,1,1);
myPadSetUp(myPad11,0.15,0.1,0.04,0.15);
myPad11->SetGridy();
myPad11->Draw();
myPad11->cd();
myHistSetUp(hLHCstate);
hLHCstate->SetMarkerStyle(kFullCircle);
hLHCstate->GetYaxis()->Set(5,-1.5,3.5);
hLHCstate->GetYaxis()->SetRangeUser(-0.5,3.5);
hLHCstate->GetYaxis()->SetBinLabel(2,"No Beam");
hLHCstate->GetYaxis()->SetBinLabel(3,"Squeeze");
hLHCstate->GetYaxis()->SetBinLabel(4,"Adjust");
hLHCstate->GetYaxis()->SetBinLabel(5,"Stable beams");
hLHCstate->Draw("P");
c11->Print(Form("%s/QA_Resume_%d_%d.pdf",plotDir.Data(),minRun,maxRun));
TCanvas *c12 = new TCanvas("Number of events"," ",800,400);
c12->Draw();
c12->cd();
TPad *myPad12 = new TPad("myPad12", "The pad",0,0,1,1);
myPadSetUp(myPad12,0.15,0.1,0.04,0.15);
myPad12->SetGridy();
myPad12->Draw();
myPad12->cd();
gPad->SetLogy();
myHistSetUp(hNEvents);
hNEvents->SetMarkerStyle(kFullCircle);
hNEvents->Draw("P");
c12->Print(Form("%s/QA_Resume_%d_%d.pdf)",plotDir.Data(),minRun,maxRun));
return 0;
}
void AddFillSeparationLines(TH1* hFillNumber){
gPad->Update();
Double_t ymin = gPad->GetUymin();
Double_t ymax = gPad->GetUymax();
TLine * fillSeparationLine = new TLine();
fillSeparationLine->SetLineColor(kBlack);
fillSeparationLine->SetLineStyle(kDashed);
fillSeparationLine->SetLineWidth(1);
for(Int_t iBin = 1; iBin < hFillNumber->GetXaxis()->GetNbins(); iBin++) {
UInt_t fillOld = hFillNumber->GetBinContent(iBin);
UInt_t fillNew = hFillNumber->GetBinContent(iBin + 1);
if (fillOld==fillNew) continue;
fillSeparationLine->DrawLine(hFillNumber->GetBinLowEdge(iBin+1),ymin,hFillNumber->GetBinLowEdge(iBin+1),ymax);
}
}
void myScaleSetUp(TH1* histoBlue, TH1* histoRed){
Float_t min[2], max[2];
max[0] = histoBlue->GetBinContent(histoBlue->GetMaximumBin());
max[1] = histoRed->GetBinContent(histoRed->GetMaximumBin());
min[0] = histoBlue->GetBinContent(histoBlue->GetMinimumBin());
min[1] = histoRed->GetBinContent(histoRed->GetMinimumBin());
histoBlue->GetYaxis()->SetRangeUser(0.5*TMath::MinElement(2,min),1.5*TMath::MaxElement(2,max));
}
void myScaleSetUp(TH1* histo){
Float_t min, max;
max = histo->GetBinContent(histo->GetMaximumBin());
min = histo->GetBinContent(histo->GetMinimumBin());
histo->GetYaxis()->SetRangeUser(0.5*min,1.5*max);
}
void myPadSetUp(TVirtualPad *currentPad, float currentLeft=0.31, float currentTop=0.04, float currentRight=0.04, float currentBottom=0.15){
currentPad->SetLeftMargin(currentLeft);
currentPad->SetTopMargin(currentTop);
currentPad->SetRightMargin(currentRight);
currentPad->SetBottomMargin(currentBottom);
return;
}
void myPadSetUp(TPad *currentPad, float currentLeft=0.11, float currentTop=0.04, float currentRight=0.11, float currentBottom=0.15){
currentPad->SetLeftMargin(currentLeft);
currentPad->SetTopMargin(currentTop);
currentPad->SetRightMargin(currentRight);
currentPad->SetBottomMargin(currentBottom);
return;
}
void myLegendSetUp(TLegend *currentLegend=0,float currentTextSize=0.07,int columns=2){
currentLegend->SetTextFont(42);
currentLegend->SetBorderSize(0);
currentLegend->SetFillStyle(0);
currentLegend->SetFillColor(0);
currentLegend->SetMargin(0.25);
currentLegend->SetTextSize(currentTextSize);
currentLegend->SetEntrySeparation(0.5);
currentLegend->SetNColumns(columns);
return;
}
void myHistSetUp(TH1 *currentGraph=0){
currentGraph->SetLabelSize(0.05,"xyz");
currentGraph->SetLabelFont(42,"xyz");
currentGraph->SetLabelOffset(0.01,"xyz");
currentGraph->SetTitleFont(42,"xyz");
currentGraph->GetXaxis()->SetTitleOffset(1.1);
currentGraph->GetXaxis()->LabelsOption("v");
currentGraph->GetYaxis()->SetTitleOffset(1.1);
currentGraph->SetTitleSize(0.06,"xyz");
currentGraph->SetStats(kFALSE);
return;
}
void myHistSetUp(TH2 *currentGraph=0){
currentGraph->SetLabelSize(0.03,"xyz");
currentGraph->SetLabelFont(42,"xyz");
currentGraph->SetLabelOffset(0.01,"xyz");
currentGraph->SetTitleFont(42,"xyz");
currentGraph->GetXaxis()->SetTitleOffset(1.3);
currentGraph->GetYaxis()->SetTitleOffset(1.3);
currentGraph->GetYaxis()->LabelsOption("h");
currentGraph->SetTitleSize(0.05,"xyz");
currentGraph->SetStats(kFALSE);
return;
}
void myOptions(Int_t lStat=0){
// Set gStyle
int font = 42;
// From plain
gStyle->SetFrameBorderMode(0);
gStyle->SetFrameFillColor(0);
gStyle->SetCanvasBorderMode(0);
gStyle->SetPadBorderMode(0);
gStyle->SetPadColor(10);
gStyle->SetCanvasColor(10);
gStyle->SetTitleFillColor(10);
gStyle->SetTitleBorderSize(1);
gStyle->SetStatColor(10);
gStyle->SetStatBorderSize(1);
gStyle->SetLegendBorderSize(1);
//
gStyle->SetDrawBorder(0);
gStyle->SetTextFont(font);
gStyle->SetStatFont(font);
gStyle->SetStatFontSize(0.05);
gStyle->SetStatX(0.97);
gStyle->SetStatY(0.98);
gStyle->SetStatH(0.03);
gStyle->SetStatW(0.3);
gStyle->SetTickLength(0.02,"y");
gStyle->SetEndErrorSize(3);
gStyle->SetLabelSize(0.05,"xyz");
gStyle->SetLabelFont(font,"xyz");
gStyle->SetLabelOffset(0.01,"xyz");
gStyle->SetTitleFont(font,"xyz");
gStyle->SetTitleOffset(1.0,"xyz");
gStyle->SetTitleSize(0.06,"xyz");
gStyle->SetMarkerSize(1);
gStyle->SetPalette(1,0);
gStyle->SetErrorX(0);
if (lStat){
gStyle->SetOptTitle(1);
gStyle->SetOptStat(1111111);
gStyle->SetOptFit(1111111);
}
else {
gStyle->SetOptTitle(1);
gStyle->SetOptStat(0);
gStyle->SetOptFit(0);
}
}
| bsd-3-clause |
poizan42/coreclr | tests/src/JIT/HardwareIntrinsics/X86/Sse/SubtractScalar.Single.cs | 24849 | // 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractScalarSingle()
{
var test = new SimpleBinaryOpTest__SubtractScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractScalarSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SubtractScalarSingle testClass)
{
var result = Sse.SubtractScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractScalarSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.SubtractScalar(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SubtractScalarSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleBinaryOpTest__SubtractScalarSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse.SubtractScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse.SubtractScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse.SubtractScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse).GetMethod(nameof(Sse.SubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse).GetMethod(nameof(Sse.SubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse).GetMethod(nameof(Sse.SubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse.SubtractScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = Sse.SubtractScalar(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.SubtractScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.SubtractScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.SubtractScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SubtractScalarSingle();
var result = Sse.SubtractScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__SubtractScalarSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = Sse.SubtractScalar(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse.SubtractScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.SubtractScalar(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse.SubtractScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse.SubtractScalar(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(left[0] - right[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.SubtractScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| mit |
eboominathan/cakephp | src/Routing/DispatcherFactory.php | 3156 | <?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Routing;
use Cake\Core\App;
use Cake\Routing\Exception\MissingDispatcherFilterException;
/**
* A factory for creating dispatchers with all the desired middleware
* connected.
*/
class DispatcherFactory
{
/**
* Stack of middleware to apply to dispatchers.
*
* @var array
*/
protected static $_stack = [];
/**
* Add a new middleware object to the stack of middleware
* that will be executed.
*
* Instances of filters will be re-used across all sub-requests
* in a request.
*
* @param string|\Cake\Routing\DispatcherFilter $filter Either the classname of the filter
* or an instance to use.
* @param array $options Constructor arguments/options for the filter if you are using a string name.
* If you are passing an instance, this argument will be ignored.
* @return \Cake\Routing\DispatcherFilter
*/
public static function add($filter, array $options = [])
{
if (is_string($filter)) {
$filter = static::_createFilter($filter, $options);
}
static::$_stack[] = $filter;
return $filter;
}
/**
* Create an instance of a filter.
*
* @param string $name The name of the filter to build.
* @param array $options Constructor arguments/options for the filter.
* @return \Cake\Routing\DispatcherFilter
* @throws \Cake\Routing\Exception\MissingDispatcherFilterException When filters cannot be found.
*/
protected static function _createFilter($name, $options)
{
$className = App::className($name, 'Routing/Filter', 'Filter');
if (!$className) {
$msg = sprintf('Cannot locate dispatcher filter named "%s".', $name);
throw new MissingDispatcherFilterException($msg);
}
return new $className($options);
}
/**
* Create a dispatcher that has all the configured middleware applied.
*
* @return \Cake\Routing\Dispatcher
*/
public static function create()
{
$dispatcher = new Dispatcher();
foreach (static::$_stack as $middleware) {
$dispatcher->addFilter($middleware);
}
return $dispatcher;
}
/**
* Get the connected dispatcher filters.
*
* @return array
*/
public static function filters()
{
return static::$_stack;
}
/**
* Clear the middleware stack.
*
* @return void
*/
public static function clear()
{
static::$_stack = [];
}
}
| mit |
krk/coreclr | tests/src/JIT/HardwareIntrinsics/X86/Sse2/CompareScalarOrderedNotEqual.Boolean.cs | 22274 | // 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareScalarOrderedNotEqualBoolean()
{
var test = new BooleanBinaryOpTest__CompareScalarOrderedNotEqualBoolean();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__CompareScalarOrderedNotEqualBoolean
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__CompareScalarOrderedNotEqualBoolean testClass)
{
var result = Sse2.CompareScalarOrderedNotEqual(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__CompareScalarOrderedNotEqualBoolean testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareScalarOrderedNotEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__CompareScalarOrderedNotEqualBoolean()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public BooleanBinaryOpTest__CompareScalarOrderedNotEqualBoolean()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.CompareScalarOrderedNotEqual(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.CompareScalarOrderedNotEqual(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.CompareScalarOrderedNotEqual(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarOrderedNotEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarOrderedNotEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarOrderedNotEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.CompareScalarOrderedNotEqual(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse2.CompareScalarOrderedNotEqual(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareScalarOrderedNotEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareScalarOrderedNotEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareScalarOrderedNotEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__CompareScalarOrderedNotEqualBoolean();
var result = Sse2.CompareScalarOrderedNotEqual(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__CompareScalarOrderedNotEqualBoolean();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse2.CompareScalarOrderedNotEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.CompareScalarOrderedNotEqual(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareScalarOrderedNotEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.CompareScalarOrderedNotEqual(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.CompareScalarOrderedNotEqual(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, bool result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Double[] left, Double[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((left[0] != right[0]) != result)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareScalarOrderedNotEqual)}<Boolean>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| mit |
xnox/linaro-gcc-4.7-src | gcc/testsuite/g++.dg/ext/complex8.C | 1133 | // PR libstdc++/48760
// { dg-options -std=c++0x }
// { dg-do run }
constexpr _Complex int i{1,2};
constexpr _Complex int j{3};
#define SA(X) static_assert((X),#X)
SA(__real i == 1);
SA(__imag i == 2);
SA(__real j == 3);
SA(__imag j == 0);
struct A
{
_Complex int c;
constexpr A(int i, int j): c{i,j} { }
constexpr A(int i): c{i} { }
};
constexpr A a1(1,2);
constexpr A a2(3);
SA(__real a1.c == 1);
SA(__imag a1.c == 2);
SA(__real a2.c == 3);
SA(__imag a2.c == 0);
typedef _Complex int ci;
SA((__real ci{1,2} == 1));
SA((__imag ci{1,2} == 2));
SA((__real ci{3} == 3));
SA((__imag ci{3} == 0));
struct B
{
_Complex int c;
int i;
};
constexpr B b1 = { { 1,2 }, 42 };
constexpr B b2 = { { 3 }, 24 };
// No brace elision for complex.
constexpr B b3 = { 5, 6 };
SA(__real b1.c == 1);
SA(__imag b1.c == 2);
SA(b1.i == 42);
SA(__real b2.c == 3);
SA(__imag b2.c == 0);
SA(b2.i == 24);
SA(__real b3.c == 5);
SA(__imag b3.c == 0);
SA(b3.i == 6);
int main()
{
ci* p = new ci{1,2};
if (__real *p != 1 || __imag *p != 2)
return 1;
delete p;
p = new ci{3};
if (__real *p != 3 || __imag *p != 0)
return 1;
}
| gpl-2.0 |
joshwillcock/moodle | mod/lti/service/toolproxy/version.php | 1195 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Version information for the ltiservice_toolproxy service.
*
* @package ltiservice_toolproxy
* @copyright 2014 Vital Source Technologies http://vitalsource.com
* @author Stephen Vickers
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2016120500;
$plugin->requires = 2016112900;
$plugin->component = 'ltiservice_toolproxy';
$plugin->dependencies = array(
'ltiservice_profile' => 2016112900
);
| gpl-3.0 |
bearing/grif | external/boost/serialization/shared_ptr.hpp | 6552 | #ifndef BOOST_SERIALIZATION_SHARED_PTR_HPP
#define BOOST_SERIALIZATION_SHARED_PTR_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// shared_ptr.hpp: serialization for boost shared pointer
// (C) Copyright 2004 Robert Ramey and Martin Ecker
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#include <cstddef> // NULL
#include <boost/config.hpp>
#include <boost/mpl/integral_c.hpp>
#include <boost/mpl/integral_c_tag.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/tracking.hpp>
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// shared_ptr serialization traits
// version 1 to distinguish from boost 1.32 version. Note: we can only do this
// for a template when the compiler supports partial template specialization
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
namespace boost {
namespace serialization{
template<class T>
struct version< ::boost::shared_ptr< T > > {
typedef mpl::integral_c_tag tag;
#if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3206))
typedef BOOST_DEDUCED_TYPENAME mpl::int_<1> type;
#else
typedef mpl::int_<1> type;
#endif
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x570))
BOOST_STATIC_CONSTANT(int, value = 1);
#else
BOOST_STATIC_CONSTANT(int, value = type::value);
#endif
};
// don't track shared pointers
template<class T>
struct tracking_level< ::boost::shared_ptr< T > > {
typedef mpl::integral_c_tag tag;
#if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3206))
typedef BOOST_DEDUCED_TYPENAME mpl::int_< ::boost::serialization::track_never> type;
#else
typedef mpl::int_< ::boost::serialization::track_never> type;
#endif
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x570))
BOOST_STATIC_CONSTANT(int, value = ::boost::serialization::track_never);
#else
BOOST_STATIC_CONSTANT(int, value = type::value);
#endif
};
}}
#define BOOST_SERIALIZATION_SHARED_PTR(T)
#else
// define macro to let users of these compilers do this
#define BOOST_SERIALIZATION_SHARED_PTR(T) \
BOOST_CLASS_VERSION( \
::boost::shared_ptr< T >, \
1 \
) \
BOOST_CLASS_TRACKING( \
::boost::shared_ptr< T >, \
::boost::serialization::track_never \
) \
/**/
#endif
namespace boost {
namespace serialization{
struct null_deleter {
void operator()(void const *) const {}
};
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// serialization for shared_ptr
template<class Archive, class T>
inline void save(
Archive & ar,
const boost::shared_ptr< T > &t,
const unsigned int /* file_version */
){
// The most common cause of trapping here would be serializing
// something like shared_ptr<int>. This occurs because int
// is never tracked by default. Wrap int in a trackable type
BOOST_STATIC_ASSERT((tracking_level< T >::value != track_never));
const T * t_ptr = t.get();
ar << boost::serialization::make_nvp("px", t_ptr);
}
#ifdef BOOST_SERIALIZATION_SHARED_PTR_132_HPP
template<class Archive, class T>
inline void load(
Archive & ar,
boost::shared_ptr< T > &t,
const unsigned int file_version
){
// The most common cause of trapping here would be serializing
// something like shared_ptr<int>. This occurs because int
// is never tracked by default. Wrap int in a trackable type
BOOST_STATIC_ASSERT((tracking_level< T >::value != track_never));
T* r;
if(file_version < 1){
//ar.register_type(static_cast<
// boost_132::detail::sp_counted_base_impl<T *, boost::checked_deleter< T > > *
//>(NULL));
ar.register_type(static_cast<
boost_132::detail::sp_counted_base_impl<T *, null_deleter > *
>(NULL));
boost_132::shared_ptr< T > sp;
ar >> boost::serialization::make_nvp("px", sp.px);
ar >> boost::serialization::make_nvp("pn", sp.pn);
// got to keep the sps around so the sp.pns don't disappear
ar.append(sp);
r = sp.get();
}
else{
ar >> boost::serialization::make_nvp("px", r);
}
ar.reset(t,r);
}
#else
template<class Archive, class T>
inline void load(
Archive & ar,
boost::shared_ptr< T > &t,
const unsigned int /*file_version*/
){
// The most common cause of trapping here would be serializing
// something like shared_ptr<int>. This occurs because int
// is never tracked by default. Wrap int in a trackable type
BOOST_STATIC_ASSERT((tracking_level< T >::value != track_never));
T* r;
ar >> boost::serialization::make_nvp("px", r);
ar.reset(t,r);
}
#endif
template<class Archive, class T>
inline void serialize(
Archive & ar,
boost::shared_ptr< T > &t,
const unsigned int file_version
){
// correct shared_ptr serialization depends upon object tracking
// being used.
BOOST_STATIC_ASSERT(
boost::serialization::tracking_level< T >::value
!= boost::serialization::track_never
);
boost::serialization::split_free(ar, t, file_version);
}
} // namespace serialization
} // namespace boost
#endif // BOOST_SERIALIZATION_SHARED_PTR_HPP
| lgpl-3.0 |
mdegoo/angular | packages/http/test/headers_spec.ts | 6718 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Headers} from '../src/headers';
export function main() {
describe('Headers', () => {
describe('initialization', () => {
it('should conform to spec', () => {
const httpHeaders = {
'Content-Type': 'image/jpeg',
'Accept-Charset': 'utf-8',
'X-My-Custom-Header': 'Zeke are cool',
};
const secondHeaders = new Headers(httpHeaders);
const secondHeadersObj = new Headers(secondHeaders);
expect(secondHeadersObj.get('Content-Type')).toEqual('image/jpeg');
});
it('should merge values in provided dictionary', () => {
const headers = new Headers({'foo': 'bar'});
expect(headers.get('foo')).toEqual('bar');
expect(headers.getAll('foo')).toEqual(['bar']);
});
it('should not alter the values of a provided header template', () => {
// Spec at https://fetch.spec.whatwg.org/#concept-headers-fill
// test for https://github.com/angular/angular/issues/6845
const firstHeaders = new Headers();
const secondHeaders = new Headers(firstHeaders);
secondHeaders.append('Content-Type', 'image/jpeg');
expect(firstHeaders.has('Content-Type')).toEqual(false);
});
it('should preserve the list of values', () => {
const src = new Headers();
src.append('foo', 'a');
src.append('foo', 'b');
src.append('foo', 'c');
const dst = new Headers(src);
expect(dst.getAll('foo')).toEqual(src.getAll('foo'));
});
it('should keep the last value when initialized from an object', () => {
const headers = new Headers({
'foo': 'first',
'fOo': 'second',
});
expect(headers.getAll('foo')).toEqual(['second']);
});
});
describe('.set()', () => {
it('should clear all values and re-set for the provided key', () => {
const headers = new Headers({'foo': 'bar'});
expect(headers.get('foo')).toEqual('bar');
headers.set('foo', 'baz');
expect(headers.get('foo')).toEqual('baz');
headers.set('fOO', 'bat');
expect(headers.get('foo')).toEqual('bat');
});
it('should preserve the case of the first call', () => {
const headers = new Headers();
headers.set('fOo', 'baz');
headers.set('foo', 'bat');
expect(JSON.stringify(headers)).toEqual('{"fOo":["bat"]}');
});
it('should preserve cases after cloning', () => {
const headers = new Headers();
headers.set('fOo', 'baz');
headers.set('foo', 'bat');
expect(JSON.stringify(new Headers(headers))).toEqual('{"fOo":["bat"]}');
});
it('should convert input array to string', () => {
const headers = new Headers();
headers.set('foo', ['bar', 'baz']);
expect(headers.get('foo')).toEqual('bar,baz');
expect(headers.getAll('foo')).toEqual(['bar,baz']);
});
});
describe('.get()', () => {
it('should be case insensitive', () => {
const headers = new Headers();
headers.set('foo', 'baz');
expect(headers.get('foo')).toEqual('baz');
expect(headers.get('FOO')).toEqual('baz');
});
it('should return null if the header is not present', () => {
const headers = new Headers({bar: []});
expect(headers.get('bar')).toEqual(null);
expect(headers.get('foo')).toEqual(null);
});
});
describe('.getAll()', () => {
it('should be case insensitive', () => {
const headers = new Headers({foo: ['bar', 'baz']});
expect(headers.getAll('foo')).toEqual(['bar', 'baz']);
expect(headers.getAll('FOO')).toEqual(['bar', 'baz']);
});
it('should return null if the header is not present', () => {
const headers = new Headers();
expect(headers.getAll('foo')).toEqual(null);
});
});
describe('.delete', () => {
it('should be case insensitive', () => {
const headers = new Headers();
headers.set('foo', 'baz');
expect(headers.has('foo')).toEqual(true);
headers.delete('foo');
expect(headers.has('foo')).toEqual(false);
headers.set('foo', 'baz');
expect(headers.has('foo')).toEqual(true);
headers.delete('FOO');
expect(headers.has('foo')).toEqual(false);
});
});
describe('.append', () => {
it('should append a value to the list', () => {
const headers = new Headers();
headers.append('foo', 'bar');
headers.append('foo', 'baz');
expect(headers.get('foo')).toEqual('bar');
expect(headers.getAll('foo')).toEqual(['bar', 'baz']);
});
it('should preserve the case of the first call', () => {
const headers = new Headers();
headers.append('FOO', 'bar');
headers.append('foo', 'baz');
expect(JSON.stringify(headers)).toEqual('{"FOO":["bar","baz"]}');
});
});
describe('.toJSON()', () => {
let headers: Headers;
let values: string[];
let ref: {[name: string]: string[]};
beforeEach(() => {
values = ['application/jeisen', 'application/jason', 'application/patrickjs'];
headers = new Headers();
headers.set('Accept', values);
ref = {'Accept': values};
});
it('should be serializable with toJSON',
() => { expect(JSON.stringify(headers)).toEqual(JSON.stringify(ref)); });
it('should be able to recreate serializedHeaders', () => {
const parsedHeaders = JSON.parse(JSON.stringify(headers));
const recreatedHeaders = new Headers(parsedHeaders);
expect(JSON.stringify(parsedHeaders)).toEqual(JSON.stringify(recreatedHeaders));
});
});
describe('.fromResponseHeaderString()', () => {
it('should parse a response header string', () => {
const response = `Date: Fri, 20 Nov 2015 01:45:26 GMT\n` +
`Content-Type: application/json; charset=utf-8\n` +
`Transfer-Encoding: chunked\n` +
`Connection: keep-alive`;
const headers = Headers.fromResponseHeaderString(response);
expect(headers.get('Date')).toEqual('Fri, 20 Nov 2015 01:45:26 GMT');
expect(headers.get('Content-Type')).toEqual('application/json; charset=utf-8');
expect(headers.get('Transfer-Encoding')).toEqual('chunked');
expect(headers.get('Connection')).toEqual('keep-alive');
});
});
});
}
| apache-2.0 |
mglukhikh/intellij-community | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addTypeCast/afterTernary2.java | 118 | // "Cast to 'B'" "true"
class A {
void f(B b) {
B s =b == null ? null : <caret>(B) this;
}
}
class B extends A {} | apache-2.0 |
jimsimon/sky_engine | build/download_nacl_toolchains.py | 2152 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Shim to run nacl toolchain download script only if there is a nacl dir."""
import os
import shutil
import sys
def Main(args):
# Exit early if disable_nacl=1.
if 'disable_nacl=1' in os.environ.get('GYP_DEFINES', ''):
return 0
script_dir = os.path.dirname(os.path.abspath(__file__))
src_dir = os.path.dirname(script_dir)
nacl_dir = os.path.join(src_dir, 'native_client')
nacl_build_dir = os.path.join(nacl_dir, 'build')
package_version_dir = os.path.join(nacl_build_dir, 'package_version')
package_version = os.path.join(package_version_dir, 'package_version.py')
if not os.path.exists(package_version):
print "Can't find '%s'" % package_version
print 'Presumably you are intentionally building without NativeClient.'
print 'Skipping NativeClient toolchain download.'
sys.exit(0)
sys.path.insert(0, package_version_dir)
import package_version
# BUG:
# We remove this --optional-pnacl argument, and instead replace it with
# --no-pnacl for most cases. However, if the bot name is an sdk
# bot then we will go ahead and download it. This prevents increasing the
# gclient sync time for developers, or standard Chrome bots.
if '--optional-pnacl' in args:
args.remove('--optional-pnacl')
use_pnacl = False
buildbot_name = os.environ.get('BUILDBOT_BUILDERNAME', '')
if 'pnacl' in buildbot_name and 'sdk' in buildbot_name:
use_pnacl = True
if use_pnacl:
print '\n*** DOWNLOADING PNACL TOOLCHAIN ***\n'
else:
args = ['--exclude', 'pnacl_newlib'] + args
# Only download the ARM gcc toolchain if we are building for ARM
# TODO(olonho): we need to invent more reliable way to get build
# configuration info, to know if we're building for ARM.
if 'target_arch=arm' not in os.environ.get('GYP_DEFINES', ''):
args = ['--exclude', 'nacl_arm_newlib'] + args
package_version.main(args)
return 0
if __name__ == '__main__':
sys.exit(Main(sys.argv[1:]))
| bsd-3-clause |
AICP/external_chromium_org | components/dom_distiller/core/distilled_content_store_unittest.cc | 13430 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "components/dom_distiller/core/article_entry.h"
#include "components/dom_distiller/core/distilled_content_store.h"
#include "components/dom_distiller/core/proto/distilled_article.pb.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace dom_distiller {
namespace {
ArticleEntry CreateEntry(std::string entry_id,
std::string page_url1,
std::string page_url2,
std::string page_url3) {
ArticleEntry entry;
entry.set_entry_id(entry_id);
if (!page_url1.empty()) {
ArticleEntryPage* page = entry.add_pages();
page->set_url(page_url1);
}
if (!page_url2.empty()) {
ArticleEntryPage* page = entry.add_pages();
page->set_url(page_url2);
}
if (!page_url3.empty()) {
ArticleEntryPage* page = entry.add_pages();
page->set_url(page_url3);
}
return entry;
}
DistilledArticleProto CreateDistilledArticleForEntry(
const ArticleEntry& entry) {
DistilledArticleProto article;
for (int i = 0; i < entry.pages_size(); ++i) {
DistilledPageProto* page = article.add_pages();
page->set_url(entry.pages(i).url());
page->set_html("<div>" + entry.pages(i).url() + "</div>");
}
return article;
}
} // namespace
class InMemoryContentStoreTest : public testing::Test {
public:
void OnLoadCallback(bool success, scoped_ptr<DistilledArticleProto> proto) {
load_success_ = success;
loaded_proto_ = proto.Pass();
}
void OnSaveCallback(bool success) { save_success_ = success; }
protected:
// testing::Test implementation:
virtual void SetUp() OVERRIDE {
store_.reset(new InMemoryContentStore(kDefaultMaxNumCachedEntries));
save_success_ = false;
load_success_ = false;
loaded_proto_.reset();
}
scoped_ptr<InMemoryContentStore> store_;
bool save_success_;
bool load_success_;
scoped_ptr<DistilledArticleProto> loaded_proto_;
};
// Tests whether saving and then loading a single article works as expected.
TEST_F(InMemoryContentStoreTest, SaveAndLoadSingleArticle) {
base::MessageLoop loop;
const ArticleEntry entry = CreateEntry("test-id", "url1", "url2", "url3");
const DistilledArticleProto stored_proto =
CreateDistilledArticleForEntry(entry);
store_->SaveContent(entry,
stored_proto,
base::Bind(&InMemoryContentStoreTest::OnSaveCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(save_success_);
save_success_ = false;
store_->LoadContent(entry,
base::Bind(&InMemoryContentStoreTest::OnLoadCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(load_success_);
EXPECT_EQ(stored_proto.SerializeAsString(),
loaded_proto_->SerializeAsString());
}
// Tests that loading articles which have never been stored, yields a callback
// where success is false.
TEST_F(InMemoryContentStoreTest, LoadNonExistentArticle) {
base::MessageLoop loop;
const ArticleEntry entry = CreateEntry("bogus-id", "url1", "url2", "url3");
store_->LoadContent(entry,
base::Bind(&InMemoryContentStoreTest::OnLoadCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_FALSE(load_success_);
}
// Verifies that content store can store multiple articles, and that ordering
// of save and store does not matter when the total number of articles does not
// exceed |kDefaultMaxNumCachedEntries|.
TEST_F(InMemoryContentStoreTest, SaveAndLoadMultipleArticles) {
base::MessageLoop loop;
// Store first article.
const ArticleEntry first_entry = CreateEntry("first", "url1", "url2", "url3");
const DistilledArticleProto first_stored_proto =
CreateDistilledArticleForEntry(first_entry);
store_->SaveContent(first_entry,
first_stored_proto,
base::Bind(&InMemoryContentStoreTest::OnSaveCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(save_success_);
save_success_ = false;
// Store second article.
const ArticleEntry second_entry =
CreateEntry("second", "url4", "url5", "url6");
const DistilledArticleProto second_stored_proto =
CreateDistilledArticleForEntry(second_entry);
store_->SaveContent(second_entry,
second_stored_proto,
base::Bind(&InMemoryContentStoreTest::OnSaveCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(save_success_);
save_success_ = false;
// Load second article.
store_->LoadContent(second_entry,
base::Bind(&InMemoryContentStoreTest::OnLoadCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(load_success_);
load_success_ = false;
EXPECT_EQ(second_stored_proto.SerializeAsString(),
loaded_proto_->SerializeAsString());
loaded_proto_.reset();
// Load first article.
store_->LoadContent(first_entry,
base::Bind(&InMemoryContentStoreTest::OnLoadCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(load_success_);
EXPECT_EQ(first_stored_proto.SerializeAsString(),
loaded_proto_->SerializeAsString());
}
// Verifies that the content store does not store unlimited number of articles,
// but expires the oldest ones when the limit for number of articles is reached.
TEST_F(InMemoryContentStoreTest, SaveAndLoadMoreThanMaxArticles) {
base::MessageLoop loop;
// Create a new store with only |kMaxNumArticles| articles as the limit.
const int kMaxNumArticles = 3;
store_.reset(new InMemoryContentStore(kMaxNumArticles));
// Store first article.
const ArticleEntry first_entry = CreateEntry("first", "url1", "url2", "url3");
const DistilledArticleProto first_stored_proto =
CreateDistilledArticleForEntry(first_entry);
store_->SaveContent(first_entry,
first_stored_proto,
base::Bind(&InMemoryContentStoreTest::OnSaveCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(save_success_);
save_success_ = false;
// Store second article.
const ArticleEntry second_entry =
CreateEntry("second", "url4", "url5", "url6");
const DistilledArticleProto second_stored_proto =
CreateDistilledArticleForEntry(second_entry);
store_->SaveContent(second_entry,
second_stored_proto,
base::Bind(&InMemoryContentStoreTest::OnSaveCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(save_success_);
save_success_ = false;
// Store third article.
const ArticleEntry third_entry = CreateEntry("third", "url7", "url8", "url9");
const DistilledArticleProto third_stored_proto =
CreateDistilledArticleForEntry(third_entry);
store_->SaveContent(third_entry,
third_stored_proto,
base::Bind(&InMemoryContentStoreTest::OnSaveCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(save_success_);
save_success_ = false;
// Load first article. This will make the first article the most recent
// accessed article.
store_->LoadContent(first_entry,
base::Bind(&InMemoryContentStoreTest::OnLoadCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(load_success_);
load_success_ = false;
EXPECT_EQ(first_stored_proto.SerializeAsString(),
loaded_proto_->SerializeAsString());
loaded_proto_.reset();
// Store fourth article.
const ArticleEntry fourth_entry =
CreateEntry("fourth", "url10", "url11", "url12");
const DistilledArticleProto fourth_stored_proto =
CreateDistilledArticleForEntry(fourth_entry);
store_->SaveContent(fourth_entry,
fourth_stored_proto,
base::Bind(&InMemoryContentStoreTest::OnSaveCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(save_success_);
save_success_ = false;
// Load second article, which by now is the oldest accessed article, since
// the first article has been loaded once.
store_->LoadContent(second_entry,
base::Bind(&InMemoryContentStoreTest::OnLoadCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
// Since the store can only contain |kMaxNumArticles| entries, this load
// should fail.
EXPECT_FALSE(load_success_);
}
// Tests whether saving and then loading a single article works as expected.
TEST_F(InMemoryContentStoreTest, LookupArticleByURL) {
base::MessageLoop loop;
const ArticleEntry entry = CreateEntry("test-id", "url1", "url2", "url3");
const DistilledArticleProto stored_proto =
CreateDistilledArticleForEntry(entry);
store_->SaveContent(entry,
stored_proto,
base::Bind(&InMemoryContentStoreTest::OnSaveCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(save_success_);
save_success_ = false;
// Create an entry where the entry ID does not match, but the first URL does.
const ArticleEntry lookup_entry1 = CreateEntry("lookup-id", "url1", "", "");
store_->LoadContent(lookup_entry1,
base::Bind(&InMemoryContentStoreTest::OnLoadCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(load_success_);
EXPECT_EQ(stored_proto.SerializeAsString(),
loaded_proto_->SerializeAsString());
// Create an entry where the entry ID does not match, but the second URL does.
const ArticleEntry lookup_entry2 =
CreateEntry("lookup-id", "bogus", "url2", "");
store_->LoadContent(lookup_entry2,
base::Bind(&InMemoryContentStoreTest::OnLoadCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(load_success_);
EXPECT_EQ(stored_proto.SerializeAsString(),
loaded_proto_->SerializeAsString());
}
// Verifies that the content store does not store unlimited number of articles,
// but expires the oldest ones when the limit for number of articles is reached.
TEST_F(InMemoryContentStoreTest, LoadArticleByURLAfterExpungedFromCache) {
base::MessageLoop loop;
// Create a new store with only |kMaxNumArticles| articles as the limit.
const int kMaxNumArticles = 1;
store_.reset(new InMemoryContentStore(kMaxNumArticles));
// Store an article.
const ArticleEntry first_entry = CreateEntry("first", "url1", "url2", "url3");
const DistilledArticleProto first_stored_proto =
CreateDistilledArticleForEntry(first_entry);
store_->SaveContent(first_entry,
first_stored_proto,
base::Bind(&InMemoryContentStoreTest::OnSaveCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(save_success_);
save_success_ = false;
// Looking up the first entry by URL should succeed when it is still in the
// cache.
const ArticleEntry first_entry_lookup =
CreateEntry("lookup-id", "url1", "", "");
store_->LoadContent(first_entry_lookup,
base::Bind(&InMemoryContentStoreTest::OnLoadCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(load_success_);
EXPECT_EQ(first_stored_proto.SerializeAsString(),
loaded_proto_->SerializeAsString());
// Store second article. This will remove the first article from the cache.
const ArticleEntry second_entry =
CreateEntry("second", "url4", "url5", "url6");
const DistilledArticleProto second_stored_proto =
CreateDistilledArticleForEntry(second_entry);
store_->SaveContent(second_entry,
second_stored_proto,
base::Bind(&InMemoryContentStoreTest::OnSaveCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(save_success_);
save_success_ = false;
// Looking up the first entry by URL should fail when it is not in the cache.
store_->LoadContent(first_entry_lookup,
base::Bind(&InMemoryContentStoreTest::OnLoadCallback,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_FALSE(load_success_);
}
} // namespace dom_distiller
| bsd-3-clause |
ksone/php-dev-test | library/Zend/Mail/Transport/Abstract.php | 10347 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Mail
* @subpackage Transport
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Mime
*/
require_once 'Zend/Mime.php';
/**
* Abstract for sending eMails through different
* ways of transport
*
* @category Zend
* @package Zend_Mail
* @subpackage Transport
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Mail_Transport_Abstract
{
/**
* Mail body
* @var string
* @access public
*/
public $body = '';
/**
* MIME boundary
* @var string
* @access public
*/
public $boundary = '';
/**
* Mail header string
* @var string
* @access public
*/
public $header = '';
/**
* Array of message headers
* @var array
* @access protected
*/
protected $_headers = array();
/**
* Message is a multipart message
* @var boolean
* @access protected
*/
protected $_isMultipart = false;
/**
* Zend_Mail object
* @var false|Zend_Mail
* @access protected
*/
protected $_mail = false;
/**
* Array of message parts
* @var array
* @access protected
*/
protected $_parts = array();
/**
* Recipients string
* @var string
* @access public
*/
public $recipients = '';
/**
* EOL character string used by transport
* @var string
* @access public
*/
public $EOL = "\r\n";
/**
* Send an email independent from the used transport
*
* The requisite information for the email will be found in the following
* properties:
*
* - {@link $recipients} - list of recipients (string)
* - {@link $header} - message header
* - {@link $body} - message body
*/
abstract protected function _sendMail();
/**
* Return all mail headers as an array
*
* If a boundary is given, a multipart header is generated with a
* Content-Type of either multipart/alternative or multipart/mixed depending
* on the mail parts present in the {@link $_mail Zend_Mail object} present.
*
* @param string $boundary
* @return array
*/
protected function _getHeaders($boundary)
{
if (null !== $boundary) {
// Build multipart mail
$type = $this->_mail->getType();
if (!$type) {
if ($this->_mail->hasAttachments) {
$type = Zend_Mime::MULTIPART_MIXED;
} elseif ($this->_mail->getBodyText() && $this->_mail->getBodyHtml()) {
$type = Zend_Mime::MULTIPART_ALTERNATIVE;
} else {
$type = Zend_Mime::MULTIPART_MIXED;
}
}
$this->_headers['Content-Type'] = array(
$type . ';'
. $this->EOL
. " " . 'boundary="' . $boundary . '"'
);
$this->boundary = $boundary;
}
$this->_headers['MIME-Version'] = array('1.0');
return $this->_headers;
}
/**
* Prepend header name to header value
*
* @param string $item
* @param string $key
* @param string $prefix
* @static
* @access protected
* @return void
*/
protected static function _formatHeader(&$item, $key, $prefix)
{
$item = $prefix . ': ' . $item;
}
/**
* Prepare header string for use in transport
*
* Prepares and generates {@link $header} based on the headers provided.
*
* @param mixed $headers
* @access protected
* @return void
* @throws Zend_Mail_Transport_Exception if any header lines exceed 998
* characters
*/
protected function _prepareHeaders($headers)
{
if (!$this->_mail) {
/**
* @see Zend_Mail_Transport_Exception
*/
require_once 'Zend/Mail/Transport/Exception.php';
throw new Zend_Mail_Transport_Exception('Missing Zend_Mail object in _mail property');
}
$this->header = '';
foreach ($headers as $header => $content) {
if (isset($content['append'])) {
unset($content['append']);
$value = implode(',' . $this->EOL . ' ', $content);
$this->header .= $header . ': ' . $value . $this->EOL;
} else {
array_walk($content, array(get_class($this), '_formatHeader'), $header);
$this->header .= implode($this->EOL, $content) . $this->EOL;
}
}
// Sanity check on headers -- should not be > 998 characters
$sane = true;
foreach (explode($this->EOL, $this->header) as $line) {
if (strlen(trim($line)) > 998) {
$sane = false;
break;
}
}
if (!$sane) {
/**
* @see Zend_Mail_Transport_Exception
*/
require_once 'Zend/Mail/Transport/Exception.php';
throw new Zend_Mail_Exception('At least one mail header line is too long');
}
}
/**
* Generate MIME compliant message from the current configuration
*
* If both a text and HTML body are present, generates a
* multipart/alternative Zend_Mime_Part containing the headers and contents
* of each. Otherwise, uses whichever of the text or HTML parts present.
*
* The content part is then prepended to the list of Zend_Mime_Parts for
* this message.
*
* @return void
*/
protected function _buildBody()
{
if (($text = $this->_mail->getBodyText())
&& ($html = $this->_mail->getBodyHtml()))
{
// Generate unique boundary for multipart/alternative
$mime = new Zend_Mime(null);
$boundaryLine = $mime->boundaryLine($this->EOL);
$boundaryEnd = $mime->mimeEnd($this->EOL);
$text->disposition = false;
$html->disposition = false;
$body = $boundaryLine
. $text->getHeaders($this->EOL)
. $this->EOL
. $text->getContent($this->EOL)
. $this->EOL
. $boundaryLine
. $html->getHeaders($this->EOL)
. $this->EOL
. $html->getContent($this->EOL)
. $this->EOL
. $boundaryEnd;
$mp = new Zend_Mime_Part($body);
$mp->type = Zend_Mime::MULTIPART_ALTERNATIVE;
$mp->boundary = $mime->boundary();
$this->_isMultipart = true;
// Ensure first part contains text alternatives
array_unshift($this->_parts, $mp);
// Get headers
$this->_headers = $this->_mail->getHeaders();
return;
}
// If not multipart, then get the body
if (false !== ($body = $this->_mail->getBodyHtml())) {
array_unshift($this->_parts, $body);
} elseif (false !== ($body = $this->_mail->getBodyText())) {
array_unshift($this->_parts, $body);
}
if (!$body) {
/**
* @see Zend_Mail_Transport_Exception
*/
require_once 'Zend/Mail/Transport/Exception.php';
throw new Zend_Mail_Transport_Exception('No body specified');
}
// Get headers
$this->_headers = $this->_mail->getHeaders();
$headers = $body->getHeadersArray($this->EOL);
foreach ($headers as $header) {
// Headers in Zend_Mime_Part are kept as arrays with two elements, a
// key and a value
$this->_headers[$header[0]] = array($header[1]);
}
}
/**
* Send a mail using this transport
*
* @param Zend_Mail $mail
* @access public
* @return void
* @throws Zend_Mail_Transport_Exception if mail is empty
*/
public function send(Zend_Mail $mail)
{
$this->_isMultipart = false;
$this->_mail = $mail;
$this->_parts = $mail->getParts();
$mime = $mail->getMime();
// Build body content
$this->_buildBody();
// Determine number of parts and boundary
$count = count($this->_parts);
$boundary = null;
if ($count < 1) {
/**
* @see Zend_Mail_Transport_Exception
*/
require_once 'Zend/Mail/Transport/Exception.php';
throw new Zend_Mail_Transport_Exception('Empty mail cannot be sent');
}
if ($count > 1) {
// Multipart message; create new MIME object and boundary
$mime = new Zend_Mime($this->_mail->getMimeBoundary());
$boundary = $mime->boundary();
} elseif ($this->_isMultipart) {
// multipart/alternative -- grab boundary
$boundary = $this->_parts[0]->boundary;
}
// Determine recipients, and prepare headers
$this->recipients = implode(',', $mail->getRecipients());
$this->_prepareHeaders($this->_getHeaders($boundary));
// Create message body
// This is done so that the same Zend_Mail object can be used in
// multiple transports
$message = new Zend_Mime_Message();
$message->setParts($this->_parts);
$message->setMime($mime);
$this->body = $message->generateMessage($this->EOL);
// Send to transport!
$this->_sendMail();
}
}
| bsd-3-clause |
frami/openhab | bundles/binding/org.openhab.binding.weather/src/main/java/org/openhab/binding/weather/internal/annotation/ForecastMappings.java | 782 | /**
* Copyright (c) 2010-2016 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.weather.internal.annotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Container for multiple forecast annotations.
*
* @author Gerhard Riegler
* @since 1.6.0
*/
@Target({ FIELD })
@Retention(RUNTIME)
public @interface ForecastMappings {
public Forecast[]value();
}
| epl-1.0 |
mhnatiuk/phd_sociology_of_religion | scrapper/build/scrapy/scrapy/contrib/webservice/crawler.py | 203 | from scrapy.webservice import JsonRpcResource
class CrawlerResource(JsonRpcResource):
ws_name = 'crawler'
def __init__(self, crawler):
JsonRpcResource.__init__(self, crawler, crawler)
| gpl-2.0 |
h4ck3rm1k3/gcc | libstdc++-v3/testsuite/20_util/specialized_algorithms/uninitialized_fill_n/16505.cc | 951 | // Copyright (C) 2004, 2009 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/>.
// 20.4.4 specialized algorithms
// { dg-do compile }
#include <memory>
// libstdc++/16505
struct S { };
template
void
std::uninitialized_fill_n<S*, int, S>(S*, int, const S&);
| gpl-2.0 |
BackupGGCode/propgcc | gcc/libstdc++-v3/testsuite/tr1/5_numerical_facilities/special_functions/20_riemann_zeta/compile.cc | 1150 | // { dg-do compile }
// 2006-02-04 Edward Smith-Rowland <3dw4rd@verizon.net>
//
// Copyright (C) 2006-2007, 2009 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/>.
// 5.2.1.20 riemann_zeta
#include <tr1/cmath>
void
test01()
{
float xf = 0.5F;
double xd = 0.5;
long double xl = 0.5L;
std::tr1::riemann_zeta(xf);
std::tr1::riemann_zetaf(xf);
std::tr1::riemann_zeta(xd);
std::tr1::riemann_zeta(xl);
std::tr1::riemann_zetal(xl);
return;
}
| gpl-3.0 |
saicheems/google-api-php-client-services | src/Google/Service/Compute/TestFailure.php | 1373 | <?php
/*
* 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.
*/
class Google_Service_Compute_TestFailure extends Google_Model
{
public $actualService;
public $expectedService;
public $host;
public $path;
public function setActualService($actualService)
{
$this->actualService = $actualService;
}
public function getActualService()
{
return $this->actualService;
}
public function setExpectedService($expectedService)
{
$this->expectedService = $expectedService;
}
public function getExpectedService()
{
return $this->expectedService;
}
public function setHost($host)
{
$this->host = $host;
}
public function getHost()
{
return $this->host;
}
public function setPath($path)
{
$this->path = $path;
}
public function getPath()
{
return $this->path;
}
}
| apache-2.0 |
RReverser/react | src/core/ReactPropTypeLocations.js | 839 | /**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactPropTypeLocations
*/
"use strict";
var keyMirror = require('keyMirror');
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
| apache-2.0 |
madaboutcode/eSell | Modules/Orchard.Projections/FilterEditors/Forms/DateTimeFilterForm.cs | 16130 | using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Orchard.ContentManagement;
using Orchard.DisplayManagement;
using Orchard.Environment;
using Orchard.Forms.Services;
using Orchard.Localization;
using Orchard.UI.Resources;
namespace Orchard.Projections.FilterEditors.Forms {
public class DateTimeFilterForm : IFormProvider {
public const string FormName = "DateTimeFilter";
private static readonly Regex _dateRegEx = new Regex(@"(?<year>\d{1,4})(\-(?<month>\d{1,2})(\-(?<day>\d{1,2})\s*((?<hour>\d{1,2})(:(?<minute>\d{1,2})(:(?<second>\d{1,2}))?)?)?)?)?");
private readonly Work<IResourceManager> _resourceManager;
protected dynamic Shape { get; set; }
public Localizer T { get; set; }
public DateTimeFilterForm(IShapeFactory shapeFactory, Work<IResourceManager> resourceManager) {
_resourceManager = resourceManager;
Shape = shapeFactory;
T = NullLocalizer.Instance;
}
public void Describe(DescribeContext context) {
Func<IShapeFactory, object> form =
shape => {
var f = Shape.Form(
Id: "DateTimeFilter",
_Operator: Shape.SelectList(
Id: "operator", Name: "Operator",
Title: T("Operator"),
Size: 1,
Multiple: false
),
_FieldSetOption: Shape.FieldSet(
_ValueTypeDate: Shape.Radio(
Id: "value-type-date", Name: "ValueType",
Title: T("A date"), Value: "0", Checked: true,
Description: T("Please use this format: YYYY-MM-DD hh:mm:ss. e.g., 2010-04-12 would filter on the whole day. You can also use the Date token like this: {Date.Format:yyyy-MM-dd}")
),
_ValueTypeSpan: Shape.Radio(
Id: "value-type-timespan", Name: "ValueType",
Title: T("An offset from the current time"), Value: "1",
Description: T("You can provide time in the past by using negative values. e.g., -1 day")
)
),
_FieldSetSingle: Shape.FieldSet(
Id: "fieldset-single",
_Value: Shape.TextBox(
Id: "value", Name: "Value",
Title: T("Value"),
Classes: new [] {"tokenized"}
),
_ValueUnit: Shape.SelectList(
Id: "value-unit", Name: "ValueUnit",
Title: T("Unit"),
Size: 1,
Multiple: false
)
),
_FieldSetMin: Shape.FieldSet(
Id: "fieldset-min",
_Min: Shape.TextBox(
Id: "min", Name: "Min",
Title: T("Min"),
Classes: new[] { "tokenized" }
),
_MinUnit: Shape.SelectList(
Id: "min-unit", Name: "MinUnit",
Title: T("Unit"),
Size: 1,
Multiple: false
)
),
_FieldSetMax: Shape.FieldSet(
Id: "fieldset-max",
_Max: Shape.TextBox(
Id: "max", Name: "Max",
Title: T("Max"),
Classes: new[] { "tokenized" }
),
_MaxUnit: Shape.SelectList(
Id: "max-unit", Name: "MaxUnit",
Title: T("Unit"),
Size: 1,
Multiple: false
)
)
);
_resourceManager.Value.Require("script", "jQuery");
_resourceManager.Value.Include("script", "~/Modules/Orchard.Projections/Scripts/datetime-editor-filter.js", "~/Modules/Orchard.Projections/Scripts/datetime-editor-filter.js");
_resourceManager.Value.Include("stylesheet", "~/Modules/Orchard.Projections/Styles/datetime-editor-filter.css", "~/Modules/Orchard.Projections/Styles/datetime-editor-filter.css");
f._Operator.Add(new SelectListItem { Value = Convert.ToString(DateTimeOperator.LessThan), Text = T("Is less than").Text });
f._Operator.Add(new SelectListItem { Value = Convert.ToString(DateTimeOperator.LessThanEquals), Text = T("Is less than or equal to").Text });
f._Operator.Add(new SelectListItem { Value = Convert.ToString(DateTimeOperator.Equals), Text = T("Is equal to").Text });
f._Operator.Add(new SelectListItem { Value = Convert.ToString(DateTimeOperator.NotEquals), Text = T("Is not equal to").Text });
f._Operator.Add(new SelectListItem { Value = Convert.ToString(DateTimeOperator.GreaterThanEquals), Text = T("Is greater than or equal to").Text });
f._Operator.Add(new SelectListItem { Value = Convert.ToString(DateTimeOperator.GreaterThan), Text = T("Is greater than").Text });
f._Operator.Add(new SelectListItem { Value = Convert.ToString(DateTimeOperator.Between), Text = T("Is between").Text });
f._Operator.Add(new SelectListItem { Value = Convert.ToString(DateTimeOperator.NotBetween), Text = T("Is not between").Text });
foreach (var unit in new[] { f._FieldSetSingle._ValueUnit, f._FieldSetMin._MinUnit, f._FieldSetMax._MaxUnit }) {
unit.Add(new SelectListItem { Value = Convert.ToString(DateTimeSpan.Year), Text = T("Year").Text });
unit.Add(new SelectListItem { Value = Convert.ToString(DateTimeSpan.Month), Text = T("Month").Text });
unit.Add(new SelectListItem { Value = Convert.ToString(DateTimeSpan.Day), Text = T("Day").Text });
unit.Add(new SelectListItem { Value = Convert.ToString(DateTimeSpan.Hour), Text = T("Hour").Text });
unit.Add(new SelectListItem { Value = Convert.ToString(DateTimeSpan.Minute), Text = T("Minute").Text });
unit.Add(new SelectListItem { Value = Convert.ToString(DateTimeSpan.Second), Text = T("Second").Text });
}
return f;
};
context.Form(FormName, form);
}
public static Action<IHqlExpressionFactory> GetFilterPredicate(dynamic formState, string property, DateTime now, bool asTicks = false) {
var op = (DateTimeOperator)Enum.Parse(typeof(DateTimeOperator), Convert.ToString(formState.Operator));
string type = Convert.ToString(formState.ValueType);
DateTime min, max;
// Are those dates or time spans
if (type == "0") {
if (op == DateTimeOperator.Between || op == DateTimeOperator.NotBetween) {
min = GetLowBoundPattern(Convert.ToString(formState.Min));
max = GetHighBoundPattern(Convert.ToString(formState.Max));
}
else {
min = GetLowBoundPattern(Convert.ToString(formState.Value));
max = GetHighBoundPattern(Convert.ToString(formState.Value));
}
}
else {
if (op == DateTimeOperator.Between || op == DateTimeOperator.NotBetween) {
min = ApplyDelta(now, formState.MinUnit, Int32.Parse(formState.Min));
max = ApplyDelta(now, formState.MinUnit, Int32.Parse(formState.Min));
}
else {
min = max = ApplyDelta(now, formState.ValueUnit, Int32.Parse(formState.Value));
}
}
min = min.ToUniversalTime();
max = max.ToUniversalTime();
object minValue = min;
object maxValue = max;
if(asTicks) {
minValue = min.Ticks;
maxValue = max.Ticks;
}
switch (op) {
case DateTimeOperator.LessThan:
return x => x.Lt(property, maxValue);
case DateTimeOperator.LessThanEquals:
return x => x.Le(property, maxValue);
case DateTimeOperator.Equals:
if (min == max) {
return x => x.Eq(property, minValue);
}
return y => y.And(x => x.Ge(property, minValue), x => x.Le(property, maxValue));
case DateTimeOperator.NotEquals:
if (min == max) {
return x => x.Not(y => y.Eq(property, minValue));
}
return y => y.Or(x => x.Lt(property, minValue), x => x.Gt(property, maxValue));
case DateTimeOperator.GreaterThan:
return x => x.Gt(property, minValue);
case DateTimeOperator.GreaterThanEquals:
return x => x.Ge(property, minValue);
case DateTimeOperator.Between:
return y => y.And(x => x.Ge(property, minValue), x => x.Le(property, maxValue));
case DateTimeOperator.NotBetween:
return y => y.Or(x => x.Lt(property, minValue), x => x.Gt(property, maxValue));
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Returns the low bound value of a date pattern. e.g., 2011-10 will return 2011-10-01 00:00:00
/// </summary>
/// <remarks>DateTime is stored in UTC but entered in local</remarks>
protected static DateTime GetLowBoundPattern(string datePattern) {
var match = _dateRegEx.Match(datePattern);
return DateTime.Parse(
String.Format("{0}-{1}-{2} {3}:{4}:{5}",
match.Groups["year"].Success ? match.Groups["year"].Value : "1980",
match.Groups["month"].Success ? match.Groups["month"].Value : "01",
match.Groups["day"].Success ? match.Groups["day"].Value : "01",
match.Groups["hour"].Success ? match.Groups["hour"].Value : "00",
match.Groups["minute"].Success ? match.Groups["minute"].Value : "00",
match.Groups["second"].Success ? match.Groups["second"].Value : "00"),
CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
}
protected static DateTime ApplyDelta(DateTime now, string unit, int value) {
var span = (DateTimeSpan)Enum.Parse(typeof(DateTimeSpan), unit);
switch (span) {
case DateTimeSpan.Year:
return now.AddYears(value);
case DateTimeSpan.Month:
return now.AddMonths(value);
case DateTimeSpan.Day:
return now.AddDays(value);
case DateTimeSpan.Hour:
return now.AddHours(value);
case DateTimeSpan.Minute:
return now.AddMinutes(value);
case DateTimeSpan.Second:
return now.AddSeconds(value);
default:
return now;
}
}
public static LocalizedString DisplayFilter(string fieldName, dynamic formState, Localizer T) {
var op = (DateTimeOperator)Enum.Parse(typeof(DateTimeOperator), Convert.ToString(formState.Operator));
string type = Convert.ToString(formState.ValueType);
string value = Convert.ToString(formState.Value);
string min = Convert.ToString(formState.Min);
string max = Convert.ToString(formState.Max);
string valueUnit = Convert.ToString(formState.ValueUnit);
string minUnit = Convert.ToString(formState.MinUnit);
string maxUnit = Convert.ToString(formState.MaxUnit);
if (type == "0") {
valueUnit = minUnit = maxUnit = String.Empty;
}
else {
valueUnit = " " + valueUnit;
minUnit = " " + minUnit;
maxUnit = " " + maxUnit;
}
switch (op) {
case DateTimeOperator.LessThan:
return T("{0} is less than {1}{2}", fieldName, value, T(valueUnit).Text);
case DateTimeOperator.LessThanEquals:
return T("{0} is less or equal than {1}{2}", fieldName, value, T(valueUnit).Text);
case DateTimeOperator.Equals:
return T("{0} equals {1}{2}", fieldName, value, T(valueUnit).Text);
case DateTimeOperator.NotEquals:
return T("{0} is not equal to {1}{2}", fieldName, value, T(valueUnit).Text);
case DateTimeOperator.GreaterThan:
return T("{0} is greater than {1}{2}", fieldName, value, T(valueUnit).Text);
case DateTimeOperator.GreaterThanEquals:
return T("{0} is greater or equal than {1}{2}", fieldName, value, T(valueUnit).Text);
case DateTimeOperator.Between:
return T("{0} is between {1}{2} and {3}{4}", fieldName, min, T(minUnit).Text, max, T(maxUnit).Text);
case DateTimeOperator.NotBetween:
return T("{0} is not between {1}{2} and {3}{4}", fieldName, min, T(minUnit).Text, max, T(maxUnit).Text);
}
// should never be hit, but fail safe
return new LocalizedString(fieldName);
}
/// <summary>
/// Returns the low bound value of a date pattern. e.g., 2011-10 will return 2011-10-01 00:00:00
/// </summary>
/// <remarks>DateTime is stored in UTC but entered in local</remarks>
protected static DateTime GetHighBoundPattern(string datePattern) {
var match = _dateRegEx.Match(datePattern);
string year, month;
return DateTime.Parse(
String.Format("{0}-{1}-{2} {3}:{4}:{5}",
year = match.Groups["year"].Success ? match.Groups["year"].Value : "2099",
month = match.Groups["month"].Success ? match.Groups["month"].Value : "12",
match.Groups["day"].Success ? match.Groups["day"].Value : DateTime.DaysInMonth(Int32.Parse(year), Int32.Parse(month)).ToString(),
match.Groups["hour"].Success ? match.Groups["hour"].Value : "23",
match.Groups["minute"].Success ? match.Groups["minute"].Value : "59",
match.Groups["second"].Success ? match.Groups["second"].Value : "59"),
CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
}
}
public enum DateTimeOperator {
LessThan,
LessThanEquals,
Equals,
NotEquals,
GreaterThan,
GreaterThanEquals,
Between,
NotBetween
}
public enum DateTimeSpan {
Year,
Month,
Day,
Hour,
Minute,
Second
}
} | bsd-3-clause |
dhoehna/corefx | src/Common/src/Interop/Unix/System.Native/Interop.ReadLink.cs | 1161 | // 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.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Sys
{
/// <summary>
/// Takes a path to a symbolic link and attempts to place the link target path into the buffer. If the buffer is too
/// small, the path will be truncated. No matter what, the buffer will not be null terminated.
/// </summary>
/// <param name="path">The path to the symlink</param>
/// <param name="buffer">The buffer to hold the output path</param>
/// <param name="bufferSize">The size of the buffer</param>
/// <returns>
/// Returns the number of bytes placed into the buffer on success; otherwise, -1 is returned
/// </returns>
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReadLink", SetLastError = true)]
internal static extern unsafe int ReadLink(string path, byte[] buffer, int bufferSize);
}
}
| mit |
Piicksarn/cdnjs | ajax/libs/preact/4.3.0/preact.js | 34646 | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.preact = factory());
}(this, function () { 'use strict';
function VNode(nodeName, attributes, children) {
/** @type {string|function} */
this.nodeName = nodeName;
/** @type {object<string>|undefined} */
this.attributes = attributes;
/** @type {array<VNode>|undefined} */
this.children = children;
}
var NO_RENDER = { render: false };
var SYNC_RENDER = { renderSync: true };
var DOM_RENDER = { build: true };
var EMPTY = {};
var EMPTY_BASE = '';
// is this a DOM environment
var HAS_DOM = typeof document !== 'undefined';
var TEXT_CONTENT = !HAS_DOM || 'textContent' in document ? 'textContent' : 'nodeValue';
var ATTR_KEY = typeof Symbol !== 'undefined' ? Symbol('preactattr') : '__preactattr_';
var UNDEFINED_ELEMENT = 'undefined';
// DOM properties that should NOT have "px" added when numeric
var NON_DIMENSION_PROPS = {
boxFlex: 1, boxFlexGroup: 1, columnCount: 1, fillOpacity: 1, flex: 1, flexGrow: 1,
flexPositive: 1, flexShrink: 1, flexNegative: 1, fontWeight: 1, lineClamp: 1, lineHeight: 1,
opacity: 1, order: 1, orphans: 1, strokeOpacity: 1, widows: 1, zIndex: 1, zoom: 1
};
/** Copy own-properties from `props` onto `obj`.
* @returns obj
* @private
*/
function extend(obj, props) {
for (var i in props) {
if (hasOwnProperty.call(props, i)) {
obj[i] = props[i];
}
}return obj;
}
/** Fast clone. Note: does not filter out non-own properties. */
function clone(obj) {
var out = {};
/*eslint guard-for-in:0*/
for (var i in obj) {
out[i] = obj[i];
}return out;
}
/** Create a caching wrapper for the given function.
* @private
*/
function memoize(fn, mem) {
mem = mem || {};
return function (k) {
return hasOwnProperty.call(mem, k) ? mem[k] : mem[k] = fn(k);
};
}
/** Get a deep property value from the given object, expressed in dot-notation.
* @private
*/
function delve(obj, key) {
for (var p = key.split('.'), i = 0; i < p.length && obj; i++) {
obj = obj[p];
}
return obj;
}
/** Convert an Array-like object to an Array
* @private
*/
function toArray(obj) {
var arr = [],
i = obj.length;
while (i--) arr[i] = obj[i];
return arr;
}
/** @private is the given object a Function? */
var isFunction = function isFunction(obj) {
return 'function' === typeof obj;
};
/** @private is the given object a String? */
var isString = function isString(obj) {
return 'string' === typeof obj;
};
/** @private Safe reference to builtin hasOwnProperty */
var hasOwnProperty = ({}).hasOwnProperty;
/** Check if a value is `null` or `undefined`.
* @private
*/
var empty = function empty(x) {
return x == null;
};
/** Check if a value is `null`, `undefined`, or explicitly `false`. */
var falsey = function falsey(value) {
return value === false || value == null;
};
/** Convert a hashmap of styles to CSSText
* @private
*/
function styleObjToCss(s) {
var str = '';
for (var prop in s) {
if (hasOwnProperty.call(s, prop)) {
var val = s[prop];
if (!empty(val)) {
str += jsToCss(prop);
str += ': ';
str += val;
if (typeof val === 'number' && !NON_DIMENSION_PROPS[prop]) {
str += 'px';
}
str += '; ';
}
}
}
return str;
}
/** Convert a hashmap of CSS classes to a space-delimited className string
* @private
*/
function hashToClassName(c) {
var str = '';
for (var prop in c) {
if (c[prop]) {
if (str) str += ' ';
str += prop;
}
}
return str;
}
/** Convert a JavaScript camel-case CSS property name to a CSS property name
* @private
* @function
*/
var jsToCss = memoize(function (s) {
return s.replace(/([A-Z])/g, '-$1').toLowerCase();
});
/** Just a memoized String.prototype.toLowerCase */
var toLowerCase = memoize(function (s) {
return s.toLowerCase();
});
// For animations, rAF is vastly superior. However, it scores poorly on benchmarks :(
// export const setImmediate = typeof requestAnimationFrame==='function' ? requestAnimationFrame : setTimeout;
var ch = undefined;
try {
ch = new MessageChannel();
} catch (e) {}
/** Call a function asynchronously, as soon as possible.
* @param {Function} callback
*/
var setImmediate = ch ? function (f) {
ch.port1.onmessage = f;
ch.port2.postMessage('');
} : setTimeout;
/** Global options
* @public
* @namespace options {Object}
*/
var options = {
/** If `true`, `prop` changes trigger synchronous component updates.
* @name syncComponentUpdates
* @type Boolean
* @default true
*/
//syncComponentUpdates: true,
/** Processes all created VNodes.
* @param {VNode} vnode A newly-created VNode to normalize/process
*/
vnode: function vnode(n) {
var attrs = n.attributes;
if (!attrs || isFunction(n.nodeName)) return;
// normalize className to class.
var p = attrs.className;
if (p) {
attrs['class'] = p;
delete attrs.className;
}
if (attrs['class']) normalize(attrs, 'class', hashToClassName);
if (attrs.style) normalize(attrs, 'style', styleObjToCss);
}
};
function normalize(obj, prop, fn) {
var v = obj[prop];
if (v && !isString(v)) {
obj[prop] = fn(v);
}
}
/** Invoke a hook on the `options` export. */
function optionsHook(name, a, b) {
return hook(options, name, a, b);
}
/** Invoke a "hook" method with arguments if it exists.
* @private
*/
function hook(obj, name, a, b, c) {
var fn = obj[name];
if (fn && fn.call) return fn.call(obj, a, b, c);
}
/** Invoke hook() on a component and child components (recursively)
* @private
*/
function deepHook(obj, type) {
do {
hook(obj, type);
} while (obj = obj._component);
}
var SHARED_TEMP_ARRAY = [];
/** JSX/hyperscript reviver
* @see http://jasonformat.com/wtf-is-jsx
* @public
* @example
* /** @jsx h *\/
* import { render, h } from 'preact';
* render(<span>foo</span>, document.body);
*/
function h(nodeName, attributes) {
var len = arguments.length,
children = undefined,
arr = undefined,
lastSimple = undefined;
if (len > 2) {
children = [];
for (var i = 2; i < len; i++) {
var _p = arguments[i];
if (falsey(_p)) continue;
if (_p.join) {
arr = _p;
} else {
arr = SHARED_TEMP_ARRAY;
arr[0] = _p;
}
for (var j = 0; j < arr.length; j++) {
var child = arr[j],
simple = !falsey(child) && !(child instanceof VNode);
if (simple) child = String(child);
if (simple && lastSimple) {
children[children.length - 1] += child;
} else if (!falsey(child)) {
children.push(child);
}
lastSimple = simple;
}
}
}
if (attributes && attributes.children) {
delete attributes.children;
}
var p = new VNode(nodeName, attributes || undefined, children || undefined);
optionsHook('vnode', p);
return p;
}
/** Create an Event handler function that sets a given state property.
* @param {Component} component The component whose state should be updated
* @param {string} key A dot-notated key path to update in the component's state
* @param {string} eventPath A dot-notated key path to the value that should be retrieved from the Event or component
* @returns {function} linkedStateHandler
* @private
*/
function createLinkedState(component, key, eventPath) {
var path = key.split('.'),
p0 = path[0],
len = path.length;
return function (e) {
var _component$setState;
var t = this,
s = component.state,
obj = s,
v = undefined,
i = undefined;
if (isString(eventPath)) {
v = delve(e, eventPath);
if (empty(v) && (t = t._component)) {
v = delve(t, eventPath);
}
} else {
v = (t.nodeName + t.type).match(/^input(checkbox|radio)$/i) ? t.checked : t.value;
}
if (isFunction(v)) v = v.call(t);
if (len > 1) {
for (i = 0; i < len - 1; i++) {
obj = obj[path[i]] || (obj[path[i]] = {});
}
obj[path[i]] = v;
v = s[p0];
}
component.setState((_component$setState = {}, _component$setState[p0] = v, _component$setState));
};
}
var items = [];
var itemsOffline = [];
function enqueueRender(component) {
if (items.push(component) !== 1) return;
(options.debounceRendering || setImmediate)(rerender);
}
function rerender() {
if (!items.length) return;
var currentItems = items,
p = undefined;
// swap online & offline
items = itemsOffline;
itemsOffline = currentItems;
while (p = currentItems.pop()) {
if (p._dirty) renderComponent(p);
}
}
/** Check if a VNode is a reference to a stateless functional component.
* A function component is represented as a VNode whose `nodeName` property is a reference to a function.
* If that function is not a Component (ie, has no `.render()` method on a prototype), it is considered a stateless functional component.
* @param {VNode} vnode A VNode
* @private
*/
function isFunctionalComponent(_ref) {
var nodeName = _ref.nodeName;
return isFunction(nodeName) && !nodeName.prototype.render;
}
/** Construct a resultant VNode from a VNode referencing a stateless functional component.
* @param {VNode} vnode A VNode with a `nodeName` property that is a reference to a function.
* @private
*/
function buildFunctionalComponent(vnode, context) {
return vnode.nodeName(getNodeProps(vnode), context) || EMPTY_BASE;
}
function ensureNodeData(node) {
return node[ATTR_KEY] || (node[ATTR_KEY] = {});
}
function getNodeType(node) {
return node.nodeType;
}
/** Append multiple children to a Node.
* Uses a Document Fragment to batch when appending 2 or more children
* @private
*/
function appendChildren(parent, children) {
var len = children.length,
many = len > 2,
into = many ? document.createDocumentFragment() : parent;
for (var i = 0; i < len; i++) {
into.appendChild(children[i]);
}if (many) parent.appendChild(into);
}
/** Retrieve the value of a rendered attribute
* @private
*/
function getAccessor(node, name, value, cache) {
if (name !== 'type' && name !== 'style' && name in node) return node[name];
var attrs = node[ATTR_KEY];
if (cache !== false && attrs && hasOwnProperty.call(attrs, name)) return attrs[name];
if (name === 'class') return node.className;
if (name === 'style') return node.style.cssText;
return value;
}
/** Set a named attribute on the given Node, with special behavior for some names and event handlers.
* If `value` is `null`, the attribute/handler will be removed.
* @param {Element} node An element to mutate
* @param {string} name The name/key to set, such as an event or attribute name
* @param {any} value An attribute value, such as a function to be used as an event handler
* @param {any} previousValue The last value that was set for this name/node pair
* @private
*/
function setAccessor(node, name, value) {
if (name === 'class') {
node.className = value || '';
} else if (name === 'style') {
node.style.cssText = value || '';
} else if (name === 'dangerouslySetInnerHTML') {
node.innerHTML = value.__html;
} else if (name === 'key' || name in node && name !== 'type') {
node[name] = value;
if (falsey(value)) node.removeAttribute(name);
} else {
setComplexAccessor(node, name, value);
}
ensureNodeData(node)[name] = value;
}
/** For props without explicit behavior, apply to a Node as event handlers or attributes.
* @private
*/
function setComplexAccessor(node, name, value) {
if (name.substring(0, 2) === 'on') {
var _type = normalizeEventName(name),
l = node._listeners || (node._listeners = {}),
fn = !l[_type] ? 'add' : !value ? 'remove' : null;
if (fn) node[fn + 'EventListener'](_type, eventProxy);
l[_type] = value;
return;
}
var type = typeof value;
if (falsey(value)) {
node.removeAttribute(name);
} else if (type !== 'function' && type !== 'object') {
node.setAttribute(name, value);
}
}
/** Proxy an event to hooked event handlers
* @private
*/
function eventProxy(e) {
var fn = this._listeners[normalizeEventName(e.type)];
if (fn) return fn.call(this, optionsHook('event', e) || e);
}
/** Convert an Event name/type to lowercase and strip any "on*" prefix.
* @function
* @private
*/
var normalizeEventName = memoize(function (t) {
return t.replace(/^on/i, '').toLowerCase();
});
/** Get a hashmap of node properties, preferring preact's cached property values over the DOM's
* @private
*/
function getNodeAttributes(node) {
return node[ATTR_KEY] || getRawNodeAttributes(node) || EMPTY;
// let list = getRawNodeAttributes(node),
// l = node[ATTR_KEY];
// return l && list ? extend(list, l) : (l || list || EMPTY);
}
/** Get a node's attributes as a hashmap, regardless of type.
* @private
*/
function getRawNodeAttributes(node) {
var list = node.attributes;
if (!list || !list.getNamedItem) return list;
return getAttributesAsObject(list);
}
/** Convert a DOM `.attributes` NamedNodeMap to a hashmap.
* @private
*/
function getAttributesAsObject(list) {
var attrs = undefined;
for (var i = list.length; i--;) {
var item = list[i];
if (!attrs) attrs = {};
attrs[item.name] = item.value;
}
return attrs;
}
/** Check if two nodes are equivalent.
* @param {Element} node
* @param {VNode} vnode
* @private
*/
function isSameNodeType(node, vnode) {
if (isFunctionalComponent(vnode)) return true;
var nodeName = vnode.nodeName;
if (isFunction(nodeName)) return node._componentConstructor === nodeName;
if (getNodeType(node) === 3) return isString(vnode);
return toLowerCase(node.nodeName) === nodeName;
}
/**
* Reconstruct Component-style `props` from a VNode.
* Ensures default/fallback values from `defaultProps`:
* Own-properties of `defaultProps` not present in `vnode.attributes` are added.
* @param {VNode} vnode
* @returns {Object} props
*/
function getNodeProps(vnode) {
var props = clone(vnode.attributes),
c = vnode.children;
if (c) props.children = c;
var defaultProps = vnode.nodeName.defaultProps;
if (defaultProps) {
for (var i in defaultProps) {
if (hasOwnProperty.call(defaultProps, i) && !(i in props)) {
props[i] = defaultProps[i];
}
}
}
return props;
}
/** DOM node pool, keyed on nodeName. */
var nodes = {};
var normalizeName = memoize(function (name) {
return name.toUpperCase();
});
function collectNode(node) {
cleanNode(node);
var name = normalizeName(node.nodeName),
list = nodes[name];
if (list) list.push(node);else nodes[name] = [node];
}
function createNode(nodeName) {
var name = normalizeName(nodeName),
list = nodes[name],
node = list && list.pop() || document.createElement(nodeName);
ensureNodeData(node);
return node;
}
function cleanNode(node) {
var p = node.parentNode;
if (p) p.removeChild(node);
if (getNodeType(node) === 3) return;
node._component = node._componentConstructor = null;
// if (node.childNodes.length>0) {
// console.trace(`Warning: Recycler collecting <${node.nodeName}> with ${node.childNodes.length} children.`);
// for (let i=node.childNodes.length; i--; ) collectNode(node.childNodes[i]);
// }
}
/** Apply differences in a given vnode (and it's deep children) to a real DOM Node.
* @param {Element} [dom=null] A DOM node to mutate into the shape of the `vnode`
* @param {VNode} vnode A VNode (with descendants forming a tree) representing the desired DOM structure
* @returns {Element} dom The created/mutated element
* @private
*/
function diff(dom, vnode, context) {
var originalAttributes = vnode.attributes;
while (isFunctionalComponent(vnode)) {
vnode = buildFunctionalComponent(vnode, context);
}
if (isFunction(vnode.nodeName)) {
return buildComponentFromVNode(dom, vnode, context);
}
if (isString(vnode)) {
if (dom) {
var type = getNodeType(dom);
if (type === 3) {
dom[TEXT_CONTENT] = vnode;
return dom;
} else if (type === 1) {
collectNode(dom);
}
}
return document.createTextNode(vnode);
}
// return diffNode(dom, vnode, context);
// }
/** Morph a DOM node to look like the given VNode. Creates DOM if it doesn't exist. */
// function diffNode(dom, vnode, context) {
var out = dom,
nodeName = vnode.nodeName || UNDEFINED_ELEMENT;
if (!dom) {
out = createNode(nodeName);
} else if (toLowerCase(dom.nodeName) !== nodeName) {
out = createNode(nodeName);
// move children into the replacement node
appendChildren(out, toArray(dom.childNodes));
// reclaim element nodes
recollectNodeTree(dom);
}
innerDiffNode(out, vnode, context);
if (originalAttributes && originalAttributes.ref) {
(out[ATTR_KEY].ref = originalAttributes.ref)(out);
}
return out;
}
/** Apply child and attribute changes between a VNode and a DOM Node to the DOM. */
function innerDiffNode(dom, vnode, context) {
var children = undefined,
keyed = undefined,
keyedLen = 0,
len = dom.childNodes.length,
childrenLen = 0;
if (len) {
children = [];
for (var i = 0; i < len; i++) {
var child = dom.childNodes[i],
props = child._component && child._component.props,
key = props ? props.key : getAccessor(child, 'key');
if (!empty(key)) {
if (!keyed) keyed = {};
keyed[key] = child;
keyedLen++;
} else {
children[childrenLen++] = child;
}
}
}
diffAttributes(dom, vnode);
var vchildren = vnode.children,
vlen = vchildren && vchildren.length,
min = 0;
if (vlen) {
for (var i = 0; i < vlen; i++) {
var vchild = vchildren[i],
child = undefined;
// if (isFunctionalComponent(vchild)) {
// vchild = buildFunctionalComponent(vchild);
// }
// attempt to find a node based on key matching
if (keyedLen) {
var attrs = vchild.attributes,
key = attrs && attrs.key;
if (!empty(key) && keyed.hasOwnProperty(key)) {
child = keyed[key];
keyed[key] = null;
keyedLen--;
}
}
// attempt to pluck a node of the same type from the existing children
if (!child && min < childrenLen) {
for (var j = min; j < childrenLen; j++) {
var c = children[j];
if (c && isSameNodeType(c, vchild)) {
child = c;
children[j] = null;
if (j === childrenLen - 1) childrenLen--;
if (j === min) min++;
break;
}
}
}
// morph the matched/found/created DOM child to match vchild (deep)
child = diff(child, vchild, context);
if (dom.childNodes[i] !== child) {
var c = child.parentNode !== dom && child._component,
next = dom.childNodes[i + 1];
if (c) deepHook(c, 'componentWillMount');
if (next) {
dom.insertBefore(child, next);
} else {
dom.appendChild(child);
}
if (c) deepHook(c, 'componentDidMount');
}
}
}
if (keyedLen) {
/*eslint guard-for-in:0*/
for (var i in keyed) {
if (keyed.hasOwnProperty(i) && keyed[i]) {
children[min = childrenLen++] = keyed[i];
}
}
}
// remove orphaned children
if (min < childrenLen) {
removeOrphanedChildren(dom, children);
}
}
/** Reclaim children that were unreferenced in the desired VTree */
function removeOrphanedChildren(out, children, unmountOnly) {
for (var i = children.length; i--;) {
var child = children[i];
if (child) {
recollectNodeTree(child, unmountOnly);
}
}
}
/** Reclaim an entire tree of nodes, starting at the root. */
function recollectNodeTree(node, unmountOnly) {
// @TODO: Need to make a call on whether Preact should remove nodes not created by itself.
// Currently it *does* remove them. Discussion: https://github.com/developit/preact/issues/39
//if (!node[ATTR_KEY]) return;
var attrs = node[ATTR_KEY];
if (attrs) hook(attrs, 'ref', null);
var component = node._component;
if (component) {
unmountComponent(node, component);
} else {
if (!unmountOnly) {
if (getNodeType(node) !== 1) {
var p = node.parentNode;
if (p) p.removeChild(node);
return;
}
collectNode(node);
}
var c = node.childNodes;
if (c && c.length) {
removeOrphanedChildren(node, c, unmountOnly);
}
}
}
/** Apply differences in attributes from a VNode to the given DOM Node. */
function diffAttributes(dom, vnode) {
var old = getNodeAttributes(dom) || EMPTY,
attrs = vnode.attributes || EMPTY,
name = undefined,
value = undefined;
// removed
for (name in old) {
if (empty(attrs[name])) {
setAccessor(dom, name, null);
}
}
// new & updated
if (attrs !== EMPTY) {
for (name in attrs) {
if (hasOwnProperty.call(attrs, name)) {
value = attrs[name];
if (!empty(value) && value != getAccessor(dom, name)) {
setAccessor(dom, name, value);
}
}
}
}
}
var components = {};
function collectComponent(component) {
var name = component.constructor.name,
list = components[name];
if (list) list.push(component);else components[name] = [component];
}
function createComponent(ctor, props, context) {
var list = components[ctor.name],
len = list && list.length,
c = undefined;
for (var i = 0; i < len; i++) {
c = list[i];
if (c.constructor === ctor) {
list.splice(i, 1);
return c;
}
}
return new ctor(props, context);
}
/** Mark component as dirty and queue up a render.
* @param {Component} component
* @private
*/
function triggerComponentRender(component) {
if (!component._dirty) {
component._dirty = true;
enqueueRender(component);
}
}
/** Set a component's `props` (generally derived from JSX attributes).
* @param {Object} props
* @param {Object} [opts]
* @param {boolean} [opts.renderSync=false] If `true` and {@link options.syncComponentUpdates} is `true`, triggers synchronous rendering.
* @param {boolean} [opts.render=true] If `false`, no render will be triggered.
*/
function setComponentProps(component, props, opts, context) {
var d = component._disableRendering;
component._disableRendering = true;
opts = opts || EMPTY;
if (context) {
if (!component.prevContext) component.prevContext = clone(component.context);
component.context = context;
}
if (component.base) {
hook(component, 'componentWillReceiveProps', props, component.context);
}
if (!component.prevProps) component.prevProps = clone(component.props);
component.props = props;
component._disableRendering = d;
if (opts.render !== false) {
if (opts.renderSync || options.syncComponentUpdates !== false) {
renderComponent(component);
} else {
triggerComponentRender(component);
}
}
hook(props, 'ref', component);
}
/** Render a Component, triggering necessary lifecycle events and taking High-Order Components into account.
* @param {Component} component
* @param {Object} [opts]
* @param {boolean} [opts.build=false] If `true`, component will build and store a DOM node if not already associated with one.
* @private
*/
function renderComponent(component, opts) {
if (component._disableRendering) return;
var skip = undefined,
rendered = undefined,
props = component.props,
state = component.state,
context = component.context,
previousProps = component.prevProps || props,
previousState = component.prevState || state,
previousContext = component.prevContext || context,
isUpdate = component.base;
if (isUpdate) {
component.props = previousProps;
component.state = previousState;
component.context = previousContext;
if (hook(component, 'shouldComponentUpdate', props, state, context) === false) {
skip = true;
} else {
hook(component, 'componentWillUpdate', props, state, context);
}
component.props = props;
component.state = state;
component.context = context;
}
component.prevProps = component.prevState = component.prevContext = null;
component._dirty = false;
if (!skip) {
rendered = hook(component, 'render', props, state, context);
var childComponent = rendered && rendered.nodeName,
childContext = component.getChildContext ? component.getChildContext() : context,
toUnmount = undefined,
base = undefined;
if (isFunction(childComponent) && childComponent.prototype.render) {
// set up high order component link
var inst = component._component;
if (inst && inst.constructor !== childComponent) {
toUnmount = inst;
inst = null;
}
var childProps = getNodeProps(rendered);
if (inst) {
setComponentProps(inst, childProps, SYNC_RENDER, childContext);
} else {
inst = createComponent(childComponent, childProps, childContext);
inst._parentComponent = component;
component._component = inst;
if (component.base) deepHook(inst, 'componentWillMount');
setComponentProps(inst, childProps, NO_RENDER, childContext);
renderComponent(inst, DOM_RENDER);
if (component.base) deepHook(inst, 'componentDidMount');
}
base = inst.base;
} else {
var cbase = component.base;
// destroy high order component link
toUnmount = component._component;
if (toUnmount) {
cbase = component._component = null;
}
if (component.base || opts && opts.build) {
base = diff(cbase, rendered || EMPTY_BASE, childContext);
}
}
if (component.base && base !== component.base) {
var p = component.base.parentNode;
if (p) p.replaceChild(base, component.base);
}
if (toUnmount) {
unmountComponent(toUnmount.base, toUnmount);
}
component.base = base;
if (base) {
var componentRef = component,
t = component;
while (t = t._parentComponent) {
componentRef = t;
}
base._component = componentRef;
base._componentConstructor = componentRef.constructor;
}
if (isUpdate) {
hook(component, 'componentDidUpdate', previousProps, previousState, previousContext);
}
}
var cb = component._renderCallbacks,
fn = undefined;
if (cb) while (fn = cb.pop()) fn.call(component);
return rendered;
}
/** Apply the Component referenced by a VNode to the DOM.
* @param {Element} dom The DOM node to mutate
* @param {VNode} vnode A Component-referencing VNode
* @returns {Element} dom The created/mutated element
* @private
*/
function buildComponentFromVNode(dom, vnode, context) {
var c = dom && dom._component,
oldDom = dom;
var isOwner = c && dom._componentConstructor === vnode.nodeName;
while (c && !isOwner && (c = c._parentComponent)) {
isOwner = c.constructor === vnode.nodeName;
}
if (isOwner) {
setComponentProps(c, getNodeProps(vnode), SYNC_RENDER, context);
dom = c.base;
} else {
if (c) {
unmountComponent(dom, c);
dom = oldDom = null;
}
dom = createComponentFromVNode(vnode, dom, context);
if (oldDom && dom !== oldDom) {
recollectNodeTree(oldDom);
}
}
return dom;
}
/** Instantiate and render a Component, given a VNode whose nodeName is a constructor.
* @param {VNode} vnode
* @private
*/
function createComponentFromVNode(vnode, dom, context) {
var props = getNodeProps(vnode);
var component = createComponent(vnode.nodeName, props, context);
if (dom && !component.base) component.base = dom;
setComponentProps(component, props, NO_RENDER, context);
renderComponent(component, DOM_RENDER);
// let node = component.base;
//if (!node._component) {
// node._component = component;
// node._componentConstructor = vnode.nodeName;
//}
return component.base;
}
/** Remove a component from the DOM and recycle it.
* @param {Element} dom A DOM node from which to unmount the given Component
* @param {Component} component The Component instance to unmount
* @private
*/
function unmountComponent(dom, component, remove) {
// console.warn('unmounting mismatched component', component);
hook(component.props, 'ref', null);
hook(component, 'componentWillUnmount');
if (dom && dom._component === component) {
delete dom._component;
delete dom._componentConstructor;
}
// recursively tear down & recollect high-order component children:
var inner = component._component;
if (inner) {
unmountComponent(dom, inner, remove);
// high order components do not own their rendered nodes:
component.base = component._component = null;
}
var base = component.base;
if (base) {
if (remove !== false) {
var p = base.parentNode;
if (p) p.removeChild(base);
}
removeOrphanedChildren(base, base.childNodes, true);
}
component._parentComponent = null;
hook(component, 'componentDidUnmount');
collectComponent(component);
}
/** Base Component class, for he ES6 Class method of creating Components
* @public
*
* @example
* class MyFoo extends Component {
* render(props, state) {
* return <div />;
* }
* }
*/
function Component(props, context) {
/** @private */
this._dirty = this._disableRendering = false;
/** @private */
this._linkedStates = {};
/** @private */
this._renderCallbacks = [];
/** @public */
this.prevState = this.prevProps = this.prevContext = this.base = this._parentComponent = this._component = null;
/** @public */
this.context = context || null;
/** @type {object} */
this.props = props || {};
/** @type {object} */
this.state = hook(this, 'getInitialState') || {};
}
extend(Component.prototype, {
/** Returns a `boolean` value indicating if the component should re-render when receiving the given `props` and `state`.
* @param {object} nextProps
* @param {object} nextState
* @param {object} nextContext
* @returns {Boolean} should the component re-render
* @name shouldComponentUpdate
* @function
*/
// shouldComponentUpdate() {
// return true;
// },
/** Returns a function that sets a state property when called.
* Calling linkState() repeatedly with the same arguments returns a cached link function.
*
* Provides some built-in special cases:
* - Checkboxes and radio buttons link their boolean `checked` value
* - Inputs automatically link their `value` property
* - Event paths fall back to any associated Component if not found on an element
* - If linked value is a function, will invoke it and use the result
*
* @param {string} key The path to set - can be a dot-notated deep key
* @param {string} [eventPath] If set, attempts to find the new state value at a given dot-notated path within the object passed to the linkedState setter.
* @returns {function} linkStateSetter(e)
*
* @example Update a "text" state value when an input changes:
* <input onChange={ this.linkState('text') } />
*
* @example Set a deep state value on click
* <button onClick={ this.linkState('touch.coords', 'touches.0') }>Tap</button
*/
linkState: function linkState(key, eventPath) {
var c = this._linkedStates,
cacheKey = key + '|' + (eventPath || '');
return c[cacheKey] || (c[cacheKey] = createLinkedState(this, key, eventPath));
},
/** Update component state by copying properties from `state` to `this.state`.
* @param {object} state A hash of state properties to update with new values
*/
setState: function setState(state, callback) {
var s = this.state;
if (!this.prevState) this.prevState = clone(s);
extend(s, isFunction(state) ? state(s, this.props) : state);
if (callback) this._renderCallbacks.push(callback);
triggerComponentRender(this);
},
/** Immediately perform a synchronous re-render of the component.
* @private
*/
forceUpdate: function forceUpdate() {
renderComponent(this);
},
/** Accepts `props` and `state`, and returns a new Virtual DOM tree to build.
* Virtual DOM is generally constructed via [JSX](http://jasonformat.com/wtf-is-jsx).
* @param {object} props Props (eg: JSX attributes) received from parent element/component
* @param {object} state The component's current state
* @returns VNode
*/
render: function render() {
return null;
}
});
/** Render JSX into a `parent` Element.
* @param {VNode} vnode A (JSX) VNode to render
* @param {Element} parent DOM element to render into
* @param {Element} [merge] Attempt to re-use an existing DOM tree rooted at `merge`
* @public
*
* @example
* // render a div into <body>:
* render(<div id="hello">hello!</div>, document.body);
*
* @example
* // render a "Thing" component into #foo:
* const Thing = ({ name }) => <span>{ name }</span>;
* render(<Thing name="one" />, document.querySelector('#foo'));
*/
function render(vnode, parent, merge) {
var existing = merge && merge._component && merge._componentConstructor === vnode.nodeName,
built = diff(merge, vnode),
c = !existing && built._component;
if (c) deepHook(c, 'componentWillMount');
if (built.parentNode !== parent) {
parent.appendChild(built);
}
if (c) deepHook(c, 'componentDidMount');
return built;
}
var preact = {
h: h,
Component: Component,
render: render,
rerender: rerender,
options: options,
hooks: options
};
return preact;
}));
//# sourceMappingURL=preact.js.map | mit |
smpetrey/acredistilling.com | web/app/plugins/jetpack/views/admin/network-settings.php | 4154 | <?php extract( $data ); ?>
<?php if ( isset( $_GET['updated'] ) && 'true' == $_GET['updated'] ) : ?>
<div class="updated"><?php esc_html_e( 'Jetpack Network Settings Updated!', 'jetpack' ); ?></div>
<?php endif; ?>
<?php if ( isset( $_GET['error'] ) && 'jetpack_protect_whitelist' == $_GET['error'] ) : ?>
<div class="error"><?php esc_html_e( 'One of your IP addresses was not valid.', 'jetpack' ); ?></div>
<?php endif; ?>
<div class="wrap">
<h2><?php _e( 'Network Settings', 'jetpack' ); ?></h2>
<form action="edit.php?action=jetpack-network-settings" method="POST">
<h3><?php _ex( 'Global', 'Affects all sites in a Multisite network.', 'jetpack' ); ?></h3>
<p><?php _e( 'These settings affect all sites on the network.', 'jetpack' ); ?></p>
<?php wp_nonce_field( 'jetpack-network-settings' ); ?>
<table class="form-table">
<?php /*
<tr valign="top">
<th scope="row"><label for="auto-connect">Auto-Connect New Sites</label></th>
<td>
<input type="checkbox" name="auto-connect" id="auto-connect" value="1" <?php checked($options['auto-connect']); ?> />
<label for="auto-connect">Automagically connect all new sites in the network.</label>
</td>
</tr>
/**/ ?>
<tr valign="top">
<th scope="row"><label for="sub-site-override"><?php _e( 'Sub-site override', 'jetpack' ); ?></label></th>
<td>
<input type="checkbox" name="sub-site-connection-override" id="sub-site-override" value="1" <?php checked($options['sub-site-connection-override']); ?> />
<label for="sub-site-override"><?php _e( 'Allow individual site administrators to manage their own connections (connect and disconnect) to <a href="//wordpress.com">WordPress.com</a>', 'jetpack' ); ?></label>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="sub-site-override"><?php _e( 'Protect whitelist', 'jetpack' ); ?></label></th>
<td>
<p><strong><?php printf( __( 'Your current IP: %s', 'jetpack' ), jetpack_protect_get_ip() ); ?></strong></p>
<textarea name="global-whitelist" style="width: 100%;" rows="8"><?php echo implode( PHP_EOL, $jetpack_protect_whitelist['global'] ); ?></textarea> <br />
<label for="global-whitelist"><?php _e('IPv4 and IPv6 are acceptable. Enter multiple IPs on separate lines. <br />To specify a range, enter the low value and high value separated by a dash. Example: 12.12.12.1-12.12.12.100', 'jetpack' ); ?></label>
</td>
</tr>
<?php /* Remove the toggles for 2.9, re-evaluate how they're done and added for a 3.0 release. They don't feel quite right yet.
<tr>
<th scope="row"><label for="manage_auto_activated_modules">Manage modules</label></th>
<td>
<input type="checkbox" name="manage_auto_activated_modules" id="manage_auto_activated_modules" onclick="jQuery('#jpms_settings_modules').toggle();" value="1" <?php checked( $options['manage_auto_activated_modules'] ); ?>/>
<label for="manage_auto_activated_modules">Control which modules are auto-activated</label>
</td>
</tr>
/**/ ?>
</table>
<?php /* Remove the toggles for 2.9, re-evaluate how they're done and added for a 3.0 release. They don't feel quite right yet.
<?php
$display_modules = ( 1 == $this->get_option( 'manage_auto_activated_modules' ) )? 'block': 'none';
?>
<div id="jpms_settings_modules" style="display: <?php echo $display_modules; ?>">
<h3><?php _e( 'Modules', 'jetpack' ); ?></h3>
<p><?php _e( 'Modules to be automatically activated when new sites are created.', 'jetpack' ); ?></p>
<table>
<thead>
<!--
<tr>
<td><input type="checkbox"></td>
<td>Only show checked modules on subsites?</td>
</tr>
-->
</thead>
<tbody>
<?php foreach( $modules AS $module ) { ?>
<tr>
<td><input type="checkbox" name="modules[]" value="<?php echo $module['module']; ?>" id="<?php echo $module['module']; ?>" <?php checked( in_array( $module['module'], $options['modules'] ) ); ?>/></td>
<td><label for="<?php echo $module['module']; ?>"><?php echo $module['name']; ?></label></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
/**/ ?>
<?php submit_button(); ?>
</form>
</div>
| mit |
XieXianbin/openjdk | nashorn/test/script/basic/JDK-8012460.js | 2095 | /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* JDK-8012460: RegExp regression
*
* @test
* @run
*/
var semver = "\\s*[v=]*\\s*([0-9]+)" // major
+ "\\.([0-9]+)" // minor
+ "\\.([0-9]+)" // patch
+ "(-[0-9]+-?)?" // build
+ "([a-zA-Z-+][a-zA-Z0-9-\.:]*)?" // tag
, exprComparator = "^((<|>)?=?)\s*("+semver+")$|^$";
var validComparator = new RegExp("^"+exprComparator+"$");
print(exprComparator);
print(">=0.6.0-".match(validComparator));
print("=0.6.0-".match(validComparator));
print("0.6.0-".match(validComparator));
print("<=0.6.0-".match(validComparator));
print(">=0.6.0-a:b-c.d".match(validComparator));
print("=0.6.0-a:b-c.d".match(validComparator));
print("0.6.0+a:b-c.d".match(validComparator));
print("<=0.6.0+a:b-c.d".match(validComparator));
print(/[a-zA-Z-+]/.exec("a"));
print(/[a-zA-Z-+]/.exec("b"));
print(/[a-zA-Z-+]/.exec("y"));
print(/[a-zA-Z-+]/.exec("z"));
print(/[a-zA-Z-+]/.exec("B"));
print(/[a-zA-Z-+]/.exec("Y"));
print(/[a-zA-Z-+]/.exec("Z"));
print(/[a-zA-Z-+]/.exec("-"));
print(/[a-zA-Z-+]/.exec("+"));
| gpl-2.0 |
pczarn/rust | src/test/run-pass/default-method-simple.rs | 722 | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo {
fn f(&self) {
println!("Hello!");
self.g();
}
fn g(&self);
}
struct A {
x: int
}
impl Foo for A {
fn g(&self) {
println!("Goodbye!");
}
}
pub fn main() {
let a = A { x: 1 };
a.f();
}
| apache-2.0 |
vladmm/intellij-community | xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsProblemsHolderImpl.java | 8610 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.xml.highlighting;
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Factory;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomElementVisitor;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.DomUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class DomElementsProblemsHolderImpl implements DomElementsProblemsHolder {
private final Map<DomElement, Map<Class<? extends DomElementsInspection>, List<DomElementProblemDescriptor>>> myCachedErrors =
ContainerUtil.newConcurrentMap();
private final Map<DomElement, Map<Class<? extends DomElementsInspection>, List<DomElementProblemDescriptor>>> myCachedChildrenErrors =
ContainerUtil.newConcurrentMap();
private final List<Annotation> myAnnotations = new ArrayList<Annotation>();
private final Function<DomElement, List<DomElementProblemDescriptor>> myDomProblemsGetter =
new Function<DomElement, List<DomElementProblemDescriptor>>() {
@Override
public List<DomElementProblemDescriptor> fun(final DomElement s) {
final Map<Class<? extends DomElementsInspection>, List<DomElementProblemDescriptor>> map = myCachedErrors.get(s);
return map != null ? ContainerUtil.concat(map.values()) : Collections.<DomElementProblemDescriptor>emptyList();
}
};
private final DomFileElement myElement;
private static final Factory<Map<Class<? extends DomElementsInspection>,List<DomElementProblemDescriptor>>> CONCURRENT_HASH_MAP_FACTORY = new Factory<Map<Class<? extends DomElementsInspection>, List<DomElementProblemDescriptor>>>() {
@Override
public Map<Class<? extends DomElementsInspection>, List<DomElementProblemDescriptor>> create() {
return ContainerUtil.newConcurrentMap();
}
};
private static final Factory<List<DomElementProblemDescriptor>> SMART_LIST_FACTORY = new Factory<List<DomElementProblemDescriptor>>() {
@Override
public List<DomElementProblemDescriptor> create() {
return new SmartList<DomElementProblemDescriptor>();
}
};
private final Set<Class<? extends DomElementsInspection>> myPassedInspections = new THashSet<Class<? extends DomElementsInspection>>();
public DomElementsProblemsHolderImpl(final DomFileElement element) {
myElement = element;
}
public final void appendProblems(final DomElementAnnotationHolderImpl holder, final Class<? extends DomElementsInspection> inspectionClass) {
if (isInspectionCompleted(inspectionClass)) return;
for (final DomElementProblemDescriptor descriptor : holder) {
addProblem(descriptor, inspectionClass);
}
myAnnotations.addAll(holder.getAnnotations());
myPassedInspections.add(inspectionClass);
}
@Override
public final boolean isInspectionCompleted(@NotNull final DomElementsInspection inspection) {
return isInspectionCompleted(inspection.getClass());
}
public final boolean isInspectionCompleted(final Class<? extends DomElementsInspection> inspectionClass) {
synchronized (DomElementAnnotationsManagerImpl.LOCK) {
return myPassedInspections.contains(inspectionClass);
}
}
public final List<Annotation> getAnnotations() {
return myAnnotations;
}
public final void addProblem(final DomElementProblemDescriptor descriptor, final Class<? extends DomElementsInspection> inspection) {
ContainerUtil.getOrCreate(ContainerUtil.getOrCreate(myCachedErrors, descriptor.getDomElement(), CONCURRENT_HASH_MAP_FACTORY), inspection,
SMART_LIST_FACTORY).add(descriptor);
myCachedChildrenErrors.clear();
}
@Override
@NotNull
public synchronized List<DomElementProblemDescriptor> getProblems(DomElement domElement) {
if (domElement == null || !domElement.isValid()) return Collections.emptyList();
return myDomProblemsGetter.fun(domElement);
}
@Override
public List<DomElementProblemDescriptor> getProblems(final DomElement domElement, boolean includeXmlProblems) {
return getProblems(domElement);
}
@Override
public List<DomElementProblemDescriptor> getProblems(final DomElement domElement,
final boolean includeXmlProblems,
final boolean withChildren) {
if (!withChildren || domElement == null || !domElement.isValid()) {
return getProblems(domElement);
}
return ContainerUtil.concat(getProblemsMap(domElement).values());
}
@Override
public List<DomElementProblemDescriptor> getProblems(DomElement domElement,
final boolean includeXmlProblems,
final boolean withChildren,
final HighlightSeverity minSeverity) {
return getProblems(domElement, withChildren, minSeverity);
}
@Override
public List<DomElementProblemDescriptor> getProblems(final DomElement domElement, final boolean withChildren, final HighlightSeverity minSeverity) {
return ContainerUtil.findAll(getProblems(domElement, true, withChildren), new Condition<DomElementProblemDescriptor>() {
@Override
public boolean value(final DomElementProblemDescriptor object) {
return SeverityRegistrar.getSeverityRegistrar(domElement.getManager().getProject()).compare(object.getHighlightSeverity(), minSeverity) >= 0;
}
});
}
@NotNull
private Map<Class<? extends DomElementsInspection>, List<DomElementProblemDescriptor>> getProblemsMap(final DomElement domElement) {
final Map<Class<? extends DomElementsInspection>, List<DomElementProblemDescriptor>> map = myCachedChildrenErrors.get(domElement);
if (map != null) {
return map;
}
final Map<Class<? extends DomElementsInspection>, List<DomElementProblemDescriptor>> problems = new THashMap<Class<? extends DomElementsInspection>, List<DomElementProblemDescriptor>>();
if (domElement == myElement) {
for (Map<Class<? extends DomElementsInspection>, List<DomElementProblemDescriptor>> listMap : myCachedErrors.values()) {
mergeMaps(problems, listMap);
}
} else {
mergeMaps(problems, myCachedErrors.get(domElement));
if (DomUtil.hasXml(domElement)) {
domElement.acceptChildren(new DomElementVisitor() {
@Override
public void visitDomElement(DomElement element) {
mergeMaps(problems, getProblemsMap(element));
}
});
}
}
myCachedChildrenErrors.put(domElement, problems);
return problems;
}
private static <T> void mergeMaps(final Map<T, List<DomElementProblemDescriptor>> accumulator, @Nullable final Map<T, List<DomElementProblemDescriptor>> toAdd) {
if (toAdd == null) return;
for (final Map.Entry<T, List<DomElementProblemDescriptor>> entry : toAdd.entrySet()) {
ContainerUtil.getOrCreate(accumulator, entry.getKey(), SMART_LIST_FACTORY).addAll(entry.getValue());
}
}
@Override
public List<DomElementProblemDescriptor> getAllProblems() {
return getProblems(myElement, false, true);
}
@Override
public List<DomElementProblemDescriptor> getAllProblems(@NotNull DomElementsInspection inspection) {
if (!myElement.isValid()) {
return Collections.emptyList();
}
final List<DomElementProblemDescriptor> list = getProblemsMap(myElement).get(inspection.getClass());
return list != null ? new ArrayList<DomElementProblemDescriptor>(list) : Collections.<DomElementProblemDescriptor>emptyList();
}
}
| apache-2.0 |
pravi/fog | lib/fog/openstack/models/compute/service.rb | 941 | require 'fog/openstack/models/model'
module Fog
module Compute
class OpenStack
class Service < Fog::OpenStack::Model
identity :id
attribute :binary
attribute :host
attribute :state
attribute :status
attribute :updated_at
attribute :zone
#detailed
attribute :disabled_reason
def enable
requires :binary, :host
service.enable_service(self.host, self.binary)
end
def disable
requires :binary, :host
service.disable_service(self.host, self.binary)
end
def disable_and_log_reason
requires :binary, :host, :disabled_reason
service.disable_service_log_reason(self.host, self.binary, self.disabled_reason)
end
def destroy
requires :id
service.delete_service(self.id)
true
end
end
end
end
end
| mit |
arroyolabs-blog/roll-dice | app/themes/bootstrap/node_modules/gulp-uglify/index.js | 1689 | 'use strict';
var through = require('through2'),
uglify = require('uglify-js'),
merge = require('deepmerge'),
Vinyl = require('vinyl'),
uglifyError = require('./lib/error.js');
module.exports = function(opt) {
function minify(file, encoding, callback) {
/*jshint validthis:true */
if (file.isNull()) {
this.push(file);
return callback();
}
if (file.isStream()) {
return callback(uglifyError('Streaming not supported'));
}
var options = merge(opt || {}, {
fromString: true,
output: {}
});
var mangled,
map,
sourceMap;
if (options.outSourceMap === true) {
options.outSourceMap = file.relative + '.map';
}
if (options.preserveComments === 'all') {
options.output.comments = true;
} else if (options.preserveComments === 'some') {
// preserve comments with directives or that start with a bang (!)
options.output.comments = /^!|@preserve|@license|@cc_on/i;
} else if (typeof options.preserveComments === 'function') {
options.output.comments = options.preserveComments;
}
try {
mangled = uglify.minify(String(file.contents), options);
file.contents = new Buffer(mangled.code);
this.push(file);
} catch (e) {
console.warn('Error caught from uglify: ' + e.message + ' in ' + file.path + '. Returning unminifed code');
this.push(file);
return callback();
}
if (options.outSourceMap) {
sourceMap = JSON.parse(mangled.map);
sourceMap.sources = [ file.relative ];
map = new Vinyl({
cwd: file.cwd,
base: file.base,
path: file.path + '.map',
contents: new Buffer(JSON.stringify(sourceMap))
});
this.push(map);
}
callback();
}
return through.obj(minify);
};
| mit |
misas-io/misas-client | src/app/app.e2e.ts | 814 | import { browser, by, element } from 'protractor';
describe('App', () => {
beforeEach(() => {
browser.get('/');
});
it('should have a title', () => {
let subject = browser.getTitle();
let result = 'Angular2 Webpack Starter by @gdi2290 from @AngularClass';
expect(subject).toEqual(result);
});
it('should have header', () => {
let subject = element(by.css('h1')).isPresent();
let result = true;
expect(subject).toEqual(result);
});
it('should have <home>', () => {
let subject = element(by.css('app home')).isPresent();
let result = true;
expect(subject).toEqual(result);
});
it('should have buttons', () => {
let subject = element(by.css('button')).getText();
let result = 'Submit Value';
expect(subject).toEqual(result);
});
});
| mit |
podarok/csua_d8 | drupal/core/modules/block_content/src/Controller/BlockContentController.php | 3739 | <?php
/**
* @file
* Contains \Drupal\block_content\Controller\BlockContentController
*/
namespace Drupal\block_content\Controller;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\block_content\BlockContentTypeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
class BlockContentController extends ControllerBase {
/**
* The custom block storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $blockContentStorage;
/**
* The custom block type storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $blockContentTypeStorage;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$entity_manager = $container->get('entity.manager');
return new static(
$entity_manager->getStorage('block_content'),
$entity_manager->getStorage('block_content_type')
);
}
/**
* Constructs a BlockContent object.
*
* @param \Drupal\Core\Entity\EntityStorageInterface $block_content_storage
* The custom block storage.
* @param \Drupal\Core\Entity\EntityStorageInterface $block_content_type_storage
* The custom block type storage.
*/
public function __construct(EntityStorageInterface $block_content_storage, EntityStorageInterface $block_content_type_storage) {
$this->blockContentStorage = $block_content_storage;
$this->blockContentTypeStorage = $block_content_type_storage;
}
/**
* Displays add custom block links for available types.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request object.
*
* @return array
* A render array for a list of the custom block types that can be added or
* if there is only one custom block type defined for the site, the function
* returns the custom block add page for that custom block type.
*/
public function add(Request $request) {
$types = $this->blockContentTypeStorage->loadMultiple();
if ($types && count($types) == 1) {
$type = reset($types);
return $this->addForm($type, $request);
}
return array('#theme' => 'block_content_add_list', '#content' => $types);
}
/**
* Presents the custom block creation form.
*
* @param \Drupal\block_content\BlockContentTypeInterface $block_content_type
* The custom block type to add.
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request object.
*
* @return array
* A form array as expected by drupal_render().
*/
public function addForm(BlockContentTypeInterface $block_content_type, Request $request) {
$block = $this->blockContentStorage->create(array(
'type' => $block_content_type->id()
));
if (($theme = $request->query->get('theme')) && in_array($theme, array_keys(list_themes()))) {
// We have navigated to this page from the block library and will keep track
// of the theme for redirecting the user to the configuration page for the
// newly created block in the given theme.
$block->setTheme($theme);
}
return $this->entityFormBuilder()->getForm($block);
}
/**
* Provides the page title for this controller.
*
* @param \Drupal\block_content\BlockContentTypeInterface $block_content_type
* The custom block type being added.
*
* @return string
* The page title.
*/
public function getAddFormTitle(BlockContentTypeInterface $block_content_type) {
return $this->t('Add %type custom block', array('%type' => $block_content_type->label()));
}
}
| gpl-2.0 |
R3dRidle/MaineLearning | wp-content/plugins/events-manager/includes/thumbnails/timthumb.php | 50759 | <?php
/**
* TimThumb by Ben Gillbanks and Mark Maunder
* Based on work done by Tim McDaniels and Darren Hoyt
* http://code.google.com/p/timthumb/
*
* GNU General Public License, version 2
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Examples and documentation available on the project homepage
* http://www.binarymoon.co.uk/projects/timthumb/
*
* $Rev$
*/
/*
* --- TimThumb CONFIGURATION ---
* To edit the configs it is best to create a file called timthumb-config.php
* and define variables you want to customize in there. It will automatically be
* loaded by timthumb. This will save you having to re-edit these variables
* everytime you download a new version
*/
define ('VERSION', '2.8.11'); // Version of this script
//Load a config file if it exists. Otherwise, use the values below
if( file_exists(dirname(__FILE__) . '/timthumb-config.php')) require_once('timthumb-config.php');
if(! defined('DEBUG_ON') ) define ('DEBUG_ON', false); // Enable debug logging to web server error log (STDERR)
if(! defined('DEBUG_LEVEL') ) define ('DEBUG_LEVEL', 1); // Debug level 1 is less noisy and 3 is the most noisy
if(! defined('MEMORY_LIMIT') ) define ('MEMORY_LIMIT', '30M'); // Set PHP memory limit
if(! defined('BLOCK_EXTERNAL_LEECHERS') ) define ('BLOCK_EXTERNAL_LEECHERS', false); // If the image or webshot is being loaded on an external site, display a red "No Hotlinking" gif.
//Image fetching and caching
if(! defined('ALLOW_EXTERNAL') ) define ('ALLOW_EXTERNAL', TRUE); // Allow image fetching from external websites. Will check against ALLOWED_SITES if ALLOW_ALL_EXTERNAL_SITES is false
if(! defined('ALLOW_ALL_EXTERNAL_SITES') ) define ('ALLOW_ALL_EXTERNAL_SITES', false); // Less secure.
if(! defined('FILE_CACHE_ENABLED') ) define ('FILE_CACHE_ENABLED', TRUE); // Should we store resized/modified images on disk to speed things up?
if(! defined('FILE_CACHE_TIME_BETWEEN_CLEANS')) define ('FILE_CACHE_TIME_BETWEEN_CLEANS', 86400); // How often the cache is cleaned
if(! defined('FILE_CACHE_MAX_FILE_AGE') ) define ('FILE_CACHE_MAX_FILE_AGE', 86400); // How old does a file have to be to be deleted from the cache
if(! defined('FILE_CACHE_SUFFIX') ) define ('FILE_CACHE_SUFFIX', '.timthumb.txt'); // What to put at the end of all files in the cache directory so we can identify them
if(! defined('FILE_CACHE_PREFIX') ) define ('FILE_CACHE_PREFIX', 'timthumb'); // What to put at the beg of all files in the cache directory so we can identify them
if(! defined('FILE_CACHE_DIRECTORY') ) define ('FILE_CACHE_DIRECTORY', './cache'); // Directory where images are cached. Left blank it will use the system temporary directory (which is better for security)
if(! defined('MAX_FILE_SIZE') ) define ('MAX_FILE_SIZE', 10485760); // 10 Megs is 10485760. This is the max internal or external file size that we'll process.
if(! defined('CURL_TIMEOUT') ) define ('CURL_TIMEOUT', 20); // Timeout duration for Curl. This only applies if you have Curl installed and aren't using PHP's default URL fetching mechanism.
if(! defined('WAIT_BETWEEN_FETCH_ERRORS') ) define ('WAIT_BETWEEN_FETCH_ERRORS', 3600); // Time to wait between errors fetching remote file
//Browser caching
if(! defined('BROWSER_CACHE_MAX_AGE') ) define ('BROWSER_CACHE_MAX_AGE', 864000); // Time to cache in the browser
if(! defined('BROWSER_CACHE_DISABLE') ) define ('BROWSER_CACHE_DISABLE', false); // Use for testing if you want to disable all browser caching
//Image size and defaults
if(! defined('MAX_WIDTH') ) define ('MAX_WIDTH', 1500); // Maximum image width
if(! defined('MAX_HEIGHT') ) define ('MAX_HEIGHT', 1500); // Maximum image height
if(! defined('NOT_FOUND_IMAGE') ) define ('NOT_FOUND_IMAGE', ''); // Image to serve if any 404 occurs
if(! defined('ERROR_IMAGE') ) define ('ERROR_IMAGE', ''); // Image to serve if an error occurs instead of showing error message
if(! defined('PNG_IS_TRANSPARENT') ) define ('PNG_IS_TRANSPARENT', FALSE); // Define if a png image should have a transparent background color. Use False value if you want to display a custom coloured canvas_colour
if(! defined('DEFAULT_Q') ) define ('DEFAULT_Q', 90); // Default image quality. Allows overrid in timthumb-config.php
if(! defined('DEFAULT_ZC') ) define ('DEFAULT_ZC', 1); // Default zoom/crop setting. Allows overrid in timthumb-config.php
if(! defined('DEFAULT_F') ) define ('DEFAULT_F', ''); // Default image filters. Allows overrid in timthumb-config.php
if(! defined('DEFAULT_S') ) define ('DEFAULT_S', 0); // Default sharpen value. Allows overrid in timthumb-config.php
if(! defined('DEFAULT_CC') ) define ('DEFAULT_CC', 'ffffff'); // Default canvas colour. Allows overrid in timthumb-config.php
//Image compression is enabled if either of these point to valid paths
//These are now disabled by default because the file sizes of PNGs (and GIFs) are much smaller than we used to generate.
//They only work for PNGs. GIFs and JPEGs are not affected.
if(! defined('OPTIPNG_ENABLED') ) define ('OPTIPNG_ENABLED', false);
if(! defined('OPTIPNG_PATH') ) define ('OPTIPNG_PATH', '/usr/bin/optipng'); //This will run first because it gives better compression than pngcrush.
if(! defined('PNGCRUSH_ENABLED') ) define ('PNGCRUSH_ENABLED', false);
if(! defined('PNGCRUSH_PATH') ) define ('PNGCRUSH_PATH', '/usr/bin/pngcrush'); //This will only run if OPTIPNG_PATH is not set or is not valid
/*
-------====Website Screenshots configuration - BETA====-------
If you just want image thumbnails and don't want website screenshots, you can safely leave this as is.
If you would like to get website screenshots set up, you will need root access to your own server.
Enable ALLOW_ALL_EXTERNAL_SITES so you can fetch any external web page. This is more secure now that we're using a non-web folder for cache.
Enable BLOCK_EXTERNAL_LEECHERS so that your site doesn't generate thumbnails for the whole Internet.
Instructions to get website screenshots enabled on Ubuntu Linux:
1. Install Xvfb with the following command: sudo apt-get install subversion libqt4-webkit libqt4-dev g++ xvfb
2. Go to a directory where you can download some code
3. Check-out the latest version of CutyCapt with the following command: svn co https://cutycapt.svn.sourceforge.net/svnroot/cutycapt
4. Compile CutyCapt by doing: cd cutycapt/CutyCapt
5. qmake
6. make
7. cp CutyCapt /usr/local/bin/
8. Test it by running: xvfb-run --server-args="-screen 0, 1024x768x24" CutyCapt --url="http://markmaunder.com/" --out=test.png
9. If you get a file called test.png with something in it, it probably worked. Now test the script by accessing it as follows:
10. http://yoursite.com/path/to/timthumb.php?src=http://markmaunder.com/&webshot=1
Notes on performance:
The first time a webshot loads, it will take a few seconds.
From then on it uses the regular timthumb caching mechanism with the configurable options above
and loading will be very fast.
--ADVANCED USERS ONLY--
If you'd like a slight speedup (about 25%) and you know Linux, you can run the following command which will keep Xvfb running in the background.
nohup Xvfb :100 -ac -nolisten tcp -screen 0, 1024x768x24 > /dev/null 2>&1 &
Then set WEBSHOT_XVFB_RUNNING = true below. This will save your server having to fire off a new Xvfb server and shut it down every time a new shot is generated.
You will need to take responsibility for keeping Xvfb running in case it crashes. (It seems pretty stable)
You will also need to take responsibility for server security if you're running Xvfb as root.
*/
if(! defined('WEBSHOT_ENABLED') ) define ('WEBSHOT_ENABLED', false); //Beta feature. Adding webshot=1 to your query string will cause the script to return a browser screenshot rather than try to fetch an image.
if(! defined('WEBSHOT_CUTYCAPT') ) define ('WEBSHOT_CUTYCAPT', '/usr/local/bin/CutyCapt'); //The path to CutyCapt.
if(! defined('WEBSHOT_XVFB') ) define ('WEBSHOT_XVFB', '/usr/bin/xvfb-run'); //The path to the Xvfb server
if(! defined('WEBSHOT_SCREEN_X') ) define ('WEBSHOT_SCREEN_X', '1024'); //1024 works ok
if(! defined('WEBSHOT_SCREEN_Y') ) define ('WEBSHOT_SCREEN_Y', '768'); //768 works ok
if(! defined('WEBSHOT_COLOR_DEPTH') ) define ('WEBSHOT_COLOR_DEPTH', '24'); //I haven't tested anything besides 24
if(! defined('WEBSHOT_IMAGE_FORMAT') ) define ('WEBSHOT_IMAGE_FORMAT', 'png'); //png is about 2.5 times the size of jpg but is a LOT better quality
if(! defined('WEBSHOT_TIMEOUT') ) define ('WEBSHOT_TIMEOUT', '20'); //Seconds to wait for a webshot
if(! defined('WEBSHOT_USER_AGENT') ) define ('WEBSHOT_USER_AGENT', "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.18) Gecko/20110614 Firefox/3.6.18"); //I hate to do this, but a non-browser robot user agent might not show what humans see. So we pretend to be Firefox
if(! defined('WEBSHOT_JAVASCRIPT_ON') ) define ('WEBSHOT_JAVASCRIPT_ON', true); //Setting to false might give you a slight speedup and block ads. But it could cause other issues.
if(! defined('WEBSHOT_JAVA_ON') ) define ('WEBSHOT_JAVA_ON', false); //Have only tested this as fase
if(! defined('WEBSHOT_PLUGINS_ON') ) define ('WEBSHOT_PLUGINS_ON', true); //Enable flash and other plugins
if(! defined('WEBSHOT_PROXY') ) define ('WEBSHOT_PROXY', ''); //In case you're behind a proxy server.
if(! defined('WEBSHOT_XVFB_RUNNING') ) define ('WEBSHOT_XVFB_RUNNING', false); //ADVANCED: Enable this if you've got Xvfb running in the background.
// If ALLOW_EXTERNAL is true and ALLOW_ALL_EXTERNAL_SITES is false, then external images will only be fetched from these domains and their subdomains.
if(! isset($ALLOWED_SITES)){
$ALLOWED_SITES = array (
'flickr.com',
'staticflickr.com',
'picasa.com',
'img.youtube.com',
'upload.wikimedia.org',
'photobucket.com',
'imgur.com',
'imageshack.us',
'tinypic.com',
);
}
// -------------------------------------------------------------
// -------------- STOP EDITING CONFIGURATION HERE --------------
// -------------------------------------------------------------
timthumb::start();
class timthumb {
protected $src = "";
protected $is404 = false;
protected $docRoot = "";
protected $lastURLError = false;
protected $localImage = "";
protected $localImageMTime = 0;
protected $url = false;
protected $myHost = "";
protected $isURL = false;
protected $cachefile = '';
protected $errors = array();
protected $toDeletes = array();
protected $cacheDirectory = '';
protected $startTime = 0;
protected $lastBenchTime = 0;
protected $cropTop = false;
protected $salt = "";
protected $fileCacheVersion = 1; //Generally if timthumb.php is modifed (upgraded) then the salt changes and all cache files are recreated. This is a backup mechanism to force regen.
protected $filePrependSecurityBlock = "<?php die('Execution denied!'); //"; //Designed to have three letter mime type, space, question mark and greater than symbol appended. 6 bytes total.
protected static $curlDataWritten = 0;
protected static $curlFH = false;
public static function start(){
$tim = new timthumb();
$tim->handleErrors();
$tim->securityChecks();
if($tim->tryBrowserCache()){
exit(0);
}
$tim->handleErrors();
if(FILE_CACHE_ENABLED && $tim->tryServerCache()){
exit(0);
}
$tim->handleErrors();
$tim->run();
$tim->handleErrors();
exit(0);
}
public function __construct(){
global $ALLOWED_SITES;
$this->startTime = microtime(true);
date_default_timezone_set('UTC');
$this->debug(1, "Starting new request from " . $this->getIP() . " to " . $_SERVER['REQUEST_URI']);
$this->calcDocRoot();
//On windows systems I'm assuming fileinode returns an empty string or a number that doesn't change. Check this.
$this->salt = @filemtime(__FILE__) . '-' . @fileinode(__FILE__);
$this->debug(3, "Salt is: " . $this->salt);
if(FILE_CACHE_DIRECTORY){
if(! is_dir(FILE_CACHE_DIRECTORY)){
@mkdir(FILE_CACHE_DIRECTORY);
if(! is_dir(FILE_CACHE_DIRECTORY)){
$this->error("Could not create the file cache directory.");
return false;
}
}
$this->cacheDirectory = FILE_CACHE_DIRECTORY;
if (!touch($this->cacheDirectory . '/index.html')) {
$this->error("Could not create the index.html file - to fix this create an empty file named index.html file in the cache directory.");
}
} else {
$this->cacheDirectory = sys_get_temp_dir();
}
//Clean the cache before we do anything because we don't want the first visitor after FILE_CACHE_TIME_BETWEEN_CLEANS expires to get a stale image.
$this->cleanCache();
$this->myHost = preg_replace('/^www\./i', '', $_SERVER['HTTP_HOST']);
$this->src = $this->param('src');
$this->url = parse_url($this->src);
$this->src = preg_replace('/https?:\/\/(?:www\.)?' . $this->myHost . '/i', '', $this->src);
if(strlen($this->src) <= 3){
$this->error("No image specified");
return false;
}
if(BLOCK_EXTERNAL_LEECHERS && array_key_exists('HTTP_REFERER', $_SERVER) && (! preg_match('/^https?:\/\/(?:www\.)?' . $this->myHost . '(?:$|\/)/i', $_SERVER['HTTP_REFERER']))){
// base64 encoded red image that says 'no hotlinkers'
// nothing to worry about! :)
$imgData = base64_decode("R0lGODlhUAAMAIAAAP8AAP///yH5BAAHAP8ALAAAAABQAAwAAAJpjI+py+0Po5y0OgAMjjv01YUZ\nOGplhWXfNa6JCLnWkXplrcBmW+spbwvaVr/cDyg7IoFC2KbYVC2NQ5MQ4ZNao9Ynzjl9ScNYpneb\nDULB3RP6JuPuaGfuuV4fumf8PuvqFyhYtjdoeFgAADs=");
header('Content-Type: image/gif');
header('Content-Length: ' . sizeof($imgData));
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header("Pragma: no-cache");
header('Expires: ' . gmdate ('D, d M Y H:i:s', time()));
echo $imgData;
return false;
exit(0);
}
if(preg_match('/^https?:\/\/[^\/]+/i', $this->src)){
$this->debug(2, "Is a request for an external URL: " . $this->src);
$this->isURL = true;
} else {
$this->debug(2, "Is a request for an internal file: " . $this->src);
}
if($this->isURL && (! ALLOW_EXTERNAL)){
$this->error("You are not allowed to fetch images from an external website.");
return false;
}
if($this->isURL){
if(ALLOW_ALL_EXTERNAL_SITES){
$this->debug(2, "Fetching from all external sites is enabled.");
} else {
$this->debug(2, "Fetching only from selected external sites is enabled.");
$allowed = false;
foreach($ALLOWED_SITES as $site){
if ((strtolower(substr($this->url['host'],-strlen($site)-1)) === strtolower(".$site")) || (strtolower($this->url['host'])===strtolower($site))) {
$this->debug(3, "URL hostname {$this->url['host']} matches $site so allowing.");
$allowed = true;
}
}
if(! $allowed){
return $this->error("You may not fetch images from that site. To enable this site in timthumb, you can either add it to \$ALLOWED_SITES and set ALLOW_EXTERNAL=true. Or you can set ALLOW_ALL_EXTERNAL_SITES=true, depending on your security needs.");
}
}
}
$cachePrefix = ($this->isURL ? '_ext_' : '_int_');
if($this->isURL){
$arr = explode('&', $_SERVER ['QUERY_STRING']);
asort($arr);
$this->cachefile = $this->cacheDirectory . '/' . FILE_CACHE_PREFIX . $cachePrefix . md5($this->salt . implode('', $arr) . $this->fileCacheVersion) . FILE_CACHE_SUFFIX;
} else {
$this->localImage = $this->getLocalImagePath($this->src);
if(! $this->localImage){
$this->debug(1, "Could not find the local image: {$this->localImage}");
$this->error("Could not find the internal image you specified.");
$this->set404();
return false;
}
$this->debug(1, "Local image path is {$this->localImage}");
$this->localImageMTime = @filemtime($this->localImage);
//We include the mtime of the local file in case in changes on disk.
$this->cachefile = $this->cacheDirectory . '/' . FILE_CACHE_PREFIX . $cachePrefix . md5($this->salt . $this->localImageMTime . $_SERVER ['QUERY_STRING'] . $this->fileCacheVersion) . FILE_CACHE_SUFFIX;
}
$this->debug(2, "Cache file is: " . $this->cachefile);
return true;
}
public function __destruct(){
foreach($this->toDeletes as $del){
$this->debug(2, "Deleting temp file $del");
@unlink($del);
}
}
public function run(){
if($this->isURL){
if(! ALLOW_EXTERNAL){
$this->debug(1, "Got a request for an external image but ALLOW_EXTERNAL is disabled so returning error msg.");
$this->error("You are not allowed to fetch images from an external website.");
return false;
}
$this->debug(3, "Got request for external image. Starting serveExternalImage.");
if($this->param('webshot')){
if(WEBSHOT_ENABLED){
$this->debug(3, "webshot param is set, so we're going to take a webshot.");
$this->serveWebshot();
} else {
$this->error("You added the webshot parameter but webshots are disabled on this server. You need to set WEBSHOT_ENABLED == true to enable webshots.");
}
} else {
$this->debug(3, "webshot is NOT set so we're going to try to fetch a regular image.");
$this->serveExternalImage();
}
} else {
$this->debug(3, "Got request for internal image. Starting serveInternalImage()");
$this->serveInternalImage();
}
return true;
}
protected function handleErrors(){
if($this->haveErrors()){
if(NOT_FOUND_IMAGE && $this->is404()){
if($this->serveImg(NOT_FOUND_IMAGE)){
exit(0);
} else {
$this->error("Additionally, the 404 image that is configured could not be found or there was an error serving it.");
}
}
if(ERROR_IMAGE){
if($this->serveImg(ERROR_IMAGE)){
exit(0);
} else {
$this->error("Additionally, the error image that is configured could not be found or there was an error serving it.");
}
}
$this->serveErrors();
exit(0);
}
return false;
}
protected function tryBrowserCache(){
if(BROWSER_CACHE_DISABLE){ $this->debug(3, "Browser caching is disabled"); return false; }
if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ){
$this->debug(3, "Got a conditional get");
$mtime = false;
//We've already checked if the real file exists in the constructor
if(! is_file($this->cachefile)){
//If we don't have something cached, regenerate the cached image.
return false;
}
if($this->localImageMTime){
$mtime = $this->localImageMTime;
$this->debug(3, "Local real file's modification time is $mtime");
} else if(is_file($this->cachefile)){ //If it's not a local request then use the mtime of the cached file to determine the 304
$mtime = @filemtime($this->cachefile);
$this->debug(3, "Cached file's modification time is $mtime");
}
if(! $mtime){ return false; }
$iftime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
$this->debug(3, "The conditional get's if-modified-since unixtime is $iftime");
if($iftime < 1){
$this->debug(3, "Got an invalid conditional get modified since time. Returning false.");
return false;
}
if($iftime < $mtime){ //Real file or cache file has been modified since last request, so force refetch.
$this->debug(3, "File has been modified since last fetch.");
return false;
} else { //Otherwise serve a 304
$this->debug(3, "File has not been modified since last get, so serving a 304.");
header ($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
$this->debug(1, "Returning 304 not modified");
return true;
}
}
return false;
}
protected function tryServerCache(){
$this->debug(3, "Trying server cache");
if(file_exists($this->cachefile)){
$this->debug(3, "Cachefile {$this->cachefile} exists");
if($this->isURL){
$this->debug(3, "This is an external request, so checking if the cachefile is empty which means the request failed previously.");
if(filesize($this->cachefile) < 1){
$this->debug(3, "Found an empty cachefile indicating a failed earlier request. Checking how old it is.");
//Fetching error occured previously
if(time() - @filemtime($this->cachefile) > WAIT_BETWEEN_FETCH_ERRORS){
$this->debug(3, "File is older than " . WAIT_BETWEEN_FETCH_ERRORS . " seconds. Deleting and returning false so app can try and load file.");
@unlink($this->cachefile);
return false; //to indicate we didn't serve from cache and app should try and load
} else {
$this->debug(3, "Empty cachefile is still fresh so returning message saying we had an error fetching this image from remote host.");
$this->set404();
$this->error("An error occured fetching image.");
return false;
}
}
} else {
$this->debug(3, "Trying to serve cachefile {$this->cachefile}");
}
if($this->serveCacheFile()){
$this->debug(3, "Succesfully served cachefile {$this->cachefile}");
return true;
} else {
$this->debug(3, "Failed to serve cachefile {$this->cachefile} - Deleting it from cache.");
//Image serving failed. We can't retry at this point, but lets remove it from cache so the next request recreates it
@unlink($this->cachefile);
return true;
}
}
}
protected function error($err){
$this->debug(3, "Adding error message: $err");
$this->errors[] = $err;
return false;
}
protected function haveErrors(){
if(sizeof($this->errors) > 0){
return true;
}
return false;
}
protected function serveErrors(){
header ($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
$html = '<ul>';
foreach($this->errors as $err){
$html .= '<li>' . htmlentities($err) . '</li>';
}
$html .= '</ul>';
echo '<h1>A TimThumb error has occured</h1>The following error(s) occured:<br />' . $html . '<br />';
echo '<br />Query String : ' . htmlentities ($_SERVER['QUERY_STRING']);
echo '<br />TimThumb version : ' . VERSION . '</pre>';
}
protected function serveInternalImage(){
$this->debug(3, "Local image path is $this->localImage");
if(! $this->localImage){
$this->sanityFail("localImage not set after verifying it earlier in the code.");
return false;
}
$fileSize = filesize($this->localImage);
if($fileSize > MAX_FILE_SIZE){
$this->error("The file you specified is greater than the maximum allowed file size.");
return false;
}
if($fileSize <= 0){
$this->error("The file you specified is <= 0 bytes.");
return false;
}
$this->debug(3, "Calling processImageAndWriteToCache() for local image.");
if($this->processImageAndWriteToCache($this->localImage)){
$this->serveCacheFile();
return true;
} else {
return false;
}
}
protected function cleanCache(){
if (FILE_CACHE_TIME_BETWEEN_CLEANS < 0) {
return;
}
$this->debug(3, "cleanCache() called");
$lastCleanFile = $this->cacheDirectory . '/timthumb_cacheLastCleanTime.touch';
//If this is a new timthumb installation we need to create the file
if(! is_file($lastCleanFile)){
$this->debug(1, "File tracking last clean doesn't exist. Creating $lastCleanFile");
if (!touch($lastCleanFile)) {
$this->error("Could not create cache clean timestamp file.");
}
return;
}
if(@filemtime($lastCleanFile) < (time() - FILE_CACHE_TIME_BETWEEN_CLEANS) ){ //Cache was last cleaned more than 1 day ago
$this->debug(1, "Cache was last cleaned more than " . FILE_CACHE_TIME_BETWEEN_CLEANS . " seconds ago. Cleaning now.");
// Very slight race condition here, but worst case we'll have 2 or 3 servers cleaning the cache simultaneously once a day.
if (!touch($lastCleanFile)) {
$this->error("Could not create cache clean timestamp file.");
}
$files = glob($this->cacheDirectory . '/*' . FILE_CACHE_SUFFIX);
if ($files) {
$timeAgo = time() - FILE_CACHE_MAX_FILE_AGE;
foreach($files as $file){
if(@filemtime($file) < $timeAgo){
$this->debug(3, "Deleting cache file $file older than max age: " . FILE_CACHE_MAX_FILE_AGE . " seconds");
@unlink($file);
}
}
}
return true;
} else {
$this->debug(3, "Cache was cleaned less than " . FILE_CACHE_TIME_BETWEEN_CLEANS . " seconds ago so no cleaning needed.");
}
return false;
}
protected function processImageAndWriteToCache($localImage){
$sData = getimagesize($localImage);
$origType = $sData[2];
$mimeType = $sData['mime'];
$this->debug(3, "Mime type of image is $mimeType");
if(! preg_match('/^image\/(?:gif|jpg|jpeg|png)$/i', $mimeType)){
return $this->error("The image being resized is not a valid gif, jpg or png.");
}
if (!function_exists ('imagecreatetruecolor')) {
return $this->error('GD Library Error: imagecreatetruecolor does not exist - please contact your webhost and ask them to install the GD library');
}
if (function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
$imageFilters = array (
1 => array (IMG_FILTER_NEGATE, 0),
2 => array (IMG_FILTER_GRAYSCALE, 0),
3 => array (IMG_FILTER_BRIGHTNESS, 1),
4 => array (IMG_FILTER_CONTRAST, 1),
5 => array (IMG_FILTER_COLORIZE, 4),
6 => array (IMG_FILTER_EDGEDETECT, 0),
7 => array (IMG_FILTER_EMBOSS, 0),
8 => array (IMG_FILTER_GAUSSIAN_BLUR, 0),
9 => array (IMG_FILTER_SELECTIVE_BLUR, 0),
10 => array (IMG_FILTER_MEAN_REMOVAL, 0),
11 => array (IMG_FILTER_SMOOTH, 0),
);
}
// get standard input properties
$new_width = (int) abs ($this->param('w', 0));
$new_height = (int) abs ($this->param('h', 0));
$zoom_crop = (int) $this->param('zc', DEFAULT_ZC);
$quality = (int) abs ($this->param('q', DEFAULT_Q));
$align = $this->cropTop ? 't' : $this->param('a', 'c');
$filters = $this->param('f', DEFAULT_F);
$sharpen = (bool) $this->param('s', DEFAULT_S);
$canvas_color = $this->param('cc', DEFAULT_CC);
$canvas_trans = (bool) $this->param('ct', '1');
// set default width and height if neither are set already
if ($new_width == 0 && $new_height == 0) {
$new_width = 100;
$new_height = 100;
}
// ensure size limits can not be abused
$new_width = min ($new_width, MAX_WIDTH);
$new_height = min ($new_height, MAX_HEIGHT);
// set memory limit to be able to have enough space to resize larger images
$this->setMemoryLimit();
// open the existing image
$image = $this->openImage ($mimeType, $localImage);
if ($image === false) {
return $this->error('Unable to open image.');
}
// Get original width and height
$width = imagesx ($image);
$height = imagesy ($image);
$origin_x = 0;
$origin_y = 0;
// generate new w/h if not provided
if ($new_width && !$new_height) {
$new_height = floor ($height * ($new_width / $width));
} else if ($new_height && !$new_width) {
$new_width = floor ($width * ($new_height / $height));
}
// scale down and add borders
if ($zoom_crop == 3) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$new_width = $width * ($new_height / $height);
} else {
$new_height = $final_height;
}
}
// create a new true color image
$canvas = imagecreatetruecolor ($new_width, $new_height);
imagealphablending ($canvas, false);
if (strlen($canvas_color) == 3) { //if is 3-char notation, edit string into 6-char notation
$canvas_color = str_repeat(substr($canvas_color, 0, 1), 2) . str_repeat(substr($canvas_color, 1, 1), 2) . str_repeat(substr($canvas_color, 2, 1), 2);
} else if (strlen($canvas_color) != 6) {
$canvas_color = DEFAULT_CC; // on error return default canvas color
}
$canvas_color_R = hexdec (substr ($canvas_color, 0, 2));
$canvas_color_G = hexdec (substr ($canvas_color, 2, 2));
$canvas_color_B = hexdec (substr ($canvas_color, 4, 2));
// Create a new transparent color for image
// If is a png and PNG_IS_TRANSPARENT is false then remove the alpha transparency
// (and if is set a canvas color show it in the background)
if(preg_match('/^image\/png$/i', $mimeType) && !PNG_IS_TRANSPARENT && $canvas_trans){
$color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
}else{
$color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 0);
}
// Completely fill the background of the new image with allocated color.
imagefill ($canvas, 0, 0, $color);
// scale down and add borders
if ($zoom_crop == 2) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$origin_x = $new_width / 2;
$new_width = $width * ($new_height / $height);
$origin_x = round ($origin_x - ($new_width / 2));
} else {
$origin_y = $new_height / 2;
$new_height = $final_height;
$origin_y = round ($origin_y - ($new_height / 2));
}
}
// Restore transparency blending
imagesavealpha ($canvas, true);
if ($zoom_crop > 0) {
$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;
$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;
// calculate x or y coordinate and width or height of source
if ($cmp_x > $cmp_y) {
$src_w = round ($width / $cmp_x * $cmp_y);
$src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
} else if ($cmp_y > $cmp_x) {
$src_h = round ($height / $cmp_y * $cmp_x);
$src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
}
// positional cropping!
if ($align) {
if (strpos ($align, 't') !== false) {
$src_y = 0;
}
if (strpos ($align, 'b') !== false) {
$src_y = $height - $src_h;
}
if (strpos ($align, 'l') !== false) {
$src_x = 0;
}
if (strpos ($align, 'r') !== false) {
$src_x = $width - $src_w;
}
}
imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
} else {
// copy and resize part of an image with resampling
imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
}
if ($filters != '' && function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
// apply filters to image
$filterList = explode ('|', $filters);
foreach ($filterList as $fl) {
$filterSettings = explode (',', $fl);
if (isset ($imageFilters[$filterSettings[0]])) {
for ($i = 0; $i < 4; $i ++) {
if (!isset ($filterSettings[$i])) {
$filterSettings[$i] = null;
} else {
$filterSettings[$i] = (int) $filterSettings[$i];
}
}
switch ($imageFilters[$filterSettings[0]][1]) {
case 1:
imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
break;
case 2:
imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
break;
case 3:
imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
break;
case 4:
imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3], $filterSettings[4]);
break;
default:
imagefilter ($canvas, $imageFilters[$filterSettings[0]][0]);
break;
}
}
}
}
// sharpen image
if ($sharpen && function_exists ('imageconvolution')) {
$sharpenMatrix = array (
array (-1,-1,-1),
array (-1,16,-1),
array (-1,-1,-1),
);
$divisor = 8;
$offset = 0;
imageconvolution ($canvas, $sharpenMatrix, $divisor, $offset);
}
//Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
if ( (IMAGETYPE_PNG == $origType || IMAGETYPE_GIF == $origType) && function_exists('imageistruecolor') && !imageistruecolor( $image ) && imagecolortransparent( $image ) > 0 ){
imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
}
$imgType = "";
$tempfile = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
if(preg_match('/^image\/(?:jpg|jpeg)$/i', $mimeType)){
$imgType = 'jpg';
imagejpeg($canvas, $tempfile, $quality);
} else if(preg_match('/^image\/png$/i', $mimeType)){
$imgType = 'png';
imagepng($canvas, $tempfile, floor($quality * 0.09));
} else if(preg_match('/^image\/gif$/i', $mimeType)){
$imgType = 'gif';
imagegif($canvas, $tempfile);
} else {
return $this->sanityFail("Could not match mime type after verifying it previously.");
}
if($imgType == 'png' && OPTIPNG_ENABLED && OPTIPNG_PATH && @is_file(OPTIPNG_PATH)){
$exec = OPTIPNG_PATH;
$this->debug(3, "optipng'ing $tempfile");
$presize = filesize($tempfile);
$out = `$exec -o1 $tempfile`; //you can use up to -o7 but it really slows things down
clearstatcache();
$aftersize = filesize($tempfile);
$sizeDrop = $presize - $aftersize;
if($sizeDrop > 0){
$this->debug(1, "optipng reduced size by $sizeDrop");
} else if($sizeDrop < 0){
$this->debug(1, "optipng increased size! Difference was: $sizeDrop");
} else {
$this->debug(1, "optipng did not change image size.");
}
} else if($imgType == 'png' && PNGCRUSH_ENABLED && PNGCRUSH_PATH && @is_file(PNGCRUSH_PATH)){
$exec = PNGCRUSH_PATH;
$tempfile2 = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
$this->debug(3, "pngcrush'ing $tempfile to $tempfile2");
$out = `$exec $tempfile $tempfile2`;
$todel = "";
if(is_file($tempfile2)){
$sizeDrop = filesize($tempfile) - filesize($tempfile2);
if($sizeDrop > 0){
$this->debug(1, "pngcrush was succesful and gave a $sizeDrop byte size reduction");
$todel = $tempfile;
$tempfile = $tempfile2;
} else {
$this->debug(1, "pngcrush did not reduce file size. Difference was $sizeDrop bytes.");
$todel = $tempfile2;
}
} else {
$this->debug(3, "pngcrush failed with output: $out");
$todel = $tempfile2;
}
@unlink($todel);
}
$this->debug(3, "Rewriting image with security header.");
$tempfile4 = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
$context = stream_context_create ();
$fp = fopen($tempfile,'r',0,$context);
file_put_contents($tempfile4, $this->filePrependSecurityBlock . $imgType . ' ?' . '>'); //6 extra bytes, first 3 being image type
file_put_contents($tempfile4, $fp, FILE_APPEND);
fclose($fp);
@unlink($tempfile);
$this->debug(3, "Locking and replacing cache file.");
$lockFile = $this->cachefile . '.lock';
$fh = fopen($lockFile, 'w');
if(! $fh){
return $this->error("Could not open the lockfile for writing an image.");
}
if(flock($fh, LOCK_EX)){
@unlink($this->cachefile); //rename generally overwrites, but doing this in case of platform specific quirks. File might not exist yet.
rename($tempfile4, $this->cachefile);
flock($fh, LOCK_UN);
fclose($fh);
@unlink($lockFile);
} else {
fclose($fh);
@unlink($lockFile);
@unlink($tempfile4);
return $this->error("Could not get a lock for writing.");
}
$this->debug(3, "Done image replace with security header. Cleaning up and running cleanCache()");
imagedestroy($canvas);
imagedestroy($image);
return true;
}
protected function calcDocRoot(){
$docRoot = @$_SERVER['DOCUMENT_ROOT'];
if (defined('LOCAL_FILE_BASE_DIRECTORY')) {
$docRoot = LOCAL_FILE_BASE_DIRECTORY;
}
if(!isset($docRoot)){
$this->debug(3, "DOCUMENT_ROOT is not set. This is probably windows. Starting search 1.");
if(isset($_SERVER['SCRIPT_FILENAME'])){
$docRoot = str_replace( '\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF'])));
$this->debug(3, "Generated docRoot using SCRIPT_FILENAME and PHP_SELF as: $docRoot");
}
}
if(!isset($docRoot)){
$this->debug(3, "DOCUMENT_ROOT still is not set. Starting search 2.");
if(isset($_SERVER['PATH_TRANSLATED'])){
$docRoot = str_replace( '\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0-strlen($_SERVER['PHP_SELF'])));
$this->debug(3, "Generated docRoot using PATH_TRANSLATED and PHP_SELF as: $docRoot");
}
}
if($docRoot && $_SERVER['DOCUMENT_ROOT'] != '/'){ $docRoot = preg_replace('/\/$/', '', $docRoot); }
$this->debug(3, "Doc root is: " . $docRoot);
$this->docRoot = $docRoot;
}
protected function getLocalImagePath($src){
$src = ltrim($src, '/'); //strip off the leading '/'
if(! $this->docRoot){
$this->debug(3, "We have no document root set, so as a last resort, lets check if the image is in the current dir and serve that.");
//We don't support serving images outside the current dir if we don't have a doc root for security reasons.
$file = preg_replace('/^.*?([^\/\\\\]+)$/', '$1', $src); //strip off any path info and just leave the filename.
if(is_file($file)){
return $this->realpath($file);
}
return $this->error("Could not find your website document root and the file specified doesn't exist in timthumbs directory. We don't support serving files outside timthumb's directory without a document root for security reasons.");
} //Do not go past this point without docRoot set
//Try src under docRoot
if(file_exists ($this->docRoot . '/' . $src)) {
$this->debug(3, "Found file as " . $this->docRoot . '/' . $src);
$real = $this->realpath($this->docRoot . '/' . $src);
if(stripos($real, $this->docRoot) === 0){
return $real;
} else {
$this->debug(1, "Security block: The file specified occurs outside the document root.");
//allow search to continue
}
}
//Check absolute paths and then verify the real path is under doc root
$absolute = $this->realpath('/' . $src);
if($absolute && file_exists($absolute)){ //realpath does file_exists check, so can probably skip the exists check here
$this->debug(3, "Found absolute path: $absolute");
if(! $this->docRoot){ $this->sanityFail("docRoot not set when checking absolute path."); }
if(stripos($absolute, $this->docRoot) === 0){
return $absolute;
} else {
$this->debug(1, "Security block: The file specified occurs outside the document root.");
//and continue search
}
}
$base = $this->docRoot;
// account for Windows directory structure
if (strstr($_SERVER['SCRIPT_FILENAME'],':')) {
$sub_directories = explode('\\', str_replace($this->docRoot, '', $_SERVER['SCRIPT_FILENAME']));
} else {
$sub_directories = explode('/', str_replace($this->docRoot, '', $_SERVER['SCRIPT_FILENAME']));
}
foreach ($sub_directories as $sub){
$base .= $sub . '/';
$this->debug(3, "Trying file as: " . $base . $src);
if(file_exists($base . $src)){
$this->debug(3, "Found file as: " . $base . $src);
$real = $this->realpath($base . $src);
if(stripos($real, $this->realpath($this->docRoot)) === 0){
return $real;
} else {
$this->debug(1, "Security block: The file specified occurs outside the document root.");
//And continue search
}
}
}
return false;
}
protected function realpath($path){
//try to remove any relative paths
$remove_relatives = '/\w+\/\.\.\//';
while(preg_match($remove_relatives,$path)){
$path = preg_replace($remove_relatives, '', $path);
}
//if any remain use PHP realpath to strip them out, otherwise return $path
//if using realpath, any symlinks will also be resolved
return preg_match('#^\.\./|/\.\./#', $path) ? realpath($path) : $path;
}
protected function toDelete($name){
$this->debug(3, "Scheduling file $name to delete on destruct.");
$this->toDeletes[] = $name;
}
protected function serveWebshot(){
$this->debug(3, "Starting serveWebshot");
$instr = "Please follow the instructions at http://code.google.com/p/timthumb/ to set your server up for taking website screenshots.";
if(! is_file(WEBSHOT_CUTYCAPT)){
return $this->error("CutyCapt is not installed. $instr");
}
if(! is_file(WEBSHOT_XVFB)){
return $this->Error("Xvfb is not installed. $instr");
}
$cuty = WEBSHOT_CUTYCAPT;
$xv = WEBSHOT_XVFB;
$screenX = WEBSHOT_SCREEN_X;
$screenY = WEBSHOT_SCREEN_Y;
$colDepth = WEBSHOT_COLOR_DEPTH;
$format = WEBSHOT_IMAGE_FORMAT;
$timeout = WEBSHOT_TIMEOUT * 1000;
$ua = WEBSHOT_USER_AGENT;
$jsOn = WEBSHOT_JAVASCRIPT_ON ? 'on' : 'off';
$javaOn = WEBSHOT_JAVA_ON ? 'on' : 'off';
$pluginsOn = WEBSHOT_PLUGINS_ON ? 'on' : 'off';
$proxy = WEBSHOT_PROXY ? ' --http-proxy=' . WEBSHOT_PROXY : '';
$tempfile = tempnam($this->cacheDirectory, 'timthumb_webshot');
$url = $this->src;
if(! preg_match('/^https?:\/\/[a-zA-Z0-9\.\-]+/i', $url)){
return $this->error("Invalid URL supplied.");
}
$url = preg_replace('/[^A-Za-z0-9\-\.\_\~:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]+/', '', $url); //RFC 3986
//Very important we don't allow injection of shell commands here. URL is between quotes and we are only allowing through chars allowed by a the RFC
// which AFAIKT can't be used for shell injection.
if(WEBSHOT_XVFB_RUNNING){
putenv('DISPLAY=:100.0');
$command = "$cuty $proxy --max-wait=$timeout --user-agent=\"$ua\" --javascript=$jsOn --java=$javaOn --plugins=$pluginsOn --js-can-open-windows=off --url=\"$url\" --out-format=$format --out=$tempfile";
} else {
$command = "$xv --server-args=\"-screen 0, {$screenX}x{$screenY}x{$colDepth}\" $cuty $proxy --max-wait=$timeout --user-agent=\"$ua\" --javascript=$jsOn --java=$javaOn --plugins=$pluginsOn --js-can-open-windows=off --url=\"$url\" --out-format=$format --out=$tempfile";
}
$this->debug(3, "Executing command: $command");
$out = `$command`;
$this->debug(3, "Received output: $out");
if(! is_file($tempfile)){
$this->set404();
return $this->error("The command to create a thumbnail failed.");
}
$this->cropTop = true;
if($this->processImageAndWriteToCache($tempfile)){
$this->debug(3, "Image processed succesfully. Serving from cache");
return $this->serveCacheFile();
} else {
return false;
}
}
protected function serveExternalImage(){
if(! preg_match('/^https?:\/\/[a-zA-Z0-9\-\.]+/i', $this->src)){
$this->error("Invalid URL supplied.");
return false;
}
$tempfile = tempnam($this->cacheDirectory, 'timthumb');
$this->debug(3, "Fetching external image into temporary file $tempfile");
$this->toDelete($tempfile);
#fetch file here
if(! $this->getURL($this->src, $tempfile)){
@unlink($this->cachefile);
touch($this->cachefile);
$this->debug(3, "Error fetching URL: " . $this->lastURLError);
$this->error("Error reading the URL you specified from remote host." . $this->lastURLError);
return false;
}
$mimeType = $this->getMimeType($tempfile);
if(! preg_match("/^image\/(?:jpg|jpeg|gif|png)$/i", $mimeType)){
$this->debug(3, "Remote file has invalid mime type: $mimeType");
@unlink($this->cachefile);
touch($this->cachefile);
$this->error("The remote file is not a valid image. Mimetype = '" . $mimeType . "'" . $tempfile);
return false;
}
if($this->processImageAndWriteToCache($tempfile)){
$this->debug(3, "Image processed succesfully. Serving from cache");
return $this->serveCacheFile();
} else {
return false;
}
}
public static function curlWrite($h, $d){
fwrite(self::$curlFH, $d);
self::$curlDataWritten += strlen($d);
if(self::$curlDataWritten > MAX_FILE_SIZE){
return 0;
} else {
return strlen($d);
}
}
protected function serveCacheFile(){
$this->debug(3, "Serving {$this->cachefile}");
if(! is_file($this->cachefile)){
$this->error("serveCacheFile called in timthumb but we couldn't find the cached file.");
return false;
}
$fp = fopen($this->cachefile, 'rb');
if(! $fp){ return $this->error("Could not open cachefile."); }
fseek($fp, strlen($this->filePrependSecurityBlock), SEEK_SET);
$imgType = fread($fp, 3);
fseek($fp, 3, SEEK_CUR);
if(ftell($fp) != strlen($this->filePrependSecurityBlock) + 6){
@unlink($this->cachefile);
return $this->error("The cached image file seems to be corrupt.");
}
$imageDataSize = filesize($this->cachefile) - (strlen($this->filePrependSecurityBlock) + 6);
$this->sendImageHeaders($imgType, $imageDataSize);
$bytesSent = @fpassthru($fp);
fclose($fp);
if($bytesSent > 0){
return true;
}
$content = file_get_contents ($this->cachefile);
if ($content != FALSE) {
$content = substr($content, strlen($this->filePrependSecurityBlock) + 6);
echo $content;
$this->debug(3, "Served using file_get_contents and echo");
return true;
} else {
$this->error("Cache file could not be loaded.");
return false;
}
}
protected function sendImageHeaders($mimeType, $dataSize){
if(! preg_match('/^image\//i', $mimeType)){
$mimeType = 'image/' . $mimeType;
}
if(strtolower($mimeType) == 'image/jpg'){
$mimeType = 'image/jpeg';
}
$gmdate_expires = gmdate ('D, d M Y H:i:s', strtotime ('now +10 days')) . ' GMT';
$gmdate_modified = gmdate ('D, d M Y H:i:s') . ' GMT';
// send content headers then display image
header ('Content-Type: ' . $mimeType);
header ('Accept-Ranges: none'); //Changed this because we don't accept range requests
header ('Last-Modified: ' . $gmdate_modified);
header ('Content-Length: ' . $dataSize);
if(BROWSER_CACHE_DISABLE){
$this->debug(3, "Browser cache is disabled so setting non-caching headers.");
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header("Pragma: no-cache");
header('Expires: ' . gmdate ('D, d M Y H:i:s', time()));
} else {
$this->debug(3, "Browser caching is enabled");
header('Cache-Control: max-age=' . BROWSER_CACHE_MAX_AGE . ', must-revalidate');
header('Expires: ' . $gmdate_expires);
}
return true;
}
protected function securityChecks(){
}
protected function param($property, $default = ''){
if (isset ($_GET[$property])) {
return $_GET[$property];
} else {
return $default;
}
}
protected function openImage($mimeType, $src){
switch ($mimeType) {
case 'image/jpeg':
$image = imagecreatefromjpeg ($src);
break;
case 'image/png':
$image = imagecreatefrompng ($src);
imagealphablending( $image, true );
imagesavealpha( $image, true );
break;
case 'image/gif':
$image = imagecreatefromgif ($src);
break;
default:
$this->error("Unrecognised mimeType");
}
return $image;
}
protected function getIP(){
$rem = @$_SERVER["REMOTE_ADDR"];
$ff = @$_SERVER["HTTP_X_FORWARDED_FOR"];
$ci = @$_SERVER["HTTP_CLIENT_IP"];
if(preg_match('/^(?:192\.168|172\.16|10\.|127\.)/', $rem)){
if($ff){ return $ff; }
if($ci){ return $ci; }
return $rem;
} else {
if($rem){ return $rem; }
if($ff){ return $ff; }
if($ci){ return $ci; }
return "UNKNOWN";
}
}
protected function debug($level, $msg){
if(DEBUG_ON && $level <= DEBUG_LEVEL){
$execTime = sprintf('%.6f', microtime(true) - $this->startTime);
$tick = sprintf('%.6f', 0);
if($this->lastBenchTime > 0){
$tick = sprintf('%.6f', microtime(true) - $this->lastBenchTime);
}
$this->lastBenchTime = microtime(true);
error_log("TimThumb Debug line " . __LINE__ . " [$execTime : $tick]: $msg");
}
}
protected function sanityFail($msg){
return $this->error("There is a problem in the timthumb code. Message: Please report this error at <a href='http://code.google.com/p/timthumb/issues/list'>timthumb's bug tracking page</a>: $msg");
}
protected function getMimeType($file){
$info = getimagesize($file);
if(is_array($info) && $info['mime']){
return $info['mime'];
}
return '';
}
protected function setMemoryLimit(){
$inimem = ini_get('memory_limit');
$inibytes = timthumb::returnBytes($inimem);
$ourbytes = timthumb::returnBytes(MEMORY_LIMIT);
if($inibytes < $ourbytes){
ini_set ('memory_limit', MEMORY_LIMIT);
$this->debug(3, "Increased memory from $inimem to " . MEMORY_LIMIT);
} else {
$this->debug(3, "Not adjusting memory size because the current setting is " . $inimem . " and our size of " . MEMORY_LIMIT . " is smaller.");
}
}
protected static function returnBytes($size_str){
switch (substr ($size_str, -1))
{
case 'M': case 'm': return (int)$size_str * 1048576;
case 'K': case 'k': return (int)$size_str * 1024;
case 'G': case 'g': return (int)$size_str * 1073741824;
default: return $size_str;
}
}
protected function getURL($url, $tempfile){
$this->lastURLError = false;
$url = preg_replace('/ /', '%20', $url);
if(function_exists('curl_init')){
$this->debug(3, "Curl is installed so using it to fetch URL.");
self::$curlFH = fopen($tempfile, 'w');
if(! self::$curlFH){
$this->error("Could not open $tempfile for writing.");
return false;
}
self::$curlDataWritten = 0;
$this->debug(3, "Fetching url with curl: $url");
$curl = curl_init($url);
curl_setopt ($curl, CURLOPT_TIMEOUT, CURL_TIMEOUT);
curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30");
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt ($curl, CURLOPT_HEADER, 0);
curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($curl, CURLOPT_WRITEFUNCTION, 'timthumb::curlWrite');
@curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, true);
@curl_setopt ($curl, CURLOPT_MAXREDIRS, 10);
$curlResult = curl_exec($curl);
fclose(self::$curlFH);
$httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($httpStatus == 404){
$this->set404();
}
if($httpStatus == 302){
$this->error("External Image is Redirecting. Try alternate image url");
return false;
}
if($curlResult){
curl_close($curl);
return true;
} else {
$this->lastURLError = curl_error($curl);
curl_close($curl);
return false;
}
} else {
$img = @file_get_contents ($url);
if($img === false){
$err = error_get_last();
if(is_array($err) && $err['message']){
$this->lastURLError = $err['message'];
} else {
$this->lastURLError = $err;
}
if(preg_match('/404/', $this->lastURLError)){
$this->set404();
}
return false;
}
if(! file_put_contents($tempfile, $img)){
$this->error("Could not write to $tempfile.");
return false;
}
return true;
}
}
protected function serveImg($file){
$s = getimagesize($file);
if(! ($s && $s['mime'])){
return false;
}
header ('Content-Type: ' . $s['mime']);
header ('Content-Length: ' . filesize($file) );
header ('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header ("Pragma: no-cache");
$bytes = @readfile($file);
if($bytes > 0){
return true;
}
$content = @file_get_contents ($file);
if ($content != FALSE){
echo $content;
return true;
}
return false;
}
protected function set404(){
$this->is404 = true;
}
protected function is404(){
return $this->is404;
}
} | gpl-2.0 |
sanjay-jagdish/barkerby | wp-includes/class-wp-customize-widgets.php | 48585 | <?php
/**
* Customize Widgets Class
*
* Implements widget management in the Customizer.
*
* @package WordPress
* @subpackage Customize
* @since 3.9.0
*/
final class WP_Customize_Widgets {
/**
* WP_Customize_Manager instance.
*
* @since 3.9.0
* @access public
* @var WP_Customize_Manager
*/
public $manager;
/**
* All id_bases for widgets defined in core.
*
* @since 3.9.0
* @access protected
* @var array
*/
protected $core_widget_id_bases = array(
'archives', 'calendar', 'categories', 'links', 'meta',
'nav_menu', 'pages', 'recent-comments', 'recent-posts',
'rss', 'search', 'tag_cloud', 'text',
);
/**
* @since 3.9.0
* @access protected
* @var
*/
protected $_customized;
/**
* @since 3.9.0
* @access protected
* @var array
*/
protected $_prepreview_added_filters = array();
/**
* @since 3.9.0
* @access protected
* @var array
*/
protected $rendered_sidebars = array();
/**
* @since 3.9.0
* @access protected
* @var array
*/
protected $rendered_widgets = array();
/**
* @since 3.9.0
* @access protected
* @var array
*/
protected $old_sidebars_widgets = array();
/**
* Initial loader.
*
* @since 3.9.0
* @access public
*
* @param WP_Customize_Manager $manager Customize manager bootstrap instance.
*/
public function __construct( $manager ) {
$this->manager = $manager;
add_action( 'after_setup_theme', array( $this, 'setup_widget_addition_previews' ) );
add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
}
/**
* Get an unslashed post value or return a default.
*
* @since 3.9.0
*
* @access protected
*
* @param string $name Post value.
* @param mixed $default Default post value.
* @return mixed Unslashed post value or default value.
*/
protected function get_post_value( $name, $default = null ) {
if ( ! isset( $_POST[ $name ] ) ) {
return $default;
}
return wp_unslash( $_POST[$name] );
}
/**
* Set up widget addition previews.
*
* Since the widgets get registered on 'widgets_init' before the Customizer
* settings are set up on 'customize_register', we have to filter the options
* similarly to how the setting previewer will filter the options later.
*
* @since 3.9.0
*
* @access public
*/
public function setup_widget_addition_previews() {
$is_customize_preview = false;
if ( ! empty( $this->manager ) && ! is_admin() && 'on' === $this->get_post_value( 'wp_customize' ) ) {
$is_customize_preview = check_ajax_referer( 'preview-customize_' . $this->manager->get_stylesheet(), 'nonce', false );
}
$is_ajax_widget_update = false;
if ( $this->manager->doing_ajax() && 'update-widget' === $this->get_post_value( 'action' ) ) {
$is_ajax_widget_update = check_ajax_referer( 'update-widget', 'nonce', false );
}
$is_ajax_customize_save = false;
if ( $this->manager->doing_ajax() && 'customize_save' === $this->get_post_value( 'action' ) ) {
$is_ajax_customize_save = check_ajax_referer( 'save-customize_' . $this->manager->get_stylesheet(), 'nonce', false );
}
$is_valid_request = ( $is_ajax_widget_update || $is_customize_preview || $is_ajax_customize_save );
if ( ! $is_valid_request ) {
return;
}
// Input from Customizer preview.
if ( isset( $_POST['customized'] ) ) {
$this->_customized = json_decode( $this->get_post_value( 'customized' ), true );
} else { // Input from ajax widget update request.
$this->_customized = array();
$id_base = $this->get_post_value( 'id_base' );
$widget_number = $this->get_post_value( 'widget_number', false );
$option_name = 'widget_' . $id_base;
$this->_customized[ $option_name ] = array();
if ( preg_match( '/^[0-9]+$/', $widget_number ) ) {
$option_name .= '[' . $widget_number . ']';
$this->_customized[ $option_name ][ $widget_number ] = array();
}
}
$function = array( $this, 'prepreview_added_sidebars_widgets' );
$hook = 'option_sidebars_widgets';
add_filter( $hook, $function );
$this->_prepreview_added_filters[] = compact( 'hook', 'function' );
$hook = 'default_option_sidebars_widgets';
add_filter( $hook, $function );
$this->_prepreview_added_filters[] = compact( 'hook', 'function' );
$function = array( $this, 'prepreview_added_widget_instance' );
foreach ( $this->_customized as $setting_id => $value ) {
if ( preg_match( '/^(widget_.+?)(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
$option = $matches[1];
$hook = sprintf( 'option_%s', $option );
if ( ! has_filter( $hook, $function ) ) {
add_filter( $hook, $function );
$this->_prepreview_added_filters[] = compact( 'hook', 'function' );
}
$hook = sprintf( 'default_option_%s', $option );
if ( ! has_filter( $hook, $function ) ) {
add_filter( $hook, $function );
$this->_prepreview_added_filters[] = compact( 'hook', 'function' );
}
/*
* Make sure the option is registered so that the update_option()
* won't fail due to the filters providing a default value, which
* causes the update_option() to get confused.
*/
add_option( $option, array() );
}
}
}
/**
* Ensure that newly-added widgets will appear in the widgets_sidebars.
*
* This is necessary because the Customizer's setting preview filters
* are added after the widgets_init action, which is too late for the
* widgets to be set up properly.
*
* @since 3.9.0
* @access public
*
* @param array $sidebars_widgets Associative array of sidebars and their widgets.
* @return array Filtered array of sidebars and their widgets.
*/
public function prepreview_added_sidebars_widgets( $sidebars_widgets ) {
foreach ( $this->_customized as $setting_id => $value ) {
if ( preg_match( '/^sidebars_widgets\[(.+?)\]$/', $setting_id, $matches ) ) {
$sidebar_id = $matches[1];
$sidebars_widgets[ $sidebar_id ] = $value;
}
}
return $sidebars_widgets;
}
/**
* Ensure newly-added widgets have empty instances so they
* will be recognized.
*
* This is necessary because the Customizer's setting preview
* filters are added after the widgets_init action, which is
* too late for the widgets to be set up properly.
*
* @since 3.9.0
* @access public
*
* @param array|bool|mixed $value Widget instance(s), false if open was empty.
* @return array|mixed Widget instance(s) with additions.
*/
public function prepreview_added_widget_instance( $value = false ) {
if ( ! preg_match( '/^(?:default_)?option_(widget_(.+))/', current_filter(), $matches ) ) {
return $value;
}
$id_base = $matches[2];
foreach ( $this->_customized as $setting_id => $setting ) {
$parsed_setting_id = $this->parse_widget_setting_id( $setting_id );
if ( is_wp_error( $parsed_setting_id ) || $id_base !== $parsed_setting_id['id_base'] ) {
continue;
}
$widget_number = $parsed_setting_id['number'];
if ( is_null( $widget_number ) ) {
// Single widget.
if ( false === $value ) {
$value = array();
}
} else {
// Multi widget.
if ( empty( $value ) ) {
$value = array( '_multiwidget' => 1 );
}
if ( ! isset( $value[ $widget_number ] ) ) {
$value[ $widget_number ] = array();
}
}
}
return $value;
}
/**
* Remove pre-preview filters.
*
* Removes filters added in setup_widget_addition_previews()
* to ensure widgets are populating the options during
* 'widgets_init'.
*
* @since 3.9.0
* @access public
*/
public function remove_prepreview_filters() {
foreach ( $this->_prepreview_added_filters as $prepreview_added_filter ) {
remove_filter( $prepreview_added_filter['hook'], $prepreview_added_filter['function'] );
}
$this->_prepreview_added_filters = array();
}
/**
* Override sidebars_widgets for theme switch.
*
* When switching a theme via the Customizer, supply any previously-configured
* sidebars_widgets from the target theme as the initial sidebars_widgets
* setting. Also store the old theme's existing settings so that they can
* be passed along for storing in the sidebars_widgets theme_mod when the
* theme gets switched.
*
* @since 3.9.0
* @access public
*/
public function override_sidebars_widgets_for_theme_switch() {
global $sidebars_widgets;
if ( $this->manager->doing_ajax() || $this->manager->is_theme_active() ) {
return;
}
$this->old_sidebars_widgets = wp_get_sidebars_widgets();
add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
// retrieve_widgets() looks at the global $sidebars_widgets
$sidebars_widgets = $this->old_sidebars_widgets;
$sidebars_widgets = retrieve_widgets( 'customize' );
add_filter( 'option_sidebars_widgets', array( $this, 'filter_option_sidebars_widgets_for_theme_switch' ), 1 );
}
/**
* Filter old_sidebars_widgets_data Customizer setting.
*
* When switching themes, filter the Customizer setting
* old_sidebars_widgets_data to supply initial $sidebars_widgets before they
* were overridden by retrieve_widgets(). The value for
* old_sidebars_widgets_data gets set in the old theme's sidebars_widgets
* theme_mod.
*
* @see WP_Customize_Widgets::handle_theme_switch()
* @since 3.9.0
* @access public
*
* @param array $old_sidebars_widgets
*/
public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) {
return $this->old_sidebars_widgets;
}
/**
* Filter sidebars_widgets option for theme switch.
*
* When switching themes, the retrieve_widgets() function is run when the
* Customizer initializes, and then the new sidebars_widgets here get
* supplied as the default value for the sidebars_widgets option.
*
* @see WP_Customize_Widgets::handle_theme_switch()
* @since 3.9.0
* @access public
*
* @param array $sidebars_widgets
*/
public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
$sidebars_widgets = $GLOBALS['sidebars_widgets'];
$sidebars_widgets['array_version'] = 3;
return $sidebars_widgets;
}
/**
* Make sure all widgets get loaded into the Customizer.
*
* Note: these actions are also fired in wp_ajax_update_widget().
*
* @since 3.9.0
* @access public
*/
public function customize_controls_init() {
/** This action is documented in wp-admin/includes/ajax-actions.php */
do_action( 'load-widgets.php' );
/** This action is documented in wp-admin/includes/ajax-actions.php */
do_action( 'widgets.php' );
/** This action is documented in wp-admin/widgets.php */
do_action( 'sidebar_admin_setup' );
}
/**
* Ensure widgets are available for all types of previews.
*
* When in preview, hook to 'customize_register' for settings
* after WordPress is loaded so that all filters have been
* initialized (e.g. Widget Visibility).
*
* @since 3.9.0
* @access public
*/
public function schedule_customize_register() {
if ( is_admin() ) { // @todo for some reason, $wp_customize->is_preview() is true here?
$this->customize_register();
} else {
add_action( 'wp', array( $this, 'customize_register' ) );
}
}
/**
* Register Customizer settings and controls for all sidebars and widgets.
*
* @since 3.9.0
* @access public
*/
public function customize_register() {
global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_sidebars;
$sidebars_widgets = array_merge(
array( 'wp_inactive_widgets' => array() ),
array_fill_keys( array_keys( $GLOBALS['wp_registered_sidebars'] ), array() ),
wp_get_sidebars_widgets()
);
$new_setting_ids = array();
/*
* Register a setting for all widgets, including those which are active,
* inactive, and orphaned since a widget may get suppressed from a sidebar
* via a plugin (like Widget Visibility).
*/
foreach ( array_keys( $wp_registered_widgets ) as $widget_id ) {
$setting_id = $this->get_setting_id( $widget_id );
$setting_args = $this->get_setting_args( $setting_id );
$setting_args['sanitize_callback'] = array( $this, 'sanitize_widget_instance' );
$setting_args['sanitize_js_callback'] = array( $this, 'sanitize_widget_js_instance' );
$this->manager->add_setting( $setting_id, $setting_args );
$new_setting_ids[] = $setting_id;
}
/*
* Add a setting which will be supplied for the theme's sidebars_widgets
* theme_mod when the the theme is switched.
*/
if ( ! $this->manager->is_theme_active() ) {
$setting_id = 'old_sidebars_widgets_data';
$setting_args = $this->get_setting_args( $setting_id, array(
'type' => 'global_variable',
) );
$this->manager->add_setting( $setting_id, $setting_args );
}
$this->manager->add_panel( 'widgets', array(
'title' => __( 'Widgets' ),
'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
'priority' => 110,
) );
foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
if ( empty( $sidebar_widget_ids ) ) {
$sidebar_widget_ids = array();
}
$is_registered_sidebar = isset( $GLOBALS['wp_registered_sidebars'][$sidebar_id] );
$is_inactive_widgets = ( 'wp_inactive_widgets' === $sidebar_id );
$is_active_sidebar = ( $is_registered_sidebar && ! $is_inactive_widgets );
// Add setting for managing the sidebar's widgets.
if ( $is_registered_sidebar || $is_inactive_widgets ) {
$setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
$setting_args = $this->get_setting_args( $setting_id );
$setting_args['sanitize_callback'] = array( $this, 'sanitize_sidebar_widgets' );
$setting_args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
$this->manager->add_setting( $setting_id, $setting_args );
$new_setting_ids[] = $setting_id;
// Add section to contain controls.
$section_id = sprintf( 'sidebar-widgets-%s', $sidebar_id );
if ( $is_active_sidebar ) {
$section_args = array(
'title' => $GLOBALS['wp_registered_sidebars'][ $sidebar_id ]['name'],
'description' => $GLOBALS['wp_registered_sidebars'][ $sidebar_id ]['description'],
'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ) ),
'panel' => 'widgets',
'sidebar_id' => $sidebar_id,
);
/**
* Filter Customizer widget section arguments for a given sidebar.
*
* @since 3.9.0
*
* @param array $section_args Array of Customizer widget section arguments.
* @param string $section_id Customizer section ID.
* @param int|string $sidebar_id Sidebar ID.
*/
$section_args = apply_filters( 'customizer_widgets_section_args', $section_args, $section_id, $sidebar_id );
$section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
$this->manager->add_section( $section );
$control = new WP_Widget_Area_Customize_Control( $this->manager, $setting_id, array(
'section' => $section_id,
'sidebar_id' => $sidebar_id,
'priority' => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
) );
$new_setting_ids[] = $setting_id;
$this->manager->add_control( $control );
}
}
// Add a control for each active widget (located in a sidebar).
foreach ( $sidebar_widget_ids as $i => $widget_id ) {
// Skip widgets that may have gone away due to a plugin being deactivated.
if ( ! $is_active_sidebar || ! isset( $GLOBALS['wp_registered_widgets'][$widget_id] ) ) {
continue;
}
$registered_widget = $GLOBALS['wp_registered_widgets'][$widget_id];
$setting_id = $this->get_setting_id( $widget_id );
$id_base = $GLOBALS['wp_registered_widget_controls'][$widget_id]['id_base'];
$control = new WP_Widget_Form_Customize_Control( $this->manager, $setting_id, array(
'label' => $registered_widget['name'],
'section' => $section_id,
'sidebar_id' => $sidebar_id,
'widget_id' => $widget_id,
'widget_id_base' => $id_base,
'priority' => $i,
'width' => $wp_registered_widget_controls[$widget_id]['width'],
'height' => $wp_registered_widget_controls[$widget_id]['height'],
'is_wide' => $this->is_wide_widget( $widget_id ),
) );
$this->manager->add_control( $control );
}
}
/*
* We have to register these settings later than customize_preview_init
* so that other filters have had a chance to run.
*/
if ( did_action( 'customize_preview_init' ) ) {
foreach ( $new_setting_ids as $new_setting_id ) {
$this->manager->get_setting( $new_setting_id )->preview();
}
}
$this->remove_prepreview_filters();
}
/**
* Covert a widget_id into its corresponding Customizer setting ID (option name).
*
* @since 3.9.0
* @access public
*
* @param string $widget_id Widget ID.
* @return string Maybe-parsed widget ID.
*/
public function get_setting_id( $widget_id ) {
$parsed_widget_id = $this->parse_widget_id( $widget_id );
$setting_id = sprintf( 'widget_%s', $parsed_widget_id['id_base'] );
if ( ! is_null( $parsed_widget_id['number'] ) ) {
$setting_id .= sprintf( '[%d]', $parsed_widget_id['number'] );
}
return $setting_id;
}
/**
* Determine whether the widget is considered "wide".
*
* Core widgets which may have controls wider than 250, but can
* still be shown in the narrow Customizer panel. The RSS and Text
* widgets in Core, for example, have widths of 400 and yet they
* still render fine in the Customizer panel. This method will
* return all Core widgets as being not wide, but this can be
* overridden with the is_wide_widget_in_customizer filter.
*
* @since 3.9.0
* @access public
*
* @param string $widget_id Widget ID.
* @return bool Whether or not the widget is a "wide" widget.
*/
public function is_wide_widget( $widget_id ) {
global $wp_registered_widget_controls;
$parsed_widget_id = $this->parse_widget_id( $widget_id );
$width = $wp_registered_widget_controls[$widget_id]['width'];
$is_core = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases );
$is_wide = ( $width > 250 && ! $is_core );
/**
* Filter whether the given widget is considered "wide".
*
* @since 3.9.0
*
* @param bool $is_wide Whether the widget is wide, Default false.
* @param string $widget_id Widget ID.
*/
return apply_filters( 'is_wide_widget_in_customizer', $is_wide, $widget_id );
}
/**
* Covert a widget ID into its id_base and number components.
*
* @since 3.9.0
* @access public
*
* @param string $widget_id Widget ID.
* @return array Array containing a widget's id_base and number components.
*/
public function parse_widget_id( $widget_id ) {
$parsed = array(
'number' => null,
'id_base' => null,
);
if ( preg_match( '/^(.+)-(\d+)$/', $widget_id, $matches ) ) {
$parsed['id_base'] = $matches[1];
$parsed['number'] = intval( $matches[2] );
} else {
// likely an old single widget
$parsed['id_base'] = $widget_id;
}
return $parsed;
}
/**
* Convert a widget setting ID (option path) to its id_base and number components.
*
* @since 3.9.0
* @access public
*
* @param string $setting_id Widget setting ID.
* @return WP_Error|array Array containing a widget's id_base and number components,
* or a WP_Error object.
*/
public function parse_widget_setting_id( $setting_id ) {
if ( ! preg_match( '/^(widget_(.+?))(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
return new WP_Error( 'widget_setting_invalid_id' );
}
$id_base = $matches[2];
$number = isset( $matches[3] ) ? intval( $matches[3] ) : null;
return compact( 'id_base', 'number' );
}
/**
* Call admin_print_styles-widgets.php and admin_print_styles hooks to
* allow custom styles from plugins.
*
* @since 3.9.0
* @access public
*/
public function print_styles() {
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_print_styles-widgets.php' );
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_print_styles' );
}
/**
* Call admin_print_scripts-widgets.php and admin_print_scripts hooks to
* allow custom scripts from plugins.
*
* @since 3.9.0
* @access public
*/
public function print_scripts() {
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_print_scripts-widgets.php' );
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_print_scripts' );
}
/**
* Enqueue scripts and styles for Customizer panel and export data to JavaScript.
*
* @since 3.9.0
* @access public
*/
public function enqueue_scripts() {
wp_enqueue_style( 'customize-widgets' );
wp_enqueue_script( 'customize-widgets' );
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_enqueue_scripts', 'widgets.php' );
/*
* Export available widgets with control_tpl removed from model
* since plugins need templates to be in the DOM.
*/
$available_widgets = array();
foreach ( $this->get_available_widgets() as $available_widget ) {
unset( $available_widget['control_tpl'] );
$available_widgets[] = $available_widget;
}
$widget_reorder_nav_tpl = sprintf(
'<div class="widget-reorder-nav"><span class="move-widget" tabindex="0">%1$s</span><span class="move-widget-down" tabindex="0">%2$s</span><span class="move-widget-up" tabindex="0">%3$s</span></div>',
__( 'Move to another area…' ),
__( 'Move down' ),
__( 'Move up' )
);
$move_widget_area_tpl = str_replace(
array( '{description}', '{btn}' ),
array(
__( 'Select an area to move this widget into:' ),
_x( 'Move', 'Move widget' ),
),
'<div class="move-widget-area">
<p class="description">{description}</p>
<ul class="widget-area-select">
<% _.each( sidebars, function ( sidebar ){ %>
<li class="" data-id="<%- sidebar.id %>" title="<%- sidebar.description %>" tabindex="0"><%- sidebar.name %></li>
<% }); %>
</ul>
<div class="move-widget-actions">
<button class="move-widget-btn button-secondary" type="button">{btn}</button>
</div>
</div>'
);
global $wp_scripts;
$settings = array(
'nonce' => wp_create_nonce( 'update-widget' ),
'registeredSidebars' => array_values( $GLOBALS['wp_registered_sidebars'] ),
'registeredWidgets' => $GLOBALS['wp_registered_widgets'],
'availableWidgets' => $available_widgets, // @todo Merge this with registered_widgets
'l10n' => array(
'saveBtnLabel' => __( 'Apply' ),
'saveBtnTooltip' => __( 'Save and preview changes before publishing them.' ),
'removeBtnLabel' => __( 'Remove' ),
'removeBtnTooltip' => __( 'Trash widget by moving it to the inactive widgets sidebar.' ),
'error' => __( 'An error has occurred. Please reload the page and try again.' ),
'widgetMovedUp' => __( 'Widget moved up' ),
'widgetMovedDown' => __( 'Widget moved down' ),
),
'tpl' => array(
'widgetReorderNav' => $widget_reorder_nav_tpl,
'moveWidgetArea' => $move_widget_area_tpl,
),
);
foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
unset( $registered_widget['callback'] ); // may not be JSON-serializeable
}
$wp_scripts->add_data(
'customize-widgets',
'data',
sprintf( 'var _wpCustomizeWidgetsSettings = %s;', wp_json_encode( $settings ) )
);
}
/**
* Render the widget form control templates into the DOM.
*
* @since 3.9.0
* @access public
*/
public function output_widget_control_templates() {
?>
<div id="widgets-left"><!-- compatibility with JS which looks for widget templates here -->
<div id="available-widgets">
<div id="available-widgets-filter">
<label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
<input type="search" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets…' ) ?>" />
</div>
<?php foreach ( $this->get_available_widgets() as $available_widget ): ?>
<div id="widget-tpl-<?php echo esc_attr( $available_widget['id'] ) ?>" data-widget-id="<?php echo esc_attr( $available_widget['id'] ) ?>" class="widget-tpl <?php echo esc_attr( $available_widget['id'] ) ?>" tabindex="0">
<?php echo $available_widget['control_tpl']; ?>
</div>
<?php endforeach; ?>
</div><!-- #available-widgets -->
</div><!-- #widgets-left -->
<?php
}
/**
* Call admin_print_footer_scripts and admin_print_scripts hooks to
* allow custom scripts from plugins.
*
* @since 3.9.0
* @access public
*/
public function print_footer_scripts() {
/** This action is documented in wp-admin/admin-footer.php */
do_action( 'admin_print_footer_scripts' );
/** This action is documented in wp-admin/admin-footer.php */
do_action( 'admin_footer-widgets.php' );
}
/**
* Get common arguments to supply when constructing a Customizer setting.
*
* @since 3.9.0
* @access public
*
* @param string $id Widget setting ID.
* @param array $overrides Array of setting overrides.
* @return array Possibly modified setting arguments.
*/
public function get_setting_args( $id, $overrides = array() ) {
$args = array(
'type' => 'option',
'capability' => 'edit_theme_options',
'transport' => 'refresh',
'default' => array(),
);
$args = array_merge( $args, $overrides );
/**
* Filter the common arguments supplied when constructing a Customizer setting.
*
* @since 3.9.0
*
* @see WP_Customize_Setting
*
* @param array $args Array of Customizer setting arguments.
* @param string $id Widget setting ID.
*/
return apply_filters( 'widget_customizer_setting_args', $args, $id );
}
/**
* Make sure that sidebar widget arrays only ever contain widget IDS.
*
* Used as the 'sanitize_callback' for each $sidebars_widgets setting.
*
* @since 3.9.0
* @access public
*
* @param array $widget_ids Array of widget IDs.
* @return array Array of sanitized widget IDs.
*/
public function sanitize_sidebar_widgets( $widget_ids ) {
global $wp_registered_widgets;
$widget_ids = array_map( 'strval', (array) $widget_ids );
$sanitized_widget_ids = array();
foreach ( $widget_ids as $widget_id ) {
if ( array_key_exists( $widget_id, $wp_registered_widgets ) ) {
$sanitized_widget_ids[] = $widget_id;
}
}
return $sanitized_widget_ids;
}
/**
* Build up an index of all available widgets for use in Backbone models.
*
* @since 3.9.0
* @access public
*
* @see wp_list_widgets()
*
* @return array List of available widgets.
*/
public function get_available_widgets() {
static $available_widgets = array();
if ( ! empty( $available_widgets ) ) {
return $available_widgets;
}
global $wp_registered_widgets, $wp_registered_widget_controls;
require_once ABSPATH . '/wp-admin/includes/widgets.php'; // for next_widget_id_number()
$sort = $wp_registered_widgets;
usort( $sort, array( $this, '_sort_name_callback' ) );
$done = array();
foreach ( $sort as $widget ) {
if ( in_array( $widget['callback'], $done, true ) ) { // We already showed this multi-widget
continue;
}
$sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false );
$done[] = $widget['callback'];
if ( ! isset( $widget['params'][0] ) ) {
$widget['params'][0] = array();
}
$available_widget = $widget;
unset( $available_widget['callback'] ); // not serializable to JSON
$args = array(
'widget_id' => $widget['id'],
'widget_name' => $widget['name'],
'_display' => 'template',
);
$is_disabled = false;
$is_multi_widget = ( isset( $wp_registered_widget_controls[$widget['id']]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
if ( $is_multi_widget ) {
$id_base = $wp_registered_widget_controls[$widget['id']]['id_base'];
$args['_temp_id'] = "$id_base-__i__";
$args['_multi_num'] = next_widget_id_number( $id_base );
$args['_add'] = 'multi';
} else {
$args['_add'] = 'single';
if ( $sidebar && 'wp_inactive_widgets' !== $sidebar ) {
$is_disabled = true;
}
$id_base = $widget['id'];
}
$list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar( array( 0 => $args, 1 => $widget['params'][0] ) );
$control_tpl = $this->get_widget_control( $list_widget_controls_args );
// The properties here are mapped to the Backbone Widget model.
$available_widget = array_merge( $available_widget, array(
'temp_id' => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
'is_multi' => $is_multi_widget,
'control_tpl' => $control_tpl,
'multi_number' => ( $args['_add'] === 'multi' ) ? $args['_multi_num'] : false,
'is_disabled' => $is_disabled,
'id_base' => $id_base,
'transport' => 'refresh',
'width' => $wp_registered_widget_controls[$widget['id']]['width'],
'height' => $wp_registered_widget_controls[$widget['id']]['height'],
'is_wide' => $this->is_wide_widget( $widget['id'] ),
) );
$available_widgets[] = $available_widget;
}
return $available_widgets;
}
/**
* Naturally order available widgets by name.
*
* @since 3.9.0
* @static
* @access protected
*
* @param array $widget_a The first widget to compare.
* @param array $widget_b The second widget to compare.
* @return int Reorder position for the current widget comparison.
*/
protected function _sort_name_callback( $widget_a, $widget_b ) {
return strnatcasecmp( $widget_a['name'], $widget_b['name'] );
}
/**
* Get the widget control markup.
*
* @since 3.9.0
* @access public
*
* @param array $args Widget control arguments.
* @return string Widget control form HTML markup.
*/
public function get_widget_control( $args ) {
ob_start();
call_user_func_array( 'wp_widget_control', $args );
$replacements = array(
'<form action="" method="post">' => '<div class="form">',
'</form>' => '</div><!-- .form -->',
);
$control_tpl = ob_get_clean();
$control_tpl = str_replace( array_keys( $replacements ), array_values( $replacements ), $control_tpl );
return $control_tpl;
}
/**
* Add hooks for the Customizer preview.
*
* @since 3.9.0
* @access public
*/
public function customize_preview_init() {
add_filter( 'sidebars_widgets', array( $this, 'preview_sidebars_widgets' ), 1 );
add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
}
/**
* When previewing, make sure the proper previewing widgets are used.
*
* Because wp_get_sidebars_widgets() gets called early at init
* (via wp_convert_widget_settings()) and can set global variable
* $_wp_sidebars_widgets to the value of get_option( 'sidebars_widgets' )
* before the Customizer preview filter is added, we have to reset
* it after the filter has been added.
*
* @since 3.9.0
* @access public
*
* @param array $sidebars_widgets List of widgets for the current sidebar.
*/
public function preview_sidebars_widgets( $sidebars_widgets ) {
$sidebars_widgets = get_option( 'sidebars_widgets' );
unset( $sidebars_widgets['array_version'] );
return $sidebars_widgets;
}
/**
* Enqueue scripts for the Customizer preview.
*
* @since 3.9.0
* @access public
*/
public function customize_preview_enqueue() {
wp_enqueue_script( 'customize-preview-widgets' );
}
/**
* Insert default style for highlighted widget at early point so theme
* stylesheet can override.
*
* @since 3.9.0
* @access public
*
* @action wp_print_styles
*/
public function print_preview_css() {
?>
<style>
.widget-customizer-highlighted-widget {
outline: none;
-webkit-box-shadow: 0 0 2px rgba(30,140,190,0.8);
box-shadow: 0 0 2px rgba(30,140,190,0.8);
position: relative;
z-index: 1;
}
</style>
<?php
}
/**
* At the very end of the page, at the very end of the wp_footer,
* communicate the sidebars that appeared on the page.
*
* @since 3.9.0
* @access public
*/
public function export_preview_data() {
// Prepare Customizer settings to pass to JavaScript.
$settings = array(
'renderedSidebars' => array_fill_keys( array_unique( $this->rendered_sidebars ), true ),
'renderedWidgets' => array_fill_keys( array_keys( $this->rendered_widgets ), true ),
'registeredSidebars' => array_values( $GLOBALS['wp_registered_sidebars'] ),
'registeredWidgets' => $GLOBALS['wp_registered_widgets'],
'l10n' => array(
'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
),
);
foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
unset( $registered_widget['callback'] ); // may not be JSON-serializeable
}
?>
<script type="text/javascript">
var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
</script>
<?php
}
/**
* Keep track of the widgets that were rendered.
*
* @since 3.9.0
* @access public
*
* @param array $widget Rendered widget to tally.
*/
public function tally_rendered_widgets( $widget ) {
$this->rendered_widgets[ $widget['id'] ] = true;
}
/**
* Determine if a widget is rendered on the page.
*
* @since 4.0.0
* @access public
*
* @param string $widget_id Widget ID to check.
* @return bool Whether the widget is rendered.
*/
public function is_widget_rendered( $widget_id ) {
return in_array( $widget_id, $this->rendered_widgets );
}
/**
* Determine if a sidebar is rendered on the page.
*
* @since 4.0.0
* @access public
*
* @param string $sidebar_id Sidebar ID to check.
* @return bool Whether the sidebar is rendered.
*/
public function is_sidebar_rendered( $sidebar_id ) {
return in_array( $sidebar_id, $this->rendered_sidebars );
}
/**
* Tally the sidebars rendered via is_active_sidebar().
*
* Keep track of the times that is_active_sidebar() is called
* in the template, and assume that this means that the sidebar
* would be rendered on the template if there were widgets
* populating it.
*
* @since 3.9.0
* @access public
*
* @param bool $is_active Whether the sidebar is active.
* @param string $sidebar_id Sidebar ID.
*/
public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
if ( isset( $GLOBALS['wp_registered_sidebars'][$sidebar_id] ) ) {
$this->rendered_sidebars[] = $sidebar_id;
}
/*
* We may need to force this to true, and also force-true the value
* for 'dynamic_sidebar_has_widgets' if we want to ensure that there
* is an area to drop widgets into, if the sidebar is empty.
*/
return $is_active;
}
/**
* Tally the sidebars rendered via dynamic_sidebar().
*
* Keep track of the times that dynamic_sidebar() is called in the template,
* and assume this means the sidebar would be rendered on the template if
* there were widgets populating it.
*
* @since 3.9.0
* @access public
*
* @param bool $has_widgets Whether the current sidebar has widgets.
* @param string $sidebar_id Sidebar ID.
*/
public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
if ( isset( $GLOBALS['wp_registered_sidebars'][$sidebar_id] ) ) {
$this->rendered_sidebars[] = $sidebar_id;
}
/*
* We may need to force this to true, and also force-true the value
* for 'is_active_sidebar' if we want to ensure there is an area to
* drop widgets into, if the sidebar is empty.
*/
return $has_widgets;
}
/**
* Get MAC for a serialized widget instance string.
*
* Allows values posted back from JS to be rejected if any tampering of the
* data has occurred.
*
* @since 3.9.0
* @access protected
*
* @param string $serialized_instance Widget instance.
* @return string MAC for serialized widget instance.
*/
protected function get_instance_hash_key( $serialized_instance ) {
return wp_hash( $serialized_instance );
}
/**
* Sanitize a widget instance.
*
* Unserialize the JS-instance for storing in the options. It's important
* that this filter only get applied to an instance once.
*
* @since 3.9.0
* @access public
*
* @param array $value Widget instance to sanitize.
* @return array Sanitized widget instance.
*/
public function sanitize_widget_instance( $value ) {
if ( $value === array() ) {
return $value;
}
if ( empty( $value['is_widget_customizer_js_value'] )
|| empty( $value['instance_hash_key'] )
|| empty( $value['encoded_serialized_instance'] ) )
{
return null;
}
$decoded = base64_decode( $value['encoded_serialized_instance'], true );
if ( false === $decoded ) {
return null;
}
if ( ! hash_equals( $this->get_instance_hash_key( $decoded ), $value['instance_hash_key'] ) ) {
return null;
}
$instance = unserialize( $decoded );
if ( false === $instance ) {
return null;
}
return $instance;
}
/**
* Convert widget instance into JSON-representable format.
*
* @since 3.9.0
* @access public
*
* @param array $value Widget instance to convert to JSON.
* @return array JSON-converted widget instance.
*/
public function sanitize_widget_js_instance( $value ) {
if ( empty( $value['is_widget_customizer_js_value'] ) ) {
$serialized = serialize( $value );
$value = array(
'encoded_serialized_instance' => base64_encode( $serialized ),
'title' => empty( $value['title'] ) ? '' : $value['title'],
'is_widget_customizer_js_value' => true,
'instance_hash_key' => $this->get_instance_hash_key( $serialized ),
);
}
return $value;
}
/**
* Strip out widget IDs for widgets which are no longer registered.
*
* One example where this might happen is when a plugin orphans a widget
* in a sidebar upon deactivation.
*
* @since 3.9.0
* @access public
*
* @param array $widget_ids List of widget IDs.
* @return array Parsed list of widget IDs.
*/
public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
global $wp_registered_widgets;
$widget_ids = array_values( array_intersect( $widget_ids, array_keys( $wp_registered_widgets ) ) );
return $widget_ids;
}
/**
* Find and invoke the widget update and control callbacks.
*
* Requires that $_POST be populated with the instance data.
*
* @since 3.9.0
* @access public
*
* @param string $widget_id Widget ID.
* @return WP_Error|array Array containing the updated widget information.
* A WP_Error object, otherwise.
*/
public function call_widget_update( $widget_id ) {
global $wp_registered_widget_updates, $wp_registered_widget_controls;
$this->start_capturing_option_updates();
$parsed_id = $this->parse_widget_id( $widget_id );
$option_name = 'widget_' . $parsed_id['id_base'];
/*
* If a previously-sanitized instance is provided, populate the input vars
* with its values so that the widget update callback will read this instance
*/
$added_input_vars = array();
if ( ! empty( $_POST['sanitized_widget_setting'] ) ) {
$sanitized_widget_setting = json_decode( $this->get_post_value( 'sanitized_widget_setting' ), true );
if ( false === $sanitized_widget_setting ) {
$this->stop_capturing_option_updates();
return new WP_Error( 'widget_setting_malformed' );
}
$instance = $this->sanitize_widget_instance( $sanitized_widget_setting );
if ( is_null( $instance ) ) {
$this->stop_capturing_option_updates();
return new WP_Error( 'widget_setting_unsanitized' );
}
if ( ! is_null( $parsed_id['number'] ) ) {
$value = array();
$value[$parsed_id['number']] = $instance;
$key = 'widget-' . $parsed_id['id_base'];
$_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
$added_input_vars[] = $key;
} else {
foreach ( $instance as $key => $value ) {
$_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
$added_input_vars[] = $key;
}
}
}
// Invoke the widget update callback.
foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
if ( $name === $parsed_id['id_base'] && is_callable( $control['callback'] ) ) {
ob_start();
call_user_func_array( $control['callback'], $control['params'] );
ob_end_clean();
break;
}
}
// Clean up any input vars that were manually added
foreach ( $added_input_vars as $key ) {
unset( $_POST[$key] );
unset( $_REQUEST[$key] );
}
// Make sure the expected option was updated.
if ( 0 !== $this->count_captured_options() ) {
if ( $this->count_captured_options() > 1 ) {
$this->stop_capturing_option_updates();
return new WP_Error( 'widget_setting_too_many_options' );
}
$updated_option_name = key( $this->get_captured_options() );
if ( $updated_option_name !== $option_name ) {
$this->stop_capturing_option_updates();
return new WP_Error( 'widget_setting_unexpected_option' );
}
}
// Obtain the widget control with the updated instance in place.
ob_start();
$form = $wp_registered_widget_controls[$widget_id];
if ( $form ) {
call_user_func_array( $form['callback'], $form['params'] );
}
$form = ob_get_clean();
// Obtain the widget instance.
$option = get_option( $option_name );
if ( null !== $parsed_id['number'] ) {
$instance = $option[$parsed_id['number']];
} else {
$instance = $option;
}
$this->stop_capturing_option_updates();
return compact( 'instance', 'form' );
}
/**
* Update widget settings asynchronously.
*
* Allows the Customizer to update a widget using its form, but return the new
* instance info via Ajax instead of saving it to the options table.
*
* Most code here copied from wp_ajax_save_widget()
*
* @since 3.9.0
* @access public
*
* @see wp_ajax_save_widget()
*
*/
public function wp_ajax_update_widget() {
if ( ! is_user_logged_in() ) {
wp_die( 0 );
}
check_ajax_referer( 'update-widget', 'nonce' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( -1 );
}
if ( ! isset( $_POST['widget-id'] ) ) {
wp_send_json_error();
}
/** This action is documented in wp-admin/includes/ajax-actions.php */
do_action( 'load-widgets.php' );
/** This action is documented in wp-admin/includes/ajax-actions.php */
do_action( 'widgets.php' );
/** This action is documented in wp-admin/widgets.php */
do_action( 'sidebar_admin_setup' );
$widget_id = $this->get_post_value( 'widget-id' );
$parsed_id = $this->parse_widget_id( $widget_id );
$id_base = $parsed_id['id_base'];
if ( isset( $_POST['widget-' . $id_base] ) && is_array( $_POST['widget-' . $id_base] ) && preg_match( '/__i__|%i%/', key( $_POST['widget-' . $id_base] ) ) ) {
wp_send_json_error();
}
$updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
if ( is_wp_error( $updated_widget ) ) {
wp_send_json_error();
}
$form = $updated_widget['form'];
$instance = $this->sanitize_widget_js_instance( $updated_widget['instance'] );
wp_send_json_success( compact( 'form', 'instance' ) );
}
/***************************************************************************
* Option Update Capturing
***************************************************************************/
/**
* List of captured widget option updates.
*
* @since 3.9.0
* @access protected
* @var array $_captured_options Values updated while option capture is happening.
*/
protected $_captured_options = array();
/**
* Whether option capture is currently happening.
*
* @since 3.9.0
* @access protected
* @var bool $_is_current Whether option capture is currently happening or not.
*/
protected $_is_capturing_option_updates = false;
/**
* Determine whether the captured option update should be ignored.
*
* @since 3.9.0
* @access protected
*
* @param string $option_name Option name.
* @return boolean Whether the option capture is ignored.
*/
protected function is_option_capture_ignored( $option_name ) {
return ( 0 === strpos( $option_name, '_transient_' ) );
}
/**
* Retrieve captured widget option updates.
*
* @since 3.9.0
* @access protected
*
* @return array Array of captured options.
*/
protected function get_captured_options() {
return $this->_captured_options;
}
/**
* Get the number of captured widget option updates.
*
* @since 3.9.0
* @access protected
*
* @return int Number of updated options.
*/
protected function count_captured_options() {
return count( $this->_captured_options );
}
/**
* Start keeping track of changes to widget options, caching new values.
*
* @since 3.9.0
* @access protected
*/
protected function start_capturing_option_updates() {
if ( $this->_is_capturing_option_updates ) {
return;
}
$this->_is_capturing_option_updates = true;
add_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
}
/**
* Pre-filter captured option values before updating.
*
* @since 3.9.0
* @access public
*
* @param mixed $new_value
* @param string $option_name
* @param mixed $old_value
* @return mixed
*/
public function capture_filter_pre_update_option( $new_value, $option_name, $old_value ) {
if ( $this->is_option_capture_ignored( $option_name ) ) {
return;
}
if ( ! isset( $this->_captured_options[$option_name] ) ) {
add_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
}
$this->_captured_options[$option_name] = $new_value;
return $old_value;
}
/**
* Pre-filter captured option values before retrieving.
*
* @since 3.9.0
* @access public
*
* @param mixed $value Option
* @return mixed
*/
public function capture_filter_pre_get_option( $value ) {
$option_name = preg_replace( '/^pre_option_/', '', current_filter() );
if ( isset( $this->_captured_options[$option_name] ) ) {
$value = $this->_captured_options[$option_name];
/** This filter is documented in wp-includes/option.php */
$value = apply_filters( 'option_' . $option_name, $value );
}
return $value;
}
/**
* Undo any changes to the options since options capture began.
*
* @since 3.9.0
* @access protected
*/
protected function stop_capturing_option_updates() {
if ( ! $this->_is_capturing_option_updates ) {
return;
}
remove_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
foreach ( array_keys( $this->_captured_options ) as $option_name ) {
remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
}
$this->_captured_options = array();
$this->_is_capturing_option_updates = false;
}
}
| gpl-2.0 |
ewebdevelopment/sw-galaxy | bower_components/angular-material/modules/js/content/content.js | 3151 | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.3
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.content
*
* @description
* Scrollable content
*/
mdContentDirective['$inject'] = ["$mdTheming"];
angular.module('material.components.content', [
'material.core'
])
.directive('mdContent', mdContentDirective);
/**
* @ngdoc directive
* @name mdContent
* @module material.components.content
*
* @restrict E
*
* @description
*
* The `<md-content>` directive is a container element useful for scrollable content. It achieves
* this by setting the CSS `overflow` property to `auto` so that content can properly scroll.
*
* In general, `<md-content>` components are not designed to be nested inside one another. If
* possible, it is better to make them siblings. This often results in a better user experience as
* having nested scrollbars may confuse the user.
*
* ## Troubleshooting
*
* In some cases, you may wish to apply the `md-no-momentum` class to ensure that Safari's
* momentum scrolling is disabled. Momentum scrolling can cause flickering issues while scrolling
* SVG icons and some other components.
*
* Additionally, we now also offer the `md-no-flicker` class which can be applied to any element
* and uses a Webkit-specific filter of `blur(0px)` that forces GPU rendering of all elements
* inside (which eliminates the flicker on iOS devices).
*
* _<b>Note:</b> Forcing an element to render on the GPU can have unintended side-effects, especially
* related to the z-index of elements. Please use with caution and only on the elements needed._
*
* @usage
*
* Add the `[layout-padding]` attribute to make the content padded.
*
* <hljs lang="html">
* <md-content layout-padding>
* Lorem ipsum dolor sit amet, ne quod novum mei.
* </md-content>
* </hljs>
*/
function mdContentDirective($mdTheming) {
return {
restrict: 'E',
controller: ['$scope', '$element', ContentController],
link: function(scope, element) {
element.addClass('_md'); // private md component indicator for styling
$mdTheming(element);
scope.$broadcast('$mdContentLoaded', element);
iosScrollFix(element[0]);
}
};
function ContentController($scope, $element) {
this.$scope = $scope;
this.$element = $element;
}
}
function iosScrollFix(node) {
// IOS FIX:
// If we scroll where there is no more room for the webview to scroll,
// by default the webview itself will scroll up and down, this looks really
// bad. So if we are scrolling to the very top or bottom, add/subtract one
angular.element(node).on('$md.pressdown', function(ev) {
// Only touch events
if (ev.pointer.type !== 't') return;
// Don't let a child content's touchstart ruin it for us.
if (ev.$materialScrollFixed) return;
ev.$materialScrollFixed = true;
if (node.scrollTop === 0) {
node.scrollTop = 1;
} else if (node.scrollHeight === node.scrollTop + node.offsetHeight) {
node.scrollTop -= 1;
}
});
}
})(window, window.angular); | gpl-3.0 |
kosh88/projectproperties | imagemagick/ruby/1.9.1/gems/rack-1.4.1/test/spec_runtime.rb | 1393 | require 'rack/runtime'
describe Rack::Runtime do
it "sets X-Runtime is none is set" do
app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, "Hello, World!"] }
response = Rack::Runtime.new(app).call({})
response[1]['X-Runtime'].should =~ /[\d\.]+/
end
it "doesn't set the X-Runtime if it is already set" do
app = lambda { |env| [200, {'Content-Type' => 'text/plain', "X-Runtime" => "foobar"}, "Hello, World!"] }
response = Rack::Runtime.new(app).call({})
response[1]['X-Runtime'].should == "foobar"
end
should "allow a suffix to be set" do
app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, "Hello, World!"] }
response = Rack::Runtime.new(app, "Test").call({})
response[1]['X-Runtime-Test'].should =~ /[\d\.]+/
end
should "allow multiple timers to be set" do
app = lambda { |env| sleep 0.1; [200, {'Content-Type' => 'text/plain'}, "Hello, World!"] }
runtime = Rack::Runtime.new(app, "App")
# wrap many times to guarantee a measurable difference
100.times do |i|
runtime = Rack::Runtime.new(runtime, i.to_s)
end
runtime = Rack::Runtime.new(runtime, "All")
response = runtime.call({})
response[1]['X-Runtime-App'].should =~ /[\d\.]+/
response[1]['X-Runtime-All'].should =~ /[\d\.]+/
Float(response[1]['X-Runtime-All']).should > Float(response[1]['X-Runtime-App'])
end
end
| artistic-2.0 |
kzhong1991/Flight-AR.Drone-2 | src/3rdparty/Qt4.8.4/src/3rdparty/webkit/Source/WebCore/bindings/js/JSHTMLFormElementCustom.cpp | 2595 | /*
* Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JSHTMLFormElement.h"
#include "Frame.h"
#include "HTMLCollection.h"
#include "HTMLFormElement.h"
#include "JSDOMWindowCustom.h"
#include "JSNodeList.h"
#include "StaticNodeList.h"
using namespace JSC;
namespace WebCore {
bool JSHTMLFormElement::canGetItemsForName(ExecState*, HTMLFormElement* form, const Identifier& propertyName)
{
Vector<RefPtr<Node> > namedItems;
form->getNamedElements(identifierToAtomicString(propertyName), namedItems);
return namedItems.size();
}
JSValue JSHTMLFormElement::nameGetter(ExecState* exec, JSValue slotBase, const Identifier& propertyName)
{
JSHTMLElement* jsForm = static_cast<JSHTMLFormElement*>(asObject(slotBase));
HTMLFormElement* form = static_cast<HTMLFormElement*>(jsForm->impl());
Vector<RefPtr<Node> > namedItems;
form->getNamedElements(identifierToAtomicString(propertyName), namedItems);
if (namedItems.isEmpty())
return jsUndefined();
if (namedItems.size() == 1)
return toJS(exec, jsForm->globalObject(), namedItems[0].get());
// FIXME: HTML5 specifies that this should be a RadioNodeList.
return toJS(exec, jsForm->globalObject(), StaticNodeList::adopt(namedItems).get());
}
}
| bsd-3-clause |
Slaffka/moodel | lib/google/Google/Service/YouTubeAnalytics.php | 16726 | <?php
/*
* Copyright 2010 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.
*/
/**
* Service definition for YouTubeAnalytics (v1).
*
* <p>
* Retrieve your YouTube Analytics reports.
* </p>
*
* <p>
* For more information about this service, see the API
* <a href="http://developers.google.com/youtube/analytics/" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_YouTubeAnalytics extends Google_Service
{
/** View YouTube Analytics monetary reports for your YouTube content. */
const YT_ANALYTICS_MONETARY_READONLY = "https://www.googleapis.com/auth/yt-analytics-monetary.readonly";
/** View YouTube Analytics reports for your YouTube content. */
const YT_ANALYTICS_READONLY = "https://www.googleapis.com/auth/yt-analytics.readonly";
public $batchReportDefinitions;
public $batchReports;
public $reports;
/**
* Constructs the internal representation of the YouTubeAnalytics service.
*
* @param Google_Client $client
*/
public function __construct(Google_Client $client)
{
parent::__construct($client);
$this->servicePath = 'youtube/analytics/v1/';
$this->version = 'v1';
$this->serviceName = 'youtubeAnalytics';
$this->batchReportDefinitions = new Google_Service_YouTubeAnalytics_BatchReportDefinitions_Resource(
$this,
$this->serviceName,
'batchReportDefinitions',
array(
'methods' => array(
'list' => array(
'path' => 'batchReportDefinitions',
'httpMethod' => 'GET',
'parameters' => array(
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
$this->batchReports = new Google_Service_YouTubeAnalytics_BatchReports_Resource(
$this,
$this->serviceName,
'batchReports',
array(
'methods' => array(
'list' => array(
'path' => 'batchReports',
'httpMethod' => 'GET',
'parameters' => array(
'batchReportDefinitionId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
$this->reports = new Google_Service_YouTubeAnalytics_Reports_Resource(
$this,
$this->serviceName,
'reports',
array(
'methods' => array(
'query' => array(
'path' => 'reports',
'httpMethod' => 'GET',
'parameters' => array(
'ids' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'start-date' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'end-date' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'metrics' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'max-results' => array(
'location' => 'query',
'type' => 'integer',
),
'sort' => array(
'location' => 'query',
'type' => 'string',
),
'dimensions' => array(
'location' => 'query',
'type' => 'string',
),
'start-index' => array(
'location' => 'query',
'type' => 'integer',
),
'filters' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
}
}
/**
* The "batchReportDefinitions" collection of methods.
* Typical usage is:
* <code>
* $youtubeAnalyticsService = new Google_Service_YouTubeAnalytics(...);
* $batchReportDefinitions = $youtubeAnalyticsService->batchReportDefinitions;
* </code>
*/
class Google_Service_YouTubeAnalytics_BatchReportDefinitions_Resource extends Google_Service_Resource
{
/**
* Retrieves a list of available batch report definitions.
* (batchReportDefinitions.listBatchReportDefinitions)
*
* @param string $onBehalfOfContentOwner
* The onBehalfOfContentOwner parameter identifies the content owner that the user is acting on
* behalf of.
* @param array $optParams Optional parameters.
* @return Google_Service_YouTubeAnalytics_BatchReportDefinitionList
*/
public function listBatchReportDefinitions($onBehalfOfContentOwner, $optParams = array())
{
$params = array('onBehalfOfContentOwner' => $onBehalfOfContentOwner);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTubeAnalytics_BatchReportDefinitionList");
}
}
/**
* The "batchReports" collection of methods.
* Typical usage is:
* <code>
* $youtubeAnalyticsService = new Google_Service_YouTubeAnalytics(...);
* $batchReports = $youtubeAnalyticsService->batchReports;
* </code>
*/
class Google_Service_YouTubeAnalytics_BatchReports_Resource extends Google_Service_Resource
{
/**
* Retrieves a list of processed batch reports. (batchReports.listBatchReports)
*
* @param string $batchReportDefinitionId
* The batchReportDefinitionId parameter specifies the ID of the batch reportort definition for
* which you are retrieving reports.
* @param string $onBehalfOfContentOwner
* The onBehalfOfContentOwner parameter identifies the content owner that the user is acting on
* behalf of.
* @param array $optParams Optional parameters.
* @return Google_Service_YouTubeAnalytics_BatchReportList
*/
public function listBatchReports($batchReportDefinitionId, $onBehalfOfContentOwner, $optParams = array())
{
$params = array('batchReportDefinitionId' => $batchReportDefinitionId, 'onBehalfOfContentOwner' => $onBehalfOfContentOwner);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTubeAnalytics_BatchReportList");
}
}
/**
* The "reports" collection of methods.
* Typical usage is:
* <code>
* $youtubeAnalyticsService = new Google_Service_YouTubeAnalytics(...);
* $reports = $youtubeAnalyticsService->reports;
* </code>
*/
class Google_Service_YouTubeAnalytics_Reports_Resource extends Google_Service_Resource
{
/**
* Retrieve your YouTube Analytics reports. (reports.query)
*
* @param string $ids
* Identifies the YouTube channel or content owner for which you are retrieving YouTube Analytics
* data.
- To request data for a YouTube user, set the ids parameter value to channel==CHANNEL_ID,
* where CHANNEL_ID specifies the unique YouTube channel ID.
- To request data for a YouTube CMS
* content owner, set the ids parameter value to contentOwner==OWNER_NAME, where OWNER_NAME is the
* CMS name of the content owner.
* @param string $startDate
* The start date for fetching YouTube Analytics data. The value should be in YYYY-MM-DD format.
* @param string $endDate
* The end date for fetching YouTube Analytics data. The value should be in YYYY-MM-DD format.
* @param string $metrics
* A comma-separated list of YouTube Analytics metrics, such as views or likes,dislikes. See the
* Available Reports document for a list of the reports that you can retrieve and the metrics
* available in each report, and see the Metrics document for definitions of those metrics.
* @param array $optParams Optional parameters.
*
* @opt_param int max-results
* The maximum number of rows to include in the response.
* @opt_param string sort
* A comma-separated list of dimensions or metrics that determine the sort order for YouTube
* Analytics data. By default the sort order is ascending. The '-' prefix causes descending sort
* order.
* @opt_param string dimensions
* A comma-separated list of YouTube Analytics dimensions, such as views or ageGroup,gender. See
* the Available Reports document for a list of the reports that you can retrieve and the
* dimensions used for those reports. Also see the Dimensions document for definitions of those
* dimensions.
* @opt_param int start-index
* An index of the first entity to retrieve. Use this parameter as a pagination mechanism along
* with the max-results parameter (one-based, inclusive).
* @opt_param string filters
* A list of filters that should be applied when retrieving YouTube Analytics data. The Available
* Reports document identifies the dimensions that can be used to filter each report, and the
* Dimensions document defines those dimensions. If a request uses multiple filters, join them
* together with a semicolon (;), and the returned result table will satisfy both filters. For
* example, a filters parameter value of video==dMH0bHeiRNg;country==IT restricts the result set to
* include data for the given video in Italy.
* @return Google_Service_YouTubeAnalytics_ResultTable
*/
public function query($ids, $startDate, $endDate, $metrics, $optParams = array())
{
$params = array('ids' => $ids, 'start-date' => $startDate, 'end-date' => $endDate, 'metrics' => $metrics);
$params = array_merge($params, $optParams);
return $this->call('query', array($params), "Google_Service_YouTubeAnalytics_ResultTable");
}
}
class Google_Service_YouTubeAnalytics_BatchReportDefinitionList extends Google_Collection
{
protected $collection_key = 'items';
protected $itemsType = 'Google_Service_YouTubeAnalytics_BatchReportDefinitionTemplate';
protected $itemsDataType = 'array';
public $kind;
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
}
class Google_Service_YouTubeAnalytics_BatchReportDefinitionTemplate extends Google_Collection
{
protected $collection_key = 'defaultOutput';
protected $defaultOutputType = 'Google_Service_YouTubeAnalytics_BatchReportDefinitionTemplateDefaultOutput';
protected $defaultOutputDataType = 'array';
public $id;
public $name;
public $status;
public $type;
public function setDefaultOutput($defaultOutput)
{
$this->defaultOutput = $defaultOutput;
}
public function getDefaultOutput()
{
return $this->defaultOutput;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setStatus($status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
class Google_Service_YouTubeAnalytics_BatchReportDefinitionTemplateDefaultOutput extends Google_Model
{
public $format;
public $type;
public function setFormat($format)
{
$this->format = $format;
}
public function getFormat()
{
return $this->format;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
class Google_Service_YouTubeAnalytics_BatchReportList extends Google_Collection
{
protected $collection_key = 'items';
protected $itemsType = 'Google_Service_YouTubeAnalytics_BatchReportTemplate';
protected $itemsDataType = 'array';
public $kind;
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
}
class Google_Service_YouTubeAnalytics_BatchReportTemplate extends Google_Collection
{
protected $collection_key = 'outputs';
public $id;
protected $outputsType = 'Google_Service_YouTubeAnalytics_BatchReportTemplateOutputs';
protected $outputsDataType = 'array';
public $reportId;
protected $timeSpanType = 'Google_Service_YouTubeAnalytics_BatchReportTemplateTimeSpan';
protected $timeSpanDataType = '';
public $timeUpdated;
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setOutputs($outputs)
{
$this->outputs = $outputs;
}
public function getOutputs()
{
return $this->outputs;
}
public function setReportId($reportId)
{
$this->reportId = $reportId;
}
public function getReportId()
{
return $this->reportId;
}
public function setTimeSpan(Google_Service_YouTubeAnalytics_BatchReportTemplateTimeSpan $timeSpan)
{
$this->timeSpan = $timeSpan;
}
public function getTimeSpan()
{
return $this->timeSpan;
}
public function setTimeUpdated($timeUpdated)
{
$this->timeUpdated = $timeUpdated;
}
public function getTimeUpdated()
{
return $this->timeUpdated;
}
}
class Google_Service_YouTubeAnalytics_BatchReportTemplateOutputs extends Google_Model
{
public $downloadUrl;
public $format;
public $type;
public function setDownloadUrl($downloadUrl)
{
$this->downloadUrl = $downloadUrl;
}
public function getDownloadUrl()
{
return $this->downloadUrl;
}
public function setFormat($format)
{
$this->format = $format;
}
public function getFormat()
{
return $this->format;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
class Google_Service_YouTubeAnalytics_BatchReportTemplateTimeSpan extends Google_Model
{
public $endTime;
public $startTime;
public function setEndTime($endTime)
{
$this->endTime = $endTime;
}
public function getEndTime()
{
return $this->endTime;
}
public function setStartTime($startTime)
{
$this->startTime = $startTime;
}
public function getStartTime()
{
return $this->startTime;
}
}
class Google_Service_YouTubeAnalytics_ResultTable extends Google_Collection
{
protected $collection_key = 'rows';
protected $columnHeadersType = 'Google_Service_YouTubeAnalytics_ResultTableColumnHeaders';
protected $columnHeadersDataType = 'array';
public $kind;
public $rows;
public function setColumnHeaders($columnHeaders)
{
$this->columnHeaders = $columnHeaders;
}
public function getColumnHeaders()
{
return $this->columnHeaders;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setRows($rows)
{
$this->rows = $rows;
}
public function getRows()
{
return $this->rows;
}
}
class Google_Service_YouTubeAnalytics_ResultTableColumnHeaders extends Google_Model
{
public $columnType;
public $dataType;
public $name;
public function setColumnType($columnType)
{
$this->columnType = $columnType;
}
public function getColumnType()
{
return $this->columnType;
}
public function setDataType($dataType)
{
$this->dataType = $dataType;
}
public function getDataType()
{
return $this->dataType;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
| gpl-3.0 |
lulf/qpid-dispatch | console/dispatch-dashboard/dispatch/static/dashboard/dispatch/lib/slider.js | 11238 | /*
jQuery UI Slider plugin wrapper
*/
angular.module('ui.slider', []).value('uiSliderConfig',{}).directive('uiSlider', ['uiSliderConfig', '$timeout', function(uiSliderConfig, $timeout) {
uiSliderConfig = uiSliderConfig || {};
return {
require: 'ngModel',
compile: function() {
var preLink = function (scope, elm, attrs, ngModel) {
function parseNumber(n, decimals) {
return (decimals) ? parseFloat(n) : parseInt(n, 10);
}
var directiveOptions = angular.copy(scope.$eval(attrs.uiSlider));
var options = angular.extend(directiveOptions || {}, uiSliderConfig);
// Object holding range values
var prevRangeValues = {
min: null,
max: null
};
// convenience properties
var properties = ['min', 'max', 'step', 'lowerBound', 'upperBound'];
var useDecimals = (!angular.isUndefined(attrs.useDecimals)) ? true : false;
var updateOn = (angular.isDefined(options['updateOn'])) ? options['updateOn'] : 'slide'
var init = function() {
// When ngModel is assigned an array of values then range is expected to be true.
// Warn user and change range to true else an error occurs when trying to drag handle
if (angular.isArray(ngModel.$viewValue) && options.range !== true) {
console.warn('Change your range option of ui-slider. When assigning ngModel an array of values then the range option should be set to true.');
options.range = true;
}
// Ensure the convenience properties are passed as options if they're defined
// This avoids init ordering issues where the slider's initial state (eg handle
// position) is calculated using widget defaults
// Note the properties take precedence over any duplicates in options
angular.forEach(properties, function(property) {
if (angular.isDefined(attrs[property])) {
options[property] = parseNumber(attrs[property], useDecimals);
}
});
elm.slider(options);
init = angular.noop;
};
// Find out if decimals are to be used for slider
angular.forEach(properties, function(property) {
// support {{}} and watch for updates
attrs.$observe(property, function(newVal) {
if (!!newVal) {
init();
options[property] = parseNumber(newVal, useDecimals);
elm.slider('option', property, parseNumber(newVal, useDecimals));
ngModel.$render();
}
});
});
attrs.$observe('disabled', function(newVal) {
init();
elm.slider('option', 'disabled', !!newVal);
});
// Watch ui-slider (byVal) for changes and update
scope.$watch(attrs.uiSlider, function(newVal) {
init();
if(newVal !== undefined) {
elm.slider('option', newVal);
}
}, true);
// Late-bind to prevent compiler clobbering
$timeout(init, 0, true);
// Update model value from slider
elm.bind(updateOn, function(event, ui) {
var valuesChanged;
if (ui.values) {
var boundedValues = ui.values.slice();
if (options.lowerBound && boundedValues[0] < options.lowerBound) {
boundedValues[0] = Math.max(boundedValues[0], options.lowerBound);
}
if (options.upperBound && boundedValues[1] > options.upperBound) {
boundedValues[1] = Math.min(boundedValues[1], options.upperBound);
}
if (boundedValues[0] !== ui.values[0] || boundedValues[1] !== ui.values[1]) {
valuesChanged = true;
ui.values = boundedValues;
}
} else {
var boundedValue = ui.value;
if (options.lowerBound && boundedValue < options.lowerBound) {
boundedValue = Math.max(boundedValue, options.lowerBound);
}
if (options.upperBound && boundedValue > options.upperBound) {
boundedValue = Math.min(boundedValue, options.upperBound);
}
if (boundedValue !== ui.value) {
valuesChanged = true;
ui.value = boundedValue;
}
}
ngModel.$setViewValue(ui.values || ui.value);
$(ui.handle).find('.ui-slider-tip').text(ui.value);
scope.$apply();
if (valuesChanged) {
setTimeout(function() {
elm.slider('value', ui.values || ui.value);
}, 0);
return false;
}
});
// Update slider from model value
ngModel.$render = function() {
init();
var method = options.range === true ? 'values' : 'value';
if (options.range !== true && isNaN(ngModel.$viewValue) && !(ngModel.$viewValue instanceof Array)) {
ngModel.$viewValue = 0;
}
else if (options.range && !angular.isDefined(ngModel.$viewValue)) {
ngModel.$viewValue = [0,0];
}
// Do some sanity check of range values
if (options.range === true) {
// previously, the model was a string b/c it was in a text input, need to convert to a array.
// make sure input exists, comma exists once, and it is a string.
if (ngModel.$viewValue && angular.isString(ngModel.$viewValue) && (ngModel.$viewValue.match(/,/g) || []).length === 1) {
// transform string model into array.
var valueArr = ngModel.$viewValue.split(',');
ngModel.$viewValue = [Number(valueArr[0]), Number(valueArr[1])];
}
// Check outer bounds for min and max values
if (angular.isDefined(options.min) && options.min > ngModel.$viewValue[0]) {
ngModel.$viewValue[0] = options.min;
}
if (angular.isDefined(options.max) && options.max < ngModel.$viewValue[1]) {
ngModel.$viewValue[1] = options.max;
}
// Check min and max range values
if (ngModel.$viewValue[0] > ngModel.$viewValue[1]) {
// Min value should be less to equal to max value
if (prevRangeValues.min >= ngModel.$viewValue[1]) {
ngModel.$viewValue[1] = prevRangeValues.min;
}
// Max value should be less to equal to min value
if (prevRangeValues.max <= ngModel.$viewValue[0]) {
ngModel.$viewValue[0] = prevRangeValues.max;
}
}
// Store values for later user
prevRangeValues.min = ngModel.$viewValue[0];
prevRangeValues.max = ngModel.$viewValue[1];
}
elm.slider(method, ngModel.$viewValue);
};
scope.$watch(attrs.ngModel, function() {
if (options.range === true) {
ngModel.$render();
$(elm).find('.ui-slider-tip').each(function(i, tipElm) {
$(tipElm).text(ngModel.$viewValue[i]);
});
} else {
$(elm).find('.ui-slider-tip').text(ngModel.$viewValue);
}
}, true);
function destroy() {
if (elm.hasClass('ui-slider')) {
elm.slider('destroy');
}
}
scope.$on("$destroy", destroy);
elm.one('$destroy', destroy);
};
var postLink = function (scope, element, attrs, ngModel) {
// Add tick marks if 'tick' and 'step' attributes have been setted on element.
// Support horizontal slider bar so far. 'tick' and 'step' attributes are required.
var options = angular.extend({}, scope.$eval(attrs.uiSlider));
var properties = ['min', 'max', 'step', 'tick', 'tip'];
angular.forEach(properties, function(property) {
if (angular.isDefined(attrs[property])) {
options[property] = attrs[property];
}
});
if (angular.isDefined(options['tick']) && angular.isDefined(options['step'])) {
var total = parseInt( (parseInt(options['max']) - parseInt(options['min'])) /parseInt(options['step']));
for (var i = total; i >= 0; i--) {
var left = ((i / total) * 100) + '%';
$("<div/>").addClass("ui-slider-tick").appendTo(element).css({left: left});
};
}
if(angular.isDefined(options['tip'])) {
$timeout(function(){
var handles = element.find('.ui-slider-handle');
if(handles && handles.length>1 && ngModel.$viewValue && angular.isArray(ngModel.$viewValue)){
$(handles[0]).append('<div class="ui-slider-tip">'+ngModel.$viewValue[0]+'</div>');
$(handles[1]).append('<div class="ui-slider-tip">'+ngModel.$viewValue[1]+'</div>');
}else{
element.find('.ui-slider-handle').append('<div class="ui-slider-tip">'+ngModel.$viewValue+'</div>');
}
},10);
}
}
return {
pre: preLink,
post: postLink
};
}
};
}]);
| apache-2.0 |
boliza/elasticsearch | src/main/java/org/elasticsearch/action/admin/indices/create/CreateIndexAction.java | 1565 | /*
* 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.action.admin.indices.create;
import org.elasticsearch.action.admin.indices.IndicesAction;
import org.elasticsearch.client.IndicesAdminClient;
/**
*/
public class CreateIndexAction extends IndicesAction<CreateIndexRequest, CreateIndexResponse, CreateIndexRequestBuilder> {
public static final CreateIndexAction INSTANCE = new CreateIndexAction();
public static final String NAME = "indices:admin/create";
private CreateIndexAction() {
super(NAME);
}
@Override
public CreateIndexResponse newResponse() {
return new CreateIndexResponse();
}
@Override
public CreateIndexRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new CreateIndexRequestBuilder(client);
}
}
| apache-2.0 |
ol-loginov/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GroovyDocCheckInspection.java | 3476 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.codeInspection.bugs;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection;
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor;
import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocFieldReference;
import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocMemberReference;
import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocMethodReference;
import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GroovyDocPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
/**
* @author Max Medvedev
*/
public class GroovyDocCheckInspection extends BaseInspection {
@Nls
@NotNull
@Override
public String getGroupDisplayName() {
return PROBABLE_BUGS;
}
@Nls
@NotNull
@Override
public String getDisplayName() {
return "GroovyDoc issues";
}
@Override
protected String buildErrorString(Object... args) {
return (String)args[0];
}
@Override
public boolean isEnabledByDefault() {
return true;
}
@NotNull
@Override
protected BaseInspectionVisitor buildVisitor() {
return new BaseInspectionVisitor() {
@Override
public void visitDocMethodReference(GrDocMethodReference reference) {
checkGrDocMemberReference(reference);
}
@Override
public void visitDocFieldReference(GrDocFieldReference reference) {
checkGrDocMemberReference(reference);
}
@Override
public void visitCodeReferenceElement(GrCodeReferenceElement refElement) {
GroovyResolveResult resolveResult = refElement.advancedResolve();
if (refElement.getReferenceName() == null) return;
if (PsiTreeUtil.getParentOfType(refElement, GroovyDocPsiElement.class, true, GrMember.class, GrCodeBlock.class) == null) return;
final PsiElement resolved = resolveResult.getElement();
if (resolved != null) return;
final PsiElement toHighlight = refElement.getReferenceNameElement();
registerError(toHighlight, GroovyBundle.message("cannot.resolve", refElement.getReferenceName()));
}
private void checkGrDocMemberReference(final GrDocMemberReference reference) {
if (reference.resolve() != null) return;
registerError(reference.getReferenceNameElement(), GroovyBundle.message("cannot.resolve", reference.getReferenceName()));
}
};
}
}
| apache-2.0 |
anirudhSK/chromium | chrome/common/extensions/manifest_tests/extension_manifests_web_unittest.cc | 2287 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/manifest_tests/extension_manifest_test.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/manifest_constants.h"
#include "testing/gtest/include/gtest/gtest.h"
using extensions::ErrorUtils;
using extensions::Extension;
namespace errors = extensions::manifest_errors;
TEST_F(ExtensionManifestTest, AppWebUrls) {
Testcase testcases[] = {
Testcase("web_urls_wrong_type.json", errors::kInvalidWebURLs),
Testcase("web_urls_invalid_1.json",
ErrorUtils::FormatErrorMessage(
errors::kInvalidWebURL,
base::IntToString(0),
errors::kExpectString)),
Testcase("web_urls_invalid_2.json",
ErrorUtils::FormatErrorMessage(
errors::kInvalidWebURL,
base::IntToString(0),
URLPattern::GetParseResultString(
URLPattern::PARSE_ERROR_MISSING_SCHEME_SEPARATOR))),
Testcase("web_urls_invalid_3.json",
ErrorUtils::FormatErrorMessage(
errors::kInvalidWebURL,
base::IntToString(0),
errors::kNoWildCardsInPaths)),
Testcase("web_urls_invalid_4.json",
ErrorUtils::FormatErrorMessage(
errors::kInvalidWebURL,
base::IntToString(0),
errors::kCannotClaimAllURLsInExtent)),
Testcase("web_urls_invalid_5.json",
ErrorUtils::FormatErrorMessage(
errors::kInvalidWebURL,
base::IntToString(1),
errors::kCannotClaimAllHostsInExtent))
};
RunTestcases(testcases, arraysize(testcases),
EXPECT_TYPE_ERROR);
LoadAndExpectSuccess("web_urls_has_port.json");
scoped_refptr<Extension> extension(
LoadAndExpectSuccess("web_urls_default.json"));
ASSERT_EQ(1u, extension->web_extent().patterns().size());
EXPECT_EQ("*://www.google.com/*",
extension->web_extent().patterns().begin()->GetAsString());
}
| bsd-3-clause |
cvisger/Visger-Lab | vendor/bundle/ruby/2.3.0/gems/sass-3.5.6/test/sass/util/normalized_map_test.rb | 1283 | require File.dirname(__FILE__) + '/../../test_helper'
require 'sass/util/normalized_map'
class NormalizedMapTest < MiniTest::Test
extend PublicApiLinter
lint_api Hash, Sass::Util::NormalizedMap
def lint_instance
Sass::Util::NormalizedMap.new
end
def test_normalized_map_errors_unless_explicitly_implemented
assert Sass.tests_running
assert_raise_message(ArgumentError, "The method invert must be implemented explicitly") do
Sass::Util::NormalizedMap.new.invert
end
end
def test_normalized_map_does_not_error_when_released
Sass.tests_running = false
assert_equal({}, Sass::Util::NormalizedMap.new.invert)
ensure
Sass.tests_running = true
end
def test_basic_lifecycle
m = Sass::Util::NormalizedMap.new
m["a-b"] = 1
assert_equal ["a_b"], m.keys
assert_equal 1, m["a_b"]
assert_equal 1, m["a-b"]
assert m.has_key?("a_b")
assert m.has_key?("a-b")
assert_equal({"a-b" => 1}, m.as_stored)
assert_equal 1, m.delete("a-b")
assert !m.has_key?("a-b")
m["a_b"] = 2
assert_equal({"a_b" => 2}, m.as_stored)
end
def test_dup
m = Sass::Util::NormalizedMap.new
m["a-b"] = 1
m2 = m.dup
m.delete("a-b")
assert !m.has_key?("a-b")
assert m2.has_key?("a-b")
end
end
| mit |
iains/darwin-gcc-5 | libstdc++-v3/testsuite/23_containers/multimap/23781_neg.cc | 1054 | // 2005-09-10 Paolo Carlini <pcarlini@suse.de>
//
// Copyright (C) 2005-2015 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/>.
//
// { dg-do compile }
// libstdc++/23781
#include <map>
#include <cstddef>
std::multimap<int, int>::iterator it = NULL; // { dg-error "conversion" }
std::multimap<int, int>::const_iterator cit = NULL; // { dg-error "conversion" }
| gpl-2.0 |
nichit93/Implementation-of-TRED-in-ns-3 | src/aodv/test/loopback.cc | 5616 | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2010 IITP RAS
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors: Pavel Boyko <boyko@iitp.ru>
*/
#include "ns3/test.h"
#include "ns3/simulator.h"
#include "ns3/socket-factory.h"
#include "ns3/udp-socket-factory.h"
#include "ns3/mobility-helper.h"
#include "ns3/double.h"
#include "ns3/uinteger.h"
#include "ns3/string.h"
#include "ns3/boolean.h"
#include "ns3/yans-wifi-helper.h"
#include "ns3/internet-stack-helper.h"
#include "ns3/ipv4-address-helper.h"
#include "ns3/abort.h"
#include "ns3/udp-echo-helper.h"
#include "ns3/mobility-model.h"
#include "ns3/pcap-file.h"
#include "ns3/aodv-helper.h"
#include "ns3/v4ping.h"
#include "ns3/config.h"
#include "ns3/constant-position-mobility-model.h"
#include "ns3/names.h"
#include <sstream>
namespace ns3
{
namespace aodv
{
/**
* \ingroup aodv
*
* \brief AODV loopback UDP echo test case
*/
class LoopbackTestCase : public TestCase
{
uint32_t m_count; //!< number of packet received;
Ptr<Socket> m_txSocket;
Ptr<Socket> m_echoSocket;
Ptr<Socket> m_rxSocket;
uint16_t m_echoSendPort;
uint16_t m_echoReplyPort;
void SendData (Ptr<Socket> socket);
void ReceivePkt (Ptr<Socket> socket);
void EchoData (Ptr<Socket> socket);
public:
LoopbackTestCase ();
void DoRun ();
};
LoopbackTestCase::LoopbackTestCase () :
TestCase ("UDP Echo 127.0.0.1 test"), m_count (0)
{
m_echoSendPort = 1233;
m_echoReplyPort = 1234;
}
void LoopbackTestCase::ReceivePkt (Ptr<Socket> socket)
{
Ptr<Packet> receivedPacket = socket->Recv (std::numeric_limits<uint32_t>::max (), 0);
m_count ++;
}
void
LoopbackTestCase::EchoData (Ptr<Socket> socket)
{
Address from;
Ptr<Packet> receivedPacket = socket->RecvFrom (std::numeric_limits<uint32_t>::max (), 0, from);
Ipv4Address src = InetSocketAddress::ConvertFrom (from).GetIpv4 ();
Address to = InetSocketAddress (src, m_echoReplyPort);
receivedPacket->RemoveAllPacketTags ();
receivedPacket->RemoveAllByteTags ();
socket->SendTo (receivedPacket, 0, to);
}
void
LoopbackTestCase::SendData (Ptr<Socket> socket)
{
Address realTo = InetSocketAddress (Ipv4Address::GetLoopback (), m_echoSendPort);
socket->SendTo (Create<Packet> (123), 0, realTo);
Simulator::ScheduleWithContext (socket->GetNode ()->GetId (), Seconds (1.0),
&LoopbackTestCase::SendData, this, socket);
}
void
LoopbackTestCase::DoRun ()
{
NodeContainer nodes;
nodes.Create (1);
Ptr<MobilityModel> m = CreateObject<ConstantPositionMobilityModel> ();
m->SetPosition (Vector (0, 0, 0));
nodes.Get (0)->AggregateObject (m);
// Setup WiFi
WifiMacHelper wifiMac;
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ());
WifiHelper wifi;
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", StringValue ("OfdmRate6Mbps"), "RtsCtsThreshold", StringValue ("2200"));
NetDeviceContainer devices = wifi.Install (wifiPhy, wifiMac, nodes);
// Setup TCP/IP & AODV
AodvHelper aodv; // Use default parameters here
InternetStackHelper internetStack;
internetStack.SetRoutingHelper (aodv);
internetStack.Install (nodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
// Setup echos
Ptr<SocketFactory> socketFactory = nodes.Get (0)->GetObject<UdpSocketFactory> ();
m_rxSocket = socketFactory->CreateSocket ();
m_rxSocket->Bind (InetSocketAddress (Ipv4Address::GetLoopback (), m_echoReplyPort));
m_rxSocket->SetRecvCallback (MakeCallback (&LoopbackTestCase::ReceivePkt, this));
m_echoSocket = socketFactory->CreateSocket ();
m_echoSocket->Bind (InetSocketAddress (Ipv4Address::GetLoopback (), m_echoSendPort));
m_echoSocket->SetRecvCallback (MakeCallback (&LoopbackTestCase::EchoData, this));
m_txSocket = socketFactory->CreateSocket ();
Simulator::ScheduleWithContext (m_txSocket->GetNode ()->GetId (), Seconds (1.0),
&LoopbackTestCase::SendData, this, m_txSocket);
// Run
Simulator::Stop (Seconds (5));
Simulator::Run ();
m_txSocket->Close ();
m_echoSocket->Close ();
m_rxSocket->Close ();
Simulator::Destroy ();
// Check that 4 packets delivered
NS_TEST_ASSERT_MSG_EQ (m_count, 4, "Exactly 4 echo replies must be delivered.");
}
//-----------------------------------------------------------------------------
// Test suite
//-----------------------------------------------------------------------------
class AodvLoopbackTestSuite : public TestSuite
{
public:
AodvLoopbackTestSuite () : TestSuite ("routing-aodv-loopback", SYSTEM)
{
SetDataDir (NS_TEST_SOURCEDIR);
// UDP Echo loopback test case
AddTestCase (new LoopbackTestCase (), TestCase::QUICK);
}
} g_aodvLoopbackTestSuite;
}
}
| gpl-2.0 |
MadcowD/libgdx | backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/utils/reflect/Method.java | 5780 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.utils.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import com.badlogic.gwtref.client.Parameter;
/** Provides information about, and access to, a single method on a class or interface.
* @author nexsoftware */
public final class Method {
private final com.badlogic.gwtref.client.Method method;
Method (com.badlogic.gwtref.client.Method method) {
this.method = method;
}
/** Returns the name of the method. */
public String getName () {
return method.getName();
}
/** Returns a Class object that represents the formal return type of the method. */
public Class getReturnType () {
return method.getReturnType();
}
/** Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method. */
public Class[] getParameterTypes () {
Parameter[] parameters = method.getParameters();
Class[] parameterTypes = new Class[parameters.length];
for (int i = 0, j = parameters.length; i < j; i++) {
parameterTypes[i] = parameters[i].getClazz();
}
return parameterTypes;
}
/** Returns the Class object representing the class or interface that declares the method. */
public Class getDeclaringClass () {
return method.getEnclosingType();
}
public boolean isAccessible () {
return method.isPublic();
}
public void setAccessible (boolean accessible) {
// NOOP in GWT
}
/** Return true if the method includes the {@code abstract} modifier. */
public boolean isAbstract () {
return method.isAbstract();
}
/** Return true if the method does not include any of the {@code private}, {@code protected}, or {@code public} modifiers. */
public boolean isDefaultAccess () {
return !isPrivate() && !isProtected() && !isPublic();
}
/** Return true if the method includes the {@code final} modifier. */
public boolean isFinal () {
return method.isFinal();
}
/** Return true if the method includes the {@code private} modifier. */
public boolean isPrivate () {
return method.isPrivate();
}
/** Return true if the method includes the {@code protected} modifier. */
public boolean isProtected () {
return method.isProtected();
}
/** Return true if the method includes the {@code public} modifier. */
public boolean isPublic () {
return method.isPublic();
}
/** Return true if the method includes the {@code native} modifier. */
public boolean isNative () {
return method.isNative();
}
/** Return true if the method includes the {@code static} modifier. */
public boolean isStatic () {
return method.isStatic();
}
/** Return true if the method takes a variable number of arguments. */
public boolean isVarArgs () {
return method.isVarArgs();
}
/** Invokes the underlying method on the supplied object with the supplied parameters. */
public Object invoke (Object obj, Object... args) throws ReflectionException {
try {
return method.invoke(obj, args);
} catch (IllegalArgumentException e) {
throw new ReflectionException("Illegal argument(s) supplied to method: " + getName(), e);
}
}
/** Returns true if the method includes an annotation of the provided class type. */
public boolean isAnnotationPresent (Class<? extends java.lang.annotation.Annotation> annotationType) {
java.lang.annotation.Annotation[] annotations = method.getDeclaredAnnotations();
if (annotations != null) {
for (java.lang.annotation.Annotation annotation : annotations) {
if (annotation.annotationType().equals(annotationType)) {
return true;
}
}
}
return false;
}
/** Returns an array of {@link Annotation} objects reflecting all annotations declared by this method,
* or an empty array if there are none. Does not include inherited annotations.
* Does not include parameter annotations. */
public Annotation[] getDeclaredAnnotations () {
java.lang.annotation.Annotation[] annotations = method.getDeclaredAnnotations();
if (annotations == null)
return new Annotation[0];
Annotation[] result = new Annotation[annotations.length];
for (int i = 0; i < annotations.length; i++) {
result[i] = new Annotation(annotations[i]);
}
return result;
}
/** Returns an {@link Annotation} object reflecting the annotation provided, or null of this method doesn't
* have such an annotation. This is a convenience function if the caller knows already which annotation
* type he's looking for. */
public Annotation getDeclaredAnnotation (Class<? extends java.lang.annotation.Annotation> annotationType) {
java.lang.annotation.Annotation[] annotations = method.getDeclaredAnnotations();
if (annotations == null)
return null;
for (java.lang.annotation.Annotation annotation : annotations) {
if (annotation.annotationType().equals(annotationType)) {
return new Annotation(annotation);
}
}
return null;
}
}
| apache-2.0 |
ryanj/origin | vendor/github.com/docker/docker/daemon/health.go | 10905 | package daemon
import (
"bytes"
"fmt"
"runtime"
"strings"
"sync"
"time"
"golang.org/x/net/context"
"github.com/docker/docker/api/types"
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/strslice"
"github.com/docker/docker/container"
"github.com/docker/docker/daemon/exec"
"github.com/sirupsen/logrus"
)
const (
// Longest healthcheck probe output message to store. Longer messages will be truncated.
maxOutputLen = 4096
// Default interval between probe runs (from the end of the first to the start of the second).
// Also the time before the first probe.
defaultProbeInterval = 30 * time.Second
// The maximum length of time a single probe run should take. If the probe takes longer
// than this, the check is considered to have failed.
defaultProbeTimeout = 30 * time.Second
// The time given for the container to start before the health check starts considering
// the container unstable. Defaults to none.
defaultStartPeriod = 0 * time.Second
// Default number of consecutive failures of the health check
// for the container to be considered unhealthy.
defaultProbeRetries = 3
// Maximum number of entries to record
maxLogEntries = 5
)
const (
// Exit status codes that can be returned by the probe command.
exitStatusHealthy = 0 // Container is healthy
)
// probe implementations know how to run a particular type of probe.
type probe interface {
// Perform one run of the check. Returns the exit code and an optional
// short diagnostic string.
run(context.Context, *Daemon, *container.Container) (*types.HealthcheckResult, error)
}
// cmdProbe implements the "CMD" probe type.
type cmdProbe struct {
// Run the command with the system's default shell instead of execing it directly.
shell bool
}
// exec the healthcheck command in the container.
// Returns the exit code and probe output (if any)
func (p *cmdProbe) run(ctx context.Context, d *Daemon, cntr *container.Container) (*types.HealthcheckResult, error) {
cmdSlice := strslice.StrSlice(cntr.Config.Healthcheck.Test)[1:]
if p.shell {
cmdSlice = append(getShell(cntr.Config), cmdSlice...)
}
entrypoint, args := d.getEntrypointAndArgs(strslice.StrSlice{}, cmdSlice)
execConfig := exec.NewConfig()
execConfig.OpenStdin = false
execConfig.OpenStdout = true
execConfig.OpenStderr = true
execConfig.ContainerID = cntr.ID
execConfig.DetachKeys = []byte{}
execConfig.Entrypoint = entrypoint
execConfig.Args = args
execConfig.Tty = false
execConfig.Privileged = false
execConfig.User = cntr.Config.User
linkedEnv, err := d.setupLinkedContainers(cntr)
if err != nil {
return nil, err
}
execConfig.Env = container.ReplaceOrAppendEnvValues(cntr.CreateDaemonEnvironment(execConfig.Tty, linkedEnv), execConfig.Env)
d.registerExecCommand(cntr, execConfig)
d.LogContainerEvent(cntr, "exec_create: "+execConfig.Entrypoint+" "+strings.Join(execConfig.Args, " "))
output := &limitedBuffer{}
err = d.ContainerExecStart(ctx, execConfig.ID, nil, output, output)
if err != nil {
return nil, err
}
info, err := d.getExecConfig(execConfig.ID)
if err != nil {
return nil, err
}
if info.ExitCode == nil {
return nil, fmt.Errorf("healthcheck for container %s has no exit code", cntr.ID)
}
// Note: Go's json package will handle invalid UTF-8 for us
out := output.String()
return &types.HealthcheckResult{
End: time.Now(),
ExitCode: *info.ExitCode,
Output: out,
}, nil
}
// Update the container's Status.Health struct based on the latest probe's result.
func handleProbeResult(d *Daemon, c *container.Container, result *types.HealthcheckResult, done chan struct{}) {
c.Lock()
defer c.Unlock()
// probe may have been cancelled while waiting on lock. Ignore result then
select {
case <-done:
return
default:
}
retries := c.Config.Healthcheck.Retries
if retries <= 0 {
retries = defaultProbeRetries
}
h := c.State.Health
oldStatus := h.Status
if len(h.Log) >= maxLogEntries {
h.Log = append(h.Log[len(h.Log)+1-maxLogEntries:], result)
} else {
h.Log = append(h.Log, result)
}
if result.ExitCode == exitStatusHealthy {
h.FailingStreak = 0
h.Status = types.Healthy
} else { // Failure (including invalid exit code)
shouldIncrementStreak := true
// If the container is starting (i.e. we never had a successful health check)
// then we check if we are within the start period of the container in which
// case we do not increment the failure streak.
if h.Status == types.Starting {
startPeriod := timeoutWithDefault(c.Config.Healthcheck.StartPeriod, defaultStartPeriod)
timeSinceStart := result.Start.Sub(c.State.StartedAt)
// If still within the start period, then don't increment failing streak.
if timeSinceStart < startPeriod {
shouldIncrementStreak = false
}
}
if shouldIncrementStreak {
h.FailingStreak++
if h.FailingStreak >= retries {
h.Status = types.Unhealthy
}
}
// Else we're starting or healthy. Stay in that state.
}
// replicate Health status changes
if err := c.CheckpointTo(d.containersReplica); err != nil {
// queries will be inconsistent until the next probe runs or other state mutations
// checkpoint the container
logrus.Errorf("Error replicating health state for container %s: %v", c.ID, err)
}
if oldStatus != h.Status {
d.LogContainerEvent(c, "health_status: "+h.Status)
}
}
// Run the container's monitoring thread until notified via "stop".
// There is never more than one monitor thread running per container at a time.
func monitor(d *Daemon, c *container.Container, stop chan struct{}, probe probe) {
probeTimeout := timeoutWithDefault(c.Config.Healthcheck.Timeout, defaultProbeTimeout)
probeInterval := timeoutWithDefault(c.Config.Healthcheck.Interval, defaultProbeInterval)
for {
select {
case <-stop:
logrus.Debugf("Stop healthcheck monitoring for container %s (received while idle)", c.ID)
return
case <-time.After(probeInterval):
logrus.Debugf("Running health check for container %s ...", c.ID)
startTime := time.Now()
ctx, cancelProbe := context.WithTimeout(context.Background(), probeTimeout)
results := make(chan *types.HealthcheckResult, 1)
go func() {
healthChecksCounter.Inc()
result, err := probe.run(ctx, d, c)
if err != nil {
healthChecksFailedCounter.Inc()
logrus.Warnf("Health check for container %s error: %v", c.ID, err)
results <- &types.HealthcheckResult{
ExitCode: -1,
Output: err.Error(),
Start: startTime,
End: time.Now(),
}
} else {
result.Start = startTime
logrus.Debugf("Health check for container %s done (exitCode=%d)", c.ID, result.ExitCode)
results <- result
}
close(results)
}()
select {
case <-stop:
logrus.Debugf("Stop healthcheck monitoring for container %s (received while probing)", c.ID)
cancelProbe()
// Wait for probe to exit (it might take a while to respond to the TERM
// signal and we don't want dying probes to pile up).
<-results
return
case result := <-results:
handleProbeResult(d, c, result, stop)
// Stop timeout
cancelProbe()
case <-ctx.Done():
logrus.Debugf("Health check for container %s taking too long", c.ID)
handleProbeResult(d, c, &types.HealthcheckResult{
ExitCode: -1,
Output: fmt.Sprintf("Health check exceeded timeout (%v)", probeTimeout),
Start: startTime,
End: time.Now(),
}, stop)
cancelProbe()
// Wait for probe to exit (it might take a while to respond to the TERM
// signal and we don't want dying probes to pile up).
<-results
}
}
}
}
// Get a suitable probe implementation for the container's healthcheck configuration.
// Nil will be returned if no healthcheck was configured or NONE was set.
func getProbe(c *container.Container) probe {
config := c.Config.Healthcheck
if config == nil || len(config.Test) == 0 {
return nil
}
switch config.Test[0] {
case "CMD":
return &cmdProbe{shell: false}
case "CMD-SHELL":
return &cmdProbe{shell: true}
default:
logrus.Warnf("Unknown healthcheck type '%s' (expected 'CMD') in container %s", config.Test[0], c.ID)
return nil
}
}
// Ensure the health-check monitor is running or not, depending on the current
// state of the container.
// Called from monitor.go, with c locked.
func (d *Daemon) updateHealthMonitor(c *container.Container) {
h := c.State.Health
if h == nil {
return // No healthcheck configured
}
probe := getProbe(c)
wantRunning := c.Running && !c.Paused && probe != nil
if wantRunning {
if stop := h.OpenMonitorChannel(); stop != nil {
go monitor(d, c, stop, probe)
}
} else {
h.CloseMonitorChannel()
}
}
// Reset the health state for a newly-started, restarted or restored container.
// initHealthMonitor is called from monitor.go and we should never be running
// two instances at once.
// Called with c locked.
func (d *Daemon) initHealthMonitor(c *container.Container) {
// If no healthcheck is setup then don't init the monitor
if getProbe(c) == nil {
return
}
// This is needed in case we're auto-restarting
d.stopHealthchecks(c)
if h := c.State.Health; h != nil {
h.Status = types.Starting
h.FailingStreak = 0
} else {
h := &container.Health{}
h.Status = types.Starting
c.State.Health = h
}
d.updateHealthMonitor(c)
}
// Called when the container is being stopped (whether because the health check is
// failing or for any other reason).
func (d *Daemon) stopHealthchecks(c *container.Container) {
h := c.State.Health
if h != nil {
h.CloseMonitorChannel()
}
}
// Buffer up to maxOutputLen bytes. Further data is discarded.
type limitedBuffer struct {
buf bytes.Buffer
mu sync.Mutex
truncated bool // indicates that data has been lost
}
// Append to limitedBuffer while there is room.
func (b *limitedBuffer) Write(data []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
bufLen := b.buf.Len()
dataLen := len(data)
keep := min(maxOutputLen-bufLen, dataLen)
if keep > 0 {
b.buf.Write(data[:keep])
}
if keep < dataLen {
b.truncated = true
}
return dataLen, nil
}
// The contents of the buffer, with "..." appended if it overflowed.
func (b *limitedBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
out := b.buf.String()
if b.truncated {
out = out + "..."
}
return out
}
// If configuredValue is zero, use defaultValue instead.
func timeoutWithDefault(configuredValue time.Duration, defaultValue time.Duration) time.Duration {
if configuredValue == 0 {
return defaultValue
}
return configuredValue
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
func getShell(config *containertypes.Config) []string {
if len(config.Shell) != 0 {
return config.Shell
}
if runtime.GOOS != "windows" {
return []string{"/bin/sh", "-c"}
}
return []string{"cmd", "/S", "/C"}
}
| apache-2.0 |
vitorgalvao/homebrew-cask | Casks/snippet-edit.rb | 457 | cask 'snippet-edit' do
version '1.2.1'
sha256 '2a6ee1b3ecd5d5d84743be9d81b36e969f05fe40209d8877008dc6f60d95d37c'
url "http://cocoaholic.com/downloads/snippet_edit/Snippet_Edit_#{version}.zip"
appcast 'http://cocoaholic.com/sparkle/snippet_edit/sparkle.xml',
checkpoint: 'd8bcf3fc1b2c9648af174988789d2034662d047cf3f9a860f4ccf05fca665f59'
name 'Snippet Edit'
homepage 'http://cocoaholic.com/snippet_edit/'
app 'Snippet Edit.app'
end
| bsd-2-clause |
Raffaello/discOpt | eigen/doc/snippets/Jacobi_makeJacobi.cpp | 292 | Matrix2f m = Matrix2f::Random();
m = (m + m.adjoint()).eval();
JacobiRotation<float> J;
J.makeJacobi(m, 0, 1);
cout << "Here is the matrix m:" << endl << m << endl;
m.applyOnTheLeft(0, 1, J.adjoint());
m.applyOnTheRight(0, 1, J);
cout << "Here is the matrix J' * m * J:" << endl << m << endl; | gpl-2.0 |
myusufe/Job | public/_lib/smarty/libs/sysplugins/smarty_internal_templateparser.php | 158712 | <?php
/**
* Smarty Internal Plugin Templateparser
*
* This is the template parser.
* It is generated from the internal.templateparser.y file
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
class TP_yyToken implements ArrayAccess
{
public $string = '';
public $metadata = array();
public function __construct($s, $m = array())
{
if ($s instanceof TP_yyToken) {
$this->string = $s->string;
$this->metadata = $s->metadata;
} else {
$this->string = (string) $s;
if ($m instanceof TP_yyToken) {
$this->metadata = $m->metadata;
} elseif (is_array($m)) {
$this->metadata = $m;
}
}
}
public function __toString()
{
return $this->_string;
}
public function offsetExists($offset)
{
return isset($this->metadata[$offset]);
}
public function offsetGet($offset)
{
return $this->metadata[$offset];
}
public function offsetSet($offset, $value)
{
if ($offset === null) {
if (isset($value[0])) {
$x = ($value instanceof TP_yyToken) ?
$value->metadata : $value;
$this->metadata = array_merge($this->metadata, $x);
return;
}
$offset = count($this->metadata);
}
if ($value === null) {
return;
}
if ($value instanceof TP_yyToken) {
if ($value->metadata) {
$this->metadata[$offset] = $value->metadata;
}
} elseif ($value) {
$this->metadata[$offset] = $value;
}
}
public function offsetUnset($offset)
{
unset($this->metadata[$offset]);
}
}
class TP_yyStackEntry
{
public $stateno; /* The state-number */
public $major; /* The major token value. This is the code
** number for the token at this stack level */
public $minor; /* The user-supplied minor token value. This
** is the value of the token */
};
#line 13 "smarty_internal_templateparser.y"
class Smarty_Internal_Templateparser#line 80 "smarty_internal_templateparser.php"
{
#line 15 "smarty_internal_templateparser.y"
const Err1 = "Security error: Call to private object member not allowed";
const Err2 = "Security error: Call to dynamic object member not allowed";
const Err3 = "PHP in template not allowed. Use SmartyBC to enable it";
// states whether the parse was successful or not
public $successful = true;
public $retvalue = 0;
public static $prefix_number = 0;
private $lex;
private $internalError = false;
private $strip = false;
function __construct($lex, $compiler) {
$this->lex = $lex;
$this->compiler = $compiler;
$this->smarty = $this->compiler->smarty;
$this->template = $this->compiler->template;
$this->compiler->has_variable_string = false;
$this->compiler->prefix_code = array();
$this->block_nesting_level = 0;
if ($this->security = isset($this->smarty->security_policy)) {
$this->php_handling = $this->smarty->security_policy->php_handling;
} else {
$this->php_handling = $this->smarty->php_handling;
}
$this->is_xml = false;
$this->asp_tags = (ini_get('asp_tags') != '0');
$this->current_buffer = $this->root_buffer = new _smarty_template_buffer($this);
}
public static function escape_start_tag($tag_text) {
$tag = preg_replace('/\A<\?(.*)\z/', '<<?php ?>?\1', $tag_text, -1 , $count); //Escape tag
return $tag;
}
public static function escape_end_tag($tag_text) {
return '?<?php ?>>';
}
public function compileVariable($variable) {
if (strpos($variable,'(') == 0) {
// not a variable variable
$var = trim($variable,'\'');
$this->compiler->tag_nocache=$this->compiler->tag_nocache|$this->template->getVariable($var, null, true, false)->nocache;
$this->template->properties['variables'][$var] = $this->compiler->tag_nocache|$this->compiler->nocache;
}
// return '(isset($_smarty_tpl->tpl_vars['. $variable .'])?$_smarty_tpl->tpl_vars['. $variable .']->value:$_smarty_tpl->getVariable('. $variable .')->value)';
return '$_smarty_tpl->tpl_vars['. $variable .']->value';
}
#line 133 "smarty_internal_templateparser.php"
const TP_VERT = 1;
const TP_COLON = 2;
const TP_RDEL = 3;
const TP_COMMENT = 4;
const TP_PHPSTARTTAG = 5;
const TP_PHPENDTAG = 6;
const TP_ASPSTARTTAG = 7;
const TP_ASPENDTAG = 8;
const TP_FAKEPHPSTARTTAG = 9;
const TP_XMLTAG = 10;
const TP_TEXT = 11;
const TP_STRIPON = 12;
const TP_STRIPOFF = 13;
const TP_BLOCKSOURCE = 14;
const TP_LITERALSTART = 15;
const TP_LITERALEND = 16;
const TP_LITERAL = 17;
const TP_LDEL = 18;
const TP_DOLLAR = 19;
const TP_ID = 20;
const TP_EQUAL = 21;
const TP_PTR = 22;
const TP_LDELIF = 23;
const TP_LDELFOR = 24;
const TP_SEMICOLON = 25;
const TP_INCDEC = 26;
const TP_TO = 27;
const TP_STEP = 28;
const TP_LDELFOREACH = 29;
const TP_SPACE = 30;
const TP_AS = 31;
const TP_APTR = 32;
const TP_LDELSETFILTER = 33;
const TP_SMARTYBLOCKCHILDPARENT = 34;
const TP_LDELSLASH = 35;
const TP_ATTR = 36;
const TP_INTEGER = 37;
const TP_COMMA = 38;
const TP_OPENP = 39;
const TP_CLOSEP = 40;
const TP_MATH = 41;
const TP_UNIMATH = 42;
const TP_ANDSYM = 43;
const TP_ISIN = 44;
const TP_ISDIVBY = 45;
const TP_ISNOTDIVBY = 46;
const TP_ISEVEN = 47;
const TP_ISNOTEVEN = 48;
const TP_ISEVENBY = 49;
const TP_ISNOTEVENBY = 50;
const TP_ISODD = 51;
const TP_ISNOTODD = 52;
const TP_ISODDBY = 53;
const TP_ISNOTODDBY = 54;
const TP_INSTANCEOF = 55;
const TP_QMARK = 56;
const TP_NOT = 57;
const TP_TYPECAST = 58;
const TP_HEX = 59;
const TP_DOT = 60;
const TP_SINGLEQUOTESTRING = 61;
const TP_DOUBLECOLON = 62;
const TP_AT = 63;
const TP_HATCH = 64;
const TP_OPENB = 65;
const TP_CLOSEB = 66;
const TP_EQUALS = 67;
const TP_NOTEQUALS = 68;
const TP_GREATERTHAN = 69;
const TP_LESSTHAN = 70;
const TP_GREATEREQUAL = 71;
const TP_LESSEQUAL = 72;
const TP_IDENTITY = 73;
const TP_NONEIDENTITY = 74;
const TP_MOD = 75;
const TP_LAND = 76;
const TP_LOR = 77;
const TP_LXOR = 78;
const TP_QUOTE = 79;
const TP_BACKTICK = 80;
const TP_DOLLARID = 81;
const YY_NO_ACTION = 570;
const YY_ACCEPT_ACTION = 569;
const YY_ERROR_ACTION = 568;
const YY_SZ_ACTTAB = 2407;
static public $yy_action = array(
/* 0 */ 219, 309, 305, 301, 302, 303, 304, 310, 311, 317,
/* 10 */ 318, 319, 201, 30, 273, 9, 33, 238, 280, 15,
/* 20 */ 5, 108, 235, 234, 220, 7, 126, 42, 30, 30,
/* 30 */ 259, 211, 256, 495, 15, 15, 10, 33, 495, 280,
/* 40 */ 46, 47, 51, 45, 24, 14, 352, 353, 39, 37,
/* 50 */ 278, 359, 12, 25, 219, 219, 326, 434, 219, 192,
/* 60 */ 434, 569, 95, 263, 227, 306, 360, 361, 358, 357,
/* 70 */ 354, 355, 356, 342, 341, 328, 329, 330, 292, 219,
/* 80 */ 202, 322, 242, 30, 434, 231, 207, 434, 143, 15,
/* 90 */ 434, 35, 158, 434, 46, 47, 51, 45, 24, 14,
/* 100 */ 352, 353, 39, 37, 278, 359, 12, 25, 219, 48,
/* 110 */ 32, 219, 48, 391, 196, 2, 31, 138, 321, 4,
/* 120 */ 360, 361, 358, 357, 354, 355, 356, 342, 341, 328,
/* 130 */ 329, 330, 127, 48, 290, 349, 251, 30, 145, 140,
/* 140 */ 30, 207, 264, 15, 200, 322, 15, 334, 46, 47,
/* 150 */ 51, 45, 24, 14, 352, 353, 39, 37, 278, 359,
/* 160 */ 12, 25, 219, 289, 219, 48, 431, 297, 219, 33,
/* 170 */ 396, 280, 18, 191, 360, 361, 358, 357, 354, 355,
/* 180 */ 356, 342, 341, 328, 329, 330, 300, 285, 286, 287,
/* 190 */ 299, 206, 219, 431, 428, 194, 201, 315, 314, 431,
/* 200 */ 207, 281, 46, 47, 51, 45, 24, 14, 352, 353,
/* 210 */ 39, 37, 278, 359, 12, 25, 219, 33, 48, 280,
/* 220 */ 34, 30, 48, 197, 322, 276, 158, 15, 360, 361,
/* 230 */ 358, 357, 354, 355, 356, 342, 341, 328, 329, 330,
/* 240 */ 230, 338, 16, 289, 103, 179, 244, 219, 295, 2,
/* 250 */ 41, 33, 265, 280, 283, 148, 46, 47, 51, 45,
/* 260 */ 24, 14, 352, 353, 39, 37, 278, 359, 12, 25,
/* 270 */ 219, 207, 145, 43, 132, 189, 109, 333, 307, 227,
/* 280 */ 306, 190, 360, 361, 358, 357, 354, 355, 356, 342,
/* 290 */ 341, 328, 329, 330, 20, 22, 248, 339, 219, 99,
/* 300 */ 174, 48, 324, 33, 346, 280, 18, 288, 207, 283,
/* 310 */ 46, 47, 51, 45, 24, 14, 352, 353, 39, 37,
/* 320 */ 278, 359, 12, 25, 219, 289, 207, 30, 41, 110,
/* 330 */ 275, 2, 41, 15, 272, 266, 360, 361, 358, 357,
/* 340 */ 354, 355, 356, 342, 341, 328, 329, 330, 242, 40,
/* 350 */ 236, 347, 104, 177, 145, 219, 44, 316, 148, 135,
/* 360 */ 228, 27, 283, 269, 46, 47, 51, 45, 24, 14,
/* 370 */ 352, 353, 39, 37, 278, 359, 12, 25, 219, 207,
/* 380 */ 208, 33, 7, 280, 245, 239, 136, 173, 241, 279,
/* 390 */ 360, 361, 358, 357, 354, 355, 356, 342, 341, 328,
/* 400 */ 329, 330, 29, 158, 106, 13, 122, 171, 181, 6,
/* 410 */ 33, 15, 226, 33, 219, 237, 283, 283, 46, 47,
/* 420 */ 51, 45, 24, 14, 352, 353, 39, 37, 278, 359,
/* 430 */ 12, 25, 219, 205, 205, 252, 313, 238, 312, 235,
/* 440 */ 232, 195, 97, 127, 360, 361, 358, 357, 354, 355,
/* 450 */ 356, 342, 341, 328, 329, 330, 28, 320, 230, 105,
/* 460 */ 182, 164, 176, 33, 279, 254, 282, 186, 207, 283,
/* 470 */ 283, 253, 46, 47, 51, 45, 24, 14, 352, 353,
/* 480 */ 39, 37, 278, 359, 12, 25, 219, 205, 260, 107,
/* 490 */ 235, 262, 33, 193, 214, 332, 166, 198, 360, 361,
/* 500 */ 358, 357, 354, 355, 356, 342, 341, 328, 329, 330,
/* 510 */ 137, 175, 167, 291, 308, 344, 185, 261, 267, 161,
/* 520 */ 283, 283, 128, 337, 124, 283, 46, 47, 51, 45,
/* 530 */ 24, 14, 352, 353, 39, 37, 278, 359, 12, 25,
/* 540 */ 219, 38, 205, 203, 141, 169, 257, 134, 35, 130,
/* 550 */ 156, 114, 360, 361, 358, 357, 354, 355, 356, 342,
/* 560 */ 341, 328, 329, 330, 320, 158, 320, 241, 36, 293,
/* 570 */ 298, 94, 21, 26, 284, 219, 292, 168, 271, 162,
/* 580 */ 46, 47, 51, 45, 24, 14, 352, 353, 39, 37,
/* 590 */ 278, 359, 12, 25, 219, 279, 229, 205, 44, 281,
/* 600 */ 187, 17, 270, 331, 98, 127, 360, 361, 358, 357,
/* 610 */ 354, 355, 356, 342, 341, 328, 329, 330, 199, 320,
/* 620 */ 331, 331, 331, 331, 331, 331, 331, 331, 331, 331,
/* 630 */ 331, 331, 331, 331, 46, 47, 51, 45, 24, 14,
/* 640 */ 352, 353, 39, 37, 278, 359, 12, 25, 219, 331,
/* 650 */ 268, 331, 331, 331, 331, 331, 331, 331, 125, 115,
/* 660 */ 360, 361, 358, 357, 354, 355, 356, 342, 341, 328,
/* 670 */ 329, 330, 279, 331, 320, 331, 331, 331, 331, 331,
/* 680 */ 331, 331, 331, 331, 331, 331, 331, 331, 46, 47,
/* 690 */ 51, 45, 24, 14, 352, 353, 39, 37, 278, 359,
/* 700 */ 12, 25, 219, 331, 204, 331, 331, 331, 331, 331,
/* 710 */ 331, 159, 100, 116, 360, 361, 358, 357, 354, 355,
/* 720 */ 356, 342, 341, 328, 329, 330, 320, 320, 320, 331,
/* 730 */ 331, 331, 331, 331, 331, 331, 331, 331, 331, 331,
/* 740 */ 331, 331, 46, 47, 51, 45, 24, 14, 352, 353,
/* 750 */ 39, 37, 278, 359, 12, 25, 219, 331, 331, 331,
/* 760 */ 331, 331, 331, 331, 331, 102, 117, 331, 360, 361,
/* 770 */ 358, 357, 354, 355, 356, 342, 341, 328, 329, 330,
/* 780 */ 320, 320, 331, 331, 331, 331, 331, 331, 331, 331,
/* 790 */ 331, 331, 331, 331, 331, 331, 46, 47, 51, 45,
/* 800 */ 24, 14, 352, 353, 39, 37, 278, 359, 12, 25,
/* 810 */ 331, 331, 331, 331, 331, 331, 331, 331, 331, 331,
/* 820 */ 158, 331, 360, 361, 358, 357, 354, 355, 356, 342,
/* 830 */ 341, 328, 329, 330, 331, 331, 331, 331, 46, 47,
/* 840 */ 51, 45, 24, 14, 352, 353, 39, 37, 278, 359,
/* 850 */ 12, 25, 331, 331, 331, 331, 331, 331, 211, 331,
/* 860 */ 331, 331, 331, 10, 360, 361, 358, 357, 354, 355,
/* 870 */ 356, 342, 341, 328, 329, 330, 331, 331, 331, 331,
/* 880 */ 331, 331, 331, 9, 142, 212, 331, 331, 5, 108,
/* 890 */ 331, 246, 331, 331, 126, 157, 183, 331, 259, 123,
/* 900 */ 256, 331, 250, 331, 23, 283, 331, 52, 277, 331,
/* 910 */ 331, 255, 350, 348, 331, 345, 331, 279, 180, 178,
/* 920 */ 331, 331, 49, 50, 296, 240, 351, 283, 283, 106,
/* 930 */ 1, 274, 331, 147, 331, 331, 331, 331, 331, 279,
/* 940 */ 279, 9, 144, 92, 96, 233, 5, 108, 331, 345,
/* 950 */ 331, 331, 126, 331, 331, 246, 259, 323, 256, 146,
/* 960 */ 250, 331, 23, 123, 184, 52, 331, 331, 331, 331,
/* 970 */ 246, 331, 343, 283, 153, 255, 350, 348, 123, 345,
/* 980 */ 49, 50, 296, 240, 351, 279, 331, 106, 1, 331,
/* 990 */ 255, 350, 348, 331, 345, 33, 331, 280, 331, 9,
/* 1000 */ 142, 224, 96, 331, 5, 108, 331, 30, 331, 247,
/* 1010 */ 126, 246, 331, 15, 259, 149, 256, 331, 250, 123,
/* 1020 */ 23, 331, 331, 52, 331, 331, 331, 331, 331, 331,
/* 1030 */ 331, 255, 350, 348, 331, 345, 331, 331, 49, 50,
/* 1040 */ 296, 240, 351, 331, 331, 106, 1, 331, 331, 331,
/* 1050 */ 331, 331, 33, 331, 280, 331, 331, 9, 135, 224,
/* 1060 */ 96, 331, 5, 108, 30, 246, 258, 331, 126, 151,
/* 1070 */ 15, 246, 259, 123, 256, 154, 250, 331, 11, 123,
/* 1080 */ 331, 52, 331, 331, 331, 255, 350, 348, 331, 345,
/* 1090 */ 331, 255, 350, 348, 331, 345, 49, 50, 296, 240,
/* 1100 */ 351, 331, 331, 106, 1, 331, 331, 331, 331, 331,
/* 1110 */ 331, 331, 331, 331, 331, 9, 142, 210, 96, 331,
/* 1120 */ 5, 108, 331, 331, 331, 331, 126, 246, 331, 331,
/* 1130 */ 259, 155, 256, 331, 216, 123, 23, 331, 331, 52,
/* 1140 */ 331, 331, 331, 331, 331, 331, 331, 255, 350, 348,
/* 1150 */ 331, 345, 331, 331, 49, 50, 296, 240, 351, 331,
/* 1160 */ 331, 106, 1, 331, 331, 331, 331, 331, 331, 331,
/* 1170 */ 331, 331, 331, 9, 131, 224, 96, 331, 5, 108,
/* 1180 */ 331, 331, 331, 331, 126, 246, 331, 331, 259, 152,
/* 1190 */ 256, 331, 250, 123, 3, 331, 331, 52, 331, 331,
/* 1200 */ 331, 331, 331, 331, 331, 255, 350, 348, 331, 345,
/* 1210 */ 331, 331, 49, 50, 296, 240, 351, 331, 331, 106,
/* 1220 */ 1, 331, 331, 331, 331, 331, 331, 331, 331, 331,
/* 1230 */ 331, 9, 142, 213, 96, 331, 5, 108, 331, 331,
/* 1240 */ 331, 331, 126, 246, 331, 331, 259, 150, 256, 331,
/* 1250 */ 250, 123, 23, 331, 331, 52, 331, 331, 331, 331,
/* 1260 */ 331, 331, 331, 255, 350, 348, 331, 345, 331, 331,
/* 1270 */ 49, 50, 296, 240, 351, 331, 331, 106, 1, 331,
/* 1280 */ 219, 331, 401, 331, 331, 331, 331, 331, 331, 9,
/* 1290 */ 142, 209, 96, 331, 5, 108, 331, 331, 331, 331,
/* 1300 */ 126, 249, 331, 331, 259, 331, 256, 331, 250, 30,
/* 1310 */ 23, 190, 163, 52, 331, 15, 331, 331, 2, 331,
/* 1320 */ 331, 283, 331, 331, 20, 22, 331, 331, 49, 50,
/* 1330 */ 296, 240, 351, 331, 331, 106, 1, 331, 207, 331,
/* 1340 */ 331, 145, 331, 331, 331, 432, 331, 9, 139, 224,
/* 1350 */ 96, 331, 5, 108, 331, 331, 331, 331, 126, 331,
/* 1360 */ 331, 331, 259, 243, 256, 331, 250, 331, 23, 190,
/* 1370 */ 188, 52, 432, 331, 331, 331, 331, 331, 432, 283,
/* 1380 */ 331, 2, 20, 22, 331, 331, 49, 50, 296, 240,
/* 1390 */ 351, 331, 331, 106, 1, 331, 207, 331, 331, 331,
/* 1400 */ 331, 331, 331, 331, 145, 9, 135, 224, 96, 331,
/* 1410 */ 5, 108, 331, 331, 331, 331, 126, 331, 331, 331,
/* 1420 */ 259, 331, 256, 331, 250, 331, 11, 101, 160, 52,
/* 1430 */ 331, 331, 331, 331, 331, 331, 331, 283, 331, 331,
/* 1440 */ 20, 22, 331, 331, 49, 50, 296, 240, 351, 331,
/* 1450 */ 331, 106, 331, 331, 207, 331, 331, 331, 331, 331,
/* 1460 */ 331, 331, 331, 9, 135, 225, 96, 331, 5, 108,
/* 1470 */ 331, 331, 331, 331, 126, 331, 331, 331, 259, 331,
/* 1480 */ 256, 331, 250, 331, 11, 331, 477, 52, 331, 331,
/* 1490 */ 331, 331, 331, 331, 331, 331, 331, 331, 331, 331,
/* 1500 */ 331, 331, 49, 50, 296, 240, 351, 331, 477, 106,
/* 1510 */ 477, 477, 331, 477, 477, 331, 331, 331, 331, 477,
/* 1520 */ 331, 477, 2, 477, 96, 331, 331, 331, 331, 331,
/* 1530 */ 331, 331, 331, 331, 331, 246, 331, 331, 477, 120,
/* 1540 */ 331, 331, 84, 123, 331, 145, 331, 331, 331, 477,
/* 1550 */ 331, 294, 327, 331, 331, 255, 350, 348, 331, 345,
/* 1560 */ 331, 331, 331, 477, 331, 331, 331, 246, 331, 218,
/* 1570 */ 362, 120, 331, 331, 84, 123, 331, 331, 331, 331,
/* 1580 */ 331, 331, 331, 294, 327, 331, 331, 255, 350, 348,
/* 1590 */ 246, 345, 331, 331, 129, 331, 331, 61, 119, 232,
/* 1600 */ 331, 246, 335, 331, 331, 129, 294, 327, 80, 123,
/* 1610 */ 255, 350, 348, 331, 345, 331, 331, 294, 327, 331,
/* 1620 */ 331, 255, 350, 348, 331, 345, 246, 331, 331, 331,
/* 1630 */ 129, 331, 215, 80, 123, 331, 331, 331, 331, 331,
/* 1640 */ 331, 331, 294, 327, 331, 331, 255, 350, 348, 331,
/* 1650 */ 345, 331, 331, 331, 246, 190, 170, 221, 129, 331,
/* 1660 */ 331, 55, 119, 133, 331, 283, 331, 331, 20, 22,
/* 1670 */ 294, 327, 331, 331, 255, 350, 348, 246, 345, 331,
/* 1680 */ 331, 129, 207, 331, 80, 123, 331, 331, 331, 331,
/* 1690 */ 331, 331, 331, 294, 327, 331, 246, 255, 350, 348,
/* 1700 */ 129, 345, 331, 89, 123, 331, 331, 331, 223, 331,
/* 1710 */ 331, 331, 294, 327, 331, 331, 255, 350, 348, 246,
/* 1720 */ 345, 331, 331, 129, 331, 331, 70, 123, 331, 331,
/* 1730 */ 246, 331, 331, 331, 111, 294, 327, 67, 123, 255,
/* 1740 */ 350, 348, 331, 345, 331, 331, 294, 327, 331, 246,
/* 1750 */ 255, 350, 348, 129, 345, 331, 86, 123, 331, 331,
/* 1760 */ 331, 331, 331, 331, 331, 294, 327, 331, 246, 255,
/* 1770 */ 350, 348, 129, 345, 331, 90, 123, 331, 331, 331,
/* 1780 */ 331, 331, 331, 331, 294, 327, 331, 246, 255, 350,
/* 1790 */ 348, 129, 345, 331, 77, 123, 331, 331, 331, 331,
/* 1800 */ 331, 331, 331, 294, 327, 331, 246, 255, 350, 348,
/* 1810 */ 129, 345, 331, 74, 123, 331, 331, 246, 331, 331,
/* 1820 */ 331, 129, 294, 327, 66, 123, 255, 350, 348, 331,
/* 1830 */ 345, 331, 331, 294, 327, 331, 246, 222, 350, 348,
/* 1840 */ 129, 345, 331, 69, 123, 331, 331, 331, 331, 331,
/* 1850 */ 331, 331, 294, 327, 331, 246, 255, 350, 348, 129,
/* 1860 */ 345, 331, 78, 123, 331, 331, 331, 331, 331, 331,
/* 1870 */ 331, 294, 327, 331, 246, 255, 350, 348, 129, 345,
/* 1880 */ 331, 60, 123, 331, 331, 331, 331, 331, 331, 331,
/* 1890 */ 294, 327, 331, 246, 255, 350, 348, 129, 345, 331,
/* 1900 */ 53, 123, 331, 331, 246, 331, 331, 331, 129, 294,
/* 1910 */ 327, 65, 123, 255, 350, 348, 331, 345, 331, 331,
/* 1920 */ 294, 327, 336, 331, 255, 350, 348, 331, 345, 8,
/* 1930 */ 331, 331, 331, 331, 5, 108, 331, 331, 331, 331,
/* 1940 */ 126, 331, 331, 246, 259, 331, 256, 129, 331, 331,
/* 1950 */ 72, 123, 331, 331, 331, 331, 331, 331, 331, 294,
/* 1960 */ 327, 331, 246, 255, 350, 348, 129, 345, 331, 85,
/* 1970 */ 123, 331, 331, 331, 331, 331, 331, 331, 294, 327,
/* 1980 */ 331, 246, 255, 350, 348, 129, 345, 331, 81, 123,
/* 1990 */ 331, 19, 340, 331, 331, 331, 331, 294, 327, 331,
/* 2000 */ 246, 255, 350, 348, 113, 345, 331, 82, 123, 331,
/* 2010 */ 331, 246, 331, 331, 331, 93, 294, 327, 54, 121,
/* 2020 */ 255, 350, 348, 331, 345, 331, 331, 294, 327, 331,
/* 2030 */ 246, 217, 350, 348, 129, 345, 331, 58, 123, 331,
/* 2040 */ 331, 331, 331, 331, 331, 331, 294, 327, 331, 336,
/* 2050 */ 255, 350, 348, 331, 345, 331, 8, 331, 331, 331,
/* 2060 */ 331, 5, 108, 331, 331, 331, 331, 126, 246, 331,
/* 2070 */ 331, 259, 129, 256, 331, 88, 123, 331, 331, 246,
/* 2080 */ 331, 331, 331, 129, 294, 327, 56, 123, 255, 350,
/* 2090 */ 348, 331, 345, 331, 331, 294, 327, 331, 331, 255,
/* 2100 */ 350, 348, 331, 345, 246, 331, 331, 331, 129, 331,
/* 2110 */ 331, 68, 123, 331, 331, 331, 331, 325, 19, 340,
/* 2120 */ 294, 327, 331, 331, 255, 350, 348, 331, 345, 331,
/* 2130 */ 331, 331, 331, 246, 331, 331, 331, 118, 331, 331,
/* 2140 */ 59, 123, 331, 331, 331, 331, 190, 172, 331, 294,
/* 2150 */ 327, 331, 331, 255, 350, 348, 283, 345, 246, 20,
/* 2160 */ 22, 331, 93, 331, 331, 57, 121, 331, 331, 331,
/* 2170 */ 331, 331, 331, 207, 294, 327, 331, 246, 255, 350,
/* 2180 */ 348, 129, 345, 331, 64, 123, 331, 331, 246, 331,
/* 2190 */ 331, 331, 129, 294, 327, 63, 123, 255, 350, 348,
/* 2200 */ 331, 345, 331, 331, 294, 327, 331, 246, 255, 350,
/* 2210 */ 348, 129, 345, 331, 73, 123, 331, 331, 331, 331,
/* 2220 */ 190, 165, 331, 294, 327, 331, 331, 255, 350, 348,
/* 2230 */ 283, 345, 331, 20, 22, 331, 246, 331, 331, 331,
/* 2240 */ 129, 331, 331, 87, 123, 331, 331, 207, 331, 331,
/* 2250 */ 331, 331, 294, 327, 331, 331, 255, 350, 348, 331,
/* 2260 */ 345, 246, 331, 331, 331, 129, 331, 331, 75, 123,
/* 2270 */ 331, 331, 246, 331, 331, 331, 129, 294, 327, 61,
/* 2280 */ 123, 255, 350, 348, 331, 345, 331, 331, 294, 327,
/* 2290 */ 331, 246, 255, 350, 348, 129, 345, 331, 71, 123,
/* 2300 */ 331, 331, 246, 331, 331, 331, 129, 294, 327, 83,
/* 2310 */ 123, 255, 350, 348, 331, 345, 331, 331, 294, 327,
/* 2320 */ 331, 331, 255, 350, 348, 331, 345, 246, 331, 331,
/* 2330 */ 331, 112, 331, 331, 76, 123, 331, 331, 331, 331,
/* 2340 */ 331, 331, 331, 294, 327, 331, 331, 255, 350, 348,
/* 2350 */ 331, 345, 246, 331, 331, 331, 129, 331, 331, 91,
/* 2360 */ 123, 331, 331, 246, 331, 331, 331, 129, 294, 327,
/* 2370 */ 62, 123, 255, 350, 348, 331, 345, 331, 331, 294,
/* 2380 */ 327, 331, 246, 255, 350, 348, 129, 345, 331, 79,
/* 2390 */ 123, 331, 331, 331, 331, 331, 331, 331, 294, 327,
/* 2400 */ 331, 331, 255, 350, 348, 331, 345,
);
static public $yy_lookahead = array(
/* 0 */ 1, 4, 5, 6, 7, 8, 9, 10, 11, 12,
/* 10 */ 13, 14, 15, 30, 66, 18, 18, 2, 20, 36,
/* 20 */ 23, 24, 94, 95, 96, 39, 29, 28, 30, 30,
/* 30 */ 33, 60, 35, 60, 36, 36, 65, 18, 65, 20,
/* 40 */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
/* 50 */ 51, 52, 53, 54, 1, 1, 3, 3, 1, 91,
/* 60 */ 3, 83, 84, 85, 86, 87, 67, 68, 69, 70,
/* 70 */ 71, 72, 73, 74, 75, 76, 77, 78, 112, 1,
/* 80 */ 114, 115, 63, 30, 30, 31, 118, 30, 19, 36,
/* 90 */ 36, 21, 22, 36, 41, 42, 43, 44, 45, 46,
/* 100 */ 47, 48, 49, 50, 51, 52, 53, 54, 1, 55,
/* 110 */ 32, 1, 55, 3, 91, 39, 18, 19, 20, 38,
/* 120 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
/* 130 */ 77, 78, 62, 55, 20, 37, 60, 30, 62, 20,
/* 140 */ 30, 118, 66, 36, 114, 115, 36, 66, 41, 42,
/* 150 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
/* 160 */ 53, 54, 1, 26, 1, 55, 3, 37, 1, 18,
/* 170 */ 3, 20, 21, 91, 67, 68, 69, 70, 71, 72,
/* 180 */ 73, 74, 75, 76, 77, 78, 5, 6, 7, 8,
/* 190 */ 9, 20, 1, 30, 3, 100, 15, 16, 17, 36,
/* 200 */ 118, 119, 41, 42, 43, 44, 45, 46, 47, 48,
/* 210 */ 49, 50, 51, 52, 53, 54, 1, 18, 55, 20,
/* 220 */ 21, 30, 55, 114, 115, 26, 22, 36, 67, 68,
/* 230 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
/* 240 */ 86, 80, 32, 26, 91, 92, 31, 1, 109, 39,
/* 250 */ 38, 18, 40, 20, 101, 116, 41, 42, 43, 44,
/* 260 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
/* 270 */ 1, 118, 62, 18, 19, 20, 122, 123, 85, 86,
/* 280 */ 87, 91, 67, 68, 69, 70, 71, 72, 73, 74,
/* 290 */ 75, 76, 77, 78, 104, 105, 63, 80, 1, 91,
/* 300 */ 92, 55, 3, 18, 115, 20, 21, 20, 118, 101,
/* 310 */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
/* 320 */ 51, 52, 53, 54, 1, 26, 118, 30, 38, 88,
/* 330 */ 40, 39, 38, 36, 40, 66, 67, 68, 69, 70,
/* 340 */ 71, 72, 73, 74, 75, 76, 77, 78, 63, 21,
/* 350 */ 63, 109, 91, 92, 62, 1, 2, 16, 116, 19,
/* 360 */ 20, 18, 101, 40, 41, 42, 43, 44, 45, 46,
/* 370 */ 47, 48, 49, 50, 51, 52, 53, 54, 1, 118,
/* 380 */ 3, 18, 39, 20, 19, 20, 19, 111, 60, 113,
/* 390 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
/* 400 */ 77, 78, 21, 22, 64, 30, 39, 92, 92, 39,
/* 410 */ 18, 36, 20, 18, 1, 20, 101, 101, 41, 42,
/* 420 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
/* 430 */ 53, 54, 1, 118, 118, 22, 87, 2, 89, 94,
/* 440 */ 95, 91, 98, 62, 67, 68, 69, 70, 71, 72,
/* 450 */ 73, 74, 75, 76, 77, 78, 21, 113, 86, 111,
/* 460 */ 92, 92, 111, 18, 113, 20, 20, 111, 118, 101,
/* 470 */ 101, 40, 41, 42, 43, 44, 45, 46, 47, 48,
/* 480 */ 49, 50, 51, 52, 53, 54, 1, 118, 3, 100,
/* 490 */ 94, 95, 18, 100, 20, 123, 111, 25, 67, 68,
/* 500 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
/* 510 */ 38, 92, 92, 20, 3, 3, 92, 20, 40, 64,
/* 520 */ 101, 101, 19, 3, 19, 101, 41, 42, 43, 44,
/* 530 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
/* 540 */ 1, 2, 118, 20, 19, 64, 20, 19, 21, 98,
/* 550 */ 20, 98, 67, 68, 69, 70, 71, 72, 73, 74,
/* 560 */ 75, 76, 77, 78, 113, 22, 113, 60, 27, 20,
/* 570 */ 37, 20, 56, 2, 101, 1, 112, 111, 116, 111,
/* 580 */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
/* 590 */ 51, 52, 53, 54, 1, 113, 97, 118, 2, 119,
/* 600 */ 111, 97, 30, 124, 98, 62, 67, 68, 69, 70,
/* 610 */ 71, 72, 73, 74, 75, 76, 77, 78, 25, 113,
/* 620 */ 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
/* 630 */ 124, 124, 124, 124, 41, 42, 43, 44, 45, 46,
/* 640 */ 47, 48, 49, 50, 51, 52, 53, 54, 1, 124,
/* 650 */ 3, 124, 124, 124, 124, 124, 124, 124, 99, 98,
/* 660 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
/* 670 */ 77, 78, 113, 124, 113, 124, 124, 124, 124, 124,
/* 680 */ 124, 124, 124, 124, 124, 124, 124, 124, 41, 42,
/* 690 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
/* 700 */ 53, 54, 1, 124, 3, 124, 124, 124, 124, 124,
/* 710 */ 124, 98, 98, 98, 67, 68, 69, 70, 71, 72,
/* 720 */ 73, 74, 75, 76, 77, 78, 113, 113, 113, 124,
/* 730 */ 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
/* 740 */ 124, 124, 41, 42, 43, 44, 45, 46, 47, 48,
/* 750 */ 49, 50, 51, 52, 53, 54, 1, 124, 124, 124,
/* 760 */ 124, 124, 124, 124, 124, 98, 98, 124, 67, 68,
/* 770 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
/* 780 */ 113, 113, 124, 124, 124, 124, 124, 124, 124, 124,
/* 790 */ 124, 124, 124, 124, 124, 124, 41, 42, 43, 44,
/* 800 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
/* 810 */ 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
/* 820 */ 22, 124, 67, 68, 69, 70, 71, 72, 73, 74,
/* 830 */ 75, 76, 77, 78, 124, 124, 124, 124, 41, 42,
/* 840 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
/* 850 */ 53, 54, 124, 124, 124, 124, 124, 124, 60, 124,
/* 860 */ 124, 124, 124, 65, 67, 68, 69, 70, 71, 72,
/* 870 */ 73, 74, 75, 76, 77, 78, 124, 124, 124, 124,
/* 880 */ 124, 124, 124, 18, 19, 20, 124, 124, 23, 24,
/* 890 */ 124, 86, 124, 124, 29, 90, 92, 124, 33, 94,
/* 900 */ 35, 124, 37, 124, 39, 101, 124, 42, 103, 124,
/* 910 */ 124, 106, 107, 108, 124, 110, 124, 113, 92, 92,
/* 920 */ 124, 124, 57, 58, 59, 60, 61, 101, 101, 64,
/* 930 */ 65, 66, 124, 94, 124, 124, 124, 124, 124, 113,
/* 940 */ 113, 18, 19, 20, 79, 106, 23, 24, 124, 110,
/* 950 */ 124, 124, 29, 124, 124, 86, 33, 34, 35, 90,
/* 960 */ 37, 124, 39, 94, 92, 42, 124, 124, 124, 124,
/* 970 */ 86, 124, 103, 101, 90, 106, 107, 108, 94, 110,
/* 980 */ 57, 58, 59, 60, 61, 113, 124, 64, 65, 124,
/* 990 */ 106, 107, 108, 124, 110, 18, 124, 20, 124, 18,
/* 1000 */ 19, 20, 79, 124, 23, 24, 124, 30, 124, 32,
/* 1010 */ 29, 86, 124, 36, 33, 90, 35, 124, 37, 94,
/* 1020 */ 39, 124, 124, 42, 124, 124, 124, 124, 124, 124,
/* 1030 */ 124, 106, 107, 108, 124, 110, 124, 124, 57, 58,
/* 1040 */ 59, 60, 61, 124, 124, 64, 65, 124, 124, 124,
/* 1050 */ 124, 124, 18, 124, 20, 124, 124, 18, 19, 20,
/* 1060 */ 79, 124, 23, 24, 30, 86, 32, 124, 29, 90,
/* 1070 */ 36, 86, 33, 94, 35, 90, 37, 124, 39, 94,
/* 1080 */ 124, 42, 124, 124, 124, 106, 107, 108, 124, 110,
/* 1090 */ 124, 106, 107, 108, 124, 110, 57, 58, 59, 60,
/* 1100 */ 61, 124, 124, 64, 65, 124, 124, 124, 124, 124,
/* 1110 */ 124, 124, 124, 124, 124, 18, 19, 20, 79, 124,
/* 1120 */ 23, 24, 124, 124, 124, 124, 29, 86, 124, 124,
/* 1130 */ 33, 90, 35, 124, 37, 94, 39, 124, 124, 42,
/* 1140 */ 124, 124, 124, 124, 124, 124, 124, 106, 107, 108,
/* 1150 */ 124, 110, 124, 124, 57, 58, 59, 60, 61, 124,
/* 1160 */ 124, 64, 65, 124, 124, 124, 124, 124, 124, 124,
/* 1170 */ 124, 124, 124, 18, 19, 20, 79, 124, 23, 24,
/* 1180 */ 124, 124, 124, 124, 29, 86, 124, 124, 33, 90,
/* 1190 */ 35, 124, 37, 94, 39, 124, 124, 42, 124, 124,
/* 1200 */ 124, 124, 124, 124, 124, 106, 107, 108, 124, 110,
/* 1210 */ 124, 124, 57, 58, 59, 60, 61, 124, 124, 64,
/* 1220 */ 65, 124, 124, 124, 124, 124, 124, 124, 124, 124,
/* 1230 */ 124, 18, 19, 20, 79, 124, 23, 24, 124, 124,
/* 1240 */ 124, 124, 29, 86, 124, 124, 33, 90, 35, 124,
/* 1250 */ 37, 94, 39, 124, 124, 42, 124, 124, 124, 124,
/* 1260 */ 124, 124, 124, 106, 107, 108, 124, 110, 124, 124,
/* 1270 */ 57, 58, 59, 60, 61, 124, 124, 64, 65, 124,
/* 1280 */ 1, 124, 3, 124, 124, 124, 124, 124, 124, 18,
/* 1290 */ 19, 20, 79, 124, 23, 24, 124, 124, 124, 124,
/* 1300 */ 29, 22, 124, 124, 33, 124, 35, 124, 37, 30,
/* 1310 */ 39, 91, 92, 42, 124, 36, 124, 124, 39, 124,
/* 1320 */ 124, 101, 124, 124, 104, 105, 124, 124, 57, 58,
/* 1330 */ 59, 60, 61, 124, 124, 64, 65, 124, 118, 124,
/* 1340 */ 124, 62, 124, 124, 124, 3, 124, 18, 19, 20,
/* 1350 */ 79, 124, 23, 24, 124, 124, 124, 124, 29, 124,
/* 1360 */ 124, 124, 33, 21, 35, 124, 37, 124, 39, 91,
/* 1370 */ 92, 42, 30, 124, 124, 124, 124, 124, 36, 101,
/* 1380 */ 124, 39, 104, 105, 124, 124, 57, 58, 59, 60,
/* 1390 */ 61, 124, 124, 64, 65, 124, 118, 124, 124, 124,
/* 1400 */ 124, 124, 124, 124, 62, 18, 19, 20, 79, 124,
/* 1410 */ 23, 24, 124, 124, 124, 124, 29, 124, 124, 124,
/* 1420 */ 33, 124, 35, 124, 37, 124, 39, 91, 92, 42,
/* 1430 */ 124, 124, 124, 124, 124, 124, 124, 101, 124, 124,
/* 1440 */ 104, 105, 124, 124, 57, 58, 59, 60, 61, 124,
/* 1450 */ 124, 64, 124, 124, 118, 124, 124, 124, 124, 124,
/* 1460 */ 124, 124, 124, 18, 19, 20, 79, 124, 23, 24,
/* 1470 */ 124, 124, 124, 124, 29, 124, 124, 124, 33, 124,
/* 1480 */ 35, 124, 37, 124, 39, 124, 3, 42, 124, 124,
/* 1490 */ 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
/* 1500 */ 124, 124, 57, 58, 59, 60, 61, 124, 25, 64,
/* 1510 */ 27, 28, 124, 30, 31, 124, 124, 124, 124, 36,
/* 1520 */ 124, 38, 39, 40, 79, 124, 124, 124, 124, 124,
/* 1530 */ 124, 124, 124, 124, 124, 86, 124, 124, 55, 90,
/* 1540 */ 124, 124, 93, 94, 124, 62, 124, 124, 124, 66,
/* 1550 */ 124, 102, 103, 124, 124, 106, 107, 108, 124, 110,
/* 1560 */ 124, 124, 124, 80, 124, 124, 124, 86, 124, 120,
/* 1570 */ 121, 90, 124, 124, 93, 94, 124, 124, 124, 124,
/* 1580 */ 124, 124, 124, 102, 103, 124, 124, 106, 107, 108,
/* 1590 */ 86, 110, 124, 124, 90, 124, 124, 93, 94, 95,
/* 1600 */ 124, 86, 121, 124, 124, 90, 102, 103, 93, 94,
/* 1610 */ 106, 107, 108, 124, 110, 124, 124, 102, 103, 124,
/* 1620 */ 124, 106, 107, 108, 124, 110, 86, 124, 124, 124,
/* 1630 */ 90, 124, 117, 93, 94, 124, 124, 124, 124, 124,
/* 1640 */ 124, 124, 102, 103, 124, 124, 106, 107, 108, 124,
/* 1650 */ 110, 124, 124, 124, 86, 91, 92, 117, 90, 124,
/* 1660 */ 124, 93, 94, 95, 124, 101, 124, 124, 104, 105,
/* 1670 */ 102, 103, 124, 124, 106, 107, 108, 86, 110, 124,
/* 1680 */ 124, 90, 118, 124, 93, 94, 124, 124, 124, 124,
/* 1690 */ 124, 124, 124, 102, 103, 124, 86, 106, 107, 108,
/* 1700 */ 90, 110, 124, 93, 94, 124, 124, 124, 117, 124,
/* 1710 */ 124, 124, 102, 103, 124, 124, 106, 107, 108, 86,
/* 1720 */ 110, 124, 124, 90, 124, 124, 93, 94, 124, 124,
/* 1730 */ 86, 124, 124, 124, 90, 102, 103, 93, 94, 106,
/* 1740 */ 107, 108, 124, 110, 124, 124, 102, 103, 124, 86,
/* 1750 */ 106, 107, 108, 90, 110, 124, 93, 94, 124, 124,
/* 1760 */ 124, 124, 124, 124, 124, 102, 103, 124, 86, 106,
/* 1770 */ 107, 108, 90, 110, 124, 93, 94, 124, 124, 124,
/* 1780 */ 124, 124, 124, 124, 102, 103, 124, 86, 106, 107,
/* 1790 */ 108, 90, 110, 124, 93, 94, 124, 124, 124, 124,
/* 1800 */ 124, 124, 124, 102, 103, 124, 86, 106, 107, 108,
/* 1810 */ 90, 110, 124, 93, 94, 124, 124, 86, 124, 124,
/* 1820 */ 124, 90, 102, 103, 93, 94, 106, 107, 108, 124,
/* 1830 */ 110, 124, 124, 102, 103, 124, 86, 106, 107, 108,
/* 1840 */ 90, 110, 124, 93, 94, 124, 124, 124, 124, 124,
/* 1850 */ 124, 124, 102, 103, 124, 86, 106, 107, 108, 90,
/* 1860 */ 110, 124, 93, 94, 124, 124, 124, 124, 124, 124,
/* 1870 */ 124, 102, 103, 124, 86, 106, 107, 108, 90, 110,
/* 1880 */ 124, 93, 94, 124, 124, 124, 124, 124, 124, 124,
/* 1890 */ 102, 103, 124, 86, 106, 107, 108, 90, 110, 124,
/* 1900 */ 93, 94, 124, 124, 86, 124, 124, 124, 90, 102,
/* 1910 */ 103, 93, 94, 106, 107, 108, 124, 110, 124, 124,
/* 1920 */ 102, 103, 11, 124, 106, 107, 108, 124, 110, 18,
/* 1930 */ 124, 124, 124, 124, 23, 24, 124, 124, 124, 124,
/* 1940 */ 29, 124, 124, 86, 33, 124, 35, 90, 124, 124,
/* 1950 */ 93, 94, 124, 124, 124, 124, 124, 124, 124, 102,
/* 1960 */ 103, 124, 86, 106, 107, 108, 90, 110, 124, 93,
/* 1970 */ 94, 124, 124, 124, 124, 124, 124, 124, 102, 103,
/* 1980 */ 124, 86, 106, 107, 108, 90, 110, 124, 93, 94,
/* 1990 */ 79, 80, 81, 124, 124, 124, 124, 102, 103, 124,
/* 2000 */ 86, 106, 107, 108, 90, 110, 124, 93, 94, 124,
/* 2010 */ 124, 86, 124, 124, 124, 90, 102, 103, 93, 94,
/* 2020 */ 106, 107, 108, 124, 110, 124, 124, 102, 103, 124,
/* 2030 */ 86, 106, 107, 108, 90, 110, 124, 93, 94, 124,
/* 2040 */ 124, 124, 124, 124, 124, 124, 102, 103, 124, 11,
/* 2050 */ 106, 107, 108, 124, 110, 124, 18, 124, 124, 124,
/* 2060 */ 124, 23, 24, 124, 124, 124, 124, 29, 86, 124,
/* 2070 */ 124, 33, 90, 35, 124, 93, 94, 124, 124, 86,
/* 2080 */ 124, 124, 124, 90, 102, 103, 93, 94, 106, 107,
/* 2090 */ 108, 124, 110, 124, 124, 102, 103, 124, 124, 106,
/* 2100 */ 107, 108, 124, 110, 86, 124, 124, 124, 90, 124,
/* 2110 */ 124, 93, 94, 124, 124, 124, 124, 79, 80, 81,
/* 2120 */ 102, 103, 124, 124, 106, 107, 108, 124, 110, 124,
/* 2130 */ 124, 124, 124, 86, 124, 124, 124, 90, 124, 124,
/* 2140 */ 93, 94, 124, 124, 124, 124, 91, 92, 124, 102,
/* 2150 */ 103, 124, 124, 106, 107, 108, 101, 110, 86, 104,
/* 2160 */ 105, 124, 90, 124, 124, 93, 94, 124, 124, 124,
/* 2170 */ 124, 124, 124, 118, 102, 103, 124, 86, 106, 107,
/* 2180 */ 108, 90, 110, 124, 93, 94, 124, 124, 86, 124,
/* 2190 */ 124, 124, 90, 102, 103, 93, 94, 106, 107, 108,
/* 2200 */ 124, 110, 124, 124, 102, 103, 124, 86, 106, 107,
/* 2210 */ 108, 90, 110, 124, 93, 94, 124, 124, 124, 124,
/* 2220 */ 91, 92, 124, 102, 103, 124, 124, 106, 107, 108,
/* 2230 */ 101, 110, 124, 104, 105, 124, 86, 124, 124, 124,
/* 2240 */ 90, 124, 124, 93, 94, 124, 124, 118, 124, 124,
/* 2250 */ 124, 124, 102, 103, 124, 124, 106, 107, 108, 124,
/* 2260 */ 110, 86, 124, 124, 124, 90, 124, 124, 93, 94,
/* 2270 */ 124, 124, 86, 124, 124, 124, 90, 102, 103, 93,
/* 2280 */ 94, 106, 107, 108, 124, 110, 124, 124, 102, 103,
/* 2290 */ 124, 86, 106, 107, 108, 90, 110, 124, 93, 94,
/* 2300 */ 124, 124, 86, 124, 124, 124, 90, 102, 103, 93,
/* 2310 */ 94, 106, 107, 108, 124, 110, 124, 124, 102, 103,
/* 2320 */ 124, 124, 106, 107, 108, 124, 110, 86, 124, 124,
/* 2330 */ 124, 90, 124, 124, 93, 94, 124, 124, 124, 124,
/* 2340 */ 124, 124, 124, 102, 103, 124, 124, 106, 107, 108,
/* 2350 */ 124, 110, 86, 124, 124, 124, 90, 124, 124, 93,
/* 2360 */ 94, 124, 124, 86, 124, 124, 124, 90, 102, 103,
/* 2370 */ 93, 94, 106, 107, 108, 124, 110, 124, 124, 102,
/* 2380 */ 103, 124, 86, 106, 107, 108, 90, 110, 124, 93,
/* 2390 */ 94, 124, 124, 124, 124, 124, 124, 124, 102, 103,
/* 2400 */ 124, 124, 106, 107, 108, 124, 110,
);
const YY_SHIFT_USE_DFLT = -53;
const YY_SHIFT_MAX = 259;
static public $yy_shift_ofst = array(
/* 0 */ -3, 1213, 981, 1155, 1213, 1155, 981, 981, 923, 923,
/* 10 */ 865, 981, 981, 1097, 981, 981, 981, 981, 981, 981,
/* 20 */ 981, 1329, 981, 981, 981, 981, 1271, 981, 981, 981,
/* 30 */ 1097, 981, 981, 981, 981, 981, 981, 981, 981, 981,
/* 40 */ 981, 981, 981, 981, 1039, 1039, 1387, 1387, 1445, 1387,
/* 50 */ 1387, 1387, 1387, -1, 53, 107, 107, 107, 107, 107,
/* 60 */ 485, 431, 593, 647, 701, 323, 161, 215, 377, 269,
/* 70 */ 539, 755, 755, 755, 755, 755, 755, 755, 755, 755,
/* 80 */ 755, 755, 755, 755, 755, 755, 755, 755, 755, 755,
/* 90 */ 797, 797, 1279, 110, 297, -3, 2038, 977, 1034, 191,
/* 100 */ -2, 191, -2, 297, 297, 798, 340, 354, 367, 1911,
/* 110 */ 181, 54, 57, 163, 199, 285, 19, 151, 167, 70,
/* 120 */ 78, 381, 367, 543, 363, -17, 375, 365, 363, 246,
/* 130 */ 363, 395, 392, -17, 363, 363, 363, 367, 363, 445,
/* 140 */ 413, 363, 395, 363, 474, 365, 574, 204, 204, 574,
/* 150 */ 574, 574, 574, 574, 574, 574, 574, -53, 255, 233,
/* 160 */ -17, -27, -29, -17, -17, -17, -29, -17, -29, -27,
/* 170 */ -17, -17, -17, -29, -17, -17, -29, -17, -17, -17,
/* 180 */ -17, -17, -17, -17, -17, -17, -29, -29, -17, 343,
/* 190 */ 574, 574, 574, 596, 596, 574, 574, 204, 572, 572,
/* 200 */ 204, 341, 204, 370, -53, -53, -53, -53, -53, 1483,
/* 210 */ 1342, 98, 76, 210, 435, 212, 328, 299, 81, 287,
/* 220 */ 472, 294, 217, 290, 292, 292, 370, 511, 455, 505,
/* 230 */ 520, 528, 478, 481, 541, 527, 446, 15, 114, -14,
/* 240 */ 533, 130, 493, 497, 503, 523, 512, 525, 549, 551,
/* 250 */ 507, 526, 530, 516, 571, 137, 119, -52, 69, 171,
);
const YY_REDUCE_USE_DFLT = -73;
const YY_REDUCE_MAX = 208;
static public $yy_reduce_ofst = array(
/* 0 */ -22, 1449, 1540, 1504, 1481, 1568, 1515, 1591, 1925, 2072,
/* 10 */ 1750, 1818, 1895, 1644, 1663, 1914, 2205, 2277, 1876, 1731,
/* 20 */ 1857, 1633, 1701, 2186, 2150, 2296, 2266, 2091, 2047, 1993,
/* 30 */ 2241, 2102, 1720, 1788, 1982, 1769, 1807, 1610, 1682, 2175,
/* 40 */ 2216, 2121, 1944, 2018, 805, 869, 884, 979, 925, 985,
/* 50 */ 1041, 1157, 1099, 1220, 1336, 2129, 1278, 1336, 1564, 2055,
/* 60 */ 190, 190, 190, 190, 190, 190, 190, 190, 190, 190,
/* 70 */ 190, 190, 190, 190, 190, 190, 190, 190, 190, 190,
/* 80 */ 190, 190, 190, 190, 190, 190, 190, 190, 190, 190,
/* 90 */ 190, 190, 261, 208, 153, 193, 154, 827, 826, 369,
/* 100 */ 804, 315, 872, 316, 424, -34, 839, 82, -72, 372,
/* 110 */ 349, -32, -32, -32, 559, 351, 351, 351, -32, 30,
/* 120 */ -32, 30, 345, 30, 453, 420, 368, 242, 344, -32,
/* 130 */ 276, 561, 451, 419, 506, 615, 668, 396, 613, 615,
/* 140 */ 350, 614, 615, 667, 615, 139, -32, 30, 109, -32,
/* 150 */ -32, -32, -32, -32, -32, -32, 23, -32, 462, 482,
/* 160 */ 473, 466, 464, 473, 473, 473, 464, 473, 464, 468,
/* 170 */ 473, 473, 473, 464, 473, 473, 464, 473, 473, 473,
/* 180 */ 473, 473, 473, 473, 473, 473, 464, 464, 473, 489,
/* 190 */ 479, 479, 479, 480, 480, 479, 479, 189, 504, 499,
/* 200 */ 189, 241, 189, 348, 356, 393, 389, 95, 385,
);
static public $yyExpectedTokens = array(
/* 0 */ array(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 23, 24, 29, 33, 35, ),
/* 1 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 2 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 3 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 4 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 5 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 6 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 7 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 8 */ array(18, 19, 20, 23, 24, 29, 33, 34, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 9 */ array(18, 19, 20, 23, 24, 29, 33, 34, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 10 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 66, 79, ),
/* 11 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 12 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 13 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 14 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 15 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 16 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 17 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 18 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 19 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 20 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 21 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 22 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 23 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 24 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 25 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 26 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 27 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 28 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 29 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 30 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 31 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 32 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 33 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 34 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 35 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 36 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 37 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 38 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 39 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 40 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 41 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 42 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 43 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 44 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 45 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 65, 79, ),
/* 46 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 79, ),
/* 47 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 79, ),
/* 48 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 79, ),
/* 49 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 79, ),
/* 50 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 79, ),
/* 51 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 79, ),
/* 52 */ array(18, 19, 20, 23, 24, 29, 33, 35, 37, 39, 42, 57, 58, 59, 60, 61, 64, 79, ),
/* 53 */ array(1, 28, 30, 36, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 54 */ array(1, 3, 30, 36, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 55 */ array(1, 30, 36, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 56 */ array(1, 30, 36, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 57 */ array(1, 30, 36, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 58 */ array(1, 30, 36, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 59 */ array(1, 30, 36, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 60 */ array(1, 3, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 61 */ array(1, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 62 */ array(1, 25, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 63 */ array(1, 3, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 64 */ array(1, 3, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 65 */ array(1, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 66 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, ),
/* 67 */ array(1, 31, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 68 */ array(1, 3, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 69 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 70 */ array(1, 2, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 71 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 72 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 73 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 74 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 75 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 76 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 77 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 78 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 79 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 80 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 81 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 82 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 83 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 84 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 85 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 86 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 87 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 88 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 89 */ array(1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 90 */ array(41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 91 */ array(41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, ),
/* 92 */ array(1, 3, 22, 30, 36, 39, 62, ),
/* 93 */ array(1, 3, 30, 36, 55, ),
/* 94 */ array(1, 30, 36, ),
/* 95 */ array(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 23, 24, 29, 33, 35, ),
/* 96 */ array(11, 18, 23, 24, 29, 33, 35, 79, 80, 81, ),
/* 97 */ array(18, 20, 30, 32, 36, ),
/* 98 */ array(18, 20, 30, 32, 36, ),
/* 99 */ array(1, 3, 30, 36, ),
/* 100 */ array(18, 20, 30, 36, ),
/* 101 */ array(1, 3, 30, 36, ),
/* 102 */ array(18, 20, 30, 36, ),
/* 103 */ array(1, 30, 36, ),
/* 104 */ array(1, 30, 36, ),
/* 105 */ array(22, 60, 65, ),
/* 106 */ array(19, 20, 64, ),
/* 107 */ array(1, 2, ),
/* 108 */ array(19, 39, ),
/* 109 */ array(11, 18, 23, 24, 29, 33, 35, 79, 80, 81, ),
/* 110 */ array(5, 6, 7, 8, 9, 15, 16, 17, ),
/* 111 */ array(1, 3, 30, 31, 36, 55, ),
/* 112 */ array(1, 3, 30, 36, 55, ),
/* 113 */ array(1, 3, 30, 36, 55, ),
/* 114 */ array(18, 20, 21, 26, ),
/* 115 */ array(18, 20, 21, 63, ),
/* 116 */ array(18, 20, 63, ),
/* 117 */ array(18, 20, 21, ),
/* 118 */ array(1, 3, 55, ),
/* 119 */ array(21, 22, 62, ),
/* 120 */ array(1, 32, 55, ),
/* 121 */ array(21, 22, 62, ),
/* 122 */ array(19, 39, ),
/* 123 */ array(22, 62, ),
/* 124 */ array(18, 20, ),
/* 125 */ array(30, 36, ),
/* 126 */ array(30, 36, ),
/* 127 */ array(19, 20, ),
/* 128 */ array(18, 20, ),
/* 129 */ array(1, 55, ),
/* 130 */ array(18, 20, ),
/* 131 */ array(18, 20, ),
/* 132 */ array(18, 20, ),
/* 133 */ array(30, 36, ),
/* 134 */ array(18, 20, ),
/* 135 */ array(18, 20, ),
/* 136 */ array(18, 20, ),
/* 137 */ array(19, 39, ),
/* 138 */ array(18, 20, ),
/* 139 */ array(18, 20, ),
/* 140 */ array(1, 22, ),
/* 141 */ array(18, 20, ),
/* 142 */ array(18, 20, ),
/* 143 */ array(18, 20, ),
/* 144 */ array(18, 20, ),
/* 145 */ array(19, 20, ),
/* 146 */ array(1, ),
/* 147 */ array(22, ),
/* 148 */ array(22, ),
/* 149 */ array(1, ),
/* 150 */ array(1, ),
/* 151 */ array(1, ),
/* 152 */ array(1, ),
/* 153 */ array(1, ),
/* 154 */ array(1, ),
/* 155 */ array(1, ),
/* 156 */ array(1, ),
/* 157 */ array(),
/* 158 */ array(18, 19, 20, ),
/* 159 */ array(18, 20, 63, ),
/* 160 */ array(30, 36, ),
/* 161 */ array(60, 65, ),
/* 162 */ array(60, 65, ),
/* 163 */ array(30, 36, ),
/* 164 */ array(30, 36, ),
/* 165 */ array(30, 36, ),
/* 166 */ array(60, 65, ),
/* 167 */ array(30, 36, ),
/* 168 */ array(60, 65, ),
/* 169 */ array(60, 65, ),
/* 170 */ array(30, 36, ),
/* 171 */ array(30, 36, ),
/* 172 */ array(30, 36, ),
/* 173 */ array(60, 65, ),
/* 174 */ array(30, 36, ),
/* 175 */ array(30, 36, ),
/* 176 */ array(60, 65, ),
/* 177 */ array(30, 36, ),
/* 178 */ array(30, 36, ),
/* 179 */ array(30, 36, ),
/* 180 */ array(30, 36, ),
/* 181 */ array(30, 36, ),
/* 182 */ array(30, 36, ),
/* 183 */ array(30, 36, ),
/* 184 */ array(30, 36, ),
/* 185 */ array(30, 36, ),
/* 186 */ array(60, 65, ),
/* 187 */ array(60, 65, ),
/* 188 */ array(30, 36, ),
/* 189 */ array(18, 39, ),
/* 190 */ array(1, ),
/* 191 */ array(1, ),
/* 192 */ array(1, ),
/* 193 */ array(2, ),
/* 194 */ array(2, ),
/* 195 */ array(1, ),
/* 196 */ array(1, ),
/* 197 */ array(22, ),
/* 198 */ array(30, ),
/* 199 */ array(30, ),
/* 200 */ array(22, ),
/* 201 */ array(16, ),
/* 202 */ array(22, ),
/* 203 */ array(39, ),
/* 204 */ array(),
/* 205 */ array(),
/* 206 */ array(),
/* 207 */ array(),
/* 208 */ array(),
/* 209 */ array(3, 25, 27, 28, 30, 31, 36, 38, 39, 40, 55, 62, 66, 80, ),
/* 210 */ array(3, 21, 30, 36, 39, 62, ),
/* 211 */ array(18, 19, 20, 37, ),
/* 212 */ array(39, 60, 62, 66, ),
/* 213 */ array(32, 39, 62, ),
/* 214 */ array(2, 21, ),
/* 215 */ array(38, 40, ),
/* 216 */ array(21, 60, ),
/* 217 */ array(3, 26, ),
/* 218 */ array(38, 66, ),
/* 219 */ array(20, 63, ),
/* 220 */ array(25, 38, ),
/* 221 */ array(38, 40, ),
/* 222 */ array(26, 80, ),
/* 223 */ array(38, 40, ),
/* 224 */ array(39, 62, ),
/* 225 */ array(39, 62, ),
/* 226 */ array(39, ),
/* 227 */ array(3, ),
/* 228 */ array(64, ),
/* 229 */ array(19, ),
/* 230 */ array(3, ),
/* 231 */ array(19, ),
/* 232 */ array(40, ),
/* 233 */ array(64, ),
/* 234 */ array(27, ),
/* 235 */ array(21, ),
/* 236 */ array(20, ),
/* 237 */ array(2, ),
/* 238 */ array(20, ),
/* 239 */ array(39, ),
/* 240 */ array(37, ),
/* 241 */ array(37, ),
/* 242 */ array(20, ),
/* 243 */ array(20, ),
/* 244 */ array(19, ),
/* 245 */ array(20, ),
/* 246 */ array(3, ),
/* 247 */ array(19, ),
/* 248 */ array(20, ),
/* 249 */ array(20, ),
/* 250 */ array(60, ),
/* 251 */ array(20, ),
/* 252 */ array(20, ),
/* 253 */ array(56, ),
/* 254 */ array(2, ),
/* 255 */ array(26, ),
/* 256 */ array(20, ),
/* 257 */ array(66, ),
/* 258 */ array(19, ),
/* 259 */ array(20, ),
/* 260 */ array(),
/* 261 */ array(),
/* 262 */ array(),
/* 263 */ array(),
/* 264 */ array(),
/* 265 */ array(),
/* 266 */ array(),
/* 267 */ array(),
/* 268 */ array(),
/* 269 */ array(),
/* 270 */ array(),
/* 271 */ array(),
/* 272 */ array(),
/* 273 */ array(),
/* 274 */ array(),
/* 275 */ array(),
/* 276 */ array(),
/* 277 */ array(),
/* 278 */ array(),
/* 279 */ array(),
/* 280 */ array(),
/* 281 */ array(),
/* 282 */ array(),
/* 283 */ array(),
/* 284 */ array(),
/* 285 */ array(),
/* 286 */ array(),
/* 287 */ array(),
/* 288 */ array(),
/* 289 */ array(),
/* 290 */ array(),
/* 291 */ array(),
/* 292 */ array(),
/* 293 */ array(),
/* 294 */ array(),
/* 295 */ array(),
/* 296 */ array(),
/* 297 */ array(),
/* 298 */ array(),
/* 299 */ array(),
/* 300 */ array(),
/* 301 */ array(),
/* 302 */ array(),
/* 303 */ array(),
/* 304 */ array(),
/* 305 */ array(),
/* 306 */ array(),
/* 307 */ array(),
/* 308 */ array(),
/* 309 */ array(),
/* 310 */ array(),
/* 311 */ array(),
/* 312 */ array(),
/* 313 */ array(),
/* 314 */ array(),
/* 315 */ array(),
/* 316 */ array(),
/* 317 */ array(),
/* 318 */ array(),
/* 319 */ array(),
/* 320 */ array(),
/* 321 */ array(),
/* 322 */ array(),
/* 323 */ array(),
/* 324 */ array(),
/* 325 */ array(),
/* 326 */ array(),
/* 327 */ array(),
/* 328 */ array(),
/* 329 */ array(),
/* 330 */ array(),
/* 331 */ array(),
/* 332 */ array(),
/* 333 */ array(),
/* 334 */ array(),
/* 335 */ array(),
/* 336 */ array(),
/* 337 */ array(),
/* 338 */ array(),
/* 339 */ array(),
/* 340 */ array(),
/* 341 */ array(),
/* 342 */ array(),
/* 343 */ array(),
/* 344 */ array(),
/* 345 */ array(),
/* 346 */ array(),
/* 347 */ array(),
/* 348 */ array(),
/* 349 */ array(),
/* 350 */ array(),
/* 351 */ array(),
/* 352 */ array(),
/* 353 */ array(),
/* 354 */ array(),
/* 355 */ array(),
/* 356 */ array(),
/* 357 */ array(),
/* 358 */ array(),
/* 359 */ array(),
/* 360 */ array(),
/* 361 */ array(),
/* 362 */ array(),
);
static public $yy_default = array(
/* 0 */ 366, 551, 522, 568, 568, 568, 522, 522, 568, 568,
/* 10 */ 568, 568, 568, 568, 568, 568, 568, 568, 568, 568,
/* 20 */ 568, 568, 568, 568, 568, 568, 568, 568, 568, 568,
/* 30 */ 568, 568, 568, 568, 568, 568, 568, 568, 568, 568,
/* 40 */ 568, 568, 568, 568, 568, 568, 568, 568, 568, 568,
/* 50 */ 568, 568, 568, 428, 568, 405, 428, 428, 428, 397,
/* 60 */ 568, 568, 568, 568, 568, 568, 568, 433, 568, 568,
/* 70 */ 568, 553, 449, 520, 552, 457, 433, 452, 439, 462,
/* 80 */ 521, 461, 430, 435, 554, 438, 454, 453, 410, 458,
/* 90 */ 466, 465, 477, 441, 428, 363, 568, 428, 428, 485,
/* 100 */ 428, 448, 428, 428, 428, 534, 568, 419, 568, 568,
/* 110 */ 568, 441, 441, 441, 568, 495, 495, 495, 441, 486,
/* 120 */ 441, 486, 568, 486, 568, 428, 428, 568, 568, 441,
/* 130 */ 495, 568, 568, 407, 568, 568, 568, 568, 568, 568,
/* 140 */ 422, 568, 568, 568, 568, 568, 451, 486, 531, 464,
/* 150 */ 446, 445, 468, 444, 469, 470, 424, 529, 568, 496,
/* 160 */ 395, 489, 492, 412, 392, 406, 514, 409, 490, 491,
/* 170 */ 413, 394, 398, 513, 393, 408, 493, 400, 417, 402,
/* 180 */ 415, 404, 414, 418, 416, 403, 515, 512, 399, 495,
/* 190 */ 448, 420, 485, 523, 524, 423, 425, 532, 567, 567,
/* 200 */ 509, 383, 535, 495, 495, 528, 528, 528, 495, 443,
/* 210 */ 477, 568, 477, 477, 507, 568, 473, 467, 568, 568,
/* 220 */ 568, 568, 467, 568, 477, 463, 507, 568, 568, 568,
/* 230 */ 568, 568, 568, 568, 436, 568, 568, 507, 568, 533,
/* 240 */ 568, 475, 568, 568, 568, 568, 568, 568, 568, 568,
/* 250 */ 473, 568, 568, 479, 507, 467, 568, 568, 568, 568,
/* 260 */ 508, 429, 437, 364, 501, 519, 503, 440, 500, 479,
/* 270 */ 566, 516, 517, 502, 504, 518, 411, 530, 459, 506,
/* 280 */ 507, 527, 525, 427, 426, 388, 389, 390, 526, 471,
/* 290 */ 443, 487, 494, 497, 442, 482, 472, 474, 476, 387,
/* 300 */ 386, 371, 372, 373, 374, 370, 369, 365, 367, 368,
/* 310 */ 375, 376, 382, 384, 385, 381, 380, 377, 378, 379,
/* 320 */ 505, 498, 510, 421, 562, 555, 563, 447, 545, 546,
/* 330 */ 547, 556, 557, 558, 548, 550, 565, 564, 560, 559,
/* 340 */ 561, 544, 543, 450, 484, 488, 511, 483, 481, 499,
/* 350 */ 478, 480, 455, 456, 540, 541, 542, 539, 538, 460,
/* 360 */ 536, 537, 549,
);
const YYNOCODE = 125;
const YYSTACKDEPTH = 500;
const YYNSTATE = 363;
const YYNRULE = 205;
const YYERRORSYMBOL = 82;
const YYERRSYMDT = 'yy0';
const YYFALLBACK = 0;
public static $yyFallback = array(
);
public static function Trace($TraceFILE, $zTracePrompt)
{
if (!$TraceFILE) {
$zTracePrompt = 0;
} elseif (!$zTracePrompt) {
$TraceFILE = 0;
}
self::$yyTraceFILE = $TraceFILE;
self::$yyTracePrompt = $zTracePrompt;
}
public static function PrintTrace()
{
self::$yyTraceFILE = fopen('php://output', 'w');
self::$yyTracePrompt = '<br>';
}
public static $yyTraceFILE;
public static $yyTracePrompt;
public $yyidx; /* Index of top element in stack */
public $yyerrcnt; /* Shifts left before out of the error */
public $yystack = array(); /* The parser's stack */
public $yyTokenName = array(
'$', 'VERT', 'COLON', 'RDEL',
'COMMENT', 'PHPSTARTTAG', 'PHPENDTAG', 'ASPSTARTTAG',
'ASPENDTAG', 'FAKEPHPSTARTTAG', 'XMLTAG', 'TEXT',
'STRIPON', 'STRIPOFF', 'BLOCKSOURCE', 'LITERALSTART',
'LITERALEND', 'LITERAL', 'LDEL', 'DOLLAR',
'ID', 'EQUAL', 'PTR', 'LDELIF',
'LDELFOR', 'SEMICOLON', 'INCDEC', 'TO',
'STEP', 'LDELFOREACH', 'SPACE', 'AS',
'APTR', 'LDELSETFILTER', 'SMARTYBLOCKCHILDPARENT', 'LDELSLASH',
'ATTR', 'INTEGER', 'COMMA', 'OPENP',
'CLOSEP', 'MATH', 'UNIMATH', 'ANDSYM',
'ISIN', 'ISDIVBY', 'ISNOTDIVBY', 'ISEVEN',
'ISNOTEVEN', 'ISEVENBY', 'ISNOTEVENBY', 'ISODD',
'ISNOTODD', 'ISODDBY', 'ISNOTODDBY', 'INSTANCEOF',
'QMARK', 'NOT', 'TYPECAST', 'HEX',
'DOT', 'SINGLEQUOTESTRING', 'DOUBLECOLON', 'AT',
'HATCH', 'OPENB', 'CLOSEB', 'EQUALS',
'NOTEQUALS', 'GREATERTHAN', 'LESSTHAN', 'GREATEREQUAL',
'LESSEQUAL', 'IDENTITY', 'NONEIDENTITY', 'MOD',
'LAND', 'LOR', 'LXOR', 'QUOTE',
'BACKTICK', 'DOLLARID', 'error', 'start',
'template', 'template_element', 'smartytag', 'literal',
'literal_elements', 'literal_element', 'value', 'modifierlist',
'attributes', 'expr', 'varindexed', 'statement',
'statements', 'optspace', 'varvar', 'foraction',
'modparameters', 'attribute', 'ternary', 'array',
'ifcond', 'lop', 'variable', 'function',
'doublequoted_with_quotes', 'static_class_access', 'object', 'arrayindex',
'indexdef', 'varvarele', 'objectchain', 'objectelement',
'method', 'params', 'modifier', 'modparameter',
'arrayelements', 'arrayelement', 'doublequoted', 'doublequotedcontent',
);
public static $yyRuleName = array(
/* 0 */ "start ::= template",
/* 1 */ "template ::= template_element",
/* 2 */ "template ::= template template_element",
/* 3 */ "template ::=",
/* 4 */ "template_element ::= smartytag RDEL",
/* 5 */ "template_element ::= COMMENT",
/* 6 */ "template_element ::= literal",
/* 7 */ "template_element ::= PHPSTARTTAG",
/* 8 */ "template_element ::= PHPENDTAG",
/* 9 */ "template_element ::= ASPSTARTTAG",
/* 10 */ "template_element ::= ASPENDTAG",
/* 11 */ "template_element ::= FAKEPHPSTARTTAG",
/* 12 */ "template_element ::= XMLTAG",
/* 13 */ "template_element ::= TEXT",
/* 14 */ "template_element ::= STRIPON",
/* 15 */ "template_element ::= STRIPOFF",
/* 16 */ "template_element ::= BLOCKSOURCE",
/* 17 */ "literal ::= LITERALSTART LITERALEND",
/* 18 */ "literal ::= LITERALSTART literal_elements LITERALEND",
/* 19 */ "literal_elements ::= literal_elements literal_element",
/* 20 */ "literal_elements ::=",
/* 21 */ "literal_element ::= literal",
/* 22 */ "literal_element ::= LITERAL",
/* 23 */ "literal_element ::= PHPSTARTTAG",
/* 24 */ "literal_element ::= FAKEPHPSTARTTAG",
/* 25 */ "literal_element ::= PHPENDTAG",
/* 26 */ "literal_element ::= ASPSTARTTAG",
/* 27 */ "literal_element ::= ASPENDTAG",
/* 28 */ "smartytag ::= LDEL value",
/* 29 */ "smartytag ::= LDEL value modifierlist attributes",
/* 30 */ "smartytag ::= LDEL value attributes",
/* 31 */ "smartytag ::= LDEL expr modifierlist attributes",
/* 32 */ "smartytag ::= LDEL expr attributes",
/* 33 */ "smartytag ::= LDEL DOLLAR ID EQUAL value",
/* 34 */ "smartytag ::= LDEL DOLLAR ID EQUAL expr",
/* 35 */ "smartytag ::= LDEL DOLLAR ID EQUAL expr attributes",
/* 36 */ "smartytag ::= LDEL varindexed EQUAL expr attributes",
/* 37 */ "smartytag ::= LDEL ID attributes",
/* 38 */ "smartytag ::= LDEL ID",
/* 39 */ "smartytag ::= LDEL ID PTR ID attributes",
/* 40 */ "smartytag ::= LDEL ID modifierlist attributes",
/* 41 */ "smartytag ::= LDEL ID PTR ID modifierlist attributes",
/* 42 */ "smartytag ::= LDELIF expr",
/* 43 */ "smartytag ::= LDELIF expr attributes",
/* 44 */ "smartytag ::= LDELIF statement",
/* 45 */ "smartytag ::= LDELIF statement attributes",
/* 46 */ "smartytag ::= LDELFOR statements SEMICOLON optspace expr SEMICOLON optspace DOLLAR varvar foraction attributes",
/* 47 */ "foraction ::= EQUAL expr",
/* 48 */ "foraction ::= INCDEC",
/* 49 */ "smartytag ::= LDELFOR statement TO expr attributes",
/* 50 */ "smartytag ::= LDELFOR statement TO expr STEP expr attributes",
/* 51 */ "smartytag ::= LDELFOREACH attributes",
/* 52 */ "smartytag ::= LDELFOREACH SPACE value AS DOLLAR varvar attributes",
/* 53 */ "smartytag ::= LDELFOREACH SPACE value AS DOLLAR varvar APTR DOLLAR varvar attributes",
/* 54 */ "smartytag ::= LDELFOREACH SPACE expr AS DOLLAR varvar attributes",
/* 55 */ "smartytag ::= LDELFOREACH SPACE expr AS DOLLAR varvar APTR DOLLAR varvar attributes",
/* 56 */ "smartytag ::= LDELSETFILTER ID modparameters",
/* 57 */ "smartytag ::= LDELSETFILTER ID modparameters modifierlist",
/* 58 */ "smartytag ::= LDEL SMARTYBLOCKCHILDPARENT",
/* 59 */ "smartytag ::= LDELSLASH ID",
/* 60 */ "smartytag ::= LDELSLASH ID modifierlist",
/* 61 */ "smartytag ::= LDELSLASH ID PTR ID",
/* 62 */ "smartytag ::= LDELSLASH ID PTR ID modifierlist",
/* 63 */ "attributes ::= attributes attribute",
/* 64 */ "attributes ::= attribute",
/* 65 */ "attributes ::=",
/* 66 */ "attribute ::= SPACE ID EQUAL ID",
/* 67 */ "attribute ::= ATTR expr",
/* 68 */ "attribute ::= ATTR value",
/* 69 */ "attribute ::= SPACE ID",
/* 70 */ "attribute ::= SPACE expr",
/* 71 */ "attribute ::= SPACE value",
/* 72 */ "attribute ::= SPACE INTEGER EQUAL expr",
/* 73 */ "statements ::= statement",
/* 74 */ "statements ::= statements COMMA statement",
/* 75 */ "statement ::= DOLLAR varvar EQUAL expr",
/* 76 */ "statement ::= varindexed EQUAL expr",
/* 77 */ "statement ::= OPENP statement CLOSEP",
/* 78 */ "expr ::= value",
/* 79 */ "expr ::= ternary",
/* 80 */ "expr ::= DOLLAR ID COLON ID",
/* 81 */ "expr ::= expr MATH value",
/* 82 */ "expr ::= expr UNIMATH value",
/* 83 */ "expr ::= expr ANDSYM value",
/* 84 */ "expr ::= array",
/* 85 */ "expr ::= expr modifierlist",
/* 86 */ "expr ::= expr ifcond expr",
/* 87 */ "expr ::= expr ISIN array",
/* 88 */ "expr ::= expr ISIN value",
/* 89 */ "expr ::= expr lop expr",
/* 90 */ "expr ::= expr ISDIVBY expr",
/* 91 */ "expr ::= expr ISNOTDIVBY expr",
/* 92 */ "expr ::= expr ISEVEN",
/* 93 */ "expr ::= expr ISNOTEVEN",
/* 94 */ "expr ::= expr ISEVENBY expr",
/* 95 */ "expr ::= expr ISNOTEVENBY expr",
/* 96 */ "expr ::= expr ISODD",
/* 97 */ "expr ::= expr ISNOTODD",
/* 98 */ "expr ::= expr ISODDBY expr",
/* 99 */ "expr ::= expr ISNOTODDBY expr",
/* 100 */ "expr ::= value INSTANCEOF ID",
/* 101 */ "expr ::= value INSTANCEOF value",
/* 102 */ "ternary ::= OPENP expr CLOSEP QMARK DOLLAR ID COLON expr",
/* 103 */ "ternary ::= OPENP expr CLOSEP QMARK expr COLON expr",
/* 104 */ "value ::= variable",
/* 105 */ "value ::= UNIMATH value",
/* 106 */ "value ::= NOT value",
/* 107 */ "value ::= TYPECAST value",
/* 108 */ "value ::= variable INCDEC",
/* 109 */ "value ::= HEX",
/* 110 */ "value ::= INTEGER",
/* 111 */ "value ::= INTEGER DOT INTEGER",
/* 112 */ "value ::= INTEGER DOT",
/* 113 */ "value ::= DOT INTEGER",
/* 114 */ "value ::= ID",
/* 115 */ "value ::= function",
/* 116 */ "value ::= OPENP expr CLOSEP",
/* 117 */ "value ::= SINGLEQUOTESTRING",
/* 118 */ "value ::= doublequoted_with_quotes",
/* 119 */ "value ::= ID DOUBLECOLON static_class_access",
/* 120 */ "value ::= varindexed DOUBLECOLON static_class_access",
/* 121 */ "value ::= smartytag RDEL",
/* 122 */ "value ::= value modifierlist",
/* 123 */ "variable ::= varindexed",
/* 124 */ "variable ::= DOLLAR varvar AT ID",
/* 125 */ "variable ::= object",
/* 126 */ "variable ::= HATCH ID HATCH",
/* 127 */ "variable ::= HATCH ID HATCH arrayindex",
/* 128 */ "variable ::= HATCH variable HATCH",
/* 129 */ "variable ::= HATCH variable HATCH arrayindex",
/* 130 */ "varindexed ::= DOLLAR varvar arrayindex",
/* 131 */ "arrayindex ::= arrayindex indexdef",
/* 132 */ "arrayindex ::=",
/* 133 */ "indexdef ::= DOT DOLLAR varvar",
/* 134 */ "indexdef ::= DOT DOLLAR varvar AT ID",
/* 135 */ "indexdef ::= DOT ID",
/* 136 */ "indexdef ::= DOT INTEGER",
/* 137 */ "indexdef ::= DOT LDEL expr RDEL",
/* 138 */ "indexdef ::= OPENB ID CLOSEB",
/* 139 */ "indexdef ::= OPENB ID DOT ID CLOSEB",
/* 140 */ "indexdef ::= OPENB expr CLOSEB",
/* 141 */ "indexdef ::= OPENB CLOSEB",
/* 142 */ "varvar ::= varvarele",
/* 143 */ "varvar ::= varvar varvarele",
/* 144 */ "varvarele ::= ID",
/* 145 */ "varvarele ::= LDEL expr RDEL",
/* 146 */ "object ::= varindexed objectchain",
/* 147 */ "objectchain ::= objectelement",
/* 148 */ "objectchain ::= objectchain objectelement",
/* 149 */ "objectelement ::= PTR ID arrayindex",
/* 150 */ "objectelement ::= PTR DOLLAR varvar arrayindex",
/* 151 */ "objectelement ::= PTR LDEL expr RDEL arrayindex",
/* 152 */ "objectelement ::= PTR ID LDEL expr RDEL arrayindex",
/* 153 */ "objectelement ::= PTR method",
/* 154 */ "function ::= ID OPENP params CLOSEP",
/* 155 */ "method ::= ID OPENP params CLOSEP",
/* 156 */ "method ::= DOLLAR ID OPENP params CLOSEP",
/* 157 */ "params ::= params COMMA expr",
/* 158 */ "params ::= expr",
/* 159 */ "params ::=",
/* 160 */ "modifierlist ::= modifierlist modifier modparameters",
/* 161 */ "modifierlist ::= modifier modparameters",
/* 162 */ "modifier ::= VERT AT ID",
/* 163 */ "modifier ::= VERT ID",
/* 164 */ "modparameters ::= modparameters modparameter",
/* 165 */ "modparameters ::=",
/* 166 */ "modparameter ::= COLON value",
/* 167 */ "modparameter ::= COLON array",
/* 168 */ "static_class_access ::= method",
/* 169 */ "static_class_access ::= method objectchain",
/* 170 */ "static_class_access ::= ID",
/* 171 */ "static_class_access ::= DOLLAR ID arrayindex",
/* 172 */ "static_class_access ::= DOLLAR ID arrayindex objectchain",
/* 173 */ "ifcond ::= EQUALS",
/* 174 */ "ifcond ::= NOTEQUALS",
/* 175 */ "ifcond ::= GREATERTHAN",
/* 176 */ "ifcond ::= LESSTHAN",
/* 177 */ "ifcond ::= GREATEREQUAL",
/* 178 */ "ifcond ::= LESSEQUAL",
/* 179 */ "ifcond ::= IDENTITY",
/* 180 */ "ifcond ::= NONEIDENTITY",
/* 181 */ "ifcond ::= MOD",
/* 182 */ "lop ::= LAND",
/* 183 */ "lop ::= LOR",
/* 184 */ "lop ::= LXOR",
/* 185 */ "array ::= OPENB arrayelements CLOSEB",
/* 186 */ "arrayelements ::= arrayelement",
/* 187 */ "arrayelements ::= arrayelements COMMA arrayelement",
/* 188 */ "arrayelements ::=",
/* 189 */ "arrayelement ::= value APTR expr",
/* 190 */ "arrayelement ::= ID APTR expr",
/* 191 */ "arrayelement ::= expr",
/* 192 */ "doublequoted_with_quotes ::= QUOTE QUOTE",
/* 193 */ "doublequoted_with_quotes ::= QUOTE doublequoted QUOTE",
/* 194 */ "doublequoted ::= doublequoted doublequotedcontent",
/* 195 */ "doublequoted ::= doublequotedcontent",
/* 196 */ "doublequotedcontent ::= BACKTICK variable BACKTICK",
/* 197 */ "doublequotedcontent ::= BACKTICK expr BACKTICK",
/* 198 */ "doublequotedcontent ::= DOLLARID",
/* 199 */ "doublequotedcontent ::= LDEL variable RDEL",
/* 200 */ "doublequotedcontent ::= LDEL expr RDEL",
/* 201 */ "doublequotedcontent ::= smartytag RDEL",
/* 202 */ "doublequotedcontent ::= TEXT",
/* 203 */ "optspace ::= SPACE",
/* 204 */ "optspace ::=",
);
public function tokenName($tokenType)
{
if ($tokenType === 0) {
return 'End of Input';
}
if ($tokenType > 0 && $tokenType < count($this->yyTokenName)) {
return $this->yyTokenName[$tokenType];
} else {
return "Unknown";
}
}
public static function yy_destructor($yymajor, $yypminor)
{
switch ($yymajor) {
default: break; /* If no destructor action specified: do nothing */
}
}
public function yy_pop_parser_stack()
{
if (!count($this->yystack)) {
return;
}
$yytos = array_pop($this->yystack);
if (self::$yyTraceFILE && $this->yyidx >= 0) {
fwrite(self::$yyTraceFILE,
self::$yyTracePrompt . 'Popping ' . $this->yyTokenName[$yytos->major] .
"\n");
}
$yymajor = $yytos->major;
self::yy_destructor($yymajor, $yytos->minor);
$this->yyidx--;
return $yymajor;
}
public function __destruct()
{
while ($this->yystack !== Array()) {
$this->yy_pop_parser_stack();
}
if (is_resource(self::$yyTraceFILE)) {
fclose(self::$yyTraceFILE);
}
}
public function yy_get_expected_tokens($token)
{
$state = $this->yystack[$this->yyidx]->stateno;
$expected = self::$yyExpectedTokens[$state];
if (in_array($token, self::$yyExpectedTokens[$state], true)) {
return $expected;
}
$stack = $this->yystack;
$yyidx = $this->yyidx;
do {
$yyact = $this->yy_find_shift_action($token);
if ($yyact >= self::YYNSTATE && $yyact < self::YYNSTATE + self::YYNRULE) {
// reduce action
$done = 0;
do {
if ($done++ == 100) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
// too much recursion prevents proper detection
// so give up
return array_unique($expected);
}
$yyruleno = $yyact - self::YYNSTATE;
$this->yyidx -= self::$yyRuleInfo[$yyruleno]['rhs'];
$nextstate = $this->yy_find_reduce_action(
$this->yystack[$this->yyidx]->stateno,
self::$yyRuleInfo[$yyruleno]['lhs']);
if (isset(self::$yyExpectedTokens[$nextstate])) {
$expected = array_merge($expected, self::$yyExpectedTokens[$nextstate]);
if (in_array($token,
self::$yyExpectedTokens[$nextstate], true)) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
return array_unique($expected);
}
}
if ($nextstate < self::YYNSTATE) {
// we need to shift a non-terminal
$this->yyidx++;
$x = new TP_yyStackEntry;
$x->stateno = $nextstate;
$x->major = self::$yyRuleInfo[$yyruleno]['lhs'];
$this->yystack[$this->yyidx] = $x;
continue 2;
} elseif ($nextstate == self::YYNSTATE + self::YYNRULE + 1) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
// the last token was just ignored, we can't accept
// by ignoring input, this is in essence ignoring a
// syntax error!
return array_unique($expected);
} elseif ($nextstate === self::YY_NO_ACTION) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
// input accepted, but not shifted (I guess)
return $expected;
} else {
$yyact = $nextstate;
}
} while (true);
}
break;
} while (true);
$this->yyidx = $yyidx;
$this->yystack = $stack;
return array_unique($expected);
}
public function yy_is_expected_token($token)
{
if ($token === 0) {
return true; // 0 is not part of this
}
$state = $this->yystack[$this->yyidx]->stateno;
if (in_array($token, self::$yyExpectedTokens[$state], true)) {
return true;
}
$stack = $this->yystack;
$yyidx = $this->yyidx;
do {
$yyact = $this->yy_find_shift_action($token);
if ($yyact >= self::YYNSTATE && $yyact < self::YYNSTATE + self::YYNRULE) {
// reduce action
$done = 0;
do {
if ($done++ == 100) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
// too much recursion prevents proper detection
// so give up
return true;
}
$yyruleno = $yyact - self::YYNSTATE;
$this->yyidx -= self::$yyRuleInfo[$yyruleno]['rhs'];
$nextstate = $this->yy_find_reduce_action(
$this->yystack[$this->yyidx]->stateno,
self::$yyRuleInfo[$yyruleno]['lhs']);
if (isset(self::$yyExpectedTokens[$nextstate]) &&
in_array($token, self::$yyExpectedTokens[$nextstate], true)) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
return true;
}
if ($nextstate < self::YYNSTATE) {
// we need to shift a non-terminal
$this->yyidx++;
$x = new TP_yyStackEntry;
$x->stateno = $nextstate;
$x->major = self::$yyRuleInfo[$yyruleno]['lhs'];
$this->yystack[$this->yyidx] = $x;
continue 2;
} elseif ($nextstate == self::YYNSTATE + self::YYNRULE + 1) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
if (!$token) {
// end of input: this is valid
return true;
}
// the last token was just ignored, we can't accept
// by ignoring input, this is in essence ignoring a
// syntax error!
return false;
} elseif ($nextstate === self::YY_NO_ACTION) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
// input accepted, but not shifted (I guess)
return true;
} else {
$yyact = $nextstate;
}
} while (true);
}
break;
} while (true);
$this->yyidx = $yyidx;
$this->yystack = $stack;
return true;
}
public function yy_find_shift_action($iLookAhead)
{
$stateno = $this->yystack[$this->yyidx]->stateno;
/* if ($this->yyidx < 0) return self::YY_NO_ACTION; */
if (!isset(self::$yy_shift_ofst[$stateno])) {
// no shift actions
return self::$yy_default[$stateno];
}
$i = self::$yy_shift_ofst[$stateno];
if ($i === self::YY_SHIFT_USE_DFLT) {
return self::$yy_default[$stateno];
}
if ($iLookAhead == self::YYNOCODE) {
return self::YY_NO_ACTION;
}
$i += $iLookAhead;
if ($i < 0 || $i >= self::YY_SZ_ACTTAB ||
self::$yy_lookahead[$i] != $iLookAhead) {
if (count(self::$yyFallback) && $iLookAhead < count(self::$yyFallback)
&& ($iFallback = self::$yyFallback[$iLookAhead]) != 0) {
if (self::$yyTraceFILE) {
fwrite(self::$yyTraceFILE, self::$yyTracePrompt . "FALLBACK " .
$this->yyTokenName[$iLookAhead] . " => " .
$this->yyTokenName[$iFallback] . "\n");
}
return $this->yy_find_shift_action($iFallback);
}
return self::$yy_default[$stateno];
} else {
return self::$yy_action[$i];
}
}
public function yy_find_reduce_action($stateno, $iLookAhead)
{
/* $stateno = $this->yystack[$this->yyidx]->stateno; */
if (!isset(self::$yy_reduce_ofst[$stateno])) {
return self::$yy_default[$stateno];
}
$i = self::$yy_reduce_ofst[$stateno];
if ($i == self::YY_REDUCE_USE_DFLT) {
return self::$yy_default[$stateno];
}
if ($iLookAhead == self::YYNOCODE) {
return self::YY_NO_ACTION;
}
$i += $iLookAhead;
if ($i < 0 || $i >= self::YY_SZ_ACTTAB ||
self::$yy_lookahead[$i] != $iLookAhead) {
return self::$yy_default[$stateno];
} else {
return self::$yy_action[$i];
}
}
public function yy_shift($yyNewState, $yyMajor, $yypMinor)
{
$this->yyidx++;
if ($this->yyidx >= self::YYSTACKDEPTH) {
$this->yyidx--;
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sStack Overflow!\n", self::$yyTracePrompt);
}
while ($this->yyidx >= 0) {
$this->yy_pop_parser_stack();
}
#line 85 "smarty_internal_templateparser.y"
$this->internalError = true;
$this->compiler->trigger_template_error("Stack overflow in template parser");
#line 1707 "smarty_internal_templateparser.php"
return;
}
$yytos = new TP_yyStackEntry;
$yytos->stateno = $yyNewState;
$yytos->major = $yyMajor;
$yytos->minor = $yypMinor;
array_push($this->yystack, $yytos);
if (self::$yyTraceFILE && $this->yyidx > 0) {
fprintf(self::$yyTraceFILE, "%sShift %d\n", self::$yyTracePrompt,
$yyNewState);
fprintf(self::$yyTraceFILE, "%sStack:", self::$yyTracePrompt);
for ($i = 1; $i <= $this->yyidx; $i++) {
fprintf(self::$yyTraceFILE, " %s",
$this->yyTokenName[$this->yystack[$i]->major]);
}
fwrite(self::$yyTraceFILE,"\n");
}
}
public static $yyRuleInfo = array(
array( 'lhs' => 83, 'rhs' => 1 ),
array( 'lhs' => 84, 'rhs' => 1 ),
array( 'lhs' => 84, 'rhs' => 2 ),
array( 'lhs' => 84, 'rhs' => 0 ),
array( 'lhs' => 85, 'rhs' => 2 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 85, 'rhs' => 1 ),
array( 'lhs' => 87, 'rhs' => 2 ),
array( 'lhs' => 87, 'rhs' => 3 ),
array( 'lhs' => 88, 'rhs' => 2 ),
array( 'lhs' => 88, 'rhs' => 0 ),
array( 'lhs' => 89, 'rhs' => 1 ),
array( 'lhs' => 89, 'rhs' => 1 ),
array( 'lhs' => 89, 'rhs' => 1 ),
array( 'lhs' => 89, 'rhs' => 1 ),
array( 'lhs' => 89, 'rhs' => 1 ),
array( 'lhs' => 89, 'rhs' => 1 ),
array( 'lhs' => 89, 'rhs' => 1 ),
array( 'lhs' => 86, 'rhs' => 2 ),
array( 'lhs' => 86, 'rhs' => 4 ),
array( 'lhs' => 86, 'rhs' => 3 ),
array( 'lhs' => 86, 'rhs' => 4 ),
array( 'lhs' => 86, 'rhs' => 3 ),
array( 'lhs' => 86, 'rhs' => 5 ),
array( 'lhs' => 86, 'rhs' => 5 ),
array( 'lhs' => 86, 'rhs' => 6 ),
array( 'lhs' => 86, 'rhs' => 5 ),
array( 'lhs' => 86, 'rhs' => 3 ),
array( 'lhs' => 86, 'rhs' => 2 ),
array( 'lhs' => 86, 'rhs' => 5 ),
array( 'lhs' => 86, 'rhs' => 4 ),
array( 'lhs' => 86, 'rhs' => 6 ),
array( 'lhs' => 86, 'rhs' => 2 ),
array( 'lhs' => 86, 'rhs' => 3 ),
array( 'lhs' => 86, 'rhs' => 2 ),
array( 'lhs' => 86, 'rhs' => 3 ),
array( 'lhs' => 86, 'rhs' => 11 ),
array( 'lhs' => 99, 'rhs' => 2 ),
array( 'lhs' => 99, 'rhs' => 1 ),
array( 'lhs' => 86, 'rhs' => 5 ),
array( 'lhs' => 86, 'rhs' => 7 ),
array( 'lhs' => 86, 'rhs' => 2 ),
array( 'lhs' => 86, 'rhs' => 7 ),
array( 'lhs' => 86, 'rhs' => 10 ),
array( 'lhs' => 86, 'rhs' => 7 ),
array( 'lhs' => 86, 'rhs' => 10 ),
array( 'lhs' => 86, 'rhs' => 3 ),
array( 'lhs' => 86, 'rhs' => 4 ),
array( 'lhs' => 86, 'rhs' => 2 ),
array( 'lhs' => 86, 'rhs' => 2 ),
array( 'lhs' => 86, 'rhs' => 3 ),
array( 'lhs' => 86, 'rhs' => 4 ),
array( 'lhs' => 86, 'rhs' => 5 ),
array( 'lhs' => 92, 'rhs' => 2 ),
array( 'lhs' => 92, 'rhs' => 1 ),
array( 'lhs' => 92, 'rhs' => 0 ),
array( 'lhs' => 101, 'rhs' => 4 ),
array( 'lhs' => 101, 'rhs' => 2 ),
array( 'lhs' => 101, 'rhs' => 2 ),
array( 'lhs' => 101, 'rhs' => 2 ),
array( 'lhs' => 101, 'rhs' => 2 ),
array( 'lhs' => 101, 'rhs' => 2 ),
array( 'lhs' => 101, 'rhs' => 4 ),
array( 'lhs' => 96, 'rhs' => 1 ),
array( 'lhs' => 96, 'rhs' => 3 ),
array( 'lhs' => 95, 'rhs' => 4 ),
array( 'lhs' => 95, 'rhs' => 3 ),
array( 'lhs' => 95, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 1 ),
array( 'lhs' => 93, 'rhs' => 1 ),
array( 'lhs' => 93, 'rhs' => 4 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 1 ),
array( 'lhs' => 93, 'rhs' => 2 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 2 ),
array( 'lhs' => 93, 'rhs' => 2 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 2 ),
array( 'lhs' => 93, 'rhs' => 2 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 93, 'rhs' => 3 ),
array( 'lhs' => 102, 'rhs' => 8 ),
array( 'lhs' => 102, 'rhs' => 7 ),
array( 'lhs' => 90, 'rhs' => 1 ),
array( 'lhs' => 90, 'rhs' => 2 ),
array( 'lhs' => 90, 'rhs' => 2 ),
array( 'lhs' => 90, 'rhs' => 2 ),
array( 'lhs' => 90, 'rhs' => 2 ),
array( 'lhs' => 90, 'rhs' => 1 ),
array( 'lhs' => 90, 'rhs' => 1 ),
array( 'lhs' => 90, 'rhs' => 3 ),
array( 'lhs' => 90, 'rhs' => 2 ),
array( 'lhs' => 90, 'rhs' => 2 ),
array( 'lhs' => 90, 'rhs' => 1 ),
array( 'lhs' => 90, 'rhs' => 1 ),
array( 'lhs' => 90, 'rhs' => 3 ),
array( 'lhs' => 90, 'rhs' => 1 ),
array( 'lhs' => 90, 'rhs' => 1 ),
array( 'lhs' => 90, 'rhs' => 3 ),
array( 'lhs' => 90, 'rhs' => 3 ),
array( 'lhs' => 90, 'rhs' => 2 ),
array( 'lhs' => 90, 'rhs' => 2 ),
array( 'lhs' => 106, 'rhs' => 1 ),
array( 'lhs' => 106, 'rhs' => 4 ),
array( 'lhs' => 106, 'rhs' => 1 ),
array( 'lhs' => 106, 'rhs' => 3 ),
array( 'lhs' => 106, 'rhs' => 4 ),
array( 'lhs' => 106, 'rhs' => 3 ),
array( 'lhs' => 106, 'rhs' => 4 ),
array( 'lhs' => 94, 'rhs' => 3 ),
array( 'lhs' => 111, 'rhs' => 2 ),
array( 'lhs' => 111, 'rhs' => 0 ),
array( 'lhs' => 112, 'rhs' => 3 ),
array( 'lhs' => 112, 'rhs' => 5 ),
array( 'lhs' => 112, 'rhs' => 2 ),
array( 'lhs' => 112, 'rhs' => 2 ),
array( 'lhs' => 112, 'rhs' => 4 ),
array( 'lhs' => 112, 'rhs' => 3 ),
array( 'lhs' => 112, 'rhs' => 5 ),
array( 'lhs' => 112, 'rhs' => 3 ),
array( 'lhs' => 112, 'rhs' => 2 ),
array( 'lhs' => 98, 'rhs' => 1 ),
array( 'lhs' => 98, 'rhs' => 2 ),
array( 'lhs' => 113, 'rhs' => 1 ),
array( 'lhs' => 113, 'rhs' => 3 ),
array( 'lhs' => 110, 'rhs' => 2 ),
array( 'lhs' => 114, 'rhs' => 1 ),
array( 'lhs' => 114, 'rhs' => 2 ),
array( 'lhs' => 115, 'rhs' => 3 ),
array( 'lhs' => 115, 'rhs' => 4 ),
array( 'lhs' => 115, 'rhs' => 5 ),
array( 'lhs' => 115, 'rhs' => 6 ),
array( 'lhs' => 115, 'rhs' => 2 ),
array( 'lhs' => 107, 'rhs' => 4 ),
array( 'lhs' => 116, 'rhs' => 4 ),
array( 'lhs' => 116, 'rhs' => 5 ),
array( 'lhs' => 117, 'rhs' => 3 ),
array( 'lhs' => 117, 'rhs' => 1 ),
array( 'lhs' => 117, 'rhs' => 0 ),
array( 'lhs' => 91, 'rhs' => 3 ),
array( 'lhs' => 91, 'rhs' => 2 ),
array( 'lhs' => 118, 'rhs' => 3 ),
array( 'lhs' => 118, 'rhs' => 2 ),
array( 'lhs' => 100, 'rhs' => 2 ),
array( 'lhs' => 100, 'rhs' => 0 ),
array( 'lhs' => 119, 'rhs' => 2 ),
array( 'lhs' => 119, 'rhs' => 2 ),
array( 'lhs' => 109, 'rhs' => 1 ),
array( 'lhs' => 109, 'rhs' => 2 ),
array( 'lhs' => 109, 'rhs' => 1 ),
array( 'lhs' => 109, 'rhs' => 3 ),
array( 'lhs' => 109, 'rhs' => 4 ),
array( 'lhs' => 104, 'rhs' => 1 ),
array( 'lhs' => 104, 'rhs' => 1 ),
array( 'lhs' => 104, 'rhs' => 1 ),
array( 'lhs' => 104, 'rhs' => 1 ),
array( 'lhs' => 104, 'rhs' => 1 ),
array( 'lhs' => 104, 'rhs' => 1 ),
array( 'lhs' => 104, 'rhs' => 1 ),
array( 'lhs' => 104, 'rhs' => 1 ),
array( 'lhs' => 104, 'rhs' => 1 ),
array( 'lhs' => 105, 'rhs' => 1 ),
array( 'lhs' => 105, 'rhs' => 1 ),
array( 'lhs' => 105, 'rhs' => 1 ),
array( 'lhs' => 103, 'rhs' => 3 ),
array( 'lhs' => 120, 'rhs' => 1 ),
array( 'lhs' => 120, 'rhs' => 3 ),
array( 'lhs' => 120, 'rhs' => 0 ),
array( 'lhs' => 121, 'rhs' => 3 ),
array( 'lhs' => 121, 'rhs' => 3 ),
array( 'lhs' => 121, 'rhs' => 1 ),
array( 'lhs' => 108, 'rhs' => 2 ),
array( 'lhs' => 108, 'rhs' => 3 ),
array( 'lhs' => 122, 'rhs' => 2 ),
array( 'lhs' => 122, 'rhs' => 1 ),
array( 'lhs' => 123, 'rhs' => 3 ),
array( 'lhs' => 123, 'rhs' => 3 ),
array( 'lhs' => 123, 'rhs' => 1 ),
array( 'lhs' => 123, 'rhs' => 3 ),
array( 'lhs' => 123, 'rhs' => 3 ),
array( 'lhs' => 123, 'rhs' => 2 ),
array( 'lhs' => 123, 'rhs' => 1 ),
array( 'lhs' => 97, 'rhs' => 1 ),
array( 'lhs' => 97, 'rhs' => 0 ),
);
public static $yyReduceMap = array(
0 => 0,
1 => 1,
2 => 1,
4 => 4,
5 => 5,
6 => 6,
7 => 7,
8 => 8,
9 => 9,
10 => 10,
11 => 11,
12 => 12,
13 => 13,
14 => 14,
15 => 15,
16 => 16,
17 => 17,
20 => 17,
204 => 17,
18 => 18,
77 => 18,
19 => 19,
105 => 19,
107 => 19,
108 => 19,
131 => 19,
169 => 19,
21 => 21,
22 => 21,
48 => 21,
70 => 21,
71 => 21,
78 => 21,
79 => 21,
84 => 21,
104 => 21,
109 => 21,
110 => 21,
115 => 21,
117 => 21,
118 => 21,
125 => 21,
142 => 21,
168 => 21,
170 => 21,
186 => 21,
191 => 21,
203 => 21,
23 => 23,
24 => 23,
25 => 25,
26 => 26,
27 => 27,
28 => 28,
29 => 29,
30 => 30,
32 => 30,
31 => 31,
33 => 33,
34 => 33,
35 => 35,
36 => 36,
37 => 37,
38 => 38,
39 => 39,
40 => 40,
41 => 41,
42 => 42,
43 => 43,
45 => 43,
44 => 44,
46 => 46,
47 => 47,
49 => 49,
50 => 50,
51 => 51,
52 => 52,
54 => 52,
53 => 53,
55 => 53,
56 => 56,
57 => 57,
58 => 58,
59 => 59,
60 => 60,
61 => 61,
62 => 62,
63 => 63,
64 => 64,
73 => 64,
158 => 64,
162 => 64,
166 => 64,
167 => 64,
65 => 65,
159 => 65,
165 => 65,
66 => 66,
67 => 67,
68 => 67,
69 => 69,
72 => 72,
74 => 74,
75 => 75,
76 => 75,
80 => 80,
81 => 81,
82 => 81,
83 => 81,
85 => 85,
122 => 85,
86 => 86,
89 => 86,
100 => 86,
87 => 87,
88 => 88,
90 => 90,
91 => 91,
92 => 92,
97 => 92,
93 => 93,
96 => 93,
94 => 94,
99 => 94,
95 => 95,
98 => 95,
101 => 101,
102 => 102,
103 => 103,
106 => 106,
111 => 111,
112 => 112,
113 => 113,
114 => 114,
116 => 116,
119 => 119,
120 => 120,
121 => 121,
123 => 123,
124 => 124,
126 => 126,
127 => 127,
128 => 128,
129 => 129,
130 => 130,
132 => 132,
188 => 132,
133 => 133,
134 => 134,
135 => 135,
136 => 136,
137 => 137,
140 => 137,
138 => 138,
139 => 139,
141 => 141,
143 => 143,
144 => 144,
145 => 145,
146 => 146,
147 => 147,
148 => 148,
149 => 149,
150 => 150,
151 => 151,
152 => 152,
153 => 153,
154 => 154,
155 => 155,
156 => 156,
157 => 157,
160 => 160,
161 => 161,
163 => 163,
164 => 164,
171 => 171,
172 => 172,
173 => 173,
174 => 174,
175 => 175,
176 => 176,
177 => 177,
178 => 178,
179 => 179,
180 => 180,
181 => 181,
182 => 182,
183 => 183,
184 => 184,
185 => 185,
187 => 187,
189 => 189,
190 => 190,
192 => 192,
193 => 193,
194 => 194,
195 => 195,
196 => 196,
197 => 196,
199 => 196,
198 => 198,
200 => 200,
201 => 201,
202 => 202,
);
#line 96 "smarty_internal_templateparser.y"
function yy_r0(){
$this->_retvalue = $this->root_buffer->to_smarty_php();
}
#line 2146 "smarty_internal_templateparser.php"
#line 104 "smarty_internal_templateparser.y"
function yy_r1(){
if ($this->yystack[$this->yyidx + 0]->minor != null) {
$this->current_buffer->append_subtree($this->yystack[$this->yyidx + 0]->minor);
}
}
#line 2153 "smarty_internal_templateparser.php"
#line 124 "smarty_internal_templateparser.y"
function yy_r4(){
if ($this->compiler->has_code) {
$tmp =''; foreach ($this->compiler->prefix_code as $code) {$tmp.=$code;} $this->compiler->prefix_code=array();
$this->_retvalue = new _smarty_tag($this, $this->compiler->processNocacheCode($tmp.$this->yystack[$this->yyidx + -1]->minor,true));
} else {
$this->_retvalue = null;
}
$this->compiler->has_variable_string = false;
$this->block_nesting_level = count($this->compiler->_tag_stack);
}
#line 2165 "smarty_internal_templateparser.php"
#line 136 "smarty_internal_templateparser.y"
function yy_r5(){
$this->_retvalue = null;
}
#line 2170 "smarty_internal_templateparser.php"
#line 141 "smarty_internal_templateparser.y"
function yy_r6(){
$this->_retvalue = new _smarty_text($this, $this->yystack[$this->yyidx + 0]->minor);
}
#line 2175 "smarty_internal_templateparser.php"
#line 146 "smarty_internal_templateparser.y"
function yy_r7(){
if ($this->php_handling == Smarty::PHP_PASSTHRU) {
$this->_retvalue = new _smarty_text($this, self::escape_start_tag($this->yystack[$this->yyidx + 0]->minor));
} elseif ($this->php_handling == Smarty::PHP_QUOTE) {
$this->_retvalue = new _smarty_text($this, htmlspecialchars($this->yystack[$this->yyidx + 0]->minor, ENT_QUOTES));
} elseif ($this->php_handling == Smarty::PHP_ALLOW) {
if (!($this->smarty instanceof SmartyBC)) {
$this->compiler->trigger_template_error (self::Err3);
}
$this->_retvalue = new _smarty_text($this, $this->compiler->processNocacheCode('<?php', true));
} elseif ($this->php_handling == Smarty::PHP_REMOVE) {
$this->_retvalue = null;
}
}
#line 2191 "smarty_internal_templateparser.php"
#line 162 "smarty_internal_templateparser.y"
function yy_r8(){
if ($this->is_xml) {
$this->compiler->tag_nocache = true;
$this->is_xml = false;
$save = $this->template->has_nocache_code;
$this->_retvalue = new _smarty_text($this, $this->compiler->processNocacheCode("<?php echo '?>';?>\n", $this->compiler, true));
$this->template->has_nocache_code = $save;
} elseif ($this->php_handling == Smarty::PHP_PASSTHRU) {
$this->_retvalue = new _smarty_text($this, '?<?php ?>>');
} elseif ($this->php_handling == Smarty::PHP_QUOTE) {
$this->_retvalue = new _smarty_text($this, htmlspecialchars('?>', ENT_QUOTES));
} elseif ($this->php_handling == Smarty::PHP_ALLOW) {
$this->_retvalue = new _smarty_text($this, $this->compiler->processNocacheCode('?>', true));
} elseif ($this->php_handling == Smarty::PHP_REMOVE) {
$this->_retvalue = null;
}
}
#line 2210 "smarty_internal_templateparser.php"
#line 181 "smarty_internal_templateparser.y"
function yy_r9(){
if ($this->php_handling == Smarty::PHP_PASSTHRU) {
$this->_retvalue = new _smarty_text($this, '<<?php ?>%');
} elseif ($this->php_handling == Smarty::PHP_QUOTE) {
$this->_retvalue = new _smarty_text($this, htmlspecialchars($this->yystack[$this->yyidx + 0]->minor, ENT_QUOTES));
} elseif ($this->php_handling == Smarty::PHP_ALLOW) {
if ($this->asp_tags) {
if (!($this->smarty instanceof SmartyBC)) {
$this->compiler->trigger_template_error (self::Err3);
}
$this->_retvalue = new _smarty_text($this, $this->compiler->processNocacheCode('<%', true));
} else {
$this->_retvalue = new _smarty_text($this, '<<?php ?>%');
}
} elseif ($this->php_handling == Smarty::PHP_REMOVE) {
if ($this->asp_tags) {
$this->_retvalue = null;
} else {
$this->_retvalue = new _smarty_text($this, '<<?php ?>%');
}
}
}
#line 2234 "smarty_internal_templateparser.php"
#line 205 "smarty_internal_templateparser.y"
function yy_r10(){
if ($this->php_handling == Smarty::PHP_PASSTHRU) {
$this->_retvalue = new _smarty_text($this, '%<?php ?>>');
} elseif ($this->php_handling == Smarty::PHP_QUOTE) {
$this->_retvalue = new _smarty_text($this, htmlspecialchars('%>', ENT_QUOTES));
} elseif ($this->php_handling == Smarty::PHP_ALLOW) {
if ($this->asp_tags) {
$this->_retvalue = new _smarty_text($this, $this->compiler->processNocacheCode('%>', true));
} else {
$this->_retvalue = new _smarty_text($this, '%<?php ?>>');
}
} elseif ($this->php_handling == Smarty::PHP_REMOVE) {
if ($this->asp_tags) {
$this->_retvalue = null;
} else {
$this->_retvalue = new _smarty_text($this, '%<?php ?>>');
}
}
}
#line 2255 "smarty_internal_templateparser.php"
#line 225 "smarty_internal_templateparser.y"
function yy_r11(){
if ($this->strip) {
$this->_retvalue = new _smarty_text($this, preg_replace('![\t ]*[\r\n]+[\t ]*!', '', self::escape_start_tag($this->yystack[$this->yyidx + 0]->minor)));
} else {
$this->_retvalue = new _smarty_text($this, self::escape_start_tag($this->yystack[$this->yyidx + 0]->minor));
}
}
#line 2264 "smarty_internal_templateparser.php"
#line 234 "smarty_internal_templateparser.y"
function yy_r12(){
$this->compiler->tag_nocache = true;
$this->is_xml = true;
$save = $this->template->has_nocache_code;
$this->_retvalue = new _smarty_text($this, $this->compiler->processNocacheCode("<?php echo '<?xml';?>", $this->compiler, true));
$this->template->has_nocache_code = $save;
}
#line 2273 "smarty_internal_templateparser.php"
#line 243 "smarty_internal_templateparser.y"
function yy_r13(){
if ($this->strip) {
$this->_retvalue = new _smarty_text($this, preg_replace('![\t ]*[\r\n]+[\t ]*!', '', $this->yystack[$this->yyidx + 0]->minor));
} else {
$this->_retvalue = new _smarty_text($this, $this->yystack[$this->yyidx + 0]->minor);
}
}
#line 2282 "smarty_internal_templateparser.php"
#line 252 "smarty_internal_templateparser.y"
function yy_r14(){
$this->strip = true;
}
#line 2287 "smarty_internal_templateparser.php"
#line 256 "smarty_internal_templateparser.y"
function yy_r15(){
$this->strip = false;
}
#line 2292 "smarty_internal_templateparser.php"
#line 260 "smarty_internal_templateparser.y"
function yy_r16(){
if ($this->strip) {
SMARTY_INTERNAL_COMPILE_BLOCK::blockSource($this->compiler, preg_replace('![\t ]*[\r\n]+[\t ]*!', '', $this->yystack[$this->yyidx + 0]->minor));
} else {
SMARTY_INTERNAL_COMPILE_BLOCK::blockSource($this->compiler, $this->yystack[$this->yyidx + 0]->minor);
}
}
#line 2301 "smarty_internal_templateparser.php"
#line 269 "smarty_internal_templateparser.y"
function yy_r17(){
$this->_retvalue = '';
}
#line 2306 "smarty_internal_templateparser.php"
#line 273 "smarty_internal_templateparser.y"
function yy_r18(){
$this->_retvalue = $this->yystack[$this->yyidx + -1]->minor;
}
#line 2311 "smarty_internal_templateparser.php"
#line 277 "smarty_internal_templateparser.y"
function yy_r19(){
$this->_retvalue = $this->yystack[$this->yyidx + -1]->minor.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2316 "smarty_internal_templateparser.php"
#line 285 "smarty_internal_templateparser.y"
function yy_r21(){
$this->_retvalue = $this->yystack[$this->yyidx + 0]->minor;
}
#line 2321 "smarty_internal_templateparser.php"
#line 293 "smarty_internal_templateparser.y"
function yy_r23(){
$this->_retvalue = self::escape_start_tag($this->yystack[$this->yyidx + 0]->minor);
}
#line 2326 "smarty_internal_templateparser.php"
#line 301 "smarty_internal_templateparser.y"
function yy_r25(){
$this->_retvalue = self::escape_end_tag($this->yystack[$this->yyidx + 0]->minor);
}
#line 2331 "smarty_internal_templateparser.php"
#line 305 "smarty_internal_templateparser.y"
function yy_r26(){
$this->_retvalue = '<<?php ?>%';
}
#line 2336 "smarty_internal_templateparser.php"
#line 309 "smarty_internal_templateparser.y"
function yy_r27(){
$this->_retvalue = '%<?php ?>>';
}
#line 2341 "smarty_internal_templateparser.php"
#line 318 "smarty_internal_templateparser.y"
function yy_r28(){
$this->_retvalue = $this->compiler->compileTag('private_print_expression',array(),array('value'=>$this->yystack[$this->yyidx + 0]->minor));
}
#line 2346 "smarty_internal_templateparser.php"
#line 322 "smarty_internal_templateparser.y"
function yy_r29(){
$this->_retvalue = $this->compiler->compileTag('private_print_expression',$this->yystack[$this->yyidx + 0]->minor,array('value'=>$this->yystack[$this->yyidx + -2]->minor, 'modifierlist'=>$this->yystack[$this->yyidx + -1]->minor));
}
#line 2351 "smarty_internal_templateparser.php"
#line 326 "smarty_internal_templateparser.y"
function yy_r30(){
$this->_retvalue = $this->compiler->compileTag('private_print_expression',$this->yystack[$this->yyidx + 0]->minor,array('value'=>$this->yystack[$this->yyidx + -1]->minor));
}
#line 2356 "smarty_internal_templateparser.php"
#line 330 "smarty_internal_templateparser.y"
function yy_r31(){
$this->_retvalue = $this->compiler->compileTag('private_print_expression',$this->yystack[$this->yyidx + 0]->minor,array('value'=>$this->yystack[$this->yyidx + -2]->minor,'modifierlist'=>$this->yystack[$this->yyidx + -1]->minor));
}
#line 2361 "smarty_internal_templateparser.php"
#line 343 "smarty_internal_templateparser.y"
function yy_r33(){
$this->_retvalue = $this->compiler->compileTag('assign',array(array('value'=>$this->yystack[$this->yyidx + 0]->minor),array('var'=>"'".$this->yystack[$this->yyidx + -2]->minor."'")));
}
#line 2366 "smarty_internal_templateparser.php"
#line 351 "smarty_internal_templateparser.y"
function yy_r35(){
$this->_retvalue = $this->compiler->compileTag('assign',array_merge(array(array('value'=>$this->yystack[$this->yyidx + -1]->minor),array('var'=>"'".$this->yystack[$this->yyidx + -3]->minor."'")),$this->yystack[$this->yyidx + 0]->minor));
}
#line 2371 "smarty_internal_templateparser.php"
#line 355 "smarty_internal_templateparser.y"
function yy_r36(){
$this->_retvalue = $this->compiler->compileTag('assign',array_merge(array(array('value'=>$this->yystack[$this->yyidx + -1]->minor),array('var'=>$this->yystack[$this->yyidx + -3]->minor['var'])),$this->yystack[$this->yyidx + 0]->minor),array('smarty_internal_index'=>$this->yystack[$this->yyidx + -3]->minor['smarty_internal_index']));
}
#line 2376 "smarty_internal_templateparser.php"
#line 360 "smarty_internal_templateparser.y"
function yy_r37(){
$this->_retvalue = $this->compiler->compileTag($this->yystack[$this->yyidx + -1]->minor,$this->yystack[$this->yyidx + 0]->minor);
}
#line 2381 "smarty_internal_templateparser.php"
#line 364 "smarty_internal_templateparser.y"
function yy_r38(){
$this->_retvalue = $this->compiler->compileTag($this->yystack[$this->yyidx + 0]->minor,array());
}
#line 2386 "smarty_internal_templateparser.php"
#line 369 "smarty_internal_templateparser.y"
function yy_r39(){
$this->_retvalue = $this->compiler->compileTag($this->yystack[$this->yyidx + -3]->minor,$this->yystack[$this->yyidx + 0]->minor,array('object_methode'=>$this->yystack[$this->yyidx + -1]->minor));
}
#line 2391 "smarty_internal_templateparser.php"
#line 374 "smarty_internal_templateparser.y"
function yy_r40(){
$this->_retvalue = '<?php ob_start();?>'.$this->compiler->compileTag($this->yystack[$this->yyidx + -2]->minor,$this->yystack[$this->yyidx + 0]->minor).'<?php echo ';
$this->_retvalue .= $this->compiler->compileTag('private_modifier',array(),array('modifierlist'=>$this->yystack[$this->yyidx + -1]->minor,'value'=>'ob_get_clean()')).'?>';
}
#line 2397 "smarty_internal_templateparser.php"
#line 380 "smarty_internal_templateparser.y"
function yy_r41(){
$this->_retvalue = '<?php ob_start();?>'.$this->compiler->compileTag($this->yystack[$this->yyidx + -4]->minor,$this->yystack[$this->yyidx + 0]->minor,array('object_methode'=>$this->yystack[$this->yyidx + -2]->minor)).'<?php echo ';
$this->_retvalue .= $this->compiler->compileTag('private_modifier',array(),array('modifierlist'=>$this->yystack[$this->yyidx + -1]->minor,'value'=>'ob_get_clean()')).'?>';
}
#line 2403 "smarty_internal_templateparser.php"
#line 386 "smarty_internal_templateparser.y"
function yy_r42(){
$tag = trim(substr($this->yystack[$this->yyidx + -1]->minor,$this->lex->ldel_length));
$this->_retvalue = $this->compiler->compileTag(($tag == 'else if')? 'elseif' : $tag,array(),array('if condition'=>$this->yystack[$this->yyidx + 0]->minor));
}
#line 2409 "smarty_internal_templateparser.php"
#line 391 "smarty_internal_templateparser.y"
function yy_r43(){
$tag = trim(substr($this->yystack[$this->yyidx + -2]->minor,$this->lex->ldel_length));
$this->_retvalue = $this->compiler->compileTag(($tag == 'else if')? 'elseif' : $tag,$this->yystack[$this->yyidx + 0]->minor,array('if condition'=>$this->yystack[$this->yyidx + -1]->minor));
}
#line 2415 "smarty_internal_templateparser.php"
#line 396 "smarty_internal_templateparser.y"
function yy_r44(){
$tag = trim(substr($this->yystack[$this->yyidx + -1]->minor,$this->lex->ldel_length));
$this->_retvalue = $this->compiler->compileTag(($tag == 'else if')? 'elseif' : $tag,array(),array('if condition'=>$this->yystack[$this->yyidx + 0]->minor));
}
#line 2421 "smarty_internal_templateparser.php"
#line 407 "smarty_internal_templateparser.y"
function yy_r46(){
$this->_retvalue = $this->compiler->compileTag('for',array_merge($this->yystack[$this->yyidx + 0]->minor,array(array('start'=>$this->yystack[$this->yyidx + -9]->minor),array('ifexp'=>$this->yystack[$this->yyidx + -6]->minor),array('var'=>$this->yystack[$this->yyidx + -2]->minor),array('step'=>$this->yystack[$this->yyidx + -1]->minor))),1);
}
#line 2426 "smarty_internal_templateparser.php"
#line 411 "smarty_internal_templateparser.y"
function yy_r47(){
$this->_retvalue = '='.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2431 "smarty_internal_templateparser.php"
#line 419 "smarty_internal_templateparser.y"
function yy_r49(){
$this->_retvalue = $this->compiler->compileTag('for',array_merge($this->yystack[$this->yyidx + 0]->minor,array(array('start'=>$this->yystack[$this->yyidx + -3]->minor),array('to'=>$this->yystack[$this->yyidx + -1]->minor))),0);
}
#line 2436 "smarty_internal_templateparser.php"
#line 423 "smarty_internal_templateparser.y"
function yy_r50(){
$this->_retvalue = $this->compiler->compileTag('for',array_merge($this->yystack[$this->yyidx + 0]->minor,array(array('start'=>$this->yystack[$this->yyidx + -5]->minor),array('to'=>$this->yystack[$this->yyidx + -3]->minor),array('step'=>$this->yystack[$this->yyidx + -1]->minor))),0);
}
#line 2441 "smarty_internal_templateparser.php"
#line 428 "smarty_internal_templateparser.y"
function yy_r51(){
$this->_retvalue = $this->compiler->compileTag('foreach',$this->yystack[$this->yyidx + 0]->minor);
}
#line 2446 "smarty_internal_templateparser.php"
#line 433 "smarty_internal_templateparser.y"
function yy_r52(){
$this->_retvalue = $this->compiler->compileTag('foreach',array_merge($this->yystack[$this->yyidx + 0]->minor,array(array('from'=>$this->yystack[$this->yyidx + -4]->minor),array('item'=>$this->yystack[$this->yyidx + -1]->minor))));
}
#line 2451 "smarty_internal_templateparser.php"
#line 437 "smarty_internal_templateparser.y"
function yy_r53(){
$this->_retvalue = $this->compiler->compileTag('foreach',array_merge($this->yystack[$this->yyidx + 0]->minor,array(array('from'=>$this->yystack[$this->yyidx + -7]->minor),array('item'=>$this->yystack[$this->yyidx + -1]->minor),array('key'=>$this->yystack[$this->yyidx + -4]->minor))));
}
#line 2456 "smarty_internal_templateparser.php"
#line 450 "smarty_internal_templateparser.y"
function yy_r56(){
$this->_retvalue = $this->compiler->compileTag('setfilter',array(),array('modifier_list'=>array(array_merge(array($this->yystack[$this->yyidx + -1]->minor),$this->yystack[$this->yyidx + 0]->minor))));
}
#line 2461 "smarty_internal_templateparser.php"
#line 454 "smarty_internal_templateparser.y"
function yy_r57(){
$this->_retvalue = $this->compiler->compileTag('setfilter',array(),array('modifier_list'=>array_merge(array(array_merge(array($this->yystack[$this->yyidx + -2]->minor),$this->yystack[$this->yyidx + -1]->minor)),$this->yystack[$this->yyidx + 0]->minor)));
}
#line 2466 "smarty_internal_templateparser.php"
#line 459 "smarty_internal_templateparser.y"
function yy_r58(){
$j = strrpos($this->yystack[$this->yyidx + 0]->minor,'.');
if ($this->yystack[$this->yyidx + 0]->minor[$j+1] == 'c') {
// {$smarty.block.child}
$this->_retvalue = SMARTY_INTERNAL_COMPILE_BLOCK::compileChildBlock($this->compiler);
} else {
// {$smarty.block.parent}
$this->_retvalue = SMARTY_INTERNAL_COMPILE_BLOCK::compileParentBlock($this->compiler);
}
}
#line 2478 "smarty_internal_templateparser.php"
#line 472 "smarty_internal_templateparser.y"
function yy_r59(){
$this->_retvalue = $this->compiler->compileTag($this->yystack[$this->yyidx + 0]->minor.'close',array());
}
#line 2483 "smarty_internal_templateparser.php"
#line 476 "smarty_internal_templateparser.y"
function yy_r60(){
$this->_retvalue = $this->compiler->compileTag($this->yystack[$this->yyidx + -1]->minor.'close',array(),array('modifier_list'=>$this->yystack[$this->yyidx + 0]->minor));
}
#line 2488 "smarty_internal_templateparser.php"
#line 481 "smarty_internal_templateparser.y"
function yy_r61(){
$this->_retvalue = $this->compiler->compileTag($this->yystack[$this->yyidx + -2]->minor.'close',array(),array('object_methode'=>$this->yystack[$this->yyidx + 0]->minor));
}
#line 2493 "smarty_internal_templateparser.php"
#line 485 "smarty_internal_templateparser.y"
function yy_r62(){
$this->_retvalue = $this->compiler->compileTag($this->yystack[$this->yyidx + -3]->minor.'close',array(),array('object_methode'=>$this->yystack[$this->yyidx + -1]->minor, 'modifier_list'=>$this->yystack[$this->yyidx + 0]->minor));
}
#line 2498 "smarty_internal_templateparser.php"
#line 493 "smarty_internal_templateparser.y"
function yy_r63(){
$this->_retvalue = $this->yystack[$this->yyidx + -1]->minor;
$this->_retvalue[] = $this->yystack[$this->yyidx + 0]->minor;
}
#line 2504 "smarty_internal_templateparser.php"
#line 499 "smarty_internal_templateparser.y"
function yy_r64(){
$this->_retvalue = array($this->yystack[$this->yyidx + 0]->minor);
}
#line 2509 "smarty_internal_templateparser.php"
#line 504 "smarty_internal_templateparser.y"
function yy_r65(){
$this->_retvalue = array();
}
#line 2514 "smarty_internal_templateparser.php"
#line 509 "smarty_internal_templateparser.y"
function yy_r66(){
if (preg_match('~^true$~i', $this->yystack[$this->yyidx + 0]->minor)) {
$this->_retvalue = array($this->yystack[$this->yyidx + -2]->minor=>'true');
} elseif (preg_match('~^false$~i', $this->yystack[$this->yyidx + 0]->minor)) {
$this->_retvalue = array($this->yystack[$this->yyidx + -2]->minor=>'false');
} elseif (preg_match('~^null$~i', $this->yystack[$this->yyidx + 0]->minor)) {
$this->_retvalue = array($this->yystack[$this->yyidx + -2]->minor=>'null');
} else {
$this->_retvalue = array($this->yystack[$this->yyidx + -2]->minor=>"'".$this->yystack[$this->yyidx + 0]->minor."'");
}
}
#line 2527 "smarty_internal_templateparser.php"
#line 521 "smarty_internal_templateparser.y"
function yy_r67(){
$this->_retvalue = array(trim($this->yystack[$this->yyidx + -1]->minor," =\n\r\t")=>$this->yystack[$this->yyidx + 0]->minor);
}
#line 2532 "smarty_internal_templateparser.php"
#line 529 "smarty_internal_templateparser.y"
function yy_r69(){
$this->_retvalue = "'".$this->yystack[$this->yyidx + 0]->minor."'";
}
#line 2537 "smarty_internal_templateparser.php"
#line 541 "smarty_internal_templateparser.y"
function yy_r72(){
$this->_retvalue = array($this->yystack[$this->yyidx + -2]->minor=>$this->yystack[$this->yyidx + 0]->minor);
}
#line 2542 "smarty_internal_templateparser.php"
#line 554 "smarty_internal_templateparser.y"
function yy_r74(){
$this->yystack[$this->yyidx + -2]->minor[]=$this->yystack[$this->yyidx + 0]->minor;
$this->_retvalue = $this->yystack[$this->yyidx + -2]->minor;
}
#line 2548 "smarty_internal_templateparser.php"
#line 559 "smarty_internal_templateparser.y"
function yy_r75(){
$this->_retvalue = array('var' => $this->yystack[$this->yyidx + -2]->minor, 'value'=>$this->yystack[$this->yyidx + 0]->minor);
}
#line 2553 "smarty_internal_templateparser.php"
#line 587 "smarty_internal_templateparser.y"
function yy_r80(){
$this->_retvalue = '$_smarty_tpl->getStreamVariable(\''. $this->yystack[$this->yyidx + -2]->minor .'://'. $this->yystack[$this->yyidx + 0]->minor . '\')';
}
#line 2558 "smarty_internal_templateparser.php"
#line 592 "smarty_internal_templateparser.y"
function yy_r81(){
$this->_retvalue = $this->yystack[$this->yyidx + -2]->minor . trim($this->yystack[$this->yyidx + -1]->minor) . $this->yystack[$this->yyidx + 0]->minor;
}
#line 2563 "smarty_internal_templateparser.php"
#line 611 "smarty_internal_templateparser.y"
function yy_r85(){
$this->_retvalue = $this->compiler->compileTag('private_modifier',array(),array('value'=>$this->yystack[$this->yyidx + -1]->minor,'modifierlist'=>$this->yystack[$this->yyidx + 0]->minor));
}
#line 2568 "smarty_internal_templateparser.php"
#line 617 "smarty_internal_templateparser.y"
function yy_r86(){
$this->_retvalue = $this->yystack[$this->yyidx + -2]->minor.$this->yystack[$this->yyidx + -1]->minor.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2573 "smarty_internal_templateparser.php"
#line 621 "smarty_internal_templateparser.y"
function yy_r87(){
$this->_retvalue = 'in_array('.$this->yystack[$this->yyidx + -2]->minor.','.$this->yystack[$this->yyidx + 0]->minor.')';
}
#line 2578 "smarty_internal_templateparser.php"
#line 625 "smarty_internal_templateparser.y"
function yy_r88(){
$this->_retvalue = 'in_array('.$this->yystack[$this->yyidx + -2]->minor.',(array)'.$this->yystack[$this->yyidx + 0]->minor.')';
}
#line 2583 "smarty_internal_templateparser.php"
#line 633 "smarty_internal_templateparser.y"
function yy_r90(){
$this->_retvalue = '!('.$this->yystack[$this->yyidx + -2]->minor.' % '.$this->yystack[$this->yyidx + 0]->minor.')';
}
#line 2588 "smarty_internal_templateparser.php"
#line 637 "smarty_internal_templateparser.y"
function yy_r91(){
$this->_retvalue = '('.$this->yystack[$this->yyidx + -2]->minor.' % '.$this->yystack[$this->yyidx + 0]->minor.')';
}
#line 2593 "smarty_internal_templateparser.php"
#line 641 "smarty_internal_templateparser.y"
function yy_r92(){
$this->_retvalue = '!(1 & '.$this->yystack[$this->yyidx + -1]->minor.')';
}
#line 2598 "smarty_internal_templateparser.php"
#line 645 "smarty_internal_templateparser.y"
function yy_r93(){
$this->_retvalue = '(1 & '.$this->yystack[$this->yyidx + -1]->minor.')';
}
#line 2603 "smarty_internal_templateparser.php"
#line 649 "smarty_internal_templateparser.y"
function yy_r94(){
$this->_retvalue = '!(1 & '.$this->yystack[$this->yyidx + -2]->minor.' / '.$this->yystack[$this->yyidx + 0]->minor.')';
}
#line 2608 "smarty_internal_templateparser.php"
#line 653 "smarty_internal_templateparser.y"
function yy_r95(){
$this->_retvalue = '(1 & '.$this->yystack[$this->yyidx + -2]->minor.' / '.$this->yystack[$this->yyidx + 0]->minor.')';
}
#line 2613 "smarty_internal_templateparser.php"
#line 677 "smarty_internal_templateparser.y"
function yy_r101(){
self::$prefix_number++;
$this->compiler->prefix_code[] = '<?php $_tmp'.self::$prefix_number.'='.$this->yystack[$this->yyidx + 0]->minor.';?>';
$this->_retvalue = $this->yystack[$this->yyidx + -2]->minor.$this->yystack[$this->yyidx + -1]->minor.'$_tmp'.self::$prefix_number;
}
#line 2620 "smarty_internal_templateparser.php"
#line 686 "smarty_internal_templateparser.y"
function yy_r102(){
$this->_retvalue = $this->yystack[$this->yyidx + -6]->minor.' ? '. $this->compileVariable("'".$this->yystack[$this->yyidx + -2]->minor."'") . ' : '.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2625 "smarty_internal_templateparser.php"
#line 690 "smarty_internal_templateparser.y"
function yy_r103(){
$this->_retvalue = $this->yystack[$this->yyidx + -5]->minor.' ? '.$this->yystack[$this->yyidx + -2]->minor.' : '.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2630 "smarty_internal_templateparser.php"
#line 705 "smarty_internal_templateparser.y"
function yy_r106(){
$this->_retvalue = '!'.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2635 "smarty_internal_templateparser.php"
#line 726 "smarty_internal_templateparser.y"
function yy_r111(){
$this->_retvalue = $this->yystack[$this->yyidx + -2]->minor.'.'.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2640 "smarty_internal_templateparser.php"
#line 730 "smarty_internal_templateparser.y"
function yy_r112(){
$this->_retvalue = $this->yystack[$this->yyidx + -1]->minor.'.';
}
#line 2645 "smarty_internal_templateparser.php"
#line 734 "smarty_internal_templateparser.y"
function yy_r113(){
$this->_retvalue = '.'.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2650 "smarty_internal_templateparser.php"
#line 739 "smarty_internal_templateparser.y"
function yy_r114(){
if (preg_match('~^true$~i', $this->yystack[$this->yyidx + 0]->minor)) {
$this->_retvalue = 'true';
} elseif (preg_match('~^false$~i', $this->yystack[$this->yyidx + 0]->minor)) {
$this->_retvalue = 'false';
} elseif (preg_match('~^null$~i', $this->yystack[$this->yyidx + 0]->minor)) {
$this->_retvalue = 'null';
} else {
$this->_retvalue = "'".$this->yystack[$this->yyidx + 0]->minor."'";
}
}
#line 2663 "smarty_internal_templateparser.php"
#line 757 "smarty_internal_templateparser.y"
function yy_r116(){
$this->_retvalue = "(". $this->yystack[$this->yyidx + -1]->minor .")";
}
#line 2668 "smarty_internal_templateparser.php"
#line 772 "smarty_internal_templateparser.y"
function yy_r119(){
if (!$this->security || isset($this->smarty->registered_classes[$this->yystack[$this->yyidx + -2]->minor]) || $this->smarty->security_policy->isTrustedStaticClass($this->yystack[$this->yyidx + -2]->minor, $this->compiler)) {
if (isset($this->smarty->registered_classes[$this->yystack[$this->yyidx + -2]->minor])) {
$this->_retvalue = $this->smarty->registered_classes[$this->yystack[$this->yyidx + -2]->minor].'::'.$this->yystack[$this->yyidx + 0]->minor;
} else {
$this->_retvalue = $this->yystack[$this->yyidx + -2]->minor.'::'.$this->yystack[$this->yyidx + 0]->minor;
}
} else {
$this->compiler->trigger_template_error ("static class '".$this->yystack[$this->yyidx + -2]->minor."' is undefined or not allowed by security setting");
}
}
#line 2681 "smarty_internal_templateparser.php"
#line 784 "smarty_internal_templateparser.y"
function yy_r120(){
if ($this->yystack[$this->yyidx + -2]->minor['var'] == '\'smarty\'') {
$this->_retvalue = $this->compiler->compileTag('private_special_variable',array(),$this->yystack[$this->yyidx + -2]->minor['smarty_internal_index']).'::'.$this->yystack[$this->yyidx + 0]->minor;
} else {
$this->_retvalue = $this->compileVariable($this->yystack[$this->yyidx + -2]->minor['var']).$this->yystack[$this->yyidx + -2]->minor['smarty_internal_index'].'::'.$this->yystack[$this->yyidx + 0]->minor;
}
}
#line 2690 "smarty_internal_templateparser.php"
#line 793 "smarty_internal_templateparser.y"
function yy_r121(){
self::$prefix_number++;
$this->compiler->prefix_code[] = '<?php ob_start();?>'.$this->yystack[$this->yyidx + -1]->minor.'<?php $_tmp'.self::$prefix_number.'=ob_get_clean();?>';
$this->_retvalue = '$_tmp'.self::$prefix_number;
}
#line 2697 "smarty_internal_templateparser.php"
#line 808 "smarty_internal_templateparser.y"
function yy_r123(){
if ($this->yystack[$this->yyidx + 0]->minor['var'] == '\'smarty\'') {
$smarty_var = $this->compiler->compileTag('private_special_variable',array(),$this->yystack[$this->yyidx + 0]->minor['smarty_internal_index']);
$this->_retvalue = $smarty_var;
} else {
// used for array reset,next,prev,end,current
$this->last_variable = $this->yystack[$this->yyidx + 0]->minor['var'];
$this->last_index = $this->yystack[$this->yyidx + 0]->minor['smarty_internal_index'];
$this->_retvalue = $this->compileVariable($this->yystack[$this->yyidx + 0]->minor['var']).$this->yystack[$this->yyidx + 0]->minor['smarty_internal_index'];
}
}
#line 2710 "smarty_internal_templateparser.php"
#line 821 "smarty_internal_templateparser.y"
function yy_r124(){
$this->_retvalue = '$_smarty_tpl->tpl_vars['. $this->yystack[$this->yyidx + -2]->minor .']->'.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2715 "smarty_internal_templateparser.php"
#line 831 "smarty_internal_templateparser.y"
function yy_r126(){
$this->_retvalue = '$_smarty_tpl->getConfigVariable(\''. $this->yystack[$this->yyidx + -1]->minor .'\')';
}
#line 2720 "smarty_internal_templateparser.php"
#line 835 "smarty_internal_templateparser.y"
function yy_r127(){
$this->_retvalue = '(is_array($tmp = $_smarty_tpl->getConfigVariable(\''. $this->yystack[$this->yyidx + -2]->minor .'\')) ? $tmp'.$this->yystack[$this->yyidx + 0]->minor.' :null)';
}
#line 2725 "smarty_internal_templateparser.php"
#line 839 "smarty_internal_templateparser.y"
function yy_r128(){
$this->_retvalue = '$_smarty_tpl->getConfigVariable('. $this->yystack[$this->yyidx + -1]->minor .')';
}
#line 2730 "smarty_internal_templateparser.php"
#line 843 "smarty_internal_templateparser.y"
function yy_r129(){
$this->_retvalue = '(is_array($tmp = $_smarty_tpl->getConfigVariable('. $this->yystack[$this->yyidx + -2]->minor .')) ? $tmp'.$this->yystack[$this->yyidx + 0]->minor.' : null)';
}
#line 2735 "smarty_internal_templateparser.php"
#line 847 "smarty_internal_templateparser.y"
function yy_r130(){
$this->_retvalue = array('var'=>$this->yystack[$this->yyidx + -1]->minor, 'smarty_internal_index'=>$this->yystack[$this->yyidx + 0]->minor);
}
#line 2740 "smarty_internal_templateparser.php"
#line 860 "smarty_internal_templateparser.y"
function yy_r132(){
return;
}
#line 2745 "smarty_internal_templateparser.php"
#line 866 "smarty_internal_templateparser.y"
function yy_r133(){
$this->_retvalue = '['.$this->compileVariable($this->yystack[$this->yyidx + 0]->minor).']';
}
#line 2750 "smarty_internal_templateparser.php"
#line 870 "smarty_internal_templateparser.y"
function yy_r134(){
$this->_retvalue = '['.$this->compileVariable($this->yystack[$this->yyidx + -2]->minor).'->'.$this->yystack[$this->yyidx + 0]->minor.']';
}
#line 2755 "smarty_internal_templateparser.php"
#line 874 "smarty_internal_templateparser.y"
function yy_r135(){
$this->_retvalue = "['". $this->yystack[$this->yyidx + 0]->minor ."']";
}
#line 2760 "smarty_internal_templateparser.php"
#line 878 "smarty_internal_templateparser.y"
function yy_r136(){
$this->_retvalue = "[". $this->yystack[$this->yyidx + 0]->minor ."]";
}
#line 2765 "smarty_internal_templateparser.php"
#line 882 "smarty_internal_templateparser.y"
function yy_r137(){
$this->_retvalue = "[". $this->yystack[$this->yyidx + -1]->minor ."]";
}
#line 2770 "smarty_internal_templateparser.php"
#line 887 "smarty_internal_templateparser.y"
function yy_r138(){
$this->_retvalue = '['.$this->compiler->compileTag('private_special_variable',array(),'[\'section\'][\''.$this->yystack[$this->yyidx + -1]->minor.'\'][\'index\']').']';
}
#line 2775 "smarty_internal_templateparser.php"
#line 891 "smarty_internal_templateparser.y"
function yy_r139(){
$this->_retvalue = '['.$this->compiler->compileTag('private_special_variable',array(),'[\'section\'][\''.$this->yystack[$this->yyidx + -3]->minor.'\'][\''.$this->yystack[$this->yyidx + -1]->minor.'\']').']';
}
#line 2780 "smarty_internal_templateparser.php"
#line 901 "smarty_internal_templateparser.y"
function yy_r141(){
$this->_retvalue = '[]';
}
#line 2785 "smarty_internal_templateparser.php"
#line 914 "smarty_internal_templateparser.y"
function yy_r143(){
$this->_retvalue = $this->yystack[$this->yyidx + -1]->minor.'.'.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2790 "smarty_internal_templateparser.php"
#line 919 "smarty_internal_templateparser.y"
function yy_r144(){
$this->_retvalue = '\''.$this->yystack[$this->yyidx + 0]->minor.'\'';
}
#line 2795 "smarty_internal_templateparser.php"
#line 924 "smarty_internal_templateparser.y"
function yy_r145(){
$this->_retvalue = '('.$this->yystack[$this->yyidx + -1]->minor.')';
}
#line 2800 "smarty_internal_templateparser.php"
#line 931 "smarty_internal_templateparser.y"
function yy_r146(){
if ($this->yystack[$this->yyidx + -1]->minor['var'] == '\'smarty\'') {
$this->_retvalue = $this->compiler->compileTag('private_special_variable',array(),$this->yystack[$this->yyidx + -1]->minor['smarty_internal_index']).$this->yystack[$this->yyidx + 0]->minor;
} else {
$this->_retvalue = $this->compileVariable($this->yystack[$this->yyidx + -1]->minor['var']).$this->yystack[$this->yyidx + -1]->minor['smarty_internal_index'].$this->yystack[$this->yyidx + 0]->minor;
}
}
#line 2809 "smarty_internal_templateparser.php"
#line 940 "smarty_internal_templateparser.y"
function yy_r147(){
$this->_retvalue = $this->yystack[$this->yyidx + 0]->minor;
}
#line 2814 "smarty_internal_templateparser.php"
#line 945 "smarty_internal_templateparser.y"
function yy_r148(){
$this->_retvalue = $this->yystack[$this->yyidx + -1]->minor.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2819 "smarty_internal_templateparser.php"
#line 950 "smarty_internal_templateparser.y"
function yy_r149(){
if ($this->security && substr($this->yystack[$this->yyidx + -1]->minor,0,1) == '_') {
$this->compiler->trigger_template_error (self::Err1);
}
$this->_retvalue = '->'.$this->yystack[$this->yyidx + -1]->minor.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2827 "smarty_internal_templateparser.php"
#line 957 "smarty_internal_templateparser.y"
function yy_r150(){
if ($this->security) {
$this->compiler->trigger_template_error (self::Err2);
}
$this->_retvalue = '->{'.$this->compileVariable($this->yystack[$this->yyidx + -1]->minor).$this->yystack[$this->yyidx + 0]->minor.'}';
}
#line 2835 "smarty_internal_templateparser.php"
#line 964 "smarty_internal_templateparser.y"
function yy_r151(){
if ($this->security) {
$this->compiler->trigger_template_error (self::Err2);
}
$this->_retvalue = '->{'.$this->yystack[$this->yyidx + -2]->minor.$this->yystack[$this->yyidx + 0]->minor.'}';
}
#line 2843 "smarty_internal_templateparser.php"
#line 971 "smarty_internal_templateparser.y"
function yy_r152(){
if ($this->security) {
$this->compiler->trigger_template_error (self::Err2);
}
$this->_retvalue = '->{\''.$this->yystack[$this->yyidx + -4]->minor.'\'.'.$this->yystack[$this->yyidx + -2]->minor.$this->yystack[$this->yyidx + 0]->minor.'}';
}
#line 2851 "smarty_internal_templateparser.php"
#line 979 "smarty_internal_templateparser.y"
function yy_r153(){
$this->_retvalue = '->'.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2856 "smarty_internal_templateparser.php"
#line 987 "smarty_internal_templateparser.y"
function yy_r154(){
if (!$this->security || $this->smarty->security_policy->isTrustedPhpFunction($this->yystack[$this->yyidx + -3]->minor, $this->compiler)) {
if (strcasecmp($this->yystack[$this->yyidx + -3]->minor,'isset') === 0 || strcasecmp($this->yystack[$this->yyidx + -3]->minor,'empty') === 0 || strcasecmp($this->yystack[$this->yyidx + -3]->minor,'array') === 0 || is_callable($this->yystack[$this->yyidx + -3]->minor)) {
$func_name = strtolower($this->yystack[$this->yyidx + -3]->minor);
if ($func_name == 'isset') {
if (count($this->yystack[$this->yyidx + -1]->minor) == 0) {
$this->compiler->trigger_template_error ('Illegal number of paramer in "isset()"');
}
$par = implode(',',$this->yystack[$this->yyidx + -1]->minor);
if (strncasecmp($par,'$_smarty_tpl->getConfigVariable',strlen('$_smarty_tpl->getConfigVariable')) === 0) {
self::$prefix_number++;
$this->compiler->prefix_code[] = '<?php $_tmp'.self::$prefix_number.'='.str_replace(')',', false)',$par).';?>';
$isset_par = '$_tmp'.self::$prefix_number;
} else {
$isset_par=str_replace("')->value","',null,true,false)->value",$par);
}
$this->_retvalue = $this->yystack[$this->yyidx + -3]->minor . "(". $isset_par .")";
} elseif (in_array($func_name,array('empty','reset','current','end','prev','next'))){
if (count($this->yystack[$this->yyidx + -1]->minor) != 1) {
$this->compiler->trigger_template_error ('Illegal number of paramer in "empty()"');
}
if ($func_name == 'empty') {
$this->_retvalue = $func_name.'('.str_replace("')->value","',null,true,false)->value",$this->yystack[$this->yyidx + -1]->minor[0]).')';
} else {
$this->_retvalue = $func_name.'('.$this->yystack[$this->yyidx + -1]->minor[0].')';
}
} else {
$this->_retvalue = $this->yystack[$this->yyidx + -3]->minor . "(". implode(',',$this->yystack[$this->yyidx + -1]->minor) .")";
}
} else {
$this->compiler->trigger_template_error ("unknown function \"" . $this->yystack[$this->yyidx + -3]->minor . "\"");
}
}
}
#line 2892 "smarty_internal_templateparser.php"
#line 1025 "smarty_internal_templateparser.y"
function yy_r155(){
if ($this->security && substr($this->yystack[$this->yyidx + -3]->minor,0,1) == '_') {
$this->compiler->trigger_template_error (self::Err1);
}
$this->_retvalue = $this->yystack[$this->yyidx + -3]->minor . "(". implode(',',$this->yystack[$this->yyidx + -1]->minor) .")";
}
#line 2900 "smarty_internal_templateparser.php"
#line 1032 "smarty_internal_templateparser.y"
function yy_r156(){
if ($this->security) {
$this->compiler->trigger_template_error (self::Err2);
}
self::$prefix_number++;
$this->compiler->prefix_code[] = '<?php $_tmp'.self::$prefix_number.'='.$this->compileVariable("'".$this->yystack[$this->yyidx + -3]->minor."'").';?>';
$this->_retvalue = '$_tmp'.self::$prefix_number.'('. implode(',',$this->yystack[$this->yyidx + -1]->minor) .')';
}
#line 2910 "smarty_internal_templateparser.php"
#line 1043 "smarty_internal_templateparser.y"
function yy_r157(){
$this->_retvalue = array_merge($this->yystack[$this->yyidx + -2]->minor,array($this->yystack[$this->yyidx + 0]->minor));
}
#line 2915 "smarty_internal_templateparser.php"
#line 1060 "smarty_internal_templateparser.y"
function yy_r160(){
$this->_retvalue = array_merge($this->yystack[$this->yyidx + -2]->minor,array(array_merge($this->yystack[$this->yyidx + -1]->minor,$this->yystack[$this->yyidx + 0]->minor)));
}
#line 2920 "smarty_internal_templateparser.php"
#line 1064 "smarty_internal_templateparser.y"
function yy_r161(){
$this->_retvalue = array(array_merge($this->yystack[$this->yyidx + -1]->minor,$this->yystack[$this->yyidx + 0]->minor));
}
#line 2925 "smarty_internal_templateparser.php"
#line 1072 "smarty_internal_templateparser.y"
function yy_r163(){
$this->_retvalue = array($this->yystack[$this->yyidx + 0]->minor);
}
#line 2930 "smarty_internal_templateparser.php"
#line 1080 "smarty_internal_templateparser.y"
function yy_r164(){
$this->_retvalue = array_merge($this->yystack[$this->yyidx + -1]->minor,$this->yystack[$this->yyidx + 0]->minor);
}
#line 2935 "smarty_internal_templateparser.php"
#line 1114 "smarty_internal_templateparser.y"
function yy_r171(){
$this->_retvalue = '$'.$this->yystack[$this->yyidx + -1]->minor.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2940 "smarty_internal_templateparser.php"
#line 1119 "smarty_internal_templateparser.y"
function yy_r172(){
$this->_retvalue = '$'.$this->yystack[$this->yyidx + -2]->minor.$this->yystack[$this->yyidx + -1]->minor.$this->yystack[$this->yyidx + 0]->minor;
}
#line 2945 "smarty_internal_templateparser.php"
#line 1125 "smarty_internal_templateparser.y"
function yy_r173(){
$this->_retvalue = '==';
}
#line 2950 "smarty_internal_templateparser.php"
#line 1129 "smarty_internal_templateparser.y"
function yy_r174(){
$this->_retvalue = '!=';
}
#line 2955 "smarty_internal_templateparser.php"
#line 1133 "smarty_internal_templateparser.y"
function yy_r175(){
$this->_retvalue = '>';
}
#line 2960 "smarty_internal_templateparser.php"
#line 1137 "smarty_internal_templateparser.y"
function yy_r176(){
$this->_retvalue = '<';
}
#line 2965 "smarty_internal_templateparser.php"
#line 1141 "smarty_internal_templateparser.y"
function yy_r177(){
$this->_retvalue = '>=';
}
#line 2970 "smarty_internal_templateparser.php"
#line 1145 "smarty_internal_templateparser.y"
function yy_r178(){
$this->_retvalue = '<=';
}
#line 2975 "smarty_internal_templateparser.php"
#line 1149 "smarty_internal_templateparser.y"
function yy_r179(){
$this->_retvalue = '===';
}
#line 2980 "smarty_internal_templateparser.php"
#line 1153 "smarty_internal_templateparser.y"
function yy_r180(){
$this->_retvalue = '!==';
}
#line 2985 "smarty_internal_templateparser.php"
#line 1157 "smarty_internal_templateparser.y"
function yy_r181(){
$this->_retvalue = '%';
}
#line 2990 "smarty_internal_templateparser.php"
#line 1161 "smarty_internal_templateparser.y"
function yy_r182(){
$this->_retvalue = '&&';
}
#line 2995 "smarty_internal_templateparser.php"
#line 1165 "smarty_internal_templateparser.y"
function yy_r183(){
$this->_retvalue = '||';
}
#line 3000 "smarty_internal_templateparser.php"
#line 1169 "smarty_internal_templateparser.y"
function yy_r184(){
$this->_retvalue = ' XOR ';
}
#line 3005 "smarty_internal_templateparser.php"
#line 1176 "smarty_internal_templateparser.y"
function yy_r185(){
$this->_retvalue = 'array('.$this->yystack[$this->yyidx + -1]->minor.')';
}
#line 3010 "smarty_internal_templateparser.php"
#line 1184 "smarty_internal_templateparser.y"
function yy_r187(){
$this->_retvalue = $this->yystack[$this->yyidx + -2]->minor.','.$this->yystack[$this->yyidx + 0]->minor;
}
#line 3015 "smarty_internal_templateparser.php"
#line 1192 "smarty_internal_templateparser.y"
function yy_r189(){
$this->_retvalue = $this->yystack[$this->yyidx + -2]->minor.'=>'.$this->yystack[$this->yyidx + 0]->minor;
}
#line 3020 "smarty_internal_templateparser.php"
#line 1196 "smarty_internal_templateparser.y"
function yy_r190(){
$this->_retvalue = '\''.$this->yystack[$this->yyidx + -2]->minor.'\'=>'.$this->yystack[$this->yyidx + 0]->minor;
}
#line 3025 "smarty_internal_templateparser.php"
#line 1208 "smarty_internal_templateparser.y"
function yy_r192(){
$this->_retvalue = "''";
}
#line 3030 "smarty_internal_templateparser.php"
#line 1212 "smarty_internal_templateparser.y"
function yy_r193(){
$this->_retvalue = $this->yystack[$this->yyidx + -1]->minor->to_smarty_php();
}
#line 3035 "smarty_internal_templateparser.php"
#line 1217 "smarty_internal_templateparser.y"
function yy_r194(){
$this->yystack[$this->yyidx + -1]->minor->append_subtree($this->yystack[$this->yyidx + 0]->minor);
$this->_retvalue = $this->yystack[$this->yyidx + -1]->minor;
}
#line 3041 "smarty_internal_templateparser.php"
#line 1222 "smarty_internal_templateparser.y"
function yy_r195(){
$this->_retvalue = new _smarty_doublequoted($this, $this->yystack[$this->yyidx + 0]->minor);
}
#line 3046 "smarty_internal_templateparser.php"
#line 1226 "smarty_internal_templateparser.y"
function yy_r196(){
$this->_retvalue = new _smarty_code($this, '(string)'.$this->yystack[$this->yyidx + -1]->minor);
}
#line 3051 "smarty_internal_templateparser.php"
#line 1234 "smarty_internal_templateparser.y"
function yy_r198(){
$this->_retvalue = new _smarty_code($this, '(string)$_smarty_tpl->tpl_vars[\''. substr($this->yystack[$this->yyidx + 0]->minor,1) .'\']->value');
}
#line 3056 "smarty_internal_templateparser.php"
#line 1242 "smarty_internal_templateparser.y"
function yy_r200(){
$this->_retvalue = new _smarty_code($this, '(string)('.$this->yystack[$this->yyidx + -1]->minor.')');
}
#line 3061 "smarty_internal_templateparser.php"
#line 1246 "smarty_internal_templateparser.y"
function yy_r201(){
$this->_retvalue = new _smarty_tag($this, $this->yystack[$this->yyidx + -1]->minor);
}
#line 3066 "smarty_internal_templateparser.php"
#line 1250 "smarty_internal_templateparser.y"
function yy_r202(){
$this->_retvalue = new _smarty_dq_content($this, $this->yystack[$this->yyidx + 0]->minor);
}
#line 3071 "smarty_internal_templateparser.php"
private $_retvalue;
public function yy_reduce($yyruleno)
{
$yymsp = $this->yystack[$this->yyidx];
if (self::$yyTraceFILE && $yyruleno >= 0
&& $yyruleno < count(self::$yyRuleName)) {
fprintf(self::$yyTraceFILE, "%sReduce (%d) [%s].\n",
self::$yyTracePrompt, $yyruleno,
self::$yyRuleName[$yyruleno]);
}
$this->_retvalue = $yy_lefthand_side = null;
if (array_key_exists($yyruleno, self::$yyReduceMap)) {
// call the action
$this->_retvalue = null;
$this->{'yy_r' . self::$yyReduceMap[$yyruleno]}();
$yy_lefthand_side = $this->_retvalue;
}
$yygoto = self::$yyRuleInfo[$yyruleno]['lhs'];
$yysize = self::$yyRuleInfo[$yyruleno]['rhs'];
$this->yyidx -= $yysize;
for ($i = $yysize; $i; $i--) {
// pop all of the right-hand side parameters
array_pop($this->yystack);
}
$yyact = $this->yy_find_reduce_action($this->yystack[$this->yyidx]->stateno, $yygoto);
if ($yyact < self::YYNSTATE) {
if (!self::$yyTraceFILE && $yysize) {
$this->yyidx++;
$x = new TP_yyStackEntry;
$x->stateno = $yyact;
$x->major = $yygoto;
$x->minor = $yy_lefthand_side;
$this->yystack[$this->yyidx] = $x;
} else {
$this->yy_shift($yyact, $yygoto, $yy_lefthand_side);
}
} elseif ($yyact == self::YYNSTATE + self::YYNRULE + 1) {
$this->yy_accept();
}
}
public function yy_parse_failed()
{
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sFail!\n", self::$yyTracePrompt);
} while ($this->yyidx >= 0) {
$this->yy_pop_parser_stack();
}
}
public function yy_syntax_error($yymajor, $TOKEN)
{
#line 78 "smarty_internal_templateparser.y"
$this->internalError = true;
$this->yymajor = $yymajor;
$this->compiler->trigger_template_error();
#line 3133 "smarty_internal_templateparser.php"
}
public function yy_accept()
{
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sAccept!\n", self::$yyTracePrompt);
} while ($this->yyidx >= 0) {
$stack = $this->yy_pop_parser_stack();
}
#line 70 "smarty_internal_templateparser.y"
$this->successful = !$this->internalError;
$this->internalError = false;
$this->retvalue = $this->_retvalue;
//echo $this->retvalue."\n\n";
#line 3150 "smarty_internal_templateparser.php"
}
public function doParse($yymajor, $yytokenvalue)
{
$yyerrorhit = 0; /* True if yymajor has invoked an error */
if ($this->yyidx === null || $this->yyidx < 0) {
$this->yyidx = 0;
$this->yyerrcnt = -1;
$x = new TP_yyStackEntry;
$x->stateno = 0;
$x->major = 0;
$this->yystack = array();
array_push($this->yystack, $x);
}
$yyendofinput = ($yymajor==0);
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sInput %s\n",
self::$yyTracePrompt, $this->yyTokenName[$yymajor]);
}
do {
$yyact = $this->yy_find_shift_action($yymajor);
if ($yymajor < self::YYERRORSYMBOL &&
!$this->yy_is_expected_token($yymajor)) {
// force a syntax error
$yyact = self::YY_ERROR_ACTION;
}
if ($yyact < self::YYNSTATE) {
$this->yy_shift($yyact, $yymajor, $yytokenvalue);
$this->yyerrcnt--;
if ($yyendofinput && $this->yyidx >= 0) {
$yymajor = 0;
} else {
$yymajor = self::YYNOCODE;
}
} elseif ($yyact < self::YYNSTATE + self::YYNRULE) {
$this->yy_reduce($yyact - self::YYNSTATE);
} elseif ($yyact == self::YY_ERROR_ACTION) {
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sSyntax Error!\n",
self::$yyTracePrompt);
}
if (self::YYERRORSYMBOL) {
if ($this->yyerrcnt < 0) {
$this->yy_syntax_error($yymajor, $yytokenvalue);
}
$yymx = $this->yystack[$this->yyidx]->major;
if ($yymx == self::YYERRORSYMBOL || $yyerrorhit) {
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sDiscard input token %s\n",
self::$yyTracePrompt, $this->yyTokenName[$yymajor]);
}
$this->yy_destructor($yymajor, $yytokenvalue);
$yymajor = self::YYNOCODE;
} else {
while ($this->yyidx >= 0 &&
$yymx != self::YYERRORSYMBOL &&
($yyact = $this->yy_find_shift_action(self::YYERRORSYMBOL)) >= self::YYNSTATE
){
$this->yy_pop_parser_stack();
}
if ($this->yyidx < 0 || $yymajor==0) {
$this->yy_destructor($yymajor, $yytokenvalue);
$this->yy_parse_failed();
$yymajor = self::YYNOCODE;
} elseif ($yymx != self::YYERRORSYMBOL) {
$u2 = 0;
$this->yy_shift($yyact, self::YYERRORSYMBOL, $u2);
}
}
$this->yyerrcnt = 3;
$yyerrorhit = 1;
} else {
if ($this->yyerrcnt <= 0) {
$this->yy_syntax_error($yymajor, $yytokenvalue);
}
$this->yyerrcnt = 3;
$this->yy_destructor($yymajor, $yytokenvalue);
if ($yyendofinput) {
$this->yy_parse_failed();
}
$yymajor = self::YYNOCODE;
}
} else {
$this->yy_accept();
$yymajor = self::YYNOCODE;
}
} while ($yymajor != self::YYNOCODE && $this->yyidx >= 0);
}
} | mit |
extend1994/cdnjs | ajax/libs/tinyscrollbar/2.1.0/jquery.tinyscrollbar.js | 8074 | ;(function (factory)
{
if (typeof define === 'function' && define.amd)
{
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object')
{
// Node/CommonJS
factory(require('jquery'));
} else
{
// Browser globals
factory(jQuery);
}
}(function ($)
{
var pluginName = "tinyscrollbar"
, defaults =
{
axis : 'y' // vertical or horizontal scrollbar? ( x || y ).
, wheel : true // enable or disable the mousewheel;
, wheelSpeed : 40 // how many pixels must the mouswheel scroll at a time.
, wheelLock : true // return mouswheel to browser if there is no more content.
, scrollInvert : false // Enable invert style scrolling
, trackSize : false // set the size of the scrollbar to auto or a fixed number.
, thumbSize : false // set the size of the thumb to auto or a fixed number.
}
;
function Plugin($container, options)
{
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
var self = this
, $viewport = $container.find(".viewport")
, $overview = $container.find(".overview")
, $scrollbar = $container.find(".scrollbar")
, $track = $scrollbar.find(".track")
, $thumb = $scrollbar.find(".thumb")
, mousePosition = 0
, isHorizontal = this.options.axis === 'x'
, hasTouchEvents = "ontouchstart" in document.documentElement
, sizeLabel = isHorizontal ? "width" : "height"
, posiLabel = isHorizontal ? "left" : "top"
;
this.contentPosition = 0;
this.viewportSize = 0;
this.contentSize = 0;
this.contentRatio = 0;
this.trackSize = 0;
this.trackRatio = 0;
this.thumbSize = 0;
this.thumbPosition = 0;
function initialize()
{
self.update();
setEvents();
return self;
}
this.update = function(scrollTo)
{
var sizeLabelCap = sizeLabel.charAt(0).toUpperCase() + sizeLabel.slice(1).toLowerCase();
this.viewportSize = $viewport[0]['offset'+ sizeLabelCap];
this.contentSize = $overview[0]['scroll'+ sizeLabelCap];
this.contentRatio = this.viewportSize / this.contentSize;
this.trackSize = this.options.trackSize || this.viewportSize;
this.thumbSize = Math.min(this.trackSize, Math.max(0, (this.options.thumbSize || (this.trackSize * this.contentRatio))));
this.trackRatio = this.options.thumbSize ? (this.contentSize - this.viewportSize) / (this.trackSize - this.thumbSize) : (this.contentSize / this.trackSize);
$scrollbar.toggleClass("disable", this.contentRatio >= 1);
switch (scrollTo)
{
case "bottom":
this.contentPosition = this.contentSize - this.viewportSize;
break;
case "relative":
this.contentPosition = Math.min(this.contentSize - this.viewportSize, Math.max(0, this.contentPosition));
break;
default:
this.contentPosition = parseInt(scrollTo, 10) || 0;
}
setSize();
return self;
};
function setSize()
{
$thumb.css(posiLabel, self.contentPosition / self.trackRatio);
$overview.css(posiLabel, -self.contentPosition);
$scrollbar.css(sizeLabel, self.trackSize);
$track.css(sizeLabel, self.trackSize);
$thumb.css(sizeLabel, self.thumbSize);
}
function setEvents()
{
if(hasTouchEvents)
{
$viewport[0].ontouchstart = function(event)
{
if(1 === event.touches.length)
{
start(event.touches[0]);
event.stopPropagation();
}
};
}
else
{
$thumb.bind("mousedown", start);
$track.bind("mousedown", drag);
}
if(self.options.wheel && window.addEventListener)
{
$container[0].addEventListener("DOMMouseScroll", wheel, false );
$container[0].addEventListener("mousewheel", wheel, false );
}
else if(self.options.wheel)
{
$container[0].onmousewheel = wheel;
}
}
function start(event)
{
$("body").addClass("noSelect");
mousePosition = isHorizontal ? event.pageX : event.pageY;
self.thumbPosition = parseInt($thumb.css(posiLabel), 10) || 0;
if(hasTouchEvents)
{
document.ontouchmove = function(event)
{
event.preventDefault();
drag(event.touches[0]);
};
document.ontouchend = end;
}
else
{
$(document).bind("mousemove", drag);
$(document).bind("mouseup", end);
$thumb.bind("mouseup", end);
}
}
function wheel(event)
{
if(self.contentRatio < 1)
{
var eventObject = event || window.event
, wheelSpeedDelta = eventObject.wheelDelta ? eventObject.wheelDelta / 120 : -eventObject.detail / 3
;
self.contentPosition -= wheelSpeedDelta * self.options.wheelSpeed;
self.contentPosition = Math.min((self.contentSize - self.viewportSize), Math.max(0, self.contentPosition));
$container.trigger("move");
$thumb.css(posiLabel, self.contentPosition / self.trackRatio);
$overview.css(posiLabel, -self.contentPosition);
if(self.options.wheelLock || (self.contentPosition !== (self.contentSize - self.viewportSize) && self.contentPosition !== 0))
{
eventObject = $.event.fix(eventObject);
eventObject.preventDefault();
}
}
}
function drag(event)
{
if(self.contentRatio < 1)
{
var mousePositionNew = isHorizontal ? event.pageX : event.pageY
, thumbPositionDelta = mousePositionNew - mousePosition
;
if(self.options.scrollInvert && hasTouchEvents)
{
thumbPositionDelta = mousePosition - mousePositionNew;
}
var thumbPositionNew = Math.min((self.trackSize - self.thumbSize), Math.max(0, self.thumbPosition + thumbPositionDelta));
self.contentPosition = thumbPositionNew * self.trackRatio;
$container.trigger("move");
$thumb.css(posiLabel, thumbPositionNew);
$overview.css(posiLabel, -self.contentPosition);
}
}
function end()
{
$("body").removeClass("noSelect");
$(document).unbind("mousemove", drag);
$(document).unbind("mouseup", end);
$thumb.unbind("mouseup", end);
document.ontouchmove = document.ontouchend = null;
}
return initialize();
}
$.fn[pluginName] = function(options)
{
return this.each(function()
{
if(!$.data(this, "plugin_" + pluginName))
{
$.data(this, "plugin_" + pluginName, new Plugin($(this), options));
}
});
};
})); | mit |
cdnjs/cdnjs | ajax/libs/simple-icons/5.10.0/bitdefender.min.js | 789 | module.exports={title:"Bitdefender",slug:"bitdefender",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Bitdefender</title><path d="M1.685 0v.357l1.232 1.046c1.477 1.204 1.67 1.439 1.67 2.526V24h8.646c4.537 0 9.083-1.629 9.083-6.849 0-3.082-2.174-5.458-5.186-5.797v-.067c2.475-.745 4.169-2.54 4.169-5.253 0-4.372-3.73-6.032-7.349-6.032L1.686 0zm7.176 3.664h3.524c2.383 0 3.121.327 3.844 1.013.548.521.799 1.237.801 2.07 0 .775-.267 1.466-.831 2.004-.705.676-1.674 1.011-3.443 1.011H8.862V3.664zm0 9.758h4.099c3.456 0 5.085.881 5.085 3.39 0 3.153-3.055 3.526-5.256 3.526H8.86v-6.916z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://www.bitdefender.com/funzone/logos.html",hex:"ED1C24",guidelines:void 0,license:void 0}; | mit |
yanndegat/terraform | vendor/google.golang.org/grpc/transport/http2_client.go | 39146 | /*
*
* Copyright 2014 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.
*
*/
package transport
import (
"bytes"
"io"
"math"
"net"
"strings"
"sync"
"sync/atomic"
"time"
"golang.org/x/net/context"
"golang.org/x/net/http2"
"golang.org/x/net/http2/hpack"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/stats"
"google.golang.org/grpc/status"
)
// http2Client implements the ClientTransport interface with HTTP2.
type http2Client struct {
ctx context.Context
target string // server name/addr
userAgent string
md interface{}
conn net.Conn // underlying communication channel
remoteAddr net.Addr
localAddr net.Addr
authInfo credentials.AuthInfo // auth info about the connection
nextID uint32 // the next stream ID to be used
// writableChan synchronizes write access to the transport.
// A writer acquires the write lock by sending a value on writableChan
// and releases it by receiving from writableChan.
writableChan chan int
// shutdownChan is closed when Close is called.
// Blocking operations should select on shutdownChan to avoid
// blocking forever after Close.
// TODO(zhaoq): Maybe have a channel context?
shutdownChan chan struct{}
// errorChan is closed to notify the I/O error to the caller.
errorChan chan struct{}
// goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor)
// that the server sent GoAway on this transport.
goAway chan struct{}
// awakenKeepalive is used to wake up keepalive when after it has gone dormant.
awakenKeepalive chan struct{}
framer *framer
hBuf *bytes.Buffer // the buffer for HPACK encoding
hEnc *hpack.Encoder // HPACK encoder
// controlBuf delivers all the control related tasks (e.g., window
// updates, reset streams, and various settings) to the controller.
controlBuf *controlBuffer
fc *inFlow
// sendQuotaPool provides flow control to outbound message.
sendQuotaPool *quotaPool
// streamsQuota limits the max number of concurrent streams.
streamsQuota *quotaPool
// The scheme used: https if TLS is on, http otherwise.
scheme string
isSecure bool
creds []credentials.PerRPCCredentials
// Boolean to keep track of reading activity on transport.
// 1 is true and 0 is false.
activity uint32 // Accessed atomically.
kp keepalive.ClientParameters
statsHandler stats.Handler
initialWindowSize int32
bdpEst *bdpEstimator
outQuotaVersion uint32
mu sync.Mutex // guard the following variables
state transportState // the state of underlying connection
activeStreams map[uint32]*Stream
// The max number of concurrent streams
maxStreams int
// the per-stream outbound flow control window size set by the peer.
streamSendQuota uint32
// prevGoAway ID records the Last-Stream-ID in the previous GOAway frame.
prevGoAwayID uint32
// goAwayReason records the http2.ErrCode and debug data received with the
// GoAway frame.
goAwayReason GoAwayReason
}
func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr string) (net.Conn, error) {
if fn != nil {
return fn(ctx, addr)
}
return dialContext(ctx, "tcp", addr)
}
func isTemporary(err error) bool {
switch err {
case io.EOF:
// Connection closures may be resolved upon retry, and are thus
// treated as temporary.
return true
case context.DeadlineExceeded:
// In Go 1.7, context.DeadlineExceeded implements Timeout(), and this
// special case is not needed. Until then, we need to keep this
// clause.
return true
}
switch err := err.(type) {
case interface {
Temporary() bool
}:
return err.Temporary()
case interface {
Timeout() bool
}:
// Timeouts may be resolved upon retry, and are thus treated as
// temporary.
return err.Timeout()
}
return false
}
// newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2
// and starts to receive messages on it. Non-nil error returns if construction
// fails.
func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions) (_ ClientTransport, err error) {
scheme := "http"
conn, err := dial(ctx, opts.Dialer, addr.Addr)
if err != nil {
if opts.FailOnNonTempDialError {
return nil, connectionErrorf(isTemporary(err), err, "transport: error while dialing: %v", err)
}
return nil, connectionErrorf(true, err, "transport: Error while dialing %v", err)
}
// Any further errors will close the underlying connection
defer func(conn net.Conn) {
if err != nil {
conn.Close()
}
}(conn)
var (
isSecure bool
authInfo credentials.AuthInfo
)
if creds := opts.TransportCredentials; creds != nil {
scheme = "https"
conn, authInfo, err = creds.ClientHandshake(ctx, addr.Addr, conn)
if err != nil {
// Credentials handshake errors are typically considered permanent
// to avoid retrying on e.g. bad certificates.
temp := isTemporary(err)
return nil, connectionErrorf(temp, err, "transport: authentication handshake failed: %v", err)
}
isSecure = true
}
kp := opts.KeepaliveParams
// Validate keepalive parameters.
if kp.Time == 0 {
kp.Time = defaultClientKeepaliveTime
}
if kp.Timeout == 0 {
kp.Timeout = defaultClientKeepaliveTimeout
}
dynamicWindow := true
icwz := int32(initialWindowSize)
if opts.InitialConnWindowSize >= defaultWindowSize {
icwz = opts.InitialConnWindowSize
dynamicWindow = false
}
var buf bytes.Buffer
t := &http2Client{
ctx: ctx,
target: addr.Addr,
userAgent: opts.UserAgent,
md: addr.Metadata,
conn: conn,
remoteAddr: conn.RemoteAddr(),
localAddr: conn.LocalAddr(),
authInfo: authInfo,
// The client initiated stream id is odd starting from 1.
nextID: 1,
writableChan: make(chan int, 1),
shutdownChan: make(chan struct{}),
errorChan: make(chan struct{}),
goAway: make(chan struct{}),
awakenKeepalive: make(chan struct{}, 1),
framer: newFramer(conn),
hBuf: &buf,
hEnc: hpack.NewEncoder(&buf),
controlBuf: newControlBuffer(),
fc: &inFlow{limit: uint32(icwz)},
sendQuotaPool: newQuotaPool(defaultWindowSize),
scheme: scheme,
state: reachable,
activeStreams: make(map[uint32]*Stream),
isSecure: isSecure,
creds: opts.PerRPCCredentials,
maxStreams: defaultMaxStreamsClient,
streamsQuota: newQuotaPool(defaultMaxStreamsClient),
streamSendQuota: defaultWindowSize,
kp: kp,
statsHandler: opts.StatsHandler,
initialWindowSize: initialWindowSize,
}
if opts.InitialWindowSize >= defaultWindowSize {
t.initialWindowSize = opts.InitialWindowSize
dynamicWindow = false
}
if dynamicWindow {
t.bdpEst = &bdpEstimator{
bdp: initialWindowSize,
updateFlowControl: t.updateFlowControl,
}
}
// Make sure awakenKeepalive can't be written upon.
// keepalive routine will make it writable, if need be.
t.awakenKeepalive <- struct{}{}
if t.statsHandler != nil {
t.ctx = t.statsHandler.TagConn(t.ctx, &stats.ConnTagInfo{
RemoteAddr: t.remoteAddr,
LocalAddr: t.localAddr,
})
connBegin := &stats.ConnBegin{
Client: true,
}
t.statsHandler.HandleConn(t.ctx, connBegin)
}
// Start the reader goroutine for incoming message. Each transport has
// a dedicated goroutine which reads HTTP2 frame from network. Then it
// dispatches the frame to the corresponding stream entity.
go t.reader()
// Send connection preface to server.
n, err := t.conn.Write(clientPreface)
if err != nil {
t.Close()
return nil, connectionErrorf(true, err, "transport: failed to write client preface: %v", err)
}
if n != len(clientPreface) {
t.Close()
return nil, connectionErrorf(true, err, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface))
}
if t.initialWindowSize != defaultWindowSize {
err = t.framer.writeSettings(true, http2.Setting{
ID: http2.SettingInitialWindowSize,
Val: uint32(t.initialWindowSize),
})
} else {
err = t.framer.writeSettings(true)
}
if err != nil {
t.Close()
return nil, connectionErrorf(true, err, "transport: failed to write initial settings frame: %v", err)
}
// Adjust the connection flow control window if needed.
if delta := uint32(icwz - defaultWindowSize); delta > 0 {
if err := t.framer.writeWindowUpdate(true, 0, delta); err != nil {
t.Close()
return nil, connectionErrorf(true, err, "transport: failed to write window update: %v", err)
}
}
go t.controller()
if t.kp.Time != infinity {
go t.keepalive()
}
t.writableChan <- 0
return t, nil
}
func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream {
// TODO(zhaoq): Handle uint32 overflow of Stream.id.
s := &Stream{
id: t.nextID,
done: make(chan struct{}),
goAway: make(chan struct{}),
method: callHdr.Method,
sendCompress: callHdr.SendCompress,
buf: newRecvBuffer(),
fc: &inFlow{limit: uint32(t.initialWindowSize)},
sendQuotaPool: newQuotaPool(int(t.streamSendQuota)),
headerChan: make(chan struct{}),
}
t.nextID += 2
s.requestRead = func(n int) {
t.adjustWindow(s, uint32(n))
}
// The client side stream context should have exactly the same life cycle with the user provided context.
// That means, s.ctx should be read-only. And s.ctx is done iff ctx is done.
// So we use the original context here instead of creating a copy.
s.ctx = ctx
s.trReader = &transportReader{
reader: &recvBufferReader{
ctx: s.ctx,
goAway: s.goAway,
recv: s.buf,
},
windowHandler: func(n int) {
t.updateWindow(s, uint32(n))
},
}
return s
}
// NewStream creates a stream and registers it into the transport as "active"
// streams.
func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) {
pr := &peer.Peer{
Addr: t.remoteAddr,
}
// Attach Auth info if there is any.
if t.authInfo != nil {
pr.AuthInfo = t.authInfo
}
ctx = peer.NewContext(ctx, pr)
var (
authData = make(map[string]string)
audience string
)
// Create an audience string only if needed.
if len(t.creds) > 0 || callHdr.Creds != nil {
// Construct URI required to get auth request metadata.
var port string
if pos := strings.LastIndex(t.target, ":"); pos != -1 {
// Omit port if it is the default one.
if t.target[pos+1:] != "443" {
port = ":" + t.target[pos+1:]
}
}
pos := strings.LastIndex(callHdr.Method, "/")
if pos == -1 {
pos = len(callHdr.Method)
}
audience = "https://" + callHdr.Host + port + callHdr.Method[:pos]
}
for _, c := range t.creds {
data, err := c.GetRequestMetadata(ctx, audience)
if err != nil {
return nil, streamErrorf(codes.Internal, "transport: %v", err)
}
for k, v := range data {
// Capital header names are illegal in HTTP/2.
k = strings.ToLower(k)
authData[k] = v
}
}
callAuthData := make(map[string]string)
// Check if credentials.PerRPCCredentials were provided via call options.
// Note: if these credentials are provided both via dial options and call
// options, then both sets of credentials will be applied.
if callCreds := callHdr.Creds; callCreds != nil {
if !t.isSecure && callCreds.RequireTransportSecurity() {
return nil, streamErrorf(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure conneciton")
}
data, err := callCreds.GetRequestMetadata(ctx, audience)
if err != nil {
return nil, streamErrorf(codes.Internal, "transport: %v", err)
}
for k, v := range data {
// Capital header names are illegal in HTTP/2
k = strings.ToLower(k)
callAuthData[k] = v
}
}
t.mu.Lock()
if t.activeStreams == nil {
t.mu.Unlock()
return nil, ErrConnClosing
}
if t.state == draining {
t.mu.Unlock()
return nil, ErrStreamDrain
}
if t.state != reachable {
t.mu.Unlock()
return nil, ErrConnClosing
}
t.mu.Unlock()
sq, err := wait(ctx, nil, nil, t.shutdownChan, t.streamsQuota.acquire())
if err != nil {
return nil, err
}
// Returns the quota balance back.
if sq > 1 {
t.streamsQuota.add(sq - 1)
}
if _, err := wait(ctx, nil, nil, t.shutdownChan, t.writableChan); err != nil {
// Return the quota back now because there is no stream returned to the caller.
if _, ok := err.(StreamError); ok {
t.streamsQuota.add(1)
}
return nil, err
}
t.mu.Lock()
if t.state == draining {
t.mu.Unlock()
t.streamsQuota.add(1)
// Need to make t writable again so that the rpc in flight can still proceed.
t.writableChan <- 0
return nil, ErrStreamDrain
}
if t.state != reachable {
t.mu.Unlock()
return nil, ErrConnClosing
}
s := t.newStream(ctx, callHdr)
t.activeStreams[s.id] = s
// If the number of active streams change from 0 to 1, then check if keepalive
// has gone dormant. If so, wake it up.
if len(t.activeStreams) == 1 {
select {
case t.awakenKeepalive <- struct{}{}:
t.framer.writePing(false, false, [8]byte{})
default:
}
}
t.mu.Unlock()
// HPACK encodes various headers. Note that once WriteField(...) is
// called, the corresponding headers/continuation frame has to be sent
// because hpack.Encoder is stateful.
t.hBuf.Reset()
t.hEnc.WriteField(hpack.HeaderField{Name: ":method", Value: "POST"})
t.hEnc.WriteField(hpack.HeaderField{Name: ":scheme", Value: t.scheme})
t.hEnc.WriteField(hpack.HeaderField{Name: ":path", Value: callHdr.Method})
t.hEnc.WriteField(hpack.HeaderField{Name: ":authority", Value: callHdr.Host})
t.hEnc.WriteField(hpack.HeaderField{Name: "content-type", Value: "application/grpc"})
t.hEnc.WriteField(hpack.HeaderField{Name: "user-agent", Value: t.userAgent})
t.hEnc.WriteField(hpack.HeaderField{Name: "te", Value: "trailers"})
if callHdr.SendCompress != "" {
t.hEnc.WriteField(hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress})
}
if dl, ok := ctx.Deadline(); ok {
// Send out timeout regardless its value. The server can detect timeout context by itself.
timeout := dl.Sub(time.Now())
t.hEnc.WriteField(hpack.HeaderField{Name: "grpc-timeout", Value: encodeTimeout(timeout)})
}
for k, v := range authData {
t.hEnc.WriteField(hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
}
for k, v := range callAuthData {
t.hEnc.WriteField(hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
}
var (
endHeaders bool
)
if md, ok := metadata.FromOutgoingContext(ctx); ok {
for k, vv := range md {
// HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set.
if isReservedHeader(k) {
continue
}
for _, v := range vv {
t.hEnc.WriteField(hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
}
}
}
if md, ok := t.md.(*metadata.MD); ok {
for k, vv := range *md {
if isReservedHeader(k) {
continue
}
for _, v := range vv {
t.hEnc.WriteField(hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
}
}
}
first := true
bufLen := t.hBuf.Len()
// Sends the headers in a single batch even when they span multiple frames.
for !endHeaders {
size := t.hBuf.Len()
if size > http2MaxFrameLen {
size = http2MaxFrameLen
} else {
endHeaders = true
}
var flush bool
if callHdr.Flush && endHeaders {
flush = true
}
if first {
// Sends a HeadersFrame to server to start a new stream.
p := http2.HeadersFrameParam{
StreamID: s.id,
BlockFragment: t.hBuf.Next(size),
EndStream: false,
EndHeaders: endHeaders,
}
// Do a force flush for the buffered frames iff it is the last headers frame
// and there is header metadata to be sent. Otherwise, there is flushing until
// the corresponding data frame is written.
err = t.framer.writeHeaders(flush, p)
first = false
} else {
// Sends Continuation frames for the leftover headers.
err = t.framer.writeContinuation(flush, s.id, endHeaders, t.hBuf.Next(size))
}
if err != nil {
t.notifyError(err)
return nil, connectionErrorf(true, err, "transport: %v", err)
}
}
s.mu.Lock()
s.bytesSent = true
s.mu.Unlock()
if t.statsHandler != nil {
outHeader := &stats.OutHeader{
Client: true,
WireLength: bufLen,
FullMethod: callHdr.Method,
RemoteAddr: t.remoteAddr,
LocalAddr: t.localAddr,
Compression: callHdr.SendCompress,
}
t.statsHandler.HandleRPC(s.ctx, outHeader)
}
t.writableChan <- 0
return s, nil
}
// CloseStream clears the footprint of a stream when the stream is not needed any more.
// This must not be executed in reader's goroutine.
func (t *http2Client) CloseStream(s *Stream, err error) {
t.mu.Lock()
if t.activeStreams == nil {
t.mu.Unlock()
return
}
if err != nil {
// notify in-flight streams, before the deletion
s.write(recvMsg{err: err})
}
delete(t.activeStreams, s.id)
if t.state == draining && len(t.activeStreams) == 0 {
// The transport is draining and s is the last live stream on t.
t.mu.Unlock()
t.Close()
return
}
t.mu.Unlock()
// rstStream is true in case the stream is being closed at the client-side
// and the server needs to be intimated about it by sending a RST_STREAM
// frame.
// To make sure this frame is written to the wire before the headers of the
// next stream waiting for streamsQuota, we add to streamsQuota pool only
// after having acquired the writableChan to send RST_STREAM out (look at
// the controller() routine).
var rstStream bool
var rstError http2.ErrCode
defer func() {
// In case, the client doesn't have to send RST_STREAM to server
// we can safely add back to streamsQuota pool now.
if !rstStream {
t.streamsQuota.add(1)
return
}
t.controlBuf.put(&resetStream{s.id, rstError})
}()
s.mu.Lock()
rstStream = s.rstStream
rstError = s.rstError
if s.state == streamDone {
s.mu.Unlock()
return
}
if !s.headerDone {
close(s.headerChan)
s.headerDone = true
}
s.state = streamDone
s.mu.Unlock()
if _, ok := err.(StreamError); ok {
rstStream = true
rstError = http2.ErrCodeCancel
}
}
// Close kicks off the shutdown process of the transport. This should be called
// only once on a transport. Once it is called, the transport should not be
// accessed any more.
func (t *http2Client) Close() (err error) {
t.mu.Lock()
if t.state == closing {
t.mu.Unlock()
return
}
if t.state == reachable || t.state == draining {
close(t.errorChan)
}
t.state = closing
t.mu.Unlock()
close(t.shutdownChan)
err = t.conn.Close()
t.mu.Lock()
streams := t.activeStreams
t.activeStreams = nil
t.mu.Unlock()
// Notify all active streams.
for _, s := range streams {
s.mu.Lock()
if !s.headerDone {
close(s.headerChan)
s.headerDone = true
}
s.mu.Unlock()
s.write(recvMsg{err: ErrConnClosing})
}
if t.statsHandler != nil {
connEnd := &stats.ConnEnd{
Client: true,
}
t.statsHandler.HandleConn(t.ctx, connEnd)
}
return
}
func (t *http2Client) GracefulClose() error {
t.mu.Lock()
switch t.state {
case unreachable:
// The server may close the connection concurrently. t is not available for
// any streams. Close it now.
t.mu.Unlock()
t.Close()
return nil
case closing:
t.mu.Unlock()
return nil
}
if t.state == draining {
t.mu.Unlock()
return nil
}
t.state = draining
active := len(t.activeStreams)
t.mu.Unlock()
if active == 0 {
return t.Close()
}
return nil
}
// Write formats the data into HTTP2 data frame(s) and sends it out. The caller
// should proceed only if Write returns nil.
// TODO(zhaoq): opts.Delay is ignored in this implementation. Support it later
// if it improves the performance.
func (t *http2Client) Write(s *Stream, data []byte, opts *Options) error {
r := bytes.NewBuffer(data)
var (
p []byte
oqv uint32
)
for {
oqv = atomic.LoadUint32(&t.outQuotaVersion)
if r.Len() > 0 || p != nil {
size := http2MaxFrameLen
// Wait until the stream has some quota to send the data.
sq, err := wait(s.ctx, s.done, s.goAway, t.shutdownChan, s.sendQuotaPool.acquire())
if err != nil {
return err
}
// Wait until the transport has some quota to send the data.
tq, err := wait(s.ctx, s.done, s.goAway, t.shutdownChan, t.sendQuotaPool.acquire())
if err != nil {
return err
}
if sq < size {
size = sq
}
if tq < size {
size = tq
}
if p == nil {
p = r.Next(size)
}
ps := len(p)
if ps < sq {
// Overbooked stream quota. Return it back.
s.sendQuotaPool.add(sq - ps)
}
if ps < tq {
// Overbooked transport quota. Return it back.
t.sendQuotaPool.add(tq - ps)
}
}
var (
endStream bool
forceFlush bool
)
if opts.Last && r.Len() == 0 {
endStream = true
}
// Indicate there is a writer who is about to write a data frame.
t.framer.adjustNumWriters(1)
// Got some quota. Try to acquire writing privilege on the transport.
if _, err := wait(s.ctx, s.done, s.goAway, t.shutdownChan, t.writableChan); err != nil {
if _, ok := err.(StreamError); ok || err == io.EOF {
// Return the connection quota back.
t.sendQuotaPool.add(len(p))
}
if t.framer.adjustNumWriters(-1) == 0 {
// This writer is the last one in this batch and has the
// responsibility to flush the buffered frames. It queues
// a flush request to controlBuf instead of flushing directly
// in order to avoid the race with other writing or flushing.
t.controlBuf.put(&flushIO{})
}
return err
}
select {
case <-s.ctx.Done():
t.sendQuotaPool.add(len(p))
if t.framer.adjustNumWriters(-1) == 0 {
t.controlBuf.put(&flushIO{})
}
t.writableChan <- 0
return ContextErr(s.ctx.Err())
default:
}
if oqv != atomic.LoadUint32(&t.outQuotaVersion) {
// InitialWindowSize settings frame must have been received after we
// acquired send quota but before we got the writable channel.
// We must forsake this write.
t.sendQuotaPool.add(len(p))
s.sendQuotaPool.add(len(p))
if t.framer.adjustNumWriters(-1) == 0 {
t.controlBuf.put(&flushIO{})
}
t.writableChan <- 0
continue
}
if r.Len() == 0 && t.framer.adjustNumWriters(0) == 1 {
// Do a force flush iff this is last frame for the entire gRPC message
// and the caller is the only writer at this moment.
forceFlush = true
}
// If WriteData fails, all the pending streams will be handled
// by http2Client.Close(). No explicit CloseStream() needs to be
// invoked.
if err := t.framer.writeData(forceFlush, s.id, endStream, p); err != nil {
t.notifyError(err)
return connectionErrorf(true, err, "transport: %v", err)
}
p = nil
if t.framer.adjustNumWriters(-1) == 0 {
t.framer.flushWrite()
}
t.writableChan <- 0
if r.Len() == 0 {
break
}
}
if !opts.Last {
return nil
}
s.mu.Lock()
if s.state != streamDone {
s.state = streamWriteDone
}
s.mu.Unlock()
return nil
}
func (t *http2Client) getStream(f http2.Frame) (*Stream, bool) {
t.mu.Lock()
defer t.mu.Unlock()
s, ok := t.activeStreams[f.Header().StreamID]
return s, ok
}
// adjustWindow sends out extra window update over the initial window size
// of stream if the application is requesting data larger in size than
// the window.
func (t *http2Client) adjustWindow(s *Stream, n uint32) {
s.mu.Lock()
defer s.mu.Unlock()
if s.state == streamDone {
return
}
if w := s.fc.maybeAdjust(n); w > 0 {
// Piggyback conneciton's window update along.
if cw := t.fc.resetPendingUpdate(); cw > 0 {
t.controlBuf.put(&windowUpdate{0, cw, false})
}
t.controlBuf.put(&windowUpdate{s.id, w, true})
}
}
// updateWindow adjusts the inbound quota for the stream and the transport.
// Window updates will deliver to the controller for sending when
// the cumulative quota exceeds the corresponding threshold.
func (t *http2Client) updateWindow(s *Stream, n uint32) {
s.mu.Lock()
defer s.mu.Unlock()
if s.state == streamDone {
return
}
if w := s.fc.onRead(n); w > 0 {
if cw := t.fc.resetPendingUpdate(); cw > 0 {
t.controlBuf.put(&windowUpdate{0, cw, false})
}
t.controlBuf.put(&windowUpdate{s.id, w, true})
}
}
// updateFlowControl updates the incoming flow control windows
// for the transport and the stream based on the current bdp
// estimation.
func (t *http2Client) updateFlowControl(n uint32) {
t.mu.Lock()
for _, s := range t.activeStreams {
s.fc.newLimit(n)
}
t.initialWindowSize = int32(n)
t.mu.Unlock()
t.controlBuf.put(&windowUpdate{0, t.fc.newLimit(n), false})
t.controlBuf.put(&settings{
ack: false,
ss: []http2.Setting{
{
ID: http2.SettingInitialWindowSize,
Val: uint32(n),
},
},
})
}
func (t *http2Client) handleData(f *http2.DataFrame) {
size := f.Header().Length
var sendBDPPing bool
if t.bdpEst != nil {
sendBDPPing = t.bdpEst.add(uint32(size))
}
// Decouple connection's flow control from application's read.
// An update on connection's flow control should not depend on
// whether user application has read the data or not. Such a
// restriction is already imposed on the stream's flow control,
// and therefore the sender will be blocked anyways.
// Decoupling the connection flow control will prevent other
// active(fast) streams from starving in presence of slow or
// inactive streams.
//
// Furthermore, if a bdpPing is being sent out we can piggyback
// connection's window update for the bytes we just received.
if sendBDPPing {
t.controlBuf.put(&windowUpdate{0, uint32(size), false})
t.controlBuf.put(bdpPing)
} else {
if err := t.fc.onData(uint32(size)); err != nil {
t.notifyError(connectionErrorf(true, err, "%v", err))
return
}
if w := t.fc.onRead(uint32(size)); w > 0 {
t.controlBuf.put(&windowUpdate{0, w, true})
}
}
// Select the right stream to dispatch.
s, ok := t.getStream(f)
if !ok {
return
}
if size > 0 {
s.mu.Lock()
if s.state == streamDone {
s.mu.Unlock()
return
}
if err := s.fc.onData(uint32(size)); err != nil {
s.rstStream = true
s.rstError = http2.ErrCodeFlowControl
s.finish(status.New(codes.Internal, err.Error()))
s.mu.Unlock()
s.write(recvMsg{err: io.EOF})
return
}
if f.Header().Flags.Has(http2.FlagDataPadded) {
if w := s.fc.onRead(uint32(size) - uint32(len(f.Data()))); w > 0 {
t.controlBuf.put(&windowUpdate{s.id, w, true})
}
}
s.mu.Unlock()
// TODO(bradfitz, zhaoq): A copy is required here because there is no
// guarantee f.Data() is consumed before the arrival of next frame.
// Can this copy be eliminated?
if len(f.Data()) > 0 {
data := make([]byte, len(f.Data()))
copy(data, f.Data())
s.write(recvMsg{data: data})
}
}
// The server has closed the stream without sending trailers. Record that
// the read direction is closed, and set the status appropriately.
if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) {
s.mu.Lock()
if s.state == streamDone {
s.mu.Unlock()
return
}
s.finish(status.New(codes.Internal, "server closed the stream without sending trailers"))
s.mu.Unlock()
s.write(recvMsg{err: io.EOF})
}
}
func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) {
s, ok := t.getStream(f)
if !ok {
return
}
s.mu.Lock()
if s.state == streamDone {
s.mu.Unlock()
return
}
if !s.headerDone {
close(s.headerChan)
s.headerDone = true
}
statusCode, ok := http2ErrConvTab[http2.ErrCode(f.ErrCode)]
if !ok {
warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode)
statusCode = codes.Unknown
}
s.finish(status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %d", f.ErrCode))
s.mu.Unlock()
s.write(recvMsg{err: io.EOF})
}
func (t *http2Client) handleSettings(f *http2.SettingsFrame) {
if f.IsAck() {
return
}
var ss []http2.Setting
f.ForeachSetting(func(s http2.Setting) error {
ss = append(ss, s)
return nil
})
// The settings will be applied once the ack is sent.
t.controlBuf.put(&settings{ack: true, ss: ss})
}
func (t *http2Client) handlePing(f *http2.PingFrame) {
if f.IsAck() {
// Maybe it's a BDP ping.
if t.bdpEst != nil {
t.bdpEst.calculate(f.Data)
}
return
}
pingAck := &ping{ack: true}
copy(pingAck.data[:], f.Data[:])
t.controlBuf.put(pingAck)
}
func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) {
t.mu.Lock()
if t.state != reachable && t.state != draining {
t.mu.Unlock()
return
}
if f.ErrCode == http2.ErrCodeEnhanceYourCalm {
infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.")
}
id := f.LastStreamID
if id > 0 && id%2 != 1 {
t.mu.Unlock()
t.notifyError(connectionErrorf(true, nil, "received illegal http2 GOAWAY frame: stream ID %d is even", f.LastStreamID))
return
}
// A client can recieve multiple GoAways from server (look at https://github.com/grpc/grpc-go/issues/1387).
// The idea is that the first GoAway will be sent with an ID of MaxInt32 and the second GoAway will be sent after an RTT delay
// with the ID of the last stream the server will process.
// Therefore, when we get the first GoAway we don't really close any streams. While in case of second GoAway we
// close all streams created after the second GoAwayId. This way streams that were in-flight while the GoAway from server
// was being sent don't get killed.
select {
case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways).
// If there are multiple GoAways the first one should always have an ID greater than the following ones.
if id > t.prevGoAwayID {
t.mu.Unlock()
t.notifyError(connectionErrorf(true, nil, "received illegal http2 GOAWAY frame: previously recv GOAWAY frame with LastStramID %d, currently recv %d", id, f.LastStreamID))
return
}
default:
t.setGoAwayReason(f)
close(t.goAway)
t.state = draining
}
// All streams with IDs greater than the GoAwayId
// and smaller than the previous GoAway ID should be killed.
upperLimit := t.prevGoAwayID
if upperLimit == 0 { // This is the first GoAway Frame.
upperLimit = math.MaxUint32 // Kill all streams after the GoAway ID.
}
for streamID, stream := range t.activeStreams {
if streamID > id && streamID <= upperLimit {
close(stream.goAway)
}
}
t.prevGoAwayID = id
active := len(t.activeStreams)
t.mu.Unlock()
if active == 0 {
t.Close()
}
}
// setGoAwayReason sets the value of t.goAwayReason based
// on the GoAway frame received.
// It expects a lock on transport's mutext to be held by
// the caller.
func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) {
t.goAwayReason = NoReason
switch f.ErrCode {
case http2.ErrCodeEnhanceYourCalm:
if string(f.DebugData()) == "too_many_pings" {
t.goAwayReason = TooManyPings
}
}
}
func (t *http2Client) GetGoAwayReason() GoAwayReason {
t.mu.Lock()
defer t.mu.Unlock()
return t.goAwayReason
}
func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) {
id := f.Header().StreamID
incr := f.Increment
if id == 0 {
t.sendQuotaPool.add(int(incr))
return
}
if s, ok := t.getStream(f); ok {
s.sendQuotaPool.add(int(incr))
}
}
// operateHeaders takes action on the decoded headers.
func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) {
s, ok := t.getStream(frame)
if !ok {
return
}
s.mu.Lock()
s.bytesReceived = true
s.mu.Unlock()
var state decodeState
if err := state.decodeResponseHeader(frame); err != nil {
s.mu.Lock()
if !s.headerDone {
close(s.headerChan)
s.headerDone = true
}
s.mu.Unlock()
s.write(recvMsg{err: err})
// Something wrong. Stops reading even when there is remaining.
return
}
endStream := frame.StreamEnded()
var isHeader bool
defer func() {
if t.statsHandler != nil {
if isHeader {
inHeader := &stats.InHeader{
Client: true,
WireLength: int(frame.Header().Length),
}
t.statsHandler.HandleRPC(s.ctx, inHeader)
} else {
inTrailer := &stats.InTrailer{
Client: true,
WireLength: int(frame.Header().Length),
}
t.statsHandler.HandleRPC(s.ctx, inTrailer)
}
}
}()
s.mu.Lock()
if !endStream {
s.recvCompress = state.encoding
}
if !s.headerDone {
if !endStream && len(state.mdata) > 0 {
s.header = state.mdata
}
close(s.headerChan)
s.headerDone = true
isHeader = true
}
if !endStream || s.state == streamDone {
s.mu.Unlock()
return
}
if len(state.mdata) > 0 {
s.trailer = state.mdata
}
s.finish(state.status())
s.mu.Unlock()
s.write(recvMsg{err: io.EOF})
}
func handleMalformedHTTP2(s *Stream, err error) {
s.mu.Lock()
if !s.headerDone {
close(s.headerChan)
s.headerDone = true
}
s.mu.Unlock()
s.write(recvMsg{err: err})
}
// reader runs as a separate goroutine in charge of reading data from network
// connection.
//
// TODO(zhaoq): currently one reader per transport. Investigate whether this is
// optimal.
// TODO(zhaoq): Check the validity of the incoming frame sequence.
func (t *http2Client) reader() {
// Check the validity of server preface.
frame, err := t.framer.readFrame()
if err != nil {
t.notifyError(err)
return
}
atomic.CompareAndSwapUint32(&t.activity, 0, 1)
sf, ok := frame.(*http2.SettingsFrame)
if !ok {
t.notifyError(err)
return
}
t.handleSettings(sf)
// loop to keep reading incoming messages on this transport.
for {
frame, err := t.framer.readFrame()
atomic.CompareAndSwapUint32(&t.activity, 0, 1)
if err != nil {
// Abort an active stream if the http2.Framer returns a
// http2.StreamError. This can happen only if the server's response
// is malformed http2.
if se, ok := err.(http2.StreamError); ok {
t.mu.Lock()
s := t.activeStreams[se.StreamID]
t.mu.Unlock()
if s != nil {
// use error detail to provide better err message
handleMalformedHTTP2(s, streamErrorf(http2ErrConvTab[se.Code], "%v", t.framer.errorDetail()))
}
continue
} else {
// Transport error.
t.notifyError(err)
return
}
}
switch frame := frame.(type) {
case *http2.MetaHeadersFrame:
t.operateHeaders(frame)
case *http2.DataFrame:
t.handleData(frame)
case *http2.RSTStreamFrame:
t.handleRSTStream(frame)
case *http2.SettingsFrame:
t.handleSettings(frame)
case *http2.PingFrame:
t.handlePing(frame)
case *http2.GoAwayFrame:
t.handleGoAway(frame)
case *http2.WindowUpdateFrame:
t.handleWindowUpdate(frame)
default:
errorf("transport: http2Client.reader got unhandled frame type %v.", frame)
}
}
}
func (t *http2Client) applySettings(ss []http2.Setting) {
for _, s := range ss {
switch s.ID {
case http2.SettingMaxConcurrentStreams:
// TODO(zhaoq): This is a hack to avoid significant refactoring of the
// code to deal with the unrealistic int32 overflow. Probably will try
// to find a better way to handle this later.
if s.Val > math.MaxInt32 {
s.Val = math.MaxInt32
}
t.mu.Lock()
ms := t.maxStreams
t.maxStreams = int(s.Val)
t.mu.Unlock()
t.streamsQuota.add(int(s.Val) - ms)
case http2.SettingInitialWindowSize:
t.mu.Lock()
for _, stream := range t.activeStreams {
// Adjust the sending quota for each stream.
stream.sendQuotaPool.add(int(s.Val) - int(t.streamSendQuota))
}
t.streamSendQuota = s.Val
t.mu.Unlock()
atomic.AddUint32(&t.outQuotaVersion, 1)
}
}
}
// controller running in a separate goroutine takes charge of sending control
// frames (e.g., window update, reset stream, setting, etc.) to the server.
func (t *http2Client) controller() {
for {
select {
case i := <-t.controlBuf.get():
t.controlBuf.load()
select {
case <-t.writableChan:
switch i := i.(type) {
case *windowUpdate:
t.framer.writeWindowUpdate(i.flush, i.streamID, i.increment)
case *settings:
if i.ack {
t.framer.writeSettingsAck(true)
t.applySettings(i.ss)
} else {
t.framer.writeSettings(true, i.ss...)
}
case *resetStream:
// If the server needs to be to intimated about stream closing,
// then we need to make sure the RST_STREAM frame is written to
// the wire before the headers of the next stream waiting on
// streamQuota. We ensure this by adding to the streamsQuota pool
// only after having acquired the writableChan to send RST_STREAM.
t.streamsQuota.add(1)
t.framer.writeRSTStream(true, i.streamID, i.code)
case *flushIO:
t.framer.flushWrite()
case *ping:
if !i.ack {
t.bdpEst.timesnap(i.data)
}
t.framer.writePing(true, i.ack, i.data)
default:
errorf("transport: http2Client.controller got unexpected item type %v\n", i)
}
t.writableChan <- 0
continue
case <-t.shutdownChan:
return
}
case <-t.shutdownChan:
return
}
}
}
// keepalive running in a separate goroutune makes sure the connection is alive by sending pings.
func (t *http2Client) keepalive() {
p := &ping{data: [8]byte{}}
timer := time.NewTimer(t.kp.Time)
for {
select {
case <-timer.C:
if atomic.CompareAndSwapUint32(&t.activity, 1, 0) {
timer.Reset(t.kp.Time)
continue
}
// Check if keepalive should go dormant.
t.mu.Lock()
if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream {
// Make awakenKeepalive writable.
<-t.awakenKeepalive
t.mu.Unlock()
select {
case <-t.awakenKeepalive:
// If the control gets here a ping has been sent
// need to reset the timer with keepalive.Timeout.
case <-t.shutdownChan:
return
}
} else {
t.mu.Unlock()
// Send ping.
t.controlBuf.put(p)
}
// By the time control gets here a ping has been sent one way or the other.
timer.Reset(t.kp.Timeout)
select {
case <-timer.C:
if atomic.CompareAndSwapUint32(&t.activity, 1, 0) {
timer.Reset(t.kp.Time)
continue
}
t.Close()
return
case <-t.shutdownChan:
if !timer.Stop() {
<-timer.C
}
return
}
case <-t.shutdownChan:
if !timer.Stop() {
<-timer.C
}
return
}
}
}
func (t *http2Client) Error() <-chan struct{} {
return t.errorChan
}
func (t *http2Client) GoAway() <-chan struct{} {
return t.goAway
}
func (t *http2Client) notifyError(err error) {
t.mu.Lock()
// make sure t.errorChan is closed only once.
if t.state == draining {
t.mu.Unlock()
t.Close()
return
}
if t.state == reachable {
t.state = unreachable
close(t.errorChan)
infof("transport: http2Client.notifyError got notified that the client transport was broken %v.", err)
}
t.mu.Unlock()
}
| mpl-2.0 |
vladisav/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/platform/compute/PlatformBroadcastingSingleClosureTask.java | 2698 | /*
* 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.platform.compute;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.compute.ComputeJob;
import org.apache.ignite.compute.ComputeTaskNoResultCache;
import org.apache.ignite.internal.processors.platform.PlatformContext;
import org.apache.ignite.internal.util.typedef.F;
import org.jetbrains.annotations.Nullable;
/**
* Interop single-closure task with broadcast semantics.
*/
@ComputeTaskNoResultCache
public class PlatformBroadcastingSingleClosureTask extends PlatformAbstractTask {
/** */
private static final long serialVersionUID = 0L;
/** */
private PlatformJob job;
/**
* Constructor.
*
* @param ctx Platform context.
* @param taskPtr Task pointer.
*/
public PlatformBroadcastingSingleClosureTask(PlatformContext ctx, long taskPtr) {
super(ctx, taskPtr);
}
/** {@inheritDoc} */
@Nullable @Override public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid,
@Nullable Object arg) {
assert job != null : "Job null-check must be performed in native platform.";
if (!F.isEmpty(subgrid)) {
Map<ComputeJob, ClusterNode> map = new HashMap<>(subgrid.size(), 1);
boolean first = true;
for (ClusterNode node : subgrid) {
if (first) {
map.put(job, node);
first = false;
}
else
map.put(ctx.createClosureJob(this, job.pointer(), job.job()), node);
}
return map;
}
else
return Collections.emptyMap();
}
/**
* @param job Job.
*/
public void job(PlatformJob job) {
this.job = job;
}
} | apache-2.0 |
loconsolutions/elasticsearch | core/src/main/java/org/elasticsearch/common/transport/InetSocketTransportAddress.java | 4578 | /*
* 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.common.transport;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
/**
* A transport address used for IP socket address (wraps {@link java.net.InetSocketAddress}).
*/
public class InetSocketTransportAddress implements TransportAddress {
private static boolean resolveAddress = false;
public static void setResolveAddress(boolean resolveAddress) {
InetSocketTransportAddress.resolveAddress = resolveAddress;
}
public static boolean getResolveAddress() {
return resolveAddress;
}
public static final InetSocketTransportAddress PROTO = new InetSocketTransportAddress();
private final InetSocketAddress address;
public InetSocketTransportAddress(StreamInput in) throws IOException {
if (in.readByte() == 0) {
int len = in.readByte();
byte[] a = new byte[len]; // 4 bytes (IPv4) or 16 bytes (IPv6)
in.readFully(a);
InetAddress inetAddress;
if (len == 16) {
int scope_id = in.readInt();
inetAddress = Inet6Address.getByAddress(null, a, scope_id);
} else {
inetAddress = InetAddress.getByAddress(a);
}
int port = in.readInt();
this.address = new InetSocketAddress(inetAddress, port);
} else {
this.address = new InetSocketAddress(in.readString(), in.readInt());
}
}
private InetSocketTransportAddress() {
address = null;
}
public InetSocketTransportAddress(String hostname, int port) {
this(new InetSocketAddress(hostname, port));
}
public InetSocketTransportAddress(InetAddress address, int port) {
this(new InetSocketAddress(address, port));
}
public InetSocketTransportAddress(InetSocketAddress address) {
this.address = address;
}
@Override
public short uniqueAddressTypeId() {
return 1;
}
@Override
public boolean sameHost(TransportAddress other) {
return other instanceof InetSocketTransportAddress &&
address.getAddress().equals(((InetSocketTransportAddress) other).address.getAddress());
}
public InetSocketAddress address() {
return this.address;
}
@Override
public TransportAddress readFrom(StreamInput in) throws IOException {
return new InetSocketTransportAddress(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
if (!resolveAddress && address.getAddress() != null) {
out.writeByte((byte) 0);
byte[] bytes = address().getAddress().getAddress(); // 4 bytes (IPv4) or 16 bytes (IPv6)
out.writeByte((byte) bytes.length); // 1 byte
out.write(bytes, 0, bytes.length);
if (address().getAddress() instanceof Inet6Address)
out.writeInt(((Inet6Address) address.getAddress()).getScopeId());
} else {
out.writeByte((byte) 1);
out.writeString(address.getHostName());
}
out.writeInt(address.getPort());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InetSocketTransportAddress address1 = (InetSocketTransportAddress) o;
return address.equals(address1.address);
}
@Override
public int hashCode() {
return address != null ? address.hashCode() : 0;
}
@Override
public String toString() {
return "inet[" + address + "]";
}
}
| apache-2.0 |
dakshshah96/cdnjs | ajax/libs/oclazyload/0.4.0/ocLazyLoad.js | 35227 | /**
* oclazyload - Load modules on demand (lazy load) with angularJS
* @version v0.4.0
* @link https://github.com/ocombe/ocLazyLoad
* @license MIT
* @author Olivier Combe <olivier.combe@gmail.com>
*/
(function() {
'use strict';
var regModules = ['ng'],
regInvokes = {},
regConfigs = [],
justLoaded = [],
ocLazyLoad = angular.module('oc.lazyLoad', ['ng']),
broadcast = angular.noop;
ocLazyLoad.provider('$ocLazyLoad', ['$controllerProvider', '$provide', '$compileProvider', '$filterProvider', '$injector', '$animateProvider',
function($controllerProvider, $provide, $compileProvider, $filterProvider, $injector, $animateProvider) {
var modules = {},
providers = {
$controllerProvider: $controllerProvider,
$compileProvider: $compileProvider,
$filterProvider: $filterProvider,
$provide: $provide, // other things
$injector: $injector,
$animateProvider: $animateProvider
},
anchor = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0],
jsLoader, cssLoader, templatesLoader,
debug = false,
events = false;
// Let's get the list of loaded modules & components
init(angular.element(window.document));
this.$get = ['$timeout', '$log', '$q', '$templateCache', '$http', '$rootElement', '$rootScope', '$cacheFactory', '$interval', function($timeout, $log, $q, $templateCache, $http, $rootElement, $rootScope, $cacheFactory, $interval) {
var instanceInjector,
filesCache = $cacheFactory('ocLazyLoad'),
uaCssChecked = false,
useCssLoadPatch = false;
if(!debug) {
$log = {};
$log['error'] = angular.noop;
$log['warn'] = angular.noop;
$log['info'] = angular.noop;
}
// Make this lazy because at the moment that $get() is called the instance injector hasn't been assigned to the rootElement yet
providers.getInstanceInjector = function() {
return (instanceInjector) ? instanceInjector : (instanceInjector = $rootElement.data('$injector'));
};
broadcast = function broadcast(eventName, params) {
if(events) {
$rootScope.$broadcast(eventName, params);
}
if(debug) {
$log.info(eventName, params);
}
}
/**
* Load a js/css file
* @param type
* @param path
* @returns promise
*/
var buildElement = function buildElement(type, path, params) {
var deferred = $q.defer(),
el, loaded,
cacheBuster = function cacheBuster(url) {
var dc = new Date().getTime();
if(url.indexOf('?') >= 0) {
if(url.substring(0, url.length - 1) === '&') {
return url + '_dc=' + dc;
}
return url + '&_dc=' + dc;
} else {
return url + '?_dc=' + dc;
}
};
// Store the promise early so the file load can be detected by other parallel lazy loads
// (ie: multiple routes on one page) a 'true' value isn't sufficient
// as it causes false positive load results.
if(angular.isUndefined(filesCache.get(path))) {
filesCache.put(path, deferred.promise);
}
// Switch in case more content types are added later
switch(type) {
case 'css':
el = document.createElement('link');
el.type = 'text/css';
el.rel = 'stylesheet';
el.href = params.cache === false ? cacheBuster(path) : path;
break;
case 'js':
el = document.createElement('script');
el.src = params.cache === false ? cacheBuster(path) : path;
break;
default:
deferred.reject(new Error('Requested type "' + type + '" is not known. Could not inject "' + path + '"'));
break;
}
el.onload = el['onreadystatechange'] = function(e) {
if((el['readyState'] && !(/^c|loade/.test(el['readyState']))) || loaded) return;
el.onload = el['onreadystatechange'] = null
loaded = 1;
broadcast('ocLazyLoad.fileLoaded', path);
deferred.resolve();
}
el.onerror = function(e) {
deferred.reject(new Error('Unable to load ' + path));
}
el.async = 1;
anchor.insertBefore(el, anchor.lastChild);
/*
The event load or readystatechange doesn't fire in:
- iOS < 6 (default mobile browser)
- Android < 4.4 (default mobile browser)
- Safari < 6 (desktop browser)
*/
if(type == 'css') {
if(!uaCssChecked) {
var ua = navigator.userAgent.toLowerCase();
// iOS < 6
if(/iP(hone|od|ad)/.test(navigator.platform)) {
var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
var iOSVersion = parseFloat([parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)].join('.'));
useCssLoadPatch = iOSVersion < 6;
} else if(ua.indexOf("android") > -1) { // Android < 4.4
var androidVersion = parseFloat(ua.slice(ua.indexOf("android") + 8));
useCssLoadPatch = androidVersion < 4.4;
} else if(ua.indexOf('safari') > -1 && ua.indexOf('chrome') == -1) {
var safariVersion = parseFloat(ua.match(/version\/([\.\d]+)/i)[1]);
useCssLoadPatch = safariVersion < 6;
}
}
if(useCssLoadPatch) {
var tries = 1000; // * 20 = 20000 miliseconds
var interval = $interval(function() {
try {
el.sheet.cssRules;
$interval.cancel(interval);
el.onload();
} catch(e) {
if(--tries <= 0) {
el.onerror();
}
}
}, 20);
}
}
return deferred.promise;
}
if(angular.isUndefined(jsLoader)) {
/**
* jsLoader function
* @type Function
* @param paths array list of js files to load
* @param callback to call when everything is loaded. We use a callback and not a promise
* @param params object config parameters
* because the user can overwrite jsLoader and it will probably not use promises :(
*/
jsLoader = function(paths, callback, params) {
var promises = [];
angular.forEach(paths, function loading(path) {
promises.push(buildElement('js', path, params));
});
$q.all(promises).then(function success() {
callback();
}, function error(err) {
callback(err);
});
}
jsLoader.ocLazyLoadLoader = true;
}
if(angular.isUndefined(cssLoader)) {
/**
* cssLoader function
* @type Function
* @param paths array list of css files to load
* @param callback to call when everything is loaded. We use a callback and not a promise
* @param params object config parameters
* because the user can overwrite cssLoader and it will probably not use promises :(
*/
cssLoader = function(paths, callback, params) {
var promises = [];
angular.forEach(paths, function loading(path) {
promises.push(buildElement('css', path, params));
});
$q.all(promises).then(function success() {
callback();
}, function error(err) {
callback(err);
});
}
cssLoader.ocLazyLoadLoader = true;
}
if(angular.isUndefined(templatesLoader)) {
/**
* templatesLoader function
* @type Function
* @param paths array list of css files to load
* @param callback to call when everything is loaded. We use a callback and not a promise
* @param params object config parameters for $http
* because the user can overwrite templatesLoader and it will probably not use promises :(
*/
templatesLoader = function(paths, callback, params) {
if(angular.isString(paths)) {
paths = [paths];
}
var promises = [];
angular.forEach(paths, function(url) {
var deferred = $q.defer();
promises.push(deferred.promise);
$http.get(url, params).success(function(data) {
angular.forEach(angular.element(data), function(node) {
if(node.nodeName === 'SCRIPT' && node.type === 'text/ng-template') {
$templateCache.put(node.id, node.innerHTML);
}
});
if(angular.isUndefined(filesCache.get(url))) {
filesCache.put(url, true);
}
deferred.resolve();
}).error(function(data) {
var err = 'Error load template "' + url + '": ' + data;
$log.error(err);
deferred.reject(new Error(err));
});
});
return $q.all(promises).then(function success() {
callback();
}, function error(err) {
callback(err);
});
}
templatesLoader.ocLazyLoadLoader = true;
}
var filesLoader = function(config, params) {
var cssFiles = [],
templatesFiles = [],
jsFiles = [],
promises = [],
cachePromise = null;
angular.extend(params || {}, config);
var pushFile = function(path) {
cachePromise = filesCache.get(path);
if(angular.isUndefined(cachePromise) || params.cache === false) {
if(/\.css[^\.]*$/.test(path) && cssFiles.indexOf(path) === -1) {
cssFiles.push(path);
} else if(/\.(htm|html)[^\.]*$/.test(path) && templatesFiles.indexOf(path) === -1) {
templatesFiles.push(path);
} else if(jsFiles.indexOf(path) === -1) {
jsFiles.push(path);
}
} else if(cachePromise) {
promises.push(cachePromise);
}
}
if(params.serie) {
pushFile(params.files.shift());
} else {
angular.forEach(params.files, function(path) {
pushFile(path);
});
}
if(cssFiles.length > 0) {
var cssDeferred = $q.defer();
cssLoader(cssFiles, function(err) {
if(angular.isDefined(err) && cssLoader.hasOwnProperty('ocLazyLoadLoader')) {
$log.error(err);
cssDeferred.reject(err);
} else {
cssDeferred.resolve();
}
}, params);
promises.push(cssDeferred.promise);
}
if(templatesFiles.length > 0) {
var templatesDeferred = $q.defer();
templatesLoader(templatesFiles, function(err) {
if(angular.isDefined(err) && templatesLoader.hasOwnProperty('ocLazyLoadLoader')) {
$log.error(err);
templatesDeferred.reject(err);
} else {
templatesDeferred.resolve();
}
}, params);
promises.push(templatesDeferred.promise);
}
if(jsFiles.length > 0) {
var jsDeferred = $q.defer();
jsLoader(jsFiles, function(err) {
if(angular.isDefined(err) && jsLoader.hasOwnProperty('ocLazyLoadLoader')) {
$log.error(err);
jsDeferred.reject(err);
} else {
jsDeferred.resolve();
}
}, params);
promises.push(jsDeferred.promise);
}
if(params.serie && params.files.length > 0) {
return $q.all(promises).then(function success() {
return filesLoader(config, params);
});
} else {
return $q.all(promises);
}
}
return {
/**
* Let you get a module config object
* @param moduleName String the name of the module
* @returns {*}
*/
getModuleConfig: function(moduleName) {
if(!angular.isString(moduleName)) {
throw new Error('You need to give the name of the module to get');
}
if(!modules[moduleName]) {
return null;
}
return modules[moduleName];
},
/**
* Let you define a module config object
* @param moduleConfig Object the module config object
* @returns {*}
*/
setModuleConfig: function(moduleConfig) {
if(!angular.isObject(moduleConfig)) {
throw new Error('You need to give the module config object to set');
}
modules[moduleConfig.name] = moduleConfig;
return moduleConfig;
},
/**
* Returns the list of loaded modules
* @returns {string[]}
*/
getModules: function() {
return regModules;
},
/**
* Let you check if a module has been loaded into Angular or not
* @param modulesNames String/Object a module name, or a list of module names
* @returns {boolean}
*/
isLoaded: function(modulesNames) {
var moduleLoaded = function(module) {
var isLoaded = regModules.indexOf(module) > -1;
if(!isLoaded) {
isLoaded = !!moduleExists(module);
}
return isLoaded;
}
if(angular.isString(modulesNames)) {
modulesNames = [modulesNames];
}
if(angular.isArray(modulesNames)) {
var i, len;
for(i = 0, len = modulesNames.length; i < len; i++) {
if(!moduleLoaded(modulesNames[i])) {
return false;
}
}
return true;
} else {
throw new Error('You need to define the module(s) name(s)');
}
},
/**
* Load a module or a list of modules into Angular
* @param module Mixed the name of a predefined module config object, or a module config object, or an array of either
* @param params Object optional parameters
* @returns promise
*/
load: function(module, params) {
var self = this,
config = null,
moduleCache = [],
deferredList = [],
deferred = $q.defer(),
moduleName,
errText;
if(angular.isUndefined(params)) {
params = {};
}
// If module is an array, break it down
if(angular.isArray(module)) {
// Resubmit each entry as a single module
angular.forEach(module, function(m) {
if(m) {
deferredList.push(self.load(m, params));
}
});
// Resolve the promise once everything has loaded
$q.all(deferredList).then(function success() {
deferred.resolve(module);
}, function error(err) {
deferred.reject(err);
});
return deferred.promise;
}
moduleName = getModuleName(module);
// Get or Set a configuration depending on what was passed in
if(typeof module === 'string') {
config = self.getModuleConfig(module);
if(!config) {
config = {
files: [module]
};
moduleName = null;
}
} else if(typeof module === 'object') {
config = self.setModuleConfig(module);
}
if(config === null) {
errText = 'Module "' + moduleName + '" is not configured, cannot load.';
$log.error(errText);
deferred.reject(new Error(errText));
} else {
// deprecated
if(angular.isDefined(config.template)) {
if(angular.isUndefined(config.files)) {
config.files = [];
}
if(angular.isString(config.template)) {
config.files.push(config.template);
} else if(angular.isArray(config.template)) {
config.files.concat(config.template);
}
}
}
moduleCache.push = function(value) {
if(this.indexOf(value) === -1) {
Array.prototype.push.apply(this, arguments);
}
};
// If this module has been loaded before, re-use it.
if(angular.isDefined(moduleName) && moduleExists(moduleName) && regModules.indexOf(moduleName) !== -1) {
moduleCache.push(moduleName);
// if we don't want to load new files, resolve here
if(angular.isUndefined(config.files)) {
deferred.resolve();
return deferred.promise;
}
}
var loadDependencies = function loadDependencies(module) {
var moduleName,
loadedModule,
requires,
diff,
promisesList = [];
moduleName = getModuleName(module);
if(moduleName === null) {
return $q.when();
} else {
try {
loadedModule = getModule(moduleName);
} catch(e) {
var deferred = $q.defer();
$log.error(e.message);
deferred.reject(e);
return deferred.promise;
}
requires = getRequires(loadedModule);
}
angular.forEach(requires, function(requireEntry) {
// If no configuration is provided, try and find one from a previous load.
// If there isn't one, bail and let the normal flow run
if(typeof requireEntry === 'string') {
var config = self.getModuleConfig(requireEntry);
if(config === null) {
moduleCache.push(requireEntry); // We don't know about this module, but something else might, so push it anyway.
return;
}
requireEntry = config;
}
// Check if this dependency has been loaded previously
if(moduleExists(requireEntry.name)) {
if(typeof module !== 'string') {
// compare against the already loaded module to see if the new definition adds any new files
diff = requireEntry.files.filter(function(n) {
return self.getModuleConfig(requireEntry.name).files.indexOf(n) < 0;
});
// If the module was redefined, advise via the console
if(diff.length !== 0) {
$log.warn('Module "', moduleName, '" attempted to redefine configuration for dependency. "', requireEntry.name, '"\n Additional Files Loaded:', diff);
}
// Push everything to the file loader, it will weed out the duplicates.
promisesList.push(filesLoader(requireEntry.files, params).then(function() {
return loadDependencies(requireEntry);
}));
}
return;
} else if(typeof requireEntry === 'object') {
if(requireEntry.hasOwnProperty('name') && requireEntry['name']) {
// The dependency doesn't exist in the module cache and is a new configuration, so store and push it.
self.setModuleConfig(requireEntry);
moduleCache.push(requireEntry['name']);
}
// CSS Loading Handler
if(requireEntry.hasOwnProperty('css') && requireEntry['css'].length !== 0) {
// Locate the document insertion point
angular.forEach(requireEntry['css'], function(path) {
buildElement('css', path, params);
});
}
// CSS End.
}
// Check if the dependency has any files that need to be loaded. If there are, push a new promise to the promise list.
if(requireEntry.hasOwnProperty('files') && requireEntry.files.length !== 0) {
if(requireEntry.files) {
promisesList.push(filesLoader(requireEntry, params).then(function() {
return loadDependencies(requireEntry);
}));
}
}
});
// Create a wrapper promise to watch the promise list and resolve it once everything is done.
return $q.all(promisesList);
}
filesLoader(config, params).then(function success() {
if(moduleName === null) {
deferred.resolve(module);
} else {
moduleCache.push(moduleName);
loadDependencies(moduleName).then(function success() {
try {
justLoaded = [];
register(providers, moduleCache, params);
} catch(e) {
$log.error(e.message);
deferred.reject(e);
return;
}
$timeout(function() {
deferred.resolve(module);
});
}, function error(err) {
$timeout(function() {
deferred.reject(err);
});
});
}
}, function error(err) {
deferred.reject(err);
});
return deferred.promise;
}
};
}];
this.config = function(config) {
if(angular.isDefined(config.jsLoader) || angular.isDefined(config.asyncLoader)) {
jsLoader = config.jsLoader || config.asyncLoader;
if(!angular.isFunction(jsLoader)) {
throw('The js loader needs to be a function');
}
}
if(angular.isDefined(config.cssLoader)) {
cssLoader = config.cssLoader;
if(!angular.isFunction(cssLoader)) {
throw('The css loader needs to be a function');
}
}
if(angular.isDefined(config.templatesLoader)) {
templatesLoader = config.templatesLoader;
if(!angular.isFunction(templatesLoader)) {
throw('The template loader needs to be a function');
}
}
// for bootstrap apps, we need to define the main module name
if(angular.isDefined(config.loadedModules)) {
var addRegModule = function(loadedModule) {
if(regModules.indexOf(loadedModule) < 0) {
regModules.push(loadedModule);
angular.forEach(angular.module(loadedModule).requires, addRegModule);
}
};
angular.forEach(config.loadedModules, addRegModule);
}
// If we want to define modules configs
if(angular.isDefined(config.modules)) {
if(angular.isArray(config.modules)) {
angular.forEach(config.modules, function(moduleConfig) {
modules[moduleConfig.name] = moduleConfig;
});
} else {
modules[config.modules.name] = config.modules;
}
}
if(angular.isDefined(config.debug)) {
debug = config.debug;
}
if(angular.isDefined(config.events)) {
events = config.events;
}
};
}]);
ocLazyLoad.directive('ocLazyLoad', ['$ocLazyLoad', '$compile', '$animate', '$parse',
function($ocLazyLoad, $compile, $animate, $parse) {
return {
restrict: 'A',
terminal: true,
priority: 1000,
compile: function(element, attrs) {
// we store the content and remove it before compilation
var content = element[0].innerHTML;
element.html('');
return function($scope, $element, $attr) {
var model = $parse($attr.ocLazyLoad);
$scope.$watch(function() {
// it can be a module name (string), an object, an array, or a scope reference to any of this
return model($scope) || $attr.ocLazyLoad;
}, function(moduleName) {
if(angular.isDefined(moduleName)) {
$ocLazyLoad.load(moduleName).then(function success(moduleConfig) {
$animate.enter($compile(content)($scope), null, $element);
});
}
}, true);
};
}
};
}]);
/**
* Get the list of required modules/services/... for this module
* @param module
* @returns {Array}
*/
function getRequires(module) {
var requires = [];
angular.forEach(module.requires, function(requireModule) {
if(regModules.indexOf(requireModule) === -1) {
requires.push(requireModule);
}
});
return requires;
}
/**
* Check if a module exists and returns it if it does
* @param moduleName
* @returns {boolean}
*/
function moduleExists(moduleName) {
try {
return angular.module(moduleName);
} catch(e) {
if(/No module/.test(e) || (e.message.indexOf('$injector:nomod') > -1)) {
return false;
}
}
}
function getModule(moduleName) {
try {
return angular.module(moduleName);
} catch(e) {
// this error message really suxx
if(/No module/.test(e) || (e.message.indexOf('$injector:nomod') > -1)) {
e.message = 'The module "' + moduleName + '" that you are trying to load does not exist. ' + e.message
}
throw e;
}
}
function invokeQueue(providers, queue, moduleName, reconfig) {
if(!queue) {
return;
}
var i, len, args, provider;
for(i = 0, len = queue.length; i < len; i++) {
args = queue[i];
if(angular.isArray(args)) {
if(providers !== null) {
if(providers.hasOwnProperty(args[0])) {
provider = providers[args[0]];
} else {
throw new Error('unsupported provider ' + args[0]);
}
}
var isNew = registerInvokeList(args, moduleName);
if(args[1] !== 'invoke') {
if(isNew && angular.isDefined(provider)) {
provider[args[1]].apply(provider, args[2]);
}
} else { // config block
var callInvoke = function(fct) {
var invoked = regConfigs.indexOf(moduleName + '-' + fct);
if(invoked === -1 || reconfig) {
if(invoked === -1) {
regConfigs.push(moduleName + '-' + fct);
}
if(angular.isDefined(provider)) {
provider[args[1]].apply(provider, args[2]);
}
}
}
if(angular.isFunction(args[2][0])) {
callInvoke(args[2][0]);
} else if(angular.isArray(args[2][0])) {
for(var j = 0, jlen = args[2][0].length; j < jlen; j++) {
if(angular.isFunction(args[2][0][j])) {
callInvoke(args[2][0][j]);
}
}
}
}
}
}
}
/**
* Register a new module and load it
* @param providers
* @param registerModules
* @returns {*}
*/
function register(providers, registerModules, params) {
if(registerModules) {
var k, moduleName, moduleFn, runBlocks = [];
for(k = registerModules.length - 1; k >= 0; k--) {
moduleName = registerModules[k];
if(typeof moduleName !== 'string') {
moduleName = getModuleName(moduleName);
}
if(!moduleName || justLoaded.indexOf(moduleName) !== -1) {
continue;
}
var newModule = regModules.indexOf(moduleName) === -1;
moduleFn = angular.module(moduleName);
if(newModule) { // new module
regModules.push(moduleName);
register(providers, moduleFn.requires, params);
}
if(newModule || params.rerun) {
runBlocks = runBlocks.concat(moduleFn._runBlocks);
}
invokeQueue(providers, moduleFn._invokeQueue, moduleName, params.reconfig);
invokeQueue(providers, moduleFn._configBlocks, moduleName, params.reconfig); // angular 1.3+
broadcast(newModule ? 'ocLazyLoad.moduleLoaded' : 'ocLazyLoad.moduleReloaded', moduleName);
registerModules.pop();
justLoaded.push(moduleName);
}
var instanceInjector = providers.getInstanceInjector();
angular.forEach(runBlocks, function(fn) {
instanceInjector.invoke(fn);
});
}
}
/**
* Register an invoke
* @param args
* @returns {*}
*/
function registerInvokeList(args, moduleName) {
var invokeList = args[2][0],
type = args[1],
newInvoke = false;
if(angular.isUndefined(regInvokes[moduleName])) {
regInvokes[moduleName] = {};
}
if(angular.isUndefined(regInvokes[moduleName][type])) {
regInvokes[moduleName][type] = [];
}
var onInvoke = function(invokeName) {
newInvoke = true;
regInvokes[moduleName][type].push(invokeName);
broadcast('ocLazyLoad.componentLoaded', [moduleName, type, invokeName]);
}
if(angular.isString(invokeList) && regInvokes[moduleName][type].indexOf(invokeList) === -1) {
onInvoke(invokeList);
} else if(angular.isObject(invokeList)) {
angular.forEach(invokeList, function(invoke) {
if(angular.isString(invoke) && regInvokes[moduleName][type].indexOf(invoke) === -1) {
onInvoke(invoke);
}
});
} else {
return false;
}
return newInvoke;
}
function getModuleName(module) {
if(module === null) {
return null;
}
var moduleName = null;
if(typeof module === 'string') {
moduleName = module;
} else if(typeof module === 'object' && module.hasOwnProperty('name') && typeof module.name === 'string') {
moduleName = module.name;
}
return moduleName;
}
/**
* Get the list of existing registered modules
* @param element
*/
function init(element) {
var elements = [element],
appElement,
moduleName,
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
function append(elm) {
return (elm && elements.push(elm));
}
angular.forEach(names, function(name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if(element[0].querySelectorAll) {
angular.forEach(element[0].querySelectorAll('.' + name), append);
angular.forEach(element[0].querySelectorAll('.' + name + '\\:'), append);
angular.forEach(element[0].querySelectorAll('[' + name + ']'), append);
}
});
//TODO: search the script tags for angular.bootstrap
angular.forEach(elements, function(elm) {
if(!appElement) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if(match) {
appElement = elm;
moduleName = (match[2] || '').replace(/\s+/g, ',');
} else {
angular.forEach(elm.attributes, function(attr) {
if(!appElement && names[attr.name]) {
appElement = elm;
moduleName = attr.value;
}
});
}
}
});
if(appElement) {
(function addReg(moduleName) {
if(regModules.indexOf(moduleName) === -1) {
// register existing modules
regModules.push(moduleName);
var mainModule = angular.module(moduleName);
// register existing components (directives, services, ...)
invokeQueue(null, mainModule._invokeQueue, moduleName);
invokeQueue(null, mainModule._configBlocks, moduleName); // angular 1.3+
angular.forEach(mainModule.requires, addReg);
}
})(moduleName);
}
}
// Array.indexOf polyfill for IE8
if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if(this == null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If len is 0, return -1.
if(len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if(Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if(n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while(k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if(k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
})();
| mit |
nonoz/mastodon | spec/models/domain_block_spec.rb | 1308 | require 'rails_helper'
RSpec.describe DomainBlock, type: :model do
describe 'validations' do
it 'has a valid fabricator' do
domain_block = Fabricate.build(:domain_block)
expect(domain_block).to be_valid
end
it 'is invalid without a domain' do
domain_block = Fabricate.build(:domain_block, domain: nil)
domain_block.valid?
expect(domain_block).to model_have_error_on_field(:domain)
end
it 'is invalid if the same normalized domain already exists' do
domain_block_1 = Fabricate(:domain_block, domain: 'にゃん')
domain_block_2 = Fabricate.build(:domain_block, domain: 'xn--r9j5b5b')
domain_block_2.valid?
expect(domain_block_2).to model_have_error_on_field(:domain)
end
end
describe 'blocked?' do
it 'returns true if the domain is suspended' do
Fabricate(:domain_block, domain: 'domain', severity: :suspend)
expect(DomainBlock.blocked?('domain')).to eq true
end
it 'returns false even if the domain is silenced' do
Fabricate(:domain_block, domain: 'domain', severity: :silence)
expect(DomainBlock.blocked?('domain')).to eq false
end
it 'returns false if the domain is not suspended nor silenced' do
expect(DomainBlock.blocked?('domain')).to eq false
end
end
end
| agpl-3.0 |
ouyangjie/zookeeper | src/java/test/org/apache/zookeeper/test/LeaderSessionTrackerTest.java | 6262 | /**
* 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.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooDefs.OpCode;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.proto.CreateRequest;
import org.apache.zookeeper.server.Request;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Due to race condition or bad client code, the leader may get request from
* expired session. We need to make sure that we never allow ephmeral node
* to be created in those case, but we do allow normal node to be created.
*/
public class LeaderSessionTrackerTest extends ZKTestCase implements Watcher {
protected static final Logger LOG = LoggerFactory
.getLogger(LeaderSessionTrackerTest.class);
QuorumUtil qu;
@Before
public void setUp() throws Exception {
qu = new QuorumUtil(1);
}
@After
public void tearDown() throws Exception {
qu.shutdownAll();
}
@Test
public void testExpiredSessionWithLocalSession() throws Exception {
testCreateEphemeral(true);
}
@Test
public void testExpiredSessionWithoutLocalSession() throws Exception {
testCreateEphemeral(false);
}
/**
* When we create ephemeral node, we need to check against global
* session, so the leader never accept request from an expired session
* (that we no longer track)
*
* This is not the same as SessionInvalidationTest since session
* is not in closing state
*/
public void testCreateEphemeral(boolean localSessionEnabled) throws Exception {
QuorumUtil qu = new QuorumUtil(1);
if (localSessionEnabled) {
qu.enableLocalSession(true);
}
qu.startAll();
QuorumPeer leader = qu.getLeaderQuorumPeer();
ZooKeeper zk = new ZooKeeper(qu.getConnectString(leader),
CONNECTION_TIMEOUT, this);
CreateRequest createRequest = new CreateRequest("/impossible",
new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
createRequest.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
// Mimic sessionId generated by follower's local session tracker
long sid = qu.getFollowerQuorumPeers().get(0).getActiveServer()
.getServerId();
long fakeSessionId = (sid << 56) + 1;
LOG.info("Fake session Id: " + Long.toHexString(fakeSessionId));
Request request = new Request(null, fakeSessionId, 0, OpCode.create,
bb, new ArrayList<Id>());
// Submit request directly to leader
leader.getActiveServer().submitRequest(request);
// Make sure that previous request is finished
zk.create("/ok", new byte[0], Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Stat stat = zk.exists("/impossible", null);
Assert.assertEquals("Node from fake session get created", null, stat);
}
/**
* When local session is enabled, leader will allow persistent node
* to be create for unknown session
*/
@Test
public void testCreatePersistent() throws Exception {
QuorumUtil qu = new QuorumUtil(1);
qu.enableLocalSession(true);
qu.startAll();
QuorumPeer leader = qu.getLeaderQuorumPeer();
ZooKeeper zk = new ZooKeeper(qu.getConnectString(leader),
CONNECTION_TIMEOUT, this);
CreateRequest createRequest = new CreateRequest("/success",
new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT.toFlag());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
createRequest.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
// Mimic sessionId generated by follower's local session tracker
long sid = qu.getFollowerQuorumPeers().get(0).getActiveServer()
.getServerId();
long locallSession = (sid << 56) + 1;
LOG.info("Local session Id: " + Long.toHexString(locallSession));
Request request = new Request(null, locallSession, 0, OpCode.create,
bb, new ArrayList<Id>());
// Submit request directly to leader
leader.getActiveServer().submitRequest(request);
// Make sure that previous request is finished
zk.create("/ok", new byte[0], Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Stat stat = zk.exists("/success", null);
Assert.assertTrue("Request from local sesson failed", stat != null);
}
@Override
public void process(WatchedEvent event) {
}
}
| apache-2.0 |
rsoaresgouveia/SISTEMA-DE-GERENCIAMENTO-DO-POLO-SIGEPOLO- | vendor/kartik-v/yii2-widget-datepicker/assets/js/locales/bootstrap-datepicker.cs.min.js | 514 | !function(a){a.fn.kvDatepicker.dates.cs={days:["Neděle","Pondělí","Úterý","Středa","Čtvrtek","Pátek","Sobota"],daysShort:["Ned","Pon","Úte","Stř","Čtv","Pát","Sob"],daysMin:["Ne","Po","Út","St","Čt","Pá","So"],months:["Leden","Únor","Březen","Duben","Květen","Červen","Červenec","Srpen","Září","Říjen","Listopad","Prosinec"],monthsShort:["Led","Úno","Bře","Dub","Kvě","Čer","Čnc","Srp","Zář","Říj","Lis","Pro"],today:"Dnes",clear:"Vymazat",weekStart:1,format:"d.m.yyyy"}}(jQuery); | bsd-3-clause |
KevinKhieu/PeaceDashboard | node_modules/gulp-less/node_modules/accord/lib/adapters/markdown/0.3.x.js | 1211 | // Generated by CoffeeScript 1.12.5
(function() {
var Adapter, Markdown, nodefn,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Adapter = require('../../adapter_base');
nodefn = require('when/node/function');
Markdown = (function(superClass) {
extend(Markdown, superClass);
function Markdown() {
return Markdown.__super__.constructor.apply(this, arguments);
}
Markdown.prototype.name = 'markdown';
Markdown.prototype.extensions = ['md', 'mdown', 'markdown'];
Markdown.prototype.output = 'html';
Markdown.prototype.supportedEngines = ['marked'];
Markdown.prototype.isolated = true;
Markdown.prototype._render = function(str, options) {
return nodefn.call(this.engine.bind(this.engine), str, options).then(function(res) {
return {
result: res
};
});
};
return Markdown;
})(Adapter);
module.exports = Markdown;
}).call(this);
| mit |
wkhtmltopdf/qtwebkit | Source/JavaScriptCore/tests/mozilla/ecma_3/Array/15.4.4.4-001.js | 3949 | /* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape 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/NPL/
*
* 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 JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): george@vanous.com, igor@icesoft.no, pschwartau@netscape.com
*
* 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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK *****
*
*
* Date: 19 September 2002
* SUMMARY: Testing Array.prototype.concat()
* See http://bugzilla.mozilla.org/show_bug.cgi?id=169795
*
*/
//-----------------------------------------------------------------------------
var UBound = 0;
var bug = 169795;
var summary = 'Testing Array.prototype.concat()';
var status = '';
var statusitems = [];
var actual = '';
var actualvalues = [];
var expect= '';
var expectedvalues = [];
var x;
status = inSection(1);
x = "Hello";
actual = [].concat(x).toString();
expect = x.toString();
addThis();
status = inSection(2);
x = 999;
actual = [].concat(x).toString();
expect = x.toString();
addThis();
status = inSection(3);
x = /Hello/g;
actual = [].concat(x).toString();
expect = x.toString();
addThis();
status = inSection(4);
x = new Error("Hello");
actual = [].concat(x).toString();
expect = x.toString();
addThis();
status = inSection(5);
x = function() {return "Hello";};
actual = [].concat(x).toString();
expect = x.toString();
addThis();
status = inSection(6);
x = [function() {return "Hello";}];
actual = [].concat(x).toString();
expect = x.toString();
addThis();
status = inSection(7);
x = [1,2,3].concat([4,5,6]);
actual = [].concat(x).toString();
expect = x.toString();
addThis();
status = inSection(8);
x = eval('this');
actual = [].concat(x).toString();
expect = x.toString();
addThis();
/*
* The next two sections are by igor@icesoft.no; see
* http://bugzilla.mozilla.org/show_bug.cgi?id=169795#c3
*/
status = inSection(9);
x={length:0};
actual = [].concat(x).toString();
expect = x.toString();
addThis();
status = inSection(10);
x={length:2, 0:0, 1:1};
actual = [].concat(x).toString();
expect = x.toString();
addThis();
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function addThis()
{
statusitems[UBound] = status;
actualvalues[UBound] = actual;
expectedvalues[UBound] = expect;
UBound++;
}
function test()
{
enterFunc('test');
printBugNumber(bug);
printStatus(summary);
for (var i=0; i<UBound; i++)
{
reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]);
}
exitFunc ('test');
}
| gpl-2.0 |
kermit666/vlc | modules/stream_filter/dash/mpd/IsoffMainManager.cpp | 5222 | /*
* IsoffMainManager.cpp
*****************************************************************************
* Copyright (C) 2010 - 2012 Klagenfurt University
*
* Created on: Jan 27, 2010
* Authors: Christopher Mueller <christopher.mueller@itec.uni-klu.ac.at>
* Christian Timmerer <christian.timmerer@itec.uni-klu.ac.at>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "IsoffMainManager.h"
using namespace dash::mpd;
IsoffMainManager::IsoffMainManager (MPD *mpd)
{
this->mpd = mpd;
}
IsoffMainManager::~IsoffMainManager ()
{
delete this->mpd;
}
std::vector<Segment*> IsoffMainManager::getSegments (const Representation *rep)
{
std::vector<Segment *> retSegments;
SegmentList* list= rep->getSegmentList();
if(rep->getSegmentBase())
{
Segment* initSegment = rep->getSegmentBase()->getInitSegment();
if(initSegment)
retSegments.push_back(initSegment);
}
retSegments.insert(retSegments.end(), list->getSegments().begin(), list->getSegments().end());
return retSegments;
}
const std::vector<Period*>& IsoffMainManager::getPeriods () const
{
return this->mpd->getPeriods();
}
Representation* IsoffMainManager::getBestRepresentation (Period *period)
{
std::vector<AdaptationSet *> adaptationSets = period->getAdaptationSets();
int bitrate = 0;
Representation *best = NULL;
for(size_t i = 0; i < adaptationSets.size(); i++)
{
std::vector<Representation *> reps = adaptationSets.at(i)->getRepresentations();
for(size_t j = 0; j < reps.size(); j++)
{
int currentBitrate = reps.at(j)->getBandwidth();
if(currentBitrate > bitrate)
{
bitrate = currentBitrate;
best = reps.at(j);
}
}
}
return best;
}
Period* IsoffMainManager::getFirstPeriod ()
{
std::vector<Period *> periods = this->mpd->getPeriods();
if(periods.size() == 0)
return NULL;
return periods.at(0);
}
Representation* IsoffMainManager::getRepresentation (Period *period, uint64_t bitrate) const
{
if(period == NULL)
return NULL;
std::vector<AdaptationSet *> adaptationSets = period->getAdaptationSets();
Representation *best = NULL;
for(size_t i = 0; i < adaptationSets.size(); i++)
{
std::vector<Representation *> reps = adaptationSets.at(i)->getRepresentations();
for( size_t j = 0; j < reps.size(); j++ )
{
uint64_t currentBitrate = reps.at(j)->getBandwidth();
if(best == NULL || (currentBitrate > best->getBandwidth() && currentBitrate < bitrate))
{
best = reps.at( j );
}
}
}
return best;
}
Period* IsoffMainManager::getNextPeriod (Period *period)
{
std::vector<Period *> periods = this->mpd->getPeriods();
for(size_t i = 0; i < periods.size(); i++)
{
if(periods.at(i) == period && (i + 1) < periods.size())
return periods.at(i + 1);
}
return NULL;
}
const MPD* IsoffMainManager::getMPD () const
{
return this->mpd;
}
Representation* IsoffMainManager::getRepresentation (Period *period, uint64_t bitrate, int width, int height) const
{
if(period == NULL)
return NULL;
std::vector<AdaptationSet *> adaptationSets = period->getAdaptationSets();
std::vector<Representation *> resMatchReps;
for(size_t i = 0; i < adaptationSets.size(); i++)
{
std::vector<Representation *> reps = adaptationSets.at(i)->getRepresentations();
for( size_t j = 0; j < reps.size(); j++ )
{
if(reps.at(j)->getWidth() == width && reps.at(j)->getHeight() == height)
resMatchReps.push_back(reps.at(j));
}
}
if(resMatchReps.size() == 0)
return this->getRepresentation(period, bitrate);
Representation *best = NULL;
for( size_t j = 0; j < resMatchReps.size(); j++ )
{
uint64_t currentBitrate = resMatchReps.at(j)->getBandwidth();
if(best == NULL || (currentBitrate > best->getBandwidth() && currentBitrate < bitrate))
{
best = resMatchReps.at(j);
}
}
return best;
}
| gpl-2.0 |
iLoop2/openmrs-core | api/src/test/java/org/openmrs/validator/RoleValidatorTest.java | 5827 | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.validator;
import org.junit.Assert;
import org.junit.Test;
import org.openmrs.Role;
import org.openmrs.test.BaseContextSensitiveTest;
import org.openmrs.test.Verifies;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
/**
* Tests methods on the {@link RoleValidator} class.
*/
public class RoleValidatorTest extends BaseContextSensitiveTest {
/**
* @see RoleValidator#validate(Object,Errors)
*/
@Test
@Verifies(value = "should fail validation if role is null or empty or whitespace", method = "validate(Object,Errors)")
public void validate_shouldFailValidationIfRoleIsNullOrEmptyOrWhitespace() throws Exception {
Role role = new Role();
role.setRole(null);
role.setDescription("some text");
//TODO: change/fix this test when it is decided whether to change the validator behavior to avoid throwing an NPE
Errors errors = new BindException(role, "type");
//new RoleValidator().validate(role, errors);
//Assert.assertTrue(errors.hasFieldErrors("role"));
role.setRole("");
errors = new BindException(role, "role");
new RoleValidator().validate(role, errors);
Assert.assertTrue(errors.hasFieldErrors("role"));
role.setRole(" ");
errors = new BindException(role, "role");
new RoleValidator().validate(role, errors);
Assert.assertTrue(errors.hasFieldErrors("role"));
}
/**
* @see RoleValidator#validate(Object,Errors)
*/
@Test
@Verifies(value = "should pass validation if description is null or empty or whitespace", method = "validate(Object,Errors)")
public void validate_shouldPassValidationIfDescriptionIsNullOrEmptyOrWhitespace() throws Exception {
Role role = new Role();
role.setRole("Bowling race car driver");
role.setDescription(null);
Errors errors = new BindException(role, "type");
new RoleValidator().validate(role, errors);
Assert.assertFalse(errors.hasFieldErrors("description"));
role.setDescription("");
errors = new BindException(role, "role");
new RoleValidator().validate(role, errors);
Assert.assertFalse(errors.hasFieldErrors("description"));
role.setDescription(" ");
errors = new BindException(role, "role");
new RoleValidator().validate(role, errors);
Assert.assertFalse(errors.hasFieldErrors("description"));
}
/**
* @see RoleValidator#validate(Object,Errors)
*/
@Test
@Verifies(value = "should fail validation if role has leading or trailing space", method = "validate(Object,Errors)")
public void validate_shouldFailValidationIfRoleHasLeadingOrTrailingSpace() throws Exception {
Role role = new Role();
role.setDescription("some text");
role.setRole(" Bowling race car driver");
Errors errors = new BindException(role, "type");
new RoleValidator().validate(role, errors);
Assert.assertTrue(errors.hasFieldErrors("role"));
Assert.assertEquals("error.trailingSpaces", errors.getFieldError("role").getCode());
role.setRole("Bowling race car driver ");
errors = new BindException(role, "role");
new RoleValidator().validate(role, errors);
Assert.assertTrue(errors.hasFieldErrors("role"));
Assert.assertEquals("error.trailingSpaces", errors.getFieldError("role").getCode());
}
/**
* @see RoleValidator#validate(Object,Errors)
*/
@Test
@Verifies(value = "should pass validation if all required fields have proper values", method = "validate(Object,Errors)")
public void validate_shouldPassValidationIfAllRequiredFieldsHaveProperValues() throws Exception {
Role role = new Role();
role.setRole("Bowling race car driver");
role.setDescription("You don't bowl or race fast cars");
Errors errors = new BindException(role, "type");
new RoleValidator().validate(role, errors);
Assert.assertFalse(errors.hasErrors());
}
/**
* @see RoleValidator#validate(Object,Errors)
*/
@Test
@Verifies(value = "should pass validation if field lengths are correct", method = "validate(Object,Errors)")
public void validate_shouldPassValidationIfFieldLengthsAreCorrect() throws Exception {
Role role = new Role();
role.setRole("Bowling race car driver");
role.setDescription("description");
Errors errors = new BindException(role, "type");
new RoleValidator().validate(role, errors);
Assert.assertFalse(errors.hasErrors());
}
/**
* @see RoleValidator#validate(Object,Errors)
*/
@Test
@Verifies(value = "should fail validation if field lengths are not correct", method = "validate(Object,Errors)")
public void validate_shouldFailValidationIfFieldLengthsAreNotCorrect() throws Exception {
Role role = new Role();
role
.setRole("too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text");
role
.setDescription("too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text");
Errors errors = new BindException(role, "type");
new RoleValidator().validate(role, errors);
Assert.assertTrue(errors.hasFieldErrors("role"));
}
}
| mpl-2.0 |
danielcweber/roslyn | src/InteractiveWindow/EditorTest/InteractiveWindowEditorsFactoryService.cs | 2073 | // 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.ComponentModel.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests
{
[Export(typeof(IInteractiveWindowEditorFactoryService))]
internal class InteractiveWindowEditorsFactoryService : IInteractiveWindowEditorFactoryService
{
public const string ContentType = "text";
private readonly ITextBufferFactoryService _textBufferFactoryService;
private readonly ITextEditorFactoryService _textEditorFactoryService;
private readonly IContentTypeRegistryService _contentTypeRegistry;
[ImportingConstructor]
public InteractiveWindowEditorsFactoryService(ITextBufferFactoryService textBufferFactoryService, ITextEditorFactoryService textEditorFactoryService, IContentTypeRegistryService contentTypeRegistry)
{
_textBufferFactoryService = textBufferFactoryService;
_textEditorFactoryService = textEditorFactoryService;
_contentTypeRegistry = contentTypeRegistry;
}
IWpfTextView IInteractiveWindowEditorFactoryService.CreateTextView(IInteractiveWindow window, ITextBuffer buffer, ITextViewRoleSet roles)
{
var textView = _textEditorFactoryService.CreateTextView(buffer, roles);
return _textEditorFactoryService.CreateTextViewHost(textView, false).TextView;
}
ITextBuffer IInteractiveWindowEditorFactoryService.CreateAndActivateBuffer(IInteractiveWindow window)
{
IContentType contentType;
if (!window.Properties.TryGetProperty(typeof(IContentType), out contentType))
{
contentType = _contentTypeRegistry.GetContentType(ContentType);
}
return _textBufferFactoryService.CreateTextBuffer(contentType);
}
}
}
| apache-2.0 |
ahb0327/intellij-community | platform/platform-api/src/com/intellij/ui/AddEditRemovePanel.java | 6882 | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.ComponentWithEmptyText;
import com.intellij.util.ui.StatusText;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.List;
/**
* @author Konstantin Bulenkov
* @author mike
*/
@SuppressWarnings("unchecked")
public abstract class AddEditRemovePanel<T> extends PanelWithButtons implements ComponentWithEmptyText {
private JBTable myTable;
private TableModel myModel;
private List<T> myData;
private AbstractTableModel myTableModel;
private String myLabel;
public AddEditRemovePanel(TableModel<T> model, List<T> data) {
this(model, data, null);
}
public AddEditRemovePanel(TableModel<T> model, List<T> data, @Nullable String label) {
myModel = model;
myData = data;
myLabel = label;
initTable();
initPanel();
}
@Nullable
protected abstract T addItem();
protected abstract boolean removeItem(T o);
@Nullable
protected abstract T editItem(T o);
@Override
protected void initPanel() {
setLayout(new BorderLayout());
final JPanel panel = ToolbarDecorator.createDecorator(myTable)
.setAddAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
doAdd();
}
})
.setRemoveAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
doRemove();
}
})
.setEditAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
if (myTable.isEditing()) {
myTable.getCellEditor().stopCellEditing();
return;
}
doEdit();
}
})
.disableUpAction()
.disableDownAction()
.createPanel();
add(panel, BorderLayout.CENTER);
final String label = getLabelText();
if (label != null) {
UIUtil.addBorder(panel, IdeBorderFactory.createTitledBorder(label, false));
}
}
protected String getLabelText(){
return myLabel;
}
@NotNull
@Override
public StatusText getEmptyText() {
return myTable.getEmptyText();
}
protected JComponent createMainComponent(){
initTable();
return ScrollPaneFactory.createScrollPane(myTable);
}
private void initTable() {
myTableModel = new AbstractTableModel() {
public int getColumnCount(){
return myModel.getColumnCount();
}
public int getRowCount(){
return myData != null ? myData.size() : 0;
}
public Class getColumnClass(int columnIndex){
return myModel.getColumnClass(columnIndex);
}
public String getColumnName(int column){
return myModel.getColumnName(column);
}
public Object getValueAt(int rowIndex, int columnIndex){
return myModel.getField(myData.get(rowIndex), columnIndex);
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
myModel.setValue(aValue, myData.get(rowIndex), columnIndex);
fireTableRowsUpdated(rowIndex, rowIndex);
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return myModel.isEditable(columnIndex);
}
};
myTable = createTable();
myTable.setModel(myTableModel);
myTable.setShowColumns(false);
myTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
myTable.setStriped(true);
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent event) {
doEdit();
return true;
}
}.installOn(myTable);
}
protected JBTable createTable() {
return new JBTable();
}
protected JButton[] createButtons(){
return new JButton[0];
}
protected void doAdd() {
T o = addItem();
if (o == null) return;
myData.add(o);
int index = myData.size() - 1;
myTableModel.fireTableRowsInserted(index, index);
myTable.setRowSelectionInterval(index, index);
}
protected void doEdit() {
int selected = myTable.getSelectedRow();
if (selected >= 0) {
T o = editItem(myData.get(selected));
if (o != null) myData.set(selected, o);
myTableModel.fireTableRowsUpdated(selected, selected);
}
}
protected void doRemove() {
if (myTable.isEditing()) {
myTable.getCellEditor().stopCellEditing();
}
final int[] selected = myTable.getSelectedRows();
if (selected == null || selected.length == 0) return;
Arrays.sort(selected);
for (int i = selected.length - 1; i >= 0; i--) {
int idx = selected[i];
if (!removeItem(myData.get(idx))) continue;
myData.remove(idx);
}
myTableModel.fireTableDataChanged();
int selection = selected[0];
if (selection >= myData.size()) {
selection = myData.size() - 1;
}
if (selection >= 0) {
myTable.setRowSelectionInterval(selection, selection);
}
}
public void setData(List<T> data) {
myData = data;
myTableModel.fireTableDataChanged();
}
public List<T> getData() {
return myData;
}
public void setRenderer(int index, TableCellRenderer renderer) {
myTable.getColumn(myModel.getColumnName(index)).setCellRenderer(renderer);
}
public void setSelected(Object o) {
for(int i = 0; i < myTableModel.getRowCount(); ++i) {
if (myData.get(i).equals(o)) {
myTable.getSelectionModel().setSelectionInterval(i,i);
break;
}
}
}
public JBTable getTable() {
return myTable;
}
public abstract static class TableModel<T> {
public abstract int getColumnCount();
@Nullable
public abstract String getColumnName(int columnIndex);
public abstract Object getField(T o, int columnIndex);
public Class getColumnClass(int columnIndex) { return String.class; }
public boolean isEditable(int column) {return false; }
public void setValue(Object aValue, T data, int columnIndex) {}
}
}
| apache-2.0 |
rubenv/kubernetes | pkg/volume/nfs/nfs.go | 8702 | /*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nfs
import (
"fmt"
"os"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume"
"github.com/golang/glog"
)
// This is the primary entrypoint for volume plugins.
// Tests covering recycling should not use this func but instead
// use their own array of plugins w/ a custom recyclerFunc as appropriate
func ProbeVolumePlugins() []volume.VolumePlugin {
return []volume.VolumePlugin{&nfsPlugin{nil, newRecycler}}
}
type nfsPlugin struct {
host volume.VolumeHost
// decouple creating recyclers by deferring to a function. Allows for easier testing.
newRecyclerFunc func(spec *volume.Spec, host volume.VolumeHost) (volume.Recycler, error)
}
var _ volume.VolumePlugin = &nfsPlugin{}
var _ volume.PersistentVolumePlugin = &nfsPlugin{}
var _ volume.RecyclableVolumePlugin = &nfsPlugin{}
const (
nfsPluginName = "kubernetes.io/nfs"
)
func (plugin *nfsPlugin) Init(host volume.VolumeHost) {
plugin.host = host
}
func (plugin *nfsPlugin) Name() string {
return nfsPluginName
}
func (plugin *nfsPlugin) CanSupport(spec *volume.Spec) bool {
return spec.VolumeSource.NFS != nil || spec.PersistentVolumeSource.NFS != nil
}
func (plugin *nfsPlugin) GetAccessModes() []api.PersistentVolumeAccessMode {
return []api.PersistentVolumeAccessMode{
api.ReadWriteOnce,
api.ReadOnlyMany,
api.ReadWriteMany,
}
}
func (plugin *nfsPlugin) NewBuilder(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions, mounter mount.Interface) (volume.Builder, error) {
return plugin.newBuilderInternal(spec, pod, mounter)
}
func (plugin *nfsPlugin) newBuilderInternal(spec *volume.Spec, pod *api.Pod, mounter mount.Interface) (volume.Builder, error) {
var source *api.NFSVolumeSource
var readOnly bool
if spec.VolumeSource.NFS != nil {
source = spec.VolumeSource.NFS
readOnly = spec.VolumeSource.NFS.ReadOnly
} else {
source = spec.PersistentVolumeSource.NFS
readOnly = spec.ReadOnly
}
return &nfsBuilder{
nfs: &nfs{
volName: spec.Name,
mounter: mounter,
pod: pod,
plugin: plugin,
},
server: source.Server,
exportPath: source.Path,
readOnly: readOnly,
}, nil
}
func (plugin *nfsPlugin) NewCleaner(volName string, podUID types.UID, mounter mount.Interface) (volume.Cleaner, error) {
return plugin.newCleanerInternal(volName, podUID, mounter)
}
func (plugin *nfsPlugin) newCleanerInternal(volName string, podUID types.UID, mounter mount.Interface) (volume.Cleaner, error) {
return &nfsCleaner{&nfs{
volName: volName,
mounter: mounter,
pod: &api.Pod{ObjectMeta: api.ObjectMeta{UID: podUID}},
plugin: plugin,
}}, nil
}
func (plugin *nfsPlugin) NewRecycler(spec *volume.Spec) (volume.Recycler, error) {
return plugin.newRecyclerFunc(spec, plugin.host)
}
// NFS volumes represent a bare host file or directory mount of an NFS export.
type nfs struct {
volName string
pod *api.Pod
mounter mount.Interface
plugin *nfsPlugin
// decouple creating recyclers by deferring to a function. Allows for easier testing.
newRecyclerFunc func(spec *volume.Spec, host volume.VolumeHost) (volume.Recycler, error)
}
func (nfsVolume *nfs) GetPath() string {
name := nfsPluginName
return nfsVolume.plugin.host.GetPodVolumeDir(nfsVolume.pod.UID, util.EscapeQualifiedNameForDisk(name), nfsVolume.volName)
}
type nfsBuilder struct {
*nfs
server string
exportPath string
readOnly bool
}
var _ volume.Builder = &nfsBuilder{}
// SetUp attaches the disk and bind mounts to the volume path.
func (b *nfsBuilder) SetUp() error {
return b.SetUpAt(b.GetPath())
}
func (b *nfsBuilder) SetUpAt(dir string) error {
mountpoint, err := b.mounter.IsMountPoint(dir)
glog.V(4).Infof("NFS mount set up: %s %v %v", dir, mountpoint, err)
if err != nil && !os.IsNotExist(err) {
return err
}
if mountpoint {
return nil
}
os.MkdirAll(dir, 0750)
source := fmt.Sprintf("%s:%s", b.server, b.exportPath)
options := []string{}
if b.readOnly {
options = append(options, "ro")
}
err = b.mounter.Mount(source, dir, "nfs", options)
if err != nil {
mountpoint, mntErr := b.mounter.IsMountPoint(dir)
if mntErr != nil {
glog.Errorf("IsMountpoint check failed: %v", mntErr)
return err
}
if mountpoint {
if mntErr = b.mounter.Unmount(dir); mntErr != nil {
glog.Errorf("Failed to unmount: %v", mntErr)
return err
}
mountpoint, mntErr := b.mounter.IsMountPoint(dir)
if mntErr != nil {
glog.Errorf("IsMountpoint check failed: %v", mntErr)
return err
}
if mountpoint {
// This is very odd, we don't expect it. We'll try again next sync loop.
glog.Errorf("%s is still mounted, despite call to unmount(). Will try again next sync loop.", dir)
return err
}
}
os.Remove(dir)
return err
}
return nil
}
func (b *nfsBuilder) IsReadOnly() bool {
return b.readOnly
}
//
//func (c *nfsCleaner) GetPath() string {
// name := nfsPluginName
// return c.plugin.host.GetPodVolumeDir(c.pod.UID, util.EscapeQualifiedNameForDisk(name), c.volName)
//}
var _ volume.Cleaner = &nfsCleaner{}
type nfsCleaner struct {
*nfs
}
func (c *nfsCleaner) TearDown() error {
return c.TearDownAt(c.GetPath())
}
func (c *nfsCleaner) TearDownAt(dir string) error {
mountpoint, err := c.mounter.IsMountPoint(dir)
if err != nil {
glog.Errorf("Error checking IsMountPoint: %v", err)
return err
}
if !mountpoint {
return os.Remove(dir)
}
if err := c.mounter.Unmount(dir); err != nil {
glog.Errorf("Unmounting failed: %v", err)
return err
}
mountpoint, mntErr := c.mounter.IsMountPoint(dir)
if mntErr != nil {
glog.Errorf("IsMountpoint check failed: %v", mntErr)
return mntErr
}
if !mountpoint {
if err := os.Remove(dir); err != nil {
return err
}
}
return nil
}
func newRecycler(spec *volume.Spec, host volume.VolumeHost) (volume.Recycler, error) {
if spec.PersistentVolumeSource.NFS == nil {
return nil, fmt.Errorf("spec.PersistentVolumeSource.NFS is nil")
}
return &nfsRecycler{
name: spec.Name,
server: spec.PersistentVolumeSource.NFS.Server,
path: spec.PersistentVolumeSource.NFS.Path,
host: host,
}, nil
}
// nfsRecycler scrubs an NFS volume by running "rm -rf" on the volume in a pod.
type nfsRecycler struct {
name string
server string
path string
host volume.VolumeHost
}
func (r *nfsRecycler) GetPath() string {
return r.path
}
// Recycler provides methods to reclaim the volume resource.
// A NFS volume is recycled by scheduling a pod to run "rm -rf" on the contents of the volume.
// Recycle blocks until the pod has completed or any error occurs.
// The scrubber pod's is expected to succeed within 5 minutes else an error will be returned
func (r *nfsRecycler) Recycle() error {
timeout := int64(300) // 5 minutes
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
GenerateName: "pv-scrubber-" + util.ShortenString(r.name, 44) + "-",
Namespace: api.NamespaceDefault,
},
Spec: api.PodSpec{
ActiveDeadlineSeconds: &timeout,
RestartPolicy: api.RestartPolicyNever,
Volumes: []api.Volume{
{
Name: "vol",
VolumeSource: api.VolumeSource{
NFS: &api.NFSVolumeSource{
Server: r.server,
Path: r.path,
},
},
},
},
Containers: []api.Container{
{
Name: "scrubber",
Image: "gcr.io/google_containers/busybox",
// delete the contents of the volume, but not the directory itself
Command: []string{"/bin/sh"},
// the scrubber:
// 1. validates the /scrub directory exists
// 2. creates a text file to be scrubbed
// 3. performs rm -rf on the directory
// 4. tests to see if the directory is empty
// the pod fails if the error code is returned
Args: []string{"-c", "test -e /scrub && echo $(date) > /scrub/trash.txt && rm -rf /scrub/* && test -z \"$(ls -A /scrub)\" || exit 1"},
VolumeMounts: []api.VolumeMount{
{
Name: "vol",
MountPath: "/scrub",
},
},
},
},
},
}
return volume.ScrubPodVolumeAndWatchUntilCompletion(pod, r.host.GetKubeClient())
}
| apache-2.0 |
Kaenn/Ghost | core/client/app/components/gh-validation-status-container.js | 945 | import Ember from 'ember';
import ValidationStateMixin from 'ghost/mixins/validation-state';
const {Component, computed} = Ember;
/**
* Handles the CSS necessary to show a specific property state. When passed a
* DS.Errors object and a property name, if the DS.Errors object has errors for
* the specified property, it will change the CSS to reflect the error state
* @param {DS.Errors} errors The DS.Errors object
* @param {string} property Name of the property
*/
export default Component.extend(ValidationStateMixin, {
classNameBindings: ['errorClass'],
errorClass: computed('property', 'hasError', 'hasValidated.[]', function () {
let hasValidated = this.get('hasValidated');
let property = this.get('property');
if (hasValidated && hasValidated.contains(property)) {
return this.get('hasError') ? 'error' : 'success';
} else {
return '';
}
})
});
| mit |
iwdmb/cdnjs | ajax/libs/ag-grid/3.3.2/lib/headerRendering/headerTemplateLoader.js | 4339 | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v3.3.2
* @link http://www.ag-grid.com/
* @license MIT
*/
var utils_1 = require('../utils');
var svgFactory_1 = require("../svgFactory");
var svgFactory = svgFactory_1.default.getInstance();
var HeaderTemplateLoader = (function () {
function HeaderTemplateLoader() {
}
HeaderTemplateLoader.prototype.init = function (gridOptionsWrapper) {
this.gridOptionsWrapper = gridOptionsWrapper;
};
HeaderTemplateLoader.prototype.createHeaderElement = function (column) {
var params = {
column: column,
colDef: column.getColDef,
context: this.gridOptionsWrapper.getContext(),
api: this.gridOptionsWrapper.getApi()
};
// option 1 - see if user provided a template in colDef
var userProvidedTemplate = column.getColDef().headerCellTemplate;
if (typeof userProvidedTemplate === 'function') {
var colDefFunc = userProvidedTemplate;
userProvidedTemplate = colDefFunc(params);
}
// option 2 - check the gridOptions for cellTemplate
if (!userProvidedTemplate && this.gridOptionsWrapper.getHeaderCellTemplate()) {
userProvidedTemplate = this.gridOptionsWrapper.getHeaderCellTemplate();
}
// option 3 - check the gridOptions for templateFunction
if (!userProvidedTemplate && this.gridOptionsWrapper.getHeaderCellTemplateFunc()) {
var gridOptionsFunc = this.gridOptionsWrapper.getHeaderCellTemplateFunc();
userProvidedTemplate = gridOptionsFunc(params);
}
// finally, if still no template, use the default
if (!userProvidedTemplate) {
userProvidedTemplate = this.createDefaultHeaderElement(column);
}
// template can be a string or a dom element, if string we need to convert to a dom element
var result;
if (typeof userProvidedTemplate === 'string') {
result = utils_1.default.loadTemplate(userProvidedTemplate);
}
else if (utils_1.default.isNodeOrElement(userProvidedTemplate)) {
result = userProvidedTemplate;
}
else {
console.error('ag-Grid: header template must be a string or an HTML element');
}
return result;
};
HeaderTemplateLoader.prototype.createDefaultHeaderElement = function (column) {
var eTemplate = utils_1.default.loadTemplate(HeaderTemplateLoader.HEADER_CELL_TEMPLATE);
this.addInIcon(eTemplate, 'sortAscending', '#agSortAsc', column, svgFactory.createArrowUpSvg);
this.addInIcon(eTemplate, 'sortDescending', '#agSortDesc', column, svgFactory.createArrowDownSvg);
this.addInIcon(eTemplate, 'sortUnSort', '#agNoSort', column, svgFactory.createArrowUpDownSvg);
this.addInIcon(eTemplate, 'menu', '#agMenu', column, svgFactory.createMenuSvg);
this.addInIcon(eTemplate, 'filter', '#agFilter', column, svgFactory.createFilterSvg);
return eTemplate;
};
HeaderTemplateLoader.prototype.addInIcon = function (eTemplate, iconName, cssSelector, column, defaultIconFactory) {
var eIcon = utils_1.default.createIconNoSpan(iconName, this.gridOptionsWrapper, column, defaultIconFactory);
eTemplate.querySelector(cssSelector).appendChild(eIcon);
};
HeaderTemplateLoader.HEADER_CELL_TEMPLATE = '<div class="ag-header-cell">' +
' <div id="agResizeBar" class="ag-header-cell-resize"></div>' +
' <span id="agMenu" class="ag-header-icon ag-header-cell-menu-button"></span>' +
' <div id="agHeaderCellLabel" class="ag-header-cell-label">' +
' <span id="agSortAsc" class="ag-header-icon ag-sort-ascending-icon"></span>' +
' <span id="agSortDesc" class="ag-header-icon ag-sort-descending-icon"></span>' +
' <span id="agNoSort" class="ag-header-icon ag-sort-none-icon"></span>' +
' <span id="agFilter" class="ag-header-icon ag-filter-icon"></span>' +
' <span id="agText" class="ag-header-cell-text"></span>' +
' </div>' +
'</div>';
return HeaderTemplateLoader;
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = HeaderTemplateLoader;
| mit |
tid-kijyun/cocos2d-x-template | cocos/editor-support/cocosbuilder/CCLayerLoader.cpp | 1712 | #include "CCLayerLoader.h"
using namespace cocos2d;
#define PROPERTY_TOUCH_ENABLED "isTouchEnabled"
#define PROPERTY_ACCELEROMETER_ENABLED "isAccelerometerEnabled"
#define PROPERTY_MOUSE_ENABLED "isMouseEnabled"
#define PROPERTY_KEYBOARD_ENABLED "isKeyboardEnabled"
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (push)
#pragma warning (disable: 4996)
#endif
using namespace cocos2d;
namespace cocosbuilder {
void LayerLoader::onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_TOUCH_ENABLED) == 0) {
((Layer *)pNode)->setTouchEnabled(pCheck);
} else if(strcmp(pPropertyName, PROPERTY_ACCELEROMETER_ENABLED) == 0) {
((Layer *)pNode)->setAccelerometerEnabled(pCheck);
} else if(strcmp(pPropertyName, PROPERTY_MOUSE_ENABLED) == 0) {
// TODO XXX
CCLOG("The property '%s' is not supported!", PROPERTY_MOUSE_ENABLED);
} else if(strcmp(pPropertyName, PROPERTY_KEYBOARD_ENABLED) == 0) {
// TODO XXX
CCLOG("The property '%s' is not supported!", PROPERTY_KEYBOARD_ENABLED);
// This comes closest: ((Layer *)pNode)->setKeypadEnabled(pCheck);
} else {
NodeLoader::onHandlePropTypeCheck(pNode, pParent, pPropertyName, pCheck, ccbReader);
}
}
}
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (pop)
#endif
| mit |
Vrian7ipx/cascadadev | vendor/laravel/framework/src/Illuminate/Cache/CacheServiceProvider.php | 1175 | <?php namespace Illuminate\Cache;
use Illuminate\Support\ServiceProvider;
class CacheServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('cache', function($app)
{
return new CacheManager($app);
});
$this->app->bindShared('cache.store', function($app)
{
return $app['cache']->driver();
});
$this->app->bindShared('memcached.connector', function()
{
return new MemcachedConnector;
});
$this->registerCommands();
}
/**
* Register the cache related console commands.
*
* @return void
*/
public function registerCommands()
{
$this->app->bindShared('command.cache.clear', function($app)
{
return new Console\ClearCommand($app['cache'], $app['files']);
});
$this->commands('command.cache.clear');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('cache', 'cache.store', 'memcached.connector', 'command.cache.clear');
}
}
| mit |