code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/**
* Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.pinot.core.query.aggregation.function;
import com.linkedin.pinot.core.common.Block;
import com.linkedin.pinot.core.common.BlockDocIdIterator;
import com.linkedin.pinot.core.common.BlockSingleValIterator;
import com.linkedin.pinot.core.common.Constants;
public class MaxAggregationNoDictionaryFunction extends MaxAggregationFunction {
@Override
public Double aggregate(Block docIdSetBlock, Block[] block) {
double ret = Double.NEGATIVE_INFINITY;
double tmp = 0;
int docId = 0;
BlockDocIdIterator docIdIterator = docIdSetBlock.getBlockDocIdSet().iterator();
BlockSingleValIterator blockValIterator = (BlockSingleValIterator) block[0].getBlockValueSet().iterator();
while ((docId = docIdIterator.next()) != Constants.EOF) {
if (blockValIterator.skipTo(docId)) {
tmp = blockValIterator.nextDoubleVal();
if (tmp > ret) {
ret = tmp;
}
}
}
return ret;
}
@Override
public Double aggregate(Double mergedResult, int docId, Block[] block) {
BlockSingleValIterator blockValIterator = (BlockSingleValIterator) block[0].getBlockValueSet().iterator();
if (blockValIterator.skipTo(docId)) {
if (mergedResult == null) {
return blockValIterator.nextDoubleVal();
}
double tmp = blockValIterator.nextDoubleVal();
if (tmp > mergedResult) {
return tmp;
}
}
return mergedResult;
}
}
| pinotlytics/pinot | pinot-core/src/main/java/com/linkedin/pinot/core/query/aggregation/function/MaxAggregationNoDictionaryFunction.java | Java | apache-2.0 | 2,078 |
package services_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
slclientfakes "github.com/maximilien/softlayer-go/client/fakes"
softlayer "github.com/maximilien/softlayer-go/softlayer"
testhelpers "github.com/maximilien/softlayer-go/test_helpers"
)
var _ = Describe("SoftLayer_Network_Storage_Allowed_Host", func() {
var (
username, apiKey string
fakeClient *slclientfakes.FakeSoftLayerClient
networkStorageAllowedHostService softlayer.SoftLayer_Network_Storage_Allowed_Host_Service
err error
)
BeforeEach(func() {
username = os.Getenv("SL_USERNAME")
Expect(username).ToNot(Equal(""))
apiKey = os.Getenv("SL_API_KEY")
Expect(apiKey).ToNot(Equal(""))
fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey)
Expect(fakeClient).ToNot(BeNil())
networkStorageAllowedHostService, err = fakeClient.GetSoftLayer_Network_Storage_Allowed_Host_Service()
Expect(err).ToNot(HaveOccurred())
Expect(networkStorageAllowedHostService).ToNot(BeNil())
})
Context("#GetName", func() {
It("returns the name for the service", func() {
name := networkStorageAllowedHostService.GetName()
Expect(name).To(Equal("SoftLayer_Network_Storage_Allowed_Host"))
})
})
Context("#GetCredential", func() {
BeforeEach(func() {
fakeClient.FakeHttpClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Network_Storage_Allowed_Host_Service_getCredential.json")
Expect(err).ToNot(HaveOccurred())
})
It("return the credential with allowed host id", func() {
credential, err := networkStorageAllowedHostService.GetCredential(123456)
Expect(err).NotTo(HaveOccurred())
Expect(credential).ToNot(BeNil())
Expect(credential.Username).To(Equal("fake-username"))
Expect(credential.Password).To(Equal("fake-password"))
})
Context("when HTTP client returns error codes 40x or 50x", func() {
It("fails for error code 40x", func() {
errorCodes := []int{400, 401, 499}
for _, errorCode := range errorCodes {
fakeClient.FakeHttpClient.DoRawHttpRequestInt = errorCode
_, err := networkStorageAllowedHostService.GetCredential(123456)
Expect(err).To(HaveOccurred())
}
})
It("fails for error code 50x", func() {
errorCodes := []int{500, 501, 599}
for _, errorCode := range errorCodes {
fakeClient.FakeHttpClient.DoRawHttpRequestInt = errorCode
_, err := networkStorageAllowedHostService.GetCredential(123456)
Expect(err).To(HaveOccurred())
}
})
})
})
})
| mattcui/softlayer-go | services/softlayer_network_storage_allowed_host_test.go | GO | apache-2.0 | 2,568 |
/**
* 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 backtype.storm.generated;
public class NotAliveException extends Exception {
private static final long serialVersionUID = -6138719666490739879L;
}
| mycFelix/heron | storm-compatibility/src/java/backtype/storm/generated/NotAliveException.java | Java | apache-2.0 | 962 |
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* 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.vaadin.ui;
import java.util.Date;
import com.vaadin.data.Property;
import com.vaadin.server.PaintException;
import com.vaadin.server.PaintTarget;
import com.vaadin.shared.ui.datefield.PopupDateFieldState;
/**
* <p>
* A date entry component, which displays the actual date selector as a popup.
*
* </p>
*
* @see DateField
* @see InlineDateField
* @author Vaadin Ltd.
* @since 5.0
*/
public class PopupDateField extends DateField {
private String inputPrompt = null;
public PopupDateField() {
super();
}
public PopupDateField(Property dataSource) throws IllegalArgumentException {
super(dataSource);
}
public PopupDateField(String caption, Date value) {
super(caption, value);
}
public PopupDateField(String caption, Property dataSource) {
super(caption, dataSource);
}
public PopupDateField(String caption) {
super(caption);
}
@Override
public void paintContent(PaintTarget target) throws PaintException {
super.paintContent(target);
if (inputPrompt != null) {
target.addAttribute("prompt", inputPrompt);
}
}
/**
* Gets the current input prompt.
*
* @see #setInputPrompt(String)
* @return the current input prompt, or null if not enabled
*/
public String getInputPrompt() {
return inputPrompt;
}
/**
* Sets the input prompt - a textual prompt that is displayed when the field
* would otherwise be empty, to prompt the user for input.
*
* @param inputPrompt
*/
public void setInputPrompt(String inputPrompt) {
this.inputPrompt = inputPrompt;
markAsDirty();
}
@Override
protected PopupDateFieldState getState() {
return (PopupDateFieldState) super.getState();
}
@Override
protected PopupDateFieldState getState(boolean markAsDirty) {
return (PopupDateFieldState) super.getState(markAsDirty);
}
/**
* Checks whether the text field is enabled (default) or not.
*
* @see PopupDateField#setTextFieldEnabled(boolean);
*
* @return <b>true</b> if the text field is enabled, <b>false</b> otherwise.
*/
public boolean isTextFieldEnabled() {
return getState(false).textFieldEnabled;
}
/**
* Enables or disables the text field. By default the text field is enabled.
* Disabling it causes only the button for date selection to be active, thus
* preventing the user from entering invalid dates.
*
* See {@link http://dev.vaadin.com/ticket/6790}.
*
* @param state
* <b>true</b> to enable text field, <b>false</b> to disable it.
*/
public void setTextFieldEnabled(boolean state) {
getState().textFieldEnabled = state;
}
/**
* Set a description that explains the usage of the Widget for users of
* assistive devices.
*
* @param description
* String with the description
*/
public void setAssistiveText(String description) {
getState().descriptionForAssistiveDevices = description;
}
/**
* Get the description that explains the usage of the Widget for users of
* assistive devices.
*
* @return String with the description
*/
public String getAssistiveText() {
return getState(false).descriptionForAssistiveDevices;
}
}
| jdahlstrom/vaadin.react | server/src/main/java/com/vaadin/ui/PopupDateField.java | Java | apache-2.0 | 4,052 |
'''This module implements specialized container datatypes providing
alternatives to Python's general purpose built-in containers, dict,
list, set, and tuple.
* namedtuple factory function for creating tuple subclasses with named fields
* deque list-like container with fast appends and pops on either end
* ChainMap dict-like class for creating a single view of multiple mappings
* Counter dict subclass for counting hashable objects
* OrderedDict dict subclass that remembers the order entries were added
* defaultdict dict subclass that calls a factory function to supply missing values
* UserDict wrapper around dictionary objects for easier dict subclassing
* UserList wrapper around list objects for easier list subclassing
* UserString wrapper around string objects for easier string subclassing
'''
__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
'UserString', 'Counter', 'OrderedDict', 'ChainMap']
import _collections_abc
from operator import itemgetter as _itemgetter, eq as _eq
from keyword import iskeyword as _iskeyword
import sys as _sys
import heapq as _heapq
from _weakref import proxy as _proxy
from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
from reprlib import recursive_repr as _recursive_repr
try:
from _collections import deque
except ImportError:
pass
else:
_collections_abc.MutableSequence.register(deque)
try:
from _collections import defaultdict
except ImportError:
pass
def __getattr__(name):
# For backwards compatibility, continue to make the collections ABCs
# through Python 3.6 available through the collections module.
# Note, no new collections ABCs were added in Python 3.7
if name in _collections_abc.__all__:
obj = getattr(_collections_abc, name)
import warnings
warnings.warn("Using or importing the ABCs from 'collections' instead "
"of from 'collections.abc' is deprecated, "
"and in 3.8 it will stop working",
DeprecationWarning, stacklevel=2)
globals()[name] = obj
return obj
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
################################################################################
### OrderedDict
################################################################################
class _OrderedDictKeysView(_collections_abc.KeysView):
def __reversed__(self):
yield from reversed(self._mapping)
class _OrderedDictItemsView(_collections_abc.ItemsView):
def __reversed__(self):
for key in reversed(self._mapping):
yield (key, self._mapping[key])
class _OrderedDictValuesView(_collections_abc.ValuesView):
def __reversed__(self):
for key in reversed(self._mapping):
yield self._mapping[key]
class _Link(object):
__slots__ = 'prev', 'next', 'key', '__weakref__'
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.
# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# The sentinel is in self.__hardroot with a weakref proxy in self.__root.
# The prev links are weakref proxies (to prevent circular references).
# Individual links are kept alive by the hard reference in self.__map.
# Those hard references disappear when a key is deleted from an OrderedDict.
def __init__(*args, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries. Keyword argument order is preserved.
'''
if not args:
raise TypeError("descriptor '__init__' of 'OrderedDict' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__hardroot = _Link()
self.__root = root = _proxy(self.__hardroot)
root.prev = root.next = root
self.__map = {}
self.__update(*args, **kwds)
def __setitem__(self, key, value,
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
self.__map[key] = link = Link()
root = self.__root
last = root.prev
link.prev, link.next, link.key = last, root, key
last.next = link
root.prev = proxy(link)
dict_setitem(self, key, value)
def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link = self.__map.pop(key)
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev
link.prev = None
link.next = None
def __iter__(self):
'od.__iter__() <==> iter(od)'
# Traverse the linked list in order.
root = self.__root
curr = root.next
while curr is not root:
yield curr.key
curr = curr.next
def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
# Traverse the linked list in reverse order.
root = self.__root
curr = root.prev
while curr is not root:
yield curr.key
curr = curr.prev
def clear(self):
'od.clear() -> None. Remove all items from od.'
root = self.__root
root.prev = root.next = root
self.__map.clear()
dict.clear(self)
def popitem(self, last=True):
'''Remove and return a (key, value) pair from the dictionary.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root.prev
link_prev = link.prev
link_prev.next = root
root.prev = link_prev
else:
link = root.next
link_next = link.next
root.next = link_next
link_next.prev = root
key = link.key
del self.__map[key]
value = dict.pop(self, key)
return key, value
def move_to_end(self, key, last=True):
'''Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist.
'''
link = self.__map[key]
link_prev = link.prev
link_next = link.next
soft_link = link_next.prev
link_prev.next = link_next
link_next.prev = link_prev
root = self.__root
if last:
last = root.prev
link.prev = last
link.next = root
root.prev = soft_link
last.next = link
else:
first = root.next
link.prev = root
link.next = first
first.prev = soft_link
root.next = link
def __sizeof__(self):
sizeof = _sys.getsizeof
n = len(self) + 1 # number of links including root
size = sizeof(self.__dict__) # instance dictionary
size += sizeof(self.__map) * 2 # internal dict and inherited dict
size += sizeof(self.__hardroot) * n # link objects
size += sizeof(self.__root) * n # proxy objects
return size
update = __update = _collections_abc.MutableMapping.update
def keys(self):
"D.keys() -> a set-like object providing a view on D's keys"
return _OrderedDictKeysView(self)
def items(self):
"D.items() -> a set-like object providing a view on D's items"
return _OrderedDictItemsView(self)
def values(self):
"D.values() -> an object providing a view on D's values"
return _OrderedDictValuesView(self)
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError
is raised.
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default
def setdefault(self, key, default=None):
'''Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
'''
if key in self:
return self[key]
self[key] = default
return default
@_recursive_repr()
def __repr__(self):
'od.__repr__() <==> repr(od)'
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self.items()))
def __reduce__(self):
'Return state information for pickling'
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
return self.__class__, (), inst_dict or None, None, iter(self.items())
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
'''Create a new ordered dictionary with keys from iterable and values set to value.
'''
self = cls()
for key in iterable:
self[key] = value
return self
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return dict.__eq__(self, other) and all(map(_eq, self, other))
return dict.__eq__(self, other)
try:
from _collections import OrderedDict
except ImportError:
# Leave the pure Python version in place.
pass
################################################################################
### namedtuple
################################################################################
_nt_itemgetters = {}
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
# Validate the field names. At the user's option, either generate an error
# message or automatically replace the field name with a valid name.
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = _sys.intern(str(typename))
if rename:
seen = set()
for index, name in enumerate(field_names):
if (not name.isidentifier()
or _iskeyword(name)
or name.startswith('_')
or name in seen):
field_names[index] = f'_{index}'
seen.add(name)
for name in [typename] + field_names:
if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
f'identifiers: {name!r}')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
f'keyword: {name!r}')
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
f'{name!r}')
if name in seen:
raise ValueError(f'Encountered duplicate field name: {name!r}')
seen.add(name)
field_defaults = {}
if defaults is not None:
defaults = tuple(defaults)
if len(defaults) > len(field_names):
raise TypeError('Got more default values than field names')
field_defaults = dict(reversed(list(zip(reversed(field_names),
reversed(defaults)))))
# Variables used in the methods and docstrings
field_names = tuple(map(_sys.intern, field_names))
num_fields = len(field_names)
arg_list = repr(field_names).replace("'", "")[1:-1]
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
tuple_new = tuple.__new__
_len = len
# Create all the named tuple methods to be added to the class namespace
s = f'def __new__(_cls, {arg_list}): return _tuple_new(_cls, ({arg_list}))'
namespace = {'_tuple_new': tuple_new, '__name__': f'namedtuple_{typename}'}
# Note: exec() has the side-effect of interning the field names
exec(s, namespace)
__new__ = namespace['__new__']
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
@classmethod
def _make(cls, iterable):
result = tuple_new(cls, iterable)
if _len(result) != num_fields:
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
return result
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
'or iterable')
def _replace(_self, **kwds):
result = _self._make(map(kwds.pop, field_names, _self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
return result
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
'fields with new values')
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values.'
return OrderedDict(zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
# Modify function metadata to help with introspection and debugging
for method in (__new__, _make.__func__, _replace,
__repr__, _asdict, __getnewargs__):
method.__qualname__ = f'{typename}.{method.__name__}'
# Build-up the class namespace dictionary
# and use type() to build the result class
class_namespace = {
'__doc__': f'{typename}({arg_list})',
'__slots__': (),
'_fields': field_names,
'_fields_defaults': field_defaults,
'__new__': __new__,
'_make': _make,
'_replace': _replace,
'__repr__': __repr__,
'_asdict': _asdict,
'__getnewargs__': __getnewargs__,
}
cache = _nt_itemgetters
for index, name in enumerate(field_names):
try:
itemgetter_object, doc = cache[index]
except KeyError:
itemgetter_object = _itemgetter(index)
doc = f'Alias for field number {index}'
cache[index] = itemgetter_object, doc
class_namespace[name] = property(itemgetter_object, doc=doc)
result = type(typename, (tuple,), class_namespace)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython), or where the user has
# specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
return result
########################################################################
### Counter
########################################################################
def _count_elements(mapping, iterable):
'Tally elements from the iterable.'
mapping_get = mapping.get
for elem in iterable:
mapping[elem] = mapping_get(elem, 0) + 1
try: # Load C helper function if available
from _collections import _count_elements
except ImportError:
pass
class Counter(dict):
'''Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
>>> c.most_common(3) # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c) # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements())) # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values()) # total of all counts
15
>>> c['a'] # count of letter 'a'
5
>>> for elem in 'shazam': # update counts from an iterable
... c[elem] += 1 # by adding 1 to each element's count
>>> c['a'] # now there are seven 'a'
7
>>> del c['b'] # remove all 'b'
>>> c['b'] # now there are zero 'b'
0
>>> d = Counter('simsalabim') # make another counter
>>> c.update(d) # add in the second counter
>>> c['a'] # now there are nine 'a'
9
>>> c.clear() # empty the counter
>>> c
Counter()
Note: If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:
>>> c = Counter('aaabbc')
>>> c['b'] -= 2 # reduce the count of 'b' by two
>>> c.most_common() # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]
'''
# References:
# http://en.wikipedia.org/wiki/Multiset
# http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
# http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
# http://code.activestate.com/recipes/259174/
# Knuth, TAOCP Vol. II section 4.6.3
def __init__(*args, **kwds):
'''Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
'''
if not args:
raise TypeError("descriptor '__init__' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
super(Counter, self).__init__()
self.update(*args, **kwds)
def __missing__(self, key):
'The count of elements not in the Counter is zero.'
# Needed so that self[missing_item] does not raise KeyError
return 0
def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
def elements(self):
'''Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
>>> product = 1
>>> for factor in prime_factors.elements(): # loop over factors
... product *= factor # and multiply them
>>> product
1836
Note, if an element's count has been set to zero or is a negative
number, elements() will ignore it.
'''
# Emulate Bag.do from Smalltalk and Multiset.begin from C++.
return _chain.from_iterable(_starmap(_repeat, self.items()))
# Override dict methods where necessary
@classmethod
def fromkeys(cls, iterable, v=None):
# There is no equivalent method for counters because setting v=1
# means that no element can have a count greater than one.
raise NotImplementedError(
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
def update(*args, **kwds):
'''Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d) # add elements from another counter
>>> c['h'] # four 'h' in which, witch, and watch
4
'''
# The regular dict.update() operation makes no sense here because the
# replace behavior results in the some of original untouched counts
# being mixed-in with all of the other counts for a mismash that
# doesn't have a straight-forward interpretation in most counting
# contexts. Instead, we implement straight-addition. Both the inputs
# and outputs are allowed to contain zero and negative counts.
if not args:
raise TypeError("descriptor 'update' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
iterable = args[0] if args else None
if iterable is not None:
if isinstance(iterable, _collections_abc.Mapping):
if self:
self_get = self.get
for elem, count in iterable.items():
self[elem] = count + self_get(elem, 0)
else:
super(Counter, self).update(iterable) # fast path when counter is empty
else:
_count_elements(self, iterable)
if kwds:
self.update(kwds)
def subtract(*args, **kwds):
'''Like dict.update() but subtracts counts instead of replacing them.
Counts can be reduced below zero. Both the inputs and outputs are
allowed to contain zero and negative counts.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.subtract('witch') # subtract elements from another iterable
>>> c.subtract(Counter('watch')) # subtract elements from another counter
>>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
-1
'''
if not args:
raise TypeError("descriptor 'subtract' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
iterable = args[0] if args else None
if iterable is not None:
self_get = self.get
if isinstance(iterable, _collections_abc.Mapping):
for elem, count in iterable.items():
self[elem] = self_get(elem, 0) - count
else:
for elem in iterable:
self[elem] = self_get(elem, 0) - 1
if kwds:
self.subtract(kwds)
def copy(self):
'Return a shallow copy.'
return self.__class__(self)
def __reduce__(self):
return self.__class__, (dict(self),)
def __delitem__(self, elem):
'Like dict.__delitem__() but does not raise KeyError for missing values.'
if elem in self:
super().__delitem__(elem)
def __repr__(self):
if not self:
return '%s()' % self.__class__.__name__
try:
items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
return '%s({%s})' % (self.__class__.__name__, items)
except TypeError:
# handle case where values are not orderable
return '{0}({1!r})'.format(self.__class__.__name__, dict(self))
# Multiset-style mathematical operations discussed in:
# Knuth TAOCP Volume II section 4.6.3 exercise 19
# and at http://en.wikipedia.org/wiki/Multiset
#
# Outputs guaranteed to only include positive counts.
#
# To strip negative and zero counts, add-in an empty counter:
# c += Counter()
def __add__(self, other):
'''Add counts from two counters.
>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count + other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
def __sub__(self, other):
''' Subtract count, but keep only results with positive counts.
>>> Counter('abbbc') - Counter('bccd')
Counter({'b': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count - other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count < 0:
result[elem] = 0 - count
return result
def __or__(self, other):
'''Union is the maximum of value in either of the input counters.
>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = other_count if count < other_count else count
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
def __and__(self, other):
''' Intersection is the minimum of corresponding counts.
>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = count if count < other_count else other_count
if newcount > 0:
result[elem] = newcount
return result
def __pos__(self):
'Adds an empty counter, effectively stripping negative and zero counts'
result = Counter()
for elem, count in self.items():
if count > 0:
result[elem] = count
return result
def __neg__(self):
'''Subtracts from an empty counter. Strips positive and zero counts,
and flips the sign on negative counts.
'''
result = Counter()
for elem, count in self.items():
if count < 0:
result[elem] = 0 - count
return result
def _keep_positive(self):
'''Internal method to strip elements with a negative or zero count'''
nonpositive = [elem for elem, count in self.items() if not count > 0]
for elem in nonpositive:
del self[elem]
return self
def __iadd__(self, other):
'''Inplace add from another counter, keeping only positive counts.
>>> c = Counter('abbb')
>>> c += Counter('bcc')
>>> c
Counter({'b': 4, 'c': 2, 'a': 1})
'''
for elem, count in other.items():
self[elem] += count
return self._keep_positive()
def __isub__(self, other):
'''Inplace subtract counter, but keep only results with positive counts.
>>> c = Counter('abbbc')
>>> c -= Counter('bccd')
>>> c
Counter({'b': 2, 'a': 1})
'''
for elem, count in other.items():
self[elem] -= count
return self._keep_positive()
def __ior__(self, other):
'''Inplace union is the maximum of value from either counter.
>>> c = Counter('abbb')
>>> c |= Counter('bcc')
>>> c
Counter({'b': 3, 'c': 2, 'a': 1})
'''
for elem, other_count in other.items():
count = self[elem]
if other_count > count:
self[elem] = other_count
return self._keep_positive()
def __iand__(self, other):
'''Inplace intersection is the minimum of corresponding counts.
>>> c = Counter('abbb')
>>> c &= Counter('bcc')
>>> c
Counter({'b': 1})
'''
for elem, count in self.items():
other_count = other[elem]
if other_count < count:
self[elem] = other_count
return self._keep_positive()
########################################################################
### ChainMap
########################################################################
class ChainMap(_collections_abc.MutableMapping):
''' A ChainMap groups multiple dicts (or other mappings) together
to create a single, updateable view.
The underlying mappings are stored in a list. That list is public and can
be accessed or updated using the *maps* attribute. There is no other
state.
Lookups search the underlying mappings successively until a key is found.
In contrast, writes, updates, and deletions only operate on the first
mapping.
'''
def __init__(self, *maps):
'''Initialize a ChainMap by setting *maps* to the given mappings.
If no mappings are provided, a single empty dictionary is used.
'''
self.maps = list(maps) or [{}] # always at least one map
def __missing__(self, key):
raise KeyError(key)
def __getitem__(self, key):
for mapping in self.maps:
try:
return mapping[key] # can't use 'key in mapping' with defaultdict
except KeyError:
pass
return self.__missing__(key) # support subclasses that define __missing__
def get(self, key, default=None):
return self[key] if key in self else default
def __len__(self):
return len(set().union(*self.maps)) # reuses stored hash values if possible
def __iter__(self):
d = {}
for mapping in reversed(self.maps):
d.update(mapping) # reuses stored hash values if possible
return iter(d)
def __contains__(self, key):
return any(key in m for m in self.maps)
def __bool__(self):
return any(self.maps)
@_recursive_repr()
def __repr__(self):
return '{0.__class__.__name__}({1})'.format(
self, ', '.join(map(repr, self.maps)))
@classmethod
def fromkeys(cls, iterable, *args):
'Create a ChainMap with a single dict created from the iterable.'
return cls(dict.fromkeys(iterable, *args))
def copy(self):
'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
return self.__class__(self.maps[0].copy(), *self.maps[1:])
__copy__ = copy
def new_child(self, m=None): # like Django's Context.push()
'''New ChainMap with a new map followed by all previous maps.
If no map is provided, an empty dict is used.
'''
if m is None:
m = {}
return self.__class__(m, *self.maps)
@property
def parents(self): # like Django's Context.pop()
'New ChainMap from maps[1:].'
return self.__class__(*self.maps[1:])
def __setitem__(self, key, value):
self.maps[0][key] = value
def __delitem__(self, key):
try:
del self.maps[0][key]
except KeyError:
raise KeyError('Key not found in the first mapping: {!r}'.format(key))
def popitem(self):
'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
try:
return self.maps[0].popitem()
except KeyError:
raise KeyError('No keys found in the first mapping.')
def pop(self, key, *args):
'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
try:
return self.maps[0].pop(key, *args)
except KeyError:
raise KeyError('Key not found in the first mapping: {!r}'.format(key))
def clear(self):
'Clear maps[0], leaving maps[1:] intact.'
self.maps[0].clear()
################################################################################
### UserDict
################################################################################
class UserDict(_collections_abc.MutableMapping):
# Start by filling-out the abstract methods
def __init__(*args, **kwargs):
if not args:
raise TypeError("descriptor '__init__' of 'UserDict' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
if args:
dict = args[0]
elif 'dict' in kwargs:
dict = kwargs.pop('dict')
import warnings
warnings.warn("Passing 'dict' as keyword argument is deprecated",
DeprecationWarning, stacklevel=2)
else:
dict = None
self.data = {}
if dict is not None:
self.update(dict)
if len(kwargs):
self.update(kwargs)
def __len__(self): return len(self.data)
def __getitem__(self, key):
if key in self.data:
return self.data[key]
if hasattr(self.__class__, "__missing__"):
return self.__class__.__missing__(self, key)
raise KeyError(key)
def __setitem__(self, key, item): self.data[key] = item
def __delitem__(self, key): del self.data[key]
def __iter__(self):
return iter(self.data)
# Modify __contains__ to work correctly when __missing__ is present
def __contains__(self, key):
return key in self.data
# Now, add the methods in dicts but not in MutableMapping
def __repr__(self): return repr(self.data)
def copy(self):
if self.__class__ is UserDict:
return UserDict(self.data.copy())
import copy
data = self.data
try:
self.data = {}
c = copy.copy(self)
finally:
self.data = data
c.update(self)
return c
@classmethod
def fromkeys(cls, iterable, value=None):
d = cls()
for key in iterable:
d[key] = value
return d
################################################################################
### UserList
################################################################################
class UserList(_collections_abc.MutableSequence):
"""A more or less complete user-defined wrapper around list objects."""
def __init__(self, initlist=None):
self.data = []
if initlist is not None:
# XXX should this accept an arbitrary sequence?
if type(initlist) == type(self.data):
self.data[:] = initlist
elif isinstance(initlist, UserList):
self.data[:] = initlist.data[:]
else:
self.data = list(initlist)
def __repr__(self): return repr(self.data)
def __lt__(self, other): return self.data < self.__cast(other)
def __le__(self, other): return self.data <= self.__cast(other)
def __eq__(self, other): return self.data == self.__cast(other)
def __gt__(self, other): return self.data > self.__cast(other)
def __ge__(self, other): return self.data >= self.__cast(other)
def __cast(self, other):
return other.data if isinstance(other, UserList) else other
def __contains__(self, item): return item in self.data
def __len__(self): return len(self.data)
def __getitem__(self, i): return self.data[i]
def __setitem__(self, i, item): self.data[i] = item
def __delitem__(self, i): del self.data[i]
def __add__(self, other):
if isinstance(other, UserList):
return self.__class__(self.data + other.data)
elif isinstance(other, type(self.data)):
return self.__class__(self.data + other)
return self.__class__(self.data + list(other))
def __radd__(self, other):
if isinstance(other, UserList):
return self.__class__(other.data + self.data)
elif isinstance(other, type(self.data)):
return self.__class__(other + self.data)
return self.__class__(list(other) + self.data)
def __iadd__(self, other):
if isinstance(other, UserList):
self.data += other.data
elif isinstance(other, type(self.data)):
self.data += other
else:
self.data += list(other)
return self
def __mul__(self, n):
return self.__class__(self.data*n)
__rmul__ = __mul__
def __imul__(self, n):
self.data *= n
return self
def append(self, item): self.data.append(item)
def insert(self, i, item): self.data.insert(i, item)
def pop(self, i=-1): return self.data.pop(i)
def remove(self, item): self.data.remove(item)
def clear(self): self.data.clear()
def copy(self): return self.__class__(self)
def count(self, item): return self.data.count(item)
def index(self, item, *args): return self.data.index(item, *args)
def reverse(self): self.data.reverse()
def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
def extend(self, other):
if isinstance(other, UserList):
self.data.extend(other.data)
else:
self.data.extend(other)
################################################################################
### UserString
################################################################################
class UserString(_collections_abc.Sequence):
def __init__(self, seq):
if isinstance(seq, str):
self.data = seq
elif isinstance(seq, UserString):
self.data = seq.data[:]
else:
self.data = str(seq)
def __str__(self): return str(self.data)
def __repr__(self): return repr(self.data)
def __int__(self): return int(self.data)
def __float__(self): return float(self.data)
def __complex__(self): return complex(self.data)
def __hash__(self): return hash(self.data)
def __getnewargs__(self):
return (self.data[:],)
def __eq__(self, string):
if isinstance(string, UserString):
return self.data == string.data
return self.data == string
def __lt__(self, string):
if isinstance(string, UserString):
return self.data < string.data
return self.data < string
def __le__(self, string):
if isinstance(string, UserString):
return self.data <= string.data
return self.data <= string
def __gt__(self, string):
if isinstance(string, UserString):
return self.data > string.data
return self.data > string
def __ge__(self, string):
if isinstance(string, UserString):
return self.data >= string.data
return self.data >= string
def __contains__(self, char):
if isinstance(char, UserString):
char = char.data
return char in self.data
def __len__(self): return len(self.data)
def __getitem__(self, index): return self.__class__(self.data[index])
def __add__(self, other):
if isinstance(other, UserString):
return self.__class__(self.data + other.data)
elif isinstance(other, str):
return self.__class__(self.data + other)
return self.__class__(self.data + str(other))
def __radd__(self, other):
if isinstance(other, str):
return self.__class__(other + self.data)
return self.__class__(str(other) + self.data)
def __mul__(self, n):
return self.__class__(self.data*n)
__rmul__ = __mul__
def __mod__(self, args):
return self.__class__(self.data % args)
def __rmod__(self, format):
return self.__class__(format % args)
# the following methods are defined in alphabetical order:
def capitalize(self): return self.__class__(self.data.capitalize())
def casefold(self):
return self.__class__(self.data.casefold())
def center(self, width, *args):
return self.__class__(self.data.center(width, *args))
def count(self, sub, start=0, end=_sys.maxsize):
if isinstance(sub, UserString):
sub = sub.data
return self.data.count(sub, start, end)
def encode(self, encoding=None, errors=None): # XXX improve this?
if encoding:
if errors:
return self.__class__(self.data.encode(encoding, errors))
return self.__class__(self.data.encode(encoding))
return self.__class__(self.data.encode())
def endswith(self, suffix, start=0, end=_sys.maxsize):
return self.data.endswith(suffix, start, end)
def expandtabs(self, tabsize=8):
return self.__class__(self.data.expandtabs(tabsize))
def find(self, sub, start=0, end=_sys.maxsize):
if isinstance(sub, UserString):
sub = sub.data
return self.data.find(sub, start, end)
def format(self, *args, **kwds):
return self.data.format(*args, **kwds)
def format_map(self, mapping):
return self.data.format_map(mapping)
def index(self, sub, start=0, end=_sys.maxsize):
return self.data.index(sub, start, end)
def isalpha(self): return self.data.isalpha()
def isalnum(self): return self.data.isalnum()
def isascii(self): return self.data.isascii()
def isdecimal(self): return self.data.isdecimal()
def isdigit(self): return self.data.isdigit()
def isidentifier(self): return self.data.isidentifier()
def islower(self): return self.data.islower()
def isnumeric(self): return self.data.isnumeric()
def isprintable(self): return self.data.isprintable()
def isspace(self): return self.data.isspace()
def istitle(self): return self.data.istitle()
def isupper(self): return self.data.isupper()
def join(self, seq): return self.data.join(seq)
def ljust(self, width, *args):
return self.__class__(self.data.ljust(width, *args))
def lower(self): return self.__class__(self.data.lower())
def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
maketrans = str.maketrans
def partition(self, sep):
return self.data.partition(sep)
def replace(self, old, new, maxsplit=-1):
if isinstance(old, UserString):
old = old.data
if isinstance(new, UserString):
new = new.data
return self.__class__(self.data.replace(old, new, maxsplit))
def rfind(self, sub, start=0, end=_sys.maxsize):
if isinstance(sub, UserString):
sub = sub.data
return self.data.rfind(sub, start, end)
def rindex(self, sub, start=0, end=_sys.maxsize):
return self.data.rindex(sub, start, end)
def rjust(self, width, *args):
return self.__class__(self.data.rjust(width, *args))
def rpartition(self, sep):
return self.data.rpartition(sep)
def rstrip(self, chars=None):
return self.__class__(self.data.rstrip(chars))
def split(self, sep=None, maxsplit=-1):
return self.data.split(sep, maxsplit)
def rsplit(self, sep=None, maxsplit=-1):
return self.data.rsplit(sep, maxsplit)
def splitlines(self, keepends=False): return self.data.splitlines(keepends)
def startswith(self, prefix, start=0, end=_sys.maxsize):
return self.data.startswith(prefix, start, end)
def strip(self, chars=None): return self.__class__(self.data.strip(chars))
def swapcase(self): return self.__class__(self.data.swapcase())
def title(self): return self.__class__(self.data.title())
def translate(self, *args):
return self.__class__(self.data.translate(*args))
def upper(self): return self.__class__(self.data.upper())
def zfill(self, width): return self.__class__(self.data.zfill(width))
| mdanielwork/intellij-community | python/testData/MockSdk3.7/Lib/collections/__init__.py | Python | apache-2.0 | 47,640 |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"k8s.io/client-go/1.4/pkg/api/unversioned"
"k8s.io/client-go/1.4/pkg/api/v1"
"k8s.io/client-go/1.4/pkg/util/intstr"
)
// PodDisruptionBudgetSpec is a description of a PodDisruptionBudget.
type PodDisruptionBudgetSpec struct {
// The minimum number of pods that must be available simultaneously. This
// can be either an integer or a string specifying a percentage, e.g. "28%".
MinAvailable intstr.IntOrString `json:"minAvailable,omitempty" protobuf:"bytes,1,opt,name=minAvailable"`
// Label query over pods whose evictions are managed by the disruption
// budget.
Selector *unversioned.LabelSelector `json:"selector,omitempty" protobuf:"bytes,2,opt,name=selector"`
}
// PodDisruptionBudgetStatus represents information about the status of a
// PodDisruptionBudget. Status may trail the actual state of a system.
type PodDisruptionBudgetStatus struct {
// Whether or not a disruption is currently allowed.
PodDisruptionAllowed bool `json:"disruptionAllowed" protobuf:"varint,1,opt,name=disruptionAllowed"`
// current number of healthy pods
CurrentHealthy int32 `json:"currentHealthy" protobuf:"varint,2,opt,name=currentHealthy"`
// minimum desired number of healthy pods
DesiredHealthy int32 `json:"desiredHealthy" protobuf:"varint,3,opt,name=desiredHealthy"`
// total number of pods counted by this disruption budget
ExpectedPods int32 `json:"expectedPods" protobuf:"varint,4,opt,name=expectedPods"`
}
// +genclient=true
// +noMethods=true
// PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods
type PodDisruptionBudget struct {
unversioned.TypeMeta `json:",inline"`
v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Specification of the desired behavior of the PodDisruptionBudget.
Spec PodDisruptionBudgetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
// Most recently observed status of the PodDisruptionBudget.
Status PodDisruptionBudgetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}
// PodDisruptionBudgetList is a collection of PodDisruptionBudgets.
type PodDisruptionBudgetList struct {
unversioned.TypeMeta `json:",inline"`
unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
Items []PodDisruptionBudget `json:"items" protobuf:"bytes,2,rep,name=items"`
}
| matthewdupre/kubernetes | staging/src/k8s.io/client-go/1.4/pkg/apis/policy/v1alpha1/types.go | GO | apache-2.0 | 2,978 |
// Copyright 2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Test that getters can be defined and called with an index as a parameter.
var o = {};
o.x = 42;
o.__defineGetter__('0', function() { return o.x; });
assertEquals(o.x, o[0]);
assertEquals(o.x, o.__lookupGetter__('0')());
o.__defineSetter__('0', function(y) { o.x = y; });
assertEquals(o.x, o[0]);
assertEquals(o.x, o.__lookupGetter__('0')());
o[0] = 21;
assertEquals(21, o.x);
o.__lookupSetter__(0)(7);
assertEquals(7, o.x);
function Pair(x, y) {
this.x = x;
this.y = y;
};
Pair.prototype.__defineGetter__('0', function() { return this.x; });
Pair.prototype.__defineGetter__('1', function() { return this.y; });
Pair.prototype.__defineSetter__('0', function(x) { this.x = x; });
Pair.prototype.__defineSetter__('1', function(y) { this.y = y; });
var p = new Pair(2, 3);
assertEquals(2, p[0]);
assertEquals(3, p[1]);
p.x = 7;
p[1] = 8;
assertEquals(7, p[0]);
assertEquals(7, p.x);
assertEquals(8, p[1]);
assertEquals(8, p.y);
// Testing that a defined getter doesn't get lost due to inline caching.
var expected = {};
var actual = {};
for (var i = 0; i < 10; i++) {
expected[i] = actual[i] = i;
}
function testArray() {
for (var i = 0; i < 10; i++) {
assertEquals(expected[i], actual[i]);
}
}
actual[1000000] = -1;
testArray();
testArray();
actual.__defineGetter__('0', function() { return expected[0]; });
expected[0] = 42;
testArray();
expected[0] = 111;
testArray();
// Using a setter where only a getter is defined does not throw an exception,
// unless we are in strict mode.
var q = {};
q.__defineGetter__('0', function() { return 42; });
assertDoesNotThrow('q[0] = 7');
// Using a getter where only a setter is defined returns undefined.
var q1 = {};
q1.__defineSetter__('0', function() {q1.b = 17;});
assertEquals(q1[0], undefined);
// Setter works
q1[0] = 3;
assertEquals(q1[0], undefined);
assertEquals(q1.b, 17);
// Complex case of using an undefined getter.
// From http://code.google.com/p/v8/issues/detail?id=298
// Reported by nth10sd.
a = function() {};
this.__defineSetter__("0", function() {});
if (a |= '') {};
assertThrows('this[a].__parent__');
assertEquals(a, 0);
assertEquals(this[a], undefined);
| zero-rp/miniblink49 | v8_7_5/test/mjsunit/indexed-accessors.js | JavaScript | apache-2.0 | 3,743 |
/**
* An assortment of Windows Store app-related tools.
*
* @module winstore
*
* @copyright
* Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved.
*
* @license
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
const
appc = require('node-appc'),
async = require('async'),
fs = require('fs'),
magik = require('./utilities').magik,
path = require('path'),
visualstudio = require('./visualstudio'),
__ = appc.i18n(__dirname).__;
var architectures = [ 'arm', 'x86', 'x64' ];
var detectCache,
deviceCache = {};
exports.install = install;
exports.launch = launch;
exports.uninstall = uninstall;
exports.detect = detect;
/**
* Installs a Windows Store application.
*
* @param {Object} [options] - An object containing various settings.
* @param {String} [options.buildConfiguration='Release'] - The type of configuration to build using. Example: "Release" or "Debug".
* @param {Function} [callback(err)] - A function to call after installing the Windows Store app.
*
* @emits module:winstore#error
* @emits module:winstore#installed
*
* @returns {EventEmitter}
*/
function install(projectDir, options, callback) {
return magik(options, callback, function (emitter, options, callback) {
var scripts = [],
packageScript = 'Add-AppDevPackage.ps1';
// find the Add-AppDevPackage.ps1
(function walk(dir) {
fs.readdirSync(dir).forEach(function (name) {
var file = path.join(dir, name);
if (fs.statSync(file).isDirectory()) {
walk(file);
} else if (name === packageScript && (!options.buildConfiguration || path.basename(dir).indexOf('_' + options.buildConfiguration) !== -1)) {
scripts.push(file);
}
});
}(projectDir));
if (!scripts.length) {
var err = new Error(__('Unable to find built application. Please rebuild the project.'));
emitter.emit('error', err);
return callback(err);
}
// let's grab the first match
appc.subprocess.getRealName(scripts[0], function (err, psScript) {
if (err) {
emitter.emit('error', err);
return callback(err);
}
appc.subprocess.run(options.powershell || 'powershell', ['-ExecutionPolicy', 'Bypass', '-NoLogo', '-NoProfile', '-File', psScript, '-Force'], function (code, out, err) {
if (!code) {
emitter.emit('installed');
return callback();
}
// I'm seeing "Please run this script without the -Force parameter" for Win 8.1 store apps.
// This originally was "Please rerun the script without the -Force parameter" (for Win 8 hybrid apps?)
// It's a hack to check for the common substring. Hopefully use of the exact error codes works better first
// Error codes 9 and 14 mean rerun without -Force
if ((code && (code == 9 || code == 14)) ||
out.indexOf('script without the -Force parameter') !== -1) {
appc.subprocess.run(options.powershell || 'powershell', ['-ExecutionPolicy', 'Bypass', '-NoLogo', '-NoProfile', '-File', psScript], function (code, out, err) {
if (err) {
emitter.emit('error', err);
callback(err);
} else {
emitter.emit('installed');
callback();
}
});
return;
}
// must have been some other issue, error out
var ex = new Error(__('Failed to install app: %s', out));
emitter.emit('error', ex);
callback(ex);
});
});
});
}
/**
* Uninstalls a Windows Store application.
*
* @param {String} appId - The application id.
* @param {Object} [options] - An object containing various settings.
* @param {String} [options.powershell='powershell'] - Path to the 'powershell' executable.
* @param {Function} [callback(err)] - A function to call after uninstalling the Windows Store app.
*
* @emits module:winstore#error
* @emits module:winstore#uninstalled
*
* @returns {EventEmitter}
*/
function uninstall(appId, options, callback) {
return magik(options, callback, function (emitter, options, callback) {
appc.subprocess.run(options.powershell || 'powershell', ['-command', 'Get-AppxPackage'], function (code, out, err) {
if (code) {
var ex = new Error(__('Could not query the list of installed Windows Store apps: %s', err || code));
emitter.emit('error', ex);
return callback(ex);
}
var packageNameRegExp = new RegExp('PackageFullName[\\s]*:[\\s]*(' + appId + '.*)'),
packageName;
out.split(/\r\n|\n/).some(function (line) {
var m = line.trim().match(packageNameRegExp);
if (m) {
packageName = m[1];
return true;
}
});
if (packageName) {
appc.subprocess.run(options.powershell || 'powershell', ['-command', 'Remove-AppxPackage', packageName], function (code, out, err) {
if (err) {
emitter.emit('error', err);
callback(err);
} else {
emitter.emit('uninstalled');
callback();
}
});
} else {
emitter.emit('uninstalled');
callback();
}
});
});
}
/**
* Launches a Windows Store application.
*
* @param {String} appId - The application id.
* @param {String} version - The application version.
* @param {Object} [options] - An object containing various settings.
* @param {String} [options.powershell='powershell'] - Path to the 'powershell' executable.
* @param {String} [options.version] - The specific version of the app to launch. If empty, picks the largest version.
* @param {Function} [callback(err)] - A function to call after uninstalling the Windows Store app.
*
* @emits module:winstore#error
* @emits module:winstore#launched
*
* @returns {EventEmitter}
*/
function launch(appId, options, callback) {
return magik(options, callback, function (emitter, options, callback) {
var wstool = path.resolve(__dirname, '..', 'bin', 'wstool.exe');
function runTool() {
var args = ['launch', appId];
options.version && args.push(options.version);
appc.subprocess.run(wstool, args, function (code, out, err) {
if (code) {
var ex = new Error(__('Erroring running wstool (code %s)', code) + '\n' + out);
emitter.emit('error', ex);
callback(ex);
} else {
emitter.emit('installed');
callback();
}
});
}
if (fs.existsSync(wstool)) {
runTool();
} else {
visualstudio.build(appc.util.mix({
buildConfiguration: 'Release',
project: path.resolve(__dirname, '..', 'wstool', 'wstool.csproj')
}, options), function (err, result) {
if (err) {
emitter.emit('error', err);
return callback(err);
}
var src = path.resolve(__dirname, '..', 'wstool', 'bin', 'Release', 'wstool.exe');
if (!fs.existsSync(src)) {
var ex = new Error(__('Failed to build the wstool executable.') + (result ? '\n' + result.out : ''));
emitter.emit('error', ex);
return callback(ex);
}
// sanity check that the wstool.exe wasn't copied by another async task in windowslib
if (!fs.existsSync(wstool)) {
fs.writeFileSync(wstool, fs.readFileSync(src));
}
runTool();
});
}
});
}
/**
* Detects Windows Store SDKs.
*
* @param {Object} [options] - An object containing various settings.
* @param {Boolean} [options.bypassCache=false] - When true, re-detects the Windows SDKs.
* @param {String} [options.preferredWindowsSDK] - The preferred version of the Windows SDK to use by default. Example "8.0".
* @param {String} [options.supportedWindowsSDKVersions] - A string with a version number or range to check if a Windows SDK is supported.
* @param {Function} [callback(err, results)] - A function to call with the Windows SDK information.
*
* @emits module:windowsphone#detected
* @emits module:windowsphone#error
*
* @returns {EventEmitter}
*/
function detect(options, callback) {
return magik(options, callback, function (emitter, options, callback) {
if (detectCache && !options.bypassCache) {
emitter.emit('detected', detectCache);
return callback(null, detectCache);
}
var results = {
windows: {},
issues: []
},
searchPaths = [
'HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Microsoft SDKs\\Windows', // probably nothing here
'HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Microsoft\\Microsoft SDKs\\Windows' // this is most likely where Windows SDK will be found
];
function finalize() {
detectCache = results;
emitter.emit('detected', results);
callback(null, results);
}
async.each(searchPaths, function (keyPath, next) {
appc.subprocess.run('reg', ['query', keyPath], function (code, out, err) {
var keyRegExp = /.+\\(v\d+\.\d)$/;
if (!code) {
out.trim().split(/\r\n|\n/).forEach(function (key) {
key = key.trim();
var m = key.match(keyRegExp);
if (!m) {
return;
}
var version = m[1].replace(/^v/, '');
if (m) {
results.windows || (results.windows = {});
results.windows[version] = {
version: version,
registryKey: keyPath + '\\' + m[1],
supported: !options.supportedWindowsSDKVersions || appc.version.satisfies(version, options.supportedWindowsSDKVersions, false), // no maybes
path: null,
signTool: null,
makeCert: null,
pvk2pfx: null,
selected: false
};
}
});
}
next();
});
}, function () {
// check if we didn't find any Windows SDKs, then we're done
if (!Object.keys(results.windows).length) {
results.issues.push({
id: 'WINDOWS_STORE_SDK_NOT_INSTALLED',
type: 'error',
message: __('Microsoft Windows Store SDK not found.') + '\n' +
__('You will be unable to build Windows Store apps.')
});
return finalize();
}
// fetch Windows SDK install information
async.each(Object.keys(results.windows), function (ver, next) {
appc.subprocess.run('reg', ['query', results.windows[ver].registryKey, '/v', '*'], function (code, out, err) {
if (code) {
// bad key? either way, remove this version
delete results.windows[ver];
} else {
// get only the values we are interested in
out.trim().split(/\r\n|\n/).forEach(function (line) {
var parts = line.trim().split(' ').map(function (p) { return p.trim(); });
if (parts.length == 3) {
if (parts[0] == 'InstallationFolder') {
results.windows[ver].path = parts[2];
function addIfExists(key, exe) {
for (var i = 0; i < architectures.length; i++) {
var arch = architectures[i],
tool = path.join(parts[2], 'bin', arch, exe);
if (fs.existsSync(tool)) {
!results.windows[ver][key] && (results.windows[ver][key] = {});
results.windows[ver][key][arch] = tool;
}
}
}
addIfExists('signTool', 'SignTool.exe');
addIfExists('makeCert', 'MakeCert.exe');
addIfExists('pvk2pfx', 'pvk2pfx.exe');
}
}
});
}
next();
});
}, function () {
// double check if we didn't find any Windows SDKs, then we're done
if (Object.keys(results.windows).every(function (v) { return !results.windows[v].path; })) {
results.issues.push({
id: 'WINDOWS_STORE_SDK_NOT_INSTALLED',
type: 'error',
message: __('Microsoft Windows Store SDK not found.') + '\n' +
__('You will be unable to build Windows Store apps.')
});
return finalize();
}
if (Object.keys(results.windows).every(function (v) { return !results.windows[v].deployCmd; })) {
results.issues.push({
id: 'WINDOWS_STORE_SDK_MISSING_DEPLOY_CMD',
type: 'error',
message: __('Microsoft Windows Store SDK is missing the deploy command.') + '\n' +
__('You will be unable to build Windows Store apps.')
});
return finalize();
}
var preferred = options.preferred;
if (!results.windows[preferred] || !results.windows[preferred].supported) {
preferred = Object.keys(results.windows).filter(function (v) { return results.windows[v].supported; }).sort().pop();
}
if (preferred) {
results.windows[preferred].selected = true;
}
finalize();
});
});
});
} | prop/titanium_mobile | node_modules/windowslib/lib/winstore.js | JavaScript | apache-2.0 | 12,463 |
/**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kns.web.taglib.html;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.taglib.html.TextareaTag;
import org.kuali.rice.kns.util.WebUtils;
import org.kuali.rice.kns.web.struts.form.pojo.PojoForm;
import javax.servlet.jsp.JspException;
/**
* This is a description of what this class does - bhargavp don't forget to fill this in.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*
* @deprecated KNS Struts deprecated, use KRAD and the Spring MVC framework.
*/
@Deprecated
public class KNSTextareaTag extends TextareaTag {
/**
* @see org.apache.struts.taglib.html.BaseInputTag#doEndTag()
*/
@Override
public int doEndTag() throws JspException {
int returnVal = super.doEndTag();
if (!getDisabled() && !getReadonly()) {
String name = prepareName();
if (StringUtils.isNotBlank(name)) {
ActionForm form = WebUtils.getKualiForm(pageContext);
if(form!=null && form instanceof PojoForm) {
((PojoForm) form).registerEditableProperty(name);
}
}
}
return returnVal;
}
}
| bhutchinson/rice | rice-middleware/kns/src/main/java/org/kuali/rice/kns/web/taglib/html/KNSTextareaTag.java | Java | apache-2.0 | 1,855 |
// Copyright 2013 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/sync_file_system/drive_backend/metadata_database.h"
#include "base/bind.h"
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/thread_task_runner_handle.h"
#include "chrome/browser/sync_file_system/drive_backend/drive_backend_constants.h"
#include "chrome/browser/sync_file_system/drive_backend/drive_backend_test_util.h"
#include "chrome/browser/sync_file_system/drive_backend/drive_backend_util.h"
#include "chrome/browser/sync_file_system/drive_backend/leveldb_wrapper.h"
#include "chrome/browser/sync_file_system/drive_backend/metadata_database.pb.h"
#include "chrome/browser/sync_file_system/drive_backend/metadata_database_index.h"
#include "chrome/browser/sync_file_system/drive_backend/metadata_database_index_interface.h"
#include "chrome/browser/sync_file_system/drive_backend/metadata_database_index_on_disk.h"
#include "chrome/browser/sync_file_system/sync_file_system_test_util.h"
#include "google_apis/drive/drive_api_parser.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/leveldatabase/src/helpers/memenv/memenv.h"
#include "third_party/leveldatabase/src/include/leveldb/db.h"
#include "third_party/leveldatabase/src/include/leveldb/env.h"
#include "third_party/leveldatabase/src/include/leveldb/write_batch.h"
#define FPL(a) FILE_PATH_LITERAL(a)
namespace sync_file_system {
namespace drive_backend {
namespace {
typedef MetadataDatabase::FileIDList FileIDList;
const int64 kInitialChangeID = 1234;
const int64 kSyncRootTrackerID = 100;
const char kSyncRootFolderID[] = "sync_root_folder_id";
// This struct is used to setup initial state of the database in the test and
// also used to match to the modified content of the database as the
// expectation.
struct TrackedFile {
// Holds the latest remote metadata which may be not-yet-synced to |tracker|.
FileMetadata metadata;
FileTracker tracker;
// Implies the file should not in the database.
bool should_be_absent;
// Implies the file should have a tracker in the database but should have no
// metadata.
bool tracker_only;
TrackedFile() : should_be_absent(false), tracker_only(false) {}
};
void ExpectEquivalentServiceMetadata(
const MetadataDatabaseIndexInterface* left,
const MetadataDatabaseIndexInterface* right) {
EXPECT_EQ(left->GetLargestChangeID(), right->GetLargestChangeID());
EXPECT_EQ(left->GetSyncRootTrackerID(), right->GetSyncRootTrackerID());
EXPECT_EQ(left->GetNextTrackerID(), right->GetNextTrackerID());
}
void ExpectEquivalent(const FileMetadata* left, const FileMetadata* right) {
if (!left) {
ASSERT_FALSE(right);
return;
}
ASSERT_TRUE(right);
test_util::ExpectEquivalentMetadata(*left, *right);
}
void ExpectEquivalent(const FileTracker* left, const FileTracker* right) {
if (!left) {
ASSERT_FALSE(right);
return;
}
ASSERT_TRUE(right);
test_util::ExpectEquivalentTrackers(*left, *right);
}
void ExpectEquivalent(int64 left, int64 right) {
EXPECT_EQ(left, right);
}
template <typename Container>
void ExpectEquivalentMaps(const Container& left, const Container& right);
template <typename Key, typename Value>
void ExpectEquivalent(const std::map<Key, Value>& left,
const std::map<Key, Value>& right) {
ExpectEquivalentMaps(left, right);
}
template <typename Key, typename Value>
void ExpectEquivalent(const base::hash_map<Key, Value>& left,
const base::hash_map<Key, Value>& right) {
ExpectEquivalentMaps(std::map<Key, Value>(left.begin(), left.end()),
std::map<Key, Value>(right.begin(), right.end()));
}
template <typename Key, typename Value>
void ExpectEquivalent(const base::ScopedPtrHashMap<Key, Value>& left,
const base::ScopedPtrHashMap<Key, Value>& right) {
ExpectEquivalentMaps(std::map<Key, Value*>(left.begin(), left.end()),
std::map<Key, Value*>(right.begin(), right.end()));
}
template <typename Container>
void ExpectEquivalentSets(const Container& left, const Container& right);
template <typename Value, typename Comparator>
void ExpectEquivalent(const std::set<Value, Comparator>& left,
const std::set<Value, Comparator>& right) {
return ExpectEquivalentSets(left, right);
}
template <typename Value>
void ExpectEquivalent(const base::hash_set<Value>& left,
const base::hash_set<Value>& right) {
return ExpectEquivalentSets(std::set<Value>(left.begin(), left.end()),
std::set<Value>(right.begin(), right.end()));
}
void ExpectEquivalent(const TrackerIDSet& left,
const TrackerIDSet& right) {
{
SCOPED_TRACE("Expect equivalent active_tracker");
EXPECT_EQ(left.active_tracker(), right.active_tracker());
}
ExpectEquivalent(left.tracker_set(), right.tracker_set());
}
template <typename Container>
void ExpectEquivalentMaps(const Container& left, const Container& right) {
ASSERT_EQ(left.size(), right.size());
typedef typename Container::const_iterator const_iterator;
const_iterator left_itr = left.begin();
const_iterator right_itr = right.begin();
while (left_itr != left.end()) {
EXPECT_EQ(left_itr->first, right_itr->first);
ExpectEquivalent(left_itr->second, right_itr->second);
++left_itr;
++right_itr;
}
}
template <typename Container>
void ExpectEquivalentSets(const Container& left, const Container& right) {
ASSERT_EQ(left.size(), right.size());
typedef typename Container::const_iterator const_iterator;
const_iterator left_itr = left.begin();
const_iterator right_itr = right.begin();
while (left_itr != left.end()) {
ExpectEquivalent(*left_itr, *right_itr);
++left_itr;
++right_itr;
}
}
base::FilePath CreateNormalizedPath(const base::FilePath::StringType& path) {
return base::FilePath(path).NormalizePathSeparators();
}
} // namespace
class MetadataDatabaseTest : public testing::TestWithParam<bool> {
public:
MetadataDatabaseTest()
: current_change_id_(kInitialChangeID),
next_tracker_id_(kSyncRootTrackerID + 1),
next_file_id_number_(1),
next_md5_sequence_number_(1) {}
virtual ~MetadataDatabaseTest() {}
void SetUp() override {
ASSERT_TRUE(database_dir_.CreateUniqueTempDir());
in_memory_env_.reset(leveldb::NewMemEnv(leveldb::Env::Default()));
}
void TearDown() override { DropDatabase(); }
protected:
std::string GenerateFileID() {
return "file_id_" + base::Int64ToString(next_file_id_number_++);
}
int64 GetTrackerIDByFileID(const std::string& file_id) {
TrackerIDSet trackers;
if (metadata_database_->FindTrackersByFileID(file_id, &trackers)) {
EXPECT_FALSE(trackers.empty());
return *trackers.begin();
}
return 0;
}
SyncStatusCode InitializeMetadataDatabase() {
SyncStatusCode status = SYNC_STATUS_UNKNOWN;
metadata_database_ = MetadataDatabase::CreateInternal(
database_dir_.path(), in_memory_env_.get(),
GetParam(), &status);
return status;
}
void DropDatabase() {
metadata_database_.reset();
message_loop_.RunUntilIdle();
}
void SetUpDatabaseByTrackedFiles(const TrackedFile** tracked_files,
int size) {
scoped_ptr<LevelDBWrapper> db = InitializeLevelDB();
ASSERT_TRUE(db);
for (int i = 0; i < size; ++i) {
const TrackedFile* file = tracked_files[i];
if (file->should_be_absent)
continue;
if (!file->tracker_only)
EXPECT_TRUE(PutFileToDB(db.get(), file->metadata).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), file->tracker).ok());
}
}
void VerifyTrackedFile(const TrackedFile& file) {
if (!file.should_be_absent) {
if (file.tracker_only) {
EXPECT_FALSE(metadata_database()->FindFileByFileID(
file.metadata.file_id(), nullptr));
} else {
VerifyFile(file.metadata);
}
VerifyTracker(file.tracker);
return;
}
EXPECT_FALSE(metadata_database()->FindFileByFileID(
file.metadata.file_id(), nullptr));
EXPECT_FALSE(metadata_database()->FindTrackerByTrackerID(
file.tracker.tracker_id(), nullptr));
}
void VerifyTrackedFiles(const TrackedFile** tracked_files, int size) {
for (int i = 0; i < size; ++i)
VerifyTrackedFile(*tracked_files[i]);
}
MetadataDatabase* metadata_database() { return metadata_database_.get(); }
scoped_ptr<LevelDBWrapper> InitializeLevelDB() {
leveldb::DB* db = nullptr;
leveldb::Options options;
options.create_if_missing = true;
options.max_open_files = 0; // Use minimum.
options.env = in_memory_env_.get();
leveldb::Status status =
leveldb::DB::Open(options, database_dir_.path().AsUTF8Unsafe(), &db);
EXPECT_TRUE(status.ok());
scoped_ptr<LevelDBWrapper> wrapper(new LevelDBWrapper(make_scoped_ptr(db)));
wrapper->Put(kDatabaseVersionKey, base::Int64ToString(3));
SetUpServiceMetadata(wrapper.get());
return wrapper.Pass();
}
void SetUpServiceMetadata(LevelDBWrapper* db) {
ServiceMetadata service_metadata;
service_metadata.set_largest_change_id(kInitialChangeID);
service_metadata.set_sync_root_tracker_id(kSyncRootTrackerID);
service_metadata.set_next_tracker_id(next_tracker_id_);
PutServiceMetadataToDB(service_metadata, db);
EXPECT_TRUE(db->Commit().ok());
}
FileMetadata CreateSyncRootMetadata() {
FileMetadata sync_root;
sync_root.set_file_id(kSyncRootFolderID);
FileDetails* details = sync_root.mutable_details();
details->set_title(kSyncRootFolderTitle);
details->set_file_kind(FILE_KIND_FOLDER);
details->set_change_id(current_change_id_);
return sync_root;
}
FileMetadata CreateFileMetadata(const FileMetadata& parent,
const std::string& title) {
FileMetadata file;
file.set_file_id(GenerateFileID());
FileDetails* details = file.mutable_details();
details->add_parent_folder_ids(parent.file_id());
details->set_title(title);
details->set_file_kind(FILE_KIND_FILE);
details->set_md5(
"md5_value_" + base::Int64ToString(next_md5_sequence_number_++));
details->set_change_id(current_change_id_);
return file;
}
FileMetadata CreateFolderMetadata(const FileMetadata& parent,
const std::string& title) {
FileMetadata folder;
folder.set_file_id(GenerateFileID());
FileDetails* details = folder.mutable_details();
details->add_parent_folder_ids(parent.file_id());
details->set_title(title);
details->set_file_kind(FILE_KIND_FOLDER);
details->set_change_id(current_change_id_);
return folder;
}
FileTracker CreateSyncRootTracker(const FileMetadata& sync_root) {
FileTracker sync_root_tracker;
sync_root_tracker.set_tracker_id(kSyncRootTrackerID);
sync_root_tracker.set_parent_tracker_id(0);
sync_root_tracker.set_file_id(sync_root.file_id());
sync_root_tracker.set_dirty(false);
sync_root_tracker.set_active(true);
sync_root_tracker.set_needs_folder_listing(false);
*sync_root_tracker.mutable_synced_details() = sync_root.details();
return sync_root_tracker;
}
FileTracker CreateTracker(const FileTracker& parent_tracker,
const FileMetadata& file) {
FileTracker tracker;
tracker.set_tracker_id(next_tracker_id_++);
tracker.set_parent_tracker_id(parent_tracker.tracker_id());
tracker.set_file_id(file.file_id());
tracker.set_app_id(parent_tracker.app_id());
tracker.set_tracker_kind(TRACKER_KIND_REGULAR);
tracker.set_dirty(false);
tracker.set_active(true);
tracker.set_needs_folder_listing(false);
*tracker.mutable_synced_details() = file.details();
return tracker;
}
TrackedFile CreateTrackedSyncRoot() {
TrackedFile sync_root;
sync_root.metadata = CreateSyncRootMetadata();
sync_root.tracker = CreateSyncRootTracker(sync_root.metadata);
return sync_root;
}
TrackedFile CreateTrackedAppRoot(const TrackedFile& sync_root,
const std::string& app_id) {
TrackedFile app_root(CreateTrackedFolder(sync_root, app_id));
app_root.tracker.set_app_id(app_id);
app_root.tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT);
return app_root;
}
TrackedFile CreateTrackedFile(const TrackedFile& parent,
const std::string& title) {
TrackedFile file;
file.metadata = CreateFileMetadata(parent.metadata, title);
file.tracker = CreateTracker(parent.tracker, file.metadata);
return file;
}
TrackedFile CreateTrackedFolder(const TrackedFile& parent,
const std::string& title) {
TrackedFile folder;
folder.metadata = CreateFolderMetadata(parent.metadata, title);
folder.tracker = CreateTracker(parent.tracker, folder.metadata);
return folder;
}
scoped_ptr<google_apis::FileResource> CreateFileResourceFromMetadata(
const FileMetadata& file) {
scoped_ptr<google_apis::FileResource> file_resource(
new google_apis::FileResource);
for (int i = 0; i < file.details().parent_folder_ids_size(); ++i) {
google_apis::ParentReference parent;
parent.set_file_id(file.details().parent_folder_ids(i));
file_resource->mutable_parents()->push_back(parent);
}
file_resource->set_file_id(file.file_id());
file_resource->set_title(file.details().title());
if (file.details().file_kind() == FILE_KIND_FOLDER) {
file_resource->set_mime_type("application/vnd.google-apps.folder");
} else if (file.details().file_kind() == FILE_KIND_FILE) {
file_resource->set_mime_type("text/plain");
file_resource->set_file_size(0);
} else {
file_resource->set_mime_type("application/vnd.google-apps.document");
}
file_resource->set_md5_checksum(file.details().md5());
file_resource->set_etag(file.details().etag());
file_resource->set_created_date(base::Time::FromInternalValue(
file.details().creation_time()));
file_resource->set_modified_date(base::Time::FromInternalValue(
file.details().modification_time()));
return file_resource.Pass();
}
scoped_ptr<google_apis::ChangeResource> CreateChangeResourceFromMetadata(
const FileMetadata& file) {
scoped_ptr<google_apis::ChangeResource> change(
new google_apis::ChangeResource);
change->set_change_id(file.details().change_id());
change->set_file_id(file.file_id());
change->set_deleted(file.details().missing());
if (change->is_deleted())
return change.Pass();
change->set_file(CreateFileResourceFromMetadata(file));
return change.Pass();
}
void ApplyRenameChangeToMetadata(const std::string& new_title,
FileMetadata* file) {
FileDetails* details = file->mutable_details();
details->set_title(new_title);
details->set_change_id(++current_change_id_);
}
void ApplyReorganizeChangeToMetadata(const std::string& new_parent,
FileMetadata* file) {
FileDetails* details = file->mutable_details();
details->clear_parent_folder_ids();
details->add_parent_folder_ids(new_parent);
details->set_change_id(++current_change_id_);
}
void ApplyContentChangeToMetadata(FileMetadata* file) {
FileDetails* details = file->mutable_details();
details->set_md5(
"md5_value_" + base::Int64ToString(next_md5_sequence_number_++));
details->set_change_id(++current_change_id_);
}
void ApplyNoopChangeToMetadata(FileMetadata* file) {
file->mutable_details()->set_change_id(++current_change_id_);
}
void PushToChangeList(scoped_ptr<google_apis::ChangeResource> change,
ScopedVector<google_apis::ChangeResource>* changes) {
changes->push_back(change.release());
}
leveldb::Status PutFileToDB(LevelDBWrapper* db, const FileMetadata& file) {
PutFileMetadataToDB(file, db);
return db->Commit();
}
leveldb::Status PutTrackerToDB(LevelDBWrapper* db,
const FileTracker& tracker) {
PutFileTrackerToDB(tracker, db);
return db->Commit();
}
void VerifyReloadConsistencyForOnMemory(MetadataDatabaseIndex* index1,
MetadataDatabaseIndex* index2) {
ExpectEquivalentServiceMetadata(index1, index2);
{
SCOPED_TRACE("Expect equivalent metadata_by_id_ contents.");
ExpectEquivalent(index1->metadata_by_id_, index2->metadata_by_id_);
}
{
SCOPED_TRACE("Expect equivalent tracker_by_id_ contents.");
ExpectEquivalent(index1->tracker_by_id_, index2->tracker_by_id_);
}
{
SCOPED_TRACE("Expect equivalent trackers_by_file_id_ contents.");
ExpectEquivalent(index1->trackers_by_file_id_,
index2->trackers_by_file_id_);
}
{
SCOPED_TRACE("Expect equivalent app_root_by_app_id_ contents.");
ExpectEquivalent(index1->app_root_by_app_id_,
index2->app_root_by_app_id_);
}
{
SCOPED_TRACE("Expect equivalent trackers_by_parent_and_title_ contents.");
ExpectEquivalent(index1->trackers_by_parent_and_title_,
index2->trackers_by_parent_and_title_);
}
{
SCOPED_TRACE("Expect equivalent dirty_trackers_ contents.");
ExpectEquivalent(index1->dirty_trackers_, index2->dirty_trackers_);
}
}
void VerifyReloadConsistencyForOnDisk(
MetadataDatabaseIndexOnDisk* index1,
MetadataDatabaseIndexOnDisk* index2) {
ExpectEquivalentServiceMetadata(index1, index2);
scoped_ptr<LevelDBWrapper::Iterator> itr1 =
index1->GetDBForTesting()->NewIterator();
scoped_ptr<LevelDBWrapper::Iterator> itr2 =
index2->GetDBForTesting()->NewIterator();
for (itr1->SeekToFirst(), itr2->SeekToFirst();
itr1->Valid() && itr2->Valid();
itr1->Next(), itr2->Next()) {
EXPECT_EQ(itr1->key().ToString(), itr2->key().ToString());
EXPECT_EQ(itr1->value().ToString(), itr2->value().ToString());
}
EXPECT_TRUE(!itr1->Valid());
EXPECT_TRUE(!itr2->Valid());
}
void VerifyReloadConsistency() {
scoped_ptr<MetadataDatabase> metadata_database_2;
ASSERT_EQ(SYNC_STATUS_OK,
MetadataDatabase::CreateForTesting(
metadata_database_->db_.Pass(),
metadata_database_->enable_on_disk_index_,
&metadata_database_2));
metadata_database_->db_ = metadata_database_2->db_.Pass();
MetadataDatabaseIndexInterface* index1 = metadata_database_->index_.get();
MetadataDatabaseIndexInterface* index2 = metadata_database_2->index_.get();
if (GetParam()) {
VerifyReloadConsistencyForOnDisk(
static_cast<MetadataDatabaseIndexOnDisk*>(index1),
static_cast<MetadataDatabaseIndexOnDisk*>(index2));
} else {
VerifyReloadConsistencyForOnMemory(
static_cast<MetadataDatabaseIndex*>(index1),
static_cast<MetadataDatabaseIndex*>(index2));
}
}
void VerifyFile(const FileMetadata& file) {
FileMetadata file_in_metadata_database;
ASSERT_TRUE(metadata_database()->FindFileByFileID(
file.file_id(), &file_in_metadata_database));
SCOPED_TRACE("Expect equivalent " + file.file_id());
ExpectEquivalent(&file, &file_in_metadata_database);
}
void VerifyTracker(const FileTracker& tracker) {
FileTracker tracker_in_metadata_database;
ASSERT_TRUE(metadata_database()->FindTrackerByTrackerID(
tracker.tracker_id(), &tracker_in_metadata_database));
SCOPED_TRACE("Expect equivalent tracker[" +
base::Int64ToString(tracker.tracker_id()) + "]");
ExpectEquivalent(&tracker, &tracker_in_metadata_database);
}
SyncStatusCode RegisterApp(const std::string& app_id,
const std::string& folder_id) {
return metadata_database_->RegisterApp(app_id, folder_id);
}
SyncStatusCode DisableApp(const std::string& app_id) {
return metadata_database_->DisableApp(app_id);
}
SyncStatusCode EnableApp(const std::string& app_id) {
return metadata_database_->EnableApp(app_id);
}
SyncStatusCode UnregisterApp(const std::string& app_id) {
return metadata_database_->UnregisterApp(app_id);
}
SyncStatusCode UpdateByChangeList(
ScopedVector<google_apis::ChangeResource> changes) {
return metadata_database_->UpdateByChangeList(
current_change_id_, changes.Pass());
}
SyncStatusCode PopulateFolder(const std::string& folder_id,
const FileIDList& listed_children) {
return metadata_database_->PopulateFolderByChildList(
folder_id, listed_children);
}
SyncStatusCode UpdateTracker(const FileTracker& tracker) {
return metadata_database_->UpdateTracker(
tracker.tracker_id(), tracker.synced_details());
}
SyncStatusCode PopulateInitialData(
int64 largest_change_id,
const google_apis::FileResource& sync_root_folder,
const ScopedVector<google_apis::FileResource>& app_root_folders) {
return metadata_database_->PopulateInitialData(
largest_change_id, sync_root_folder, app_root_folders);
}
void ResetTrackerID(FileTracker* tracker) {
tracker->set_tracker_id(GetTrackerIDByFileID(tracker->file_id()));
}
int64 current_change_id() const {
return current_change_id_;
}
private:
base::ScopedTempDir database_dir_;
base::MessageLoop message_loop_;
scoped_ptr<leveldb::Env> in_memory_env_;
scoped_ptr<MetadataDatabase> metadata_database_;
int64 current_change_id_;
int64 next_tracker_id_;
int64 next_file_id_number_;
int64 next_md5_sequence_number_;
DISALLOW_COPY_AND_ASSIGN(MetadataDatabaseTest);
};
INSTANTIATE_TEST_CASE_P(MetadataDatabaseTestWithIndexesOnDisk,
MetadataDatabaseTest,
::testing::Values(true, false));
TEST_P(MetadataDatabaseTest, InitializationTest_Empty) {
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
DropDatabase();
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
DropDatabase();
scoped_ptr<LevelDBWrapper> db = InitializeLevelDB();
db->Put(kServiceMetadataKey, "Unparsable string");
EXPECT_TRUE(db->Commit().ok());
db.reset();
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
}
TEST_P(MetadataDatabaseTest, InitializationTest_SimpleTree) {
TrackedFile sync_root(CreateTrackedSyncRoot());
TrackedFile app_root(CreateTrackedFolder(sync_root, "app_id"));
app_root.tracker.set_app_id(app_root.metadata.details().title());
app_root.tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT);
TrackedFile file(CreateTrackedFile(app_root, "file"));
TrackedFile folder(CreateTrackedFolder(app_root, "folder"));
TrackedFile file_in_folder(CreateTrackedFile(folder, "file_in_folder"));
TrackedFile orphaned_file(CreateTrackedFile(sync_root, "orphaned_file"));
orphaned_file.metadata.mutable_details()->clear_parent_folder_ids();
orphaned_file.tracker.set_parent_tracker_id(0);
const TrackedFile* tracked_files[] = {
&sync_root, &app_root, &file, &folder, &file_in_folder, &orphaned_file
};
SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files));
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
orphaned_file.should_be_absent = true;
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
}
TEST_P(MetadataDatabaseTest, AppManagementTest) {
TrackedFile sync_root(CreateTrackedSyncRoot());
TrackedFile app_root(CreateTrackedFolder(sync_root, "app_id"));
app_root.tracker.set_app_id(app_root.metadata.details().title());
app_root.tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT);
TrackedFile file(CreateTrackedFile(app_root, "file"));
TrackedFile folder(CreateTrackedFolder(sync_root, "folder"));
folder.tracker.set_active(false);
const TrackedFile* tracked_files[] = {
&sync_root, &app_root, &file, &folder,
};
SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files));
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
folder.tracker.set_app_id("foo");
EXPECT_EQ(SYNC_STATUS_OK, RegisterApp(
folder.tracker.app_id(), folder.metadata.file_id()));
folder.tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT);
folder.tracker.set_active(true);
folder.tracker.set_dirty(true);
folder.tracker.set_needs_folder_listing(true);
VerifyTrackedFile(folder);
VerifyReloadConsistency();
EXPECT_EQ(SYNC_STATUS_OK, DisableApp(folder.tracker.app_id()));
folder.tracker.set_tracker_kind(TRACKER_KIND_DISABLED_APP_ROOT);
VerifyTrackedFile(folder);
VerifyReloadConsistency();
EXPECT_EQ(SYNC_STATUS_OK, EnableApp(folder.tracker.app_id()));
folder.tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT);
VerifyTrackedFile(folder);
VerifyReloadConsistency();
EXPECT_EQ(SYNC_STATUS_OK, UnregisterApp(folder.tracker.app_id()));
folder.tracker.set_app_id(std::string());
folder.tracker.set_tracker_kind(TRACKER_KIND_REGULAR);
folder.tracker.set_active(false);
VerifyTrackedFile(folder);
VerifyReloadConsistency();
EXPECT_EQ(SYNC_STATUS_OK, UnregisterApp(app_root.tracker.app_id()));
app_root.tracker.set_app_id(std::string());
app_root.tracker.set_tracker_kind(TRACKER_KIND_REGULAR);
app_root.tracker.set_active(false);
app_root.tracker.set_dirty(true);
file.should_be_absent = true;
VerifyTrackedFile(app_root);
VerifyTrackedFile(file);
VerifyReloadConsistency();
}
TEST_P(MetadataDatabaseTest, BuildPathTest) {
FileMetadata sync_root(CreateSyncRootMetadata());
FileTracker sync_root_tracker(CreateSyncRootTracker(sync_root));
FileMetadata app_root(CreateFolderMetadata(sync_root, "app_id"));
FileTracker app_root_tracker(
CreateTracker(sync_root_tracker, app_root));
app_root_tracker.set_app_id(app_root.details().title());
app_root_tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT);
FileMetadata folder(CreateFolderMetadata(app_root, "folder"));
FileTracker folder_tracker(CreateTracker(app_root_tracker, folder));
FileMetadata file(CreateFileMetadata(folder, "file"));
FileTracker file_tracker(CreateTracker(folder_tracker, file));
FileMetadata inactive_folder(CreateFolderMetadata(app_root, "folder"));
FileTracker inactive_folder_tracker(CreateTracker(app_root_tracker,
inactive_folder));
inactive_folder_tracker.set_active(false);
{
scoped_ptr<LevelDBWrapper> db = InitializeLevelDB();
ASSERT_TRUE(db);
EXPECT_TRUE(PutFileToDB(db.get(), sync_root).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), sync_root_tracker).ok());
EXPECT_TRUE(PutFileToDB(db.get(), app_root).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), app_root_tracker).ok());
EXPECT_TRUE(PutFileToDB(db.get(), folder).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), folder_tracker).ok());
EXPECT_TRUE(PutFileToDB(db.get(), file).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), file_tracker).ok());
}
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
base::FilePath path;
EXPECT_FALSE(metadata_database()->BuildPathForTracker(
sync_root_tracker.tracker_id(), &path));
EXPECT_TRUE(metadata_database()->BuildPathForTracker(
app_root_tracker.tracker_id(), &path));
EXPECT_EQ(base::FilePath(FPL("/")).NormalizePathSeparators(), path);
EXPECT_TRUE(metadata_database()->BuildPathForTracker(
file_tracker.tracker_id(), &path));
EXPECT_EQ(base::FilePath(FPL("/folder/file")).NormalizePathSeparators(),
path);
}
TEST_P(MetadataDatabaseTest, FindNearestActiveAncestorTest) {
const std::string kAppID = "app_id";
FileMetadata sync_root(CreateSyncRootMetadata());
FileTracker sync_root_tracker(CreateSyncRootTracker(sync_root));
FileMetadata app_root(CreateFolderMetadata(sync_root, kAppID));
FileTracker app_root_tracker(
CreateTracker(sync_root_tracker, app_root));
app_root_tracker.set_app_id(app_root.details().title());
app_root_tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT);
// Create directory structure like this: "/folder1/folder2/file"
FileMetadata folder1(CreateFolderMetadata(app_root, "folder1"));
FileTracker folder_tracker1(CreateTracker(app_root_tracker, folder1));
FileMetadata folder2(CreateFolderMetadata(folder1, "folder2"));
FileTracker folder_tracker2(CreateTracker(folder_tracker1, folder2));
FileMetadata file(CreateFileMetadata(folder2, "file"));
FileTracker file_tracker(CreateTracker(folder_tracker2, file));
FileMetadata inactive_folder(CreateFolderMetadata(app_root, "folder1"));
FileTracker inactive_folder_tracker(CreateTracker(app_root_tracker,
inactive_folder));
inactive_folder_tracker.set_active(false);
{
scoped_ptr<LevelDBWrapper> db = InitializeLevelDB();
ASSERT_TRUE(db);
EXPECT_TRUE(PutFileToDB(db.get(), sync_root).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), sync_root_tracker).ok());
EXPECT_TRUE(PutFileToDB(db.get(), app_root).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), app_root_tracker).ok());
EXPECT_TRUE(PutFileToDB(db.get(), folder1).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), folder_tracker1).ok());
EXPECT_TRUE(PutFileToDB(db.get(), folder2).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), folder_tracker2).ok());
EXPECT_TRUE(PutFileToDB(db.get(), file).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), file_tracker).ok());
EXPECT_TRUE(PutFileToDB(db.get(), inactive_folder).ok());
EXPECT_TRUE(PutTrackerToDB(db.get(), inactive_folder_tracker).ok());
}
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
{
base::FilePath path;
FileTracker tracker;
EXPECT_FALSE(metadata_database()->FindNearestActiveAncestor(
"non_registered_app_id",
CreateNormalizedPath(FPL("folder1/folder2/file")),
&tracker, &path));
}
{
base::FilePath path;
FileTracker tracker;
EXPECT_TRUE(metadata_database()->FindNearestActiveAncestor(
kAppID, CreateNormalizedPath(FPL("")), &tracker, &path));
EXPECT_EQ(app_root_tracker.tracker_id(), tracker.tracker_id());
EXPECT_EQ(CreateNormalizedPath(FPL("")), path);
}
{
base::FilePath path;
FileTracker tracker;
EXPECT_TRUE(metadata_database()->FindNearestActiveAncestor(
kAppID, CreateNormalizedPath(FPL("folder1/folder2")),
&tracker, &path));
EXPECT_EQ(folder_tracker2.tracker_id(), tracker.tracker_id());
EXPECT_EQ(CreateNormalizedPath(FPL("folder1/folder2")), path);
}
{
base::FilePath path;
FileTracker tracker;
EXPECT_TRUE(metadata_database()->FindNearestActiveAncestor(
kAppID, CreateNormalizedPath(FPL("folder1/folder2/file")),
&tracker, &path));
EXPECT_EQ(file_tracker.tracker_id(), tracker.tracker_id());
EXPECT_EQ(CreateNormalizedPath(FPL("folder1/folder2/file")), path);
}
{
base::FilePath path;
FileTracker tracker;
EXPECT_TRUE(metadata_database()->FindNearestActiveAncestor(
kAppID,
CreateNormalizedPath(FPL("folder1/folder2/folder3/folder4/file")),
&tracker, &path));
EXPECT_EQ(folder_tracker2.tracker_id(), tracker.tracker_id());
EXPECT_EQ(CreateNormalizedPath(FPL("folder1/folder2")), path);
}
{
base::FilePath path;
FileTracker tracker;
EXPECT_TRUE(metadata_database()->FindNearestActiveAncestor(
kAppID, CreateNormalizedPath(FPL("folder1/folder2/file/folder4/file")),
&tracker, &path));
EXPECT_EQ(folder_tracker2.tracker_id(), tracker.tracker_id());
EXPECT_EQ(CreateNormalizedPath(FPL("folder1/folder2")), path);
}
}
TEST_P(MetadataDatabaseTest, UpdateByChangeListTest) {
TrackedFile sync_root(CreateTrackedSyncRoot());
TrackedFile app_root(CreateTrackedFolder(sync_root, "app_id"));
TrackedFile disabled_app_root(CreateTrackedFolder(sync_root, "disabled_app"));
TrackedFile file(CreateTrackedFile(app_root, "file"));
TrackedFile renamed_file(CreateTrackedFile(app_root, "to be renamed"));
TrackedFile folder(CreateTrackedFolder(app_root, "folder"));
TrackedFile reorganized_file(
CreateTrackedFile(app_root, "to be reorganized"));
TrackedFile updated_file(
CreateTrackedFile(app_root, "to be updated"));
TrackedFile noop_file(CreateTrackedFile(app_root, "has noop change"));
TrackedFile new_file(CreateTrackedFile(app_root, "to be added later"));
new_file.should_be_absent = true;
const TrackedFile* tracked_files[] = {
&sync_root, &app_root, &disabled_app_root,
&file, &renamed_file, &folder, &reorganized_file, &updated_file, &noop_file,
&new_file,
};
SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files));
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
ApplyRenameChangeToMetadata("renamed", &renamed_file.metadata);
ApplyReorganizeChangeToMetadata(folder.metadata.file_id(),
&reorganized_file.metadata);
ApplyContentChangeToMetadata(&updated_file.metadata);
// Update change ID.
ApplyNoopChangeToMetadata(&noop_file.metadata);
ScopedVector<google_apis::ChangeResource> changes;
PushToChangeList(
CreateChangeResourceFromMetadata(renamed_file.metadata), &changes);
PushToChangeList(
CreateChangeResourceFromMetadata(reorganized_file.metadata), &changes);
PushToChangeList(
CreateChangeResourceFromMetadata(updated_file.metadata), &changes);
PushToChangeList(
CreateChangeResourceFromMetadata(noop_file.metadata), &changes);
PushToChangeList(
CreateChangeResourceFromMetadata(new_file.metadata), &changes);
EXPECT_EQ(SYNC_STATUS_OK, UpdateByChangeList(changes.Pass()));
renamed_file.tracker.set_dirty(true);
reorganized_file.tracker.set_dirty(true);
updated_file.tracker.set_dirty(true);
noop_file.tracker.set_dirty(true);
new_file.tracker.mutable_synced_details()->set_missing(true);
new_file.tracker.mutable_synced_details()->clear_md5();
new_file.tracker.set_active(false);
new_file.tracker.set_dirty(true);
ResetTrackerID(&new_file.tracker);
EXPECT_NE(0, new_file.tracker.tracker_id());
new_file.should_be_absent = false;
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
VerifyReloadConsistency();
}
TEST_P(MetadataDatabaseTest, PopulateFolderTest_RegularFolder) {
TrackedFile sync_root(CreateTrackedSyncRoot());
TrackedFile app_root(CreateTrackedAppRoot(sync_root, "app_id"));
app_root.tracker.set_app_id(app_root.metadata.details().title());
TrackedFile folder_to_populate(
CreateTrackedFolder(app_root, "folder_to_populate"));
folder_to_populate.tracker.set_needs_folder_listing(true);
folder_to_populate.tracker.set_dirty(true);
TrackedFile known_file(CreateTrackedFile(folder_to_populate, "known_file"));
TrackedFile new_file(CreateTrackedFile(folder_to_populate, "new_file"));
new_file.should_be_absent = true;
const TrackedFile* tracked_files[] = {
&sync_root, &app_root, &folder_to_populate, &known_file, &new_file
};
SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files));
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
FileIDList listed_children;
listed_children.push_back(known_file.metadata.file_id());
listed_children.push_back(new_file.metadata.file_id());
EXPECT_EQ(SYNC_STATUS_OK,
PopulateFolder(folder_to_populate.metadata.file_id(),
listed_children));
folder_to_populate.tracker.set_dirty(false);
folder_to_populate.tracker.set_needs_folder_listing(false);
ResetTrackerID(&new_file.tracker);
new_file.tracker.set_dirty(true);
new_file.tracker.set_active(false);
new_file.tracker.clear_synced_details();
new_file.should_be_absent = false;
new_file.tracker_only = true;
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
VerifyReloadConsistency();
}
TEST_P(MetadataDatabaseTest, PopulateFolderTest_InactiveFolder) {
TrackedFile sync_root(CreateTrackedSyncRoot());
TrackedFile app_root(CreateTrackedAppRoot(sync_root, "app_id"));
TrackedFile inactive_folder(CreateTrackedFolder(app_root, "inactive_folder"));
inactive_folder.tracker.set_active(false);
inactive_folder.tracker.set_dirty(true);
TrackedFile new_file(
CreateTrackedFile(inactive_folder, "file_in_inactive_folder"));
new_file.should_be_absent = true;
const TrackedFile* tracked_files[] = {
&sync_root, &app_root, &inactive_folder, &new_file,
};
SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files));
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
FileIDList listed_children;
listed_children.push_back(new_file.metadata.file_id());
EXPECT_EQ(SYNC_STATUS_OK,
PopulateFolder(inactive_folder.metadata.file_id(),
listed_children));
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
VerifyReloadConsistency();
}
TEST_P(MetadataDatabaseTest, PopulateFolderTest_DisabledAppRoot) {
TrackedFile sync_root(CreateTrackedSyncRoot());
TrackedFile disabled_app_root(
CreateTrackedAppRoot(sync_root, "disabled_app"));
disabled_app_root.tracker.set_dirty(true);
disabled_app_root.tracker.set_needs_folder_listing(true);
TrackedFile known_file(CreateTrackedFile(disabled_app_root, "known_file"));
TrackedFile file(CreateTrackedFile(disabled_app_root, "file"));
file.should_be_absent = true;
const TrackedFile* tracked_files[] = {
&sync_root, &disabled_app_root, &disabled_app_root, &known_file, &file,
};
SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files));
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
FileIDList disabled_app_children;
disabled_app_children.push_back(file.metadata.file_id());
EXPECT_EQ(SYNC_STATUS_OK, PopulateFolder(
disabled_app_root.metadata.file_id(), disabled_app_children));
ResetTrackerID(&file.tracker);
file.tracker.clear_synced_details();
file.tracker.set_dirty(true);
file.tracker.set_active(false);
file.should_be_absent = false;
file.tracker_only = true;
disabled_app_root.tracker.set_dirty(false);
disabled_app_root.tracker.set_needs_folder_listing(false);
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
VerifyReloadConsistency();
}
// TODO(tzik): Fix expectation and re-enable this test.
TEST_P(MetadataDatabaseTest, DISABLED_UpdateTrackerTest) {
TrackedFile sync_root(CreateTrackedSyncRoot());
TrackedFile app_root(CreateTrackedAppRoot(sync_root, "app_root"));
TrackedFile file(CreateTrackedFile(app_root, "file"));
file.tracker.set_dirty(true);
file.metadata.mutable_details()->set_title("renamed file");
TrackedFile inactive_file(CreateTrackedFile(app_root, "inactive_file"));
inactive_file.tracker.set_active(false);
inactive_file.tracker.set_dirty(true);
inactive_file.metadata.mutable_details()->set_title("renamed inactive file");
inactive_file.metadata.mutable_details()->set_md5("modified_md5");
TrackedFile new_conflict(CreateTrackedFile(app_root, "new conflict file"));
new_conflict.tracker.set_dirty(true);
new_conflict.metadata.mutable_details()->set_title("renamed file");
const TrackedFile* tracked_files[] = {
&sync_root, &app_root, &file, &inactive_file, &new_conflict
};
SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files));
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
VerifyReloadConsistency();
*file.tracker.mutable_synced_details() = file.metadata.details();
file.tracker.set_dirty(false);
EXPECT_EQ(SYNC_STATUS_OK, UpdateTracker(file.tracker));
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
VerifyReloadConsistency();
*inactive_file.tracker.mutable_synced_details() =
inactive_file.metadata.details();
inactive_file.tracker.set_dirty(false);
inactive_file.tracker.set_active(true);
EXPECT_EQ(SYNC_STATUS_OK, UpdateTracker(inactive_file.tracker));
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
VerifyReloadConsistency();
*new_conflict.tracker.mutable_synced_details() =
new_conflict.metadata.details();
new_conflict.tracker.set_dirty(false);
new_conflict.tracker.set_active(true);
file.tracker.set_dirty(true);
file.tracker.set_active(false);
EXPECT_EQ(SYNC_STATUS_OK, UpdateTracker(new_conflict.tracker));
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
VerifyReloadConsistency();
}
TEST_P(MetadataDatabaseTest, PopulateInitialDataTest) {
TrackedFile sync_root(CreateTrackedSyncRoot());
TrackedFile app_root(CreateTrackedFolder(sync_root, "app_root"));
app_root.tracker.set_active(false);
const TrackedFile* tracked_files[] = {
&sync_root, &app_root
};
scoped_ptr<google_apis::FileResource> sync_root_folder(
CreateFileResourceFromMetadata(sync_root.metadata));
scoped_ptr<google_apis::FileResource> app_root_folder(
CreateFileResourceFromMetadata(app_root.metadata));
ScopedVector<google_apis::FileResource> app_root_folders;
app_root_folders.push_back(app_root_folder.release());
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
EXPECT_EQ(SYNC_STATUS_OK, PopulateInitialData(
current_change_id(),
*sync_root_folder,
app_root_folders));
ResetTrackerID(&sync_root.tracker);
ResetTrackerID(&app_root.tracker);
app_root.tracker.set_parent_tracker_id(sync_root.tracker.tracker_id());
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
VerifyReloadConsistency();
}
TEST_P(MetadataDatabaseTest, DumpFiles) {
TrackedFile sync_root(CreateTrackedSyncRoot());
TrackedFile app_root(CreateTrackedAppRoot(sync_root, "app_id"));
app_root.tracker.set_app_id(app_root.metadata.details().title());
TrackedFile folder_0(CreateTrackedFolder(app_root, "folder_0"));
TrackedFile file_0(CreateTrackedFile(folder_0, "file_0"));
const TrackedFile* tracked_files[] = {
&sync_root, &app_root, &folder_0, &file_0
};
SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files));
EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase());
VerifyTrackedFiles(tracked_files, arraysize(tracked_files));
scoped_ptr<base::ListValue> files =
metadata_database()->DumpFiles(app_root.tracker.app_id());
ASSERT_EQ(2u, files->GetSize());
base::DictionaryValue* file = nullptr;
std::string str;
ASSERT_TRUE(files->GetDictionary(0, &file));
EXPECT_TRUE(file->GetString("title", &str) && str == "folder_0");
EXPECT_TRUE(file->GetString("type", &str) && str == "folder");
EXPECT_TRUE(file->HasKey("details"));
ASSERT_TRUE(files->GetDictionary(1, &file));
EXPECT_TRUE(file->GetString("title", &str) && str == "file_0");
EXPECT_TRUE(file->GetString("type", &str) && str == "file");
EXPECT_TRUE(file->HasKey("details"));
}
} // namespace drive_backend
} // namespace sync_file_system
| Jonekee/chromium.src | chrome/browser/sync_file_system/drive_backend/metadata_database_unittest.cc | C++ | bsd-3-clause | 43,484 |
// 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 "ui/display/types/display_snapshot.h"
namespace ui {
DisplaySnapshot::DisplaySnapshot(int64_t display_id,
const gfx::Point& origin,
const gfx::Size& physical_size,
DisplayConnectionType type,
bool is_aspect_preserving_scaling,
bool has_overscan,
std::string display_name,
const std::vector<const DisplayMode*>& modes,
const DisplayMode* current_mode,
const DisplayMode* native_mode)
: display_id_(display_id),
origin_(origin),
physical_size_(physical_size),
type_(type),
is_aspect_preserving_scaling_(is_aspect_preserving_scaling),
has_overscan_(has_overscan),
display_name_(display_name),
modes_(modes),
current_mode_(current_mode),
native_mode_(native_mode) {}
DisplaySnapshot::~DisplaySnapshot() {}
} // namespace ui
| Jonekee/chromium.src | ui/display/types/display_snapshot.cc | C++ | bsd-3-clause | 1,255 |
"""
Helpers for embarrassingly parallel code.
"""
# Author: Gael Varoquaux < gael dot varoquaux at normalesup dot org >
# Copyright: 2010, Gael Varoquaux
# License: BSD 3 clause
from __future__ import division
import os
import sys
from math import sqrt
import functools
import time
import threading
import itertools
from numbers import Integral
from contextlib import contextmanager
import warnings
try:
import cPickle as pickle
except ImportError:
import pickle
from ._multiprocessing_helpers import mp
from .format_stack import format_outer_frames
from .logger import Logger, short_format_time
from .my_exceptions import TransportableException, _mk_exception
from .disk import memstr_to_bytes
from ._parallel_backends import (FallbackToBackend, MultiprocessingBackend,
ThreadingBackend, SequentialBackend)
from ._compat import _basestring
# Make sure that those two classes are part of the public joblib.parallel API
# so that 3rd party backend implementers can import them from here.
from ._parallel_backends import AutoBatchingMixin # noqa
from ._parallel_backends import ParallelBackendBase # noqa
BACKENDS = {
'multiprocessing': MultiprocessingBackend,
'threading': ThreadingBackend,
'sequential': SequentialBackend,
}
# name of the backend used by default by Parallel outside of any context
# managed by ``parallel_backend``.
DEFAULT_BACKEND = 'multiprocessing'
DEFAULT_N_JOBS = 1
# Thread local value that can be overridden by the ``parallel_backend`` context
# manager
_backend = threading.local()
def get_active_backend():
"""Return the active default backend"""
active_backend_and_jobs = getattr(_backend, 'backend_and_jobs', None)
if active_backend_and_jobs is not None:
return active_backend_and_jobs
# We are outside of the scope of any parallel_backend context manager,
# create the default backend instance now
active_backend = BACKENDS[DEFAULT_BACKEND]()
return active_backend, DEFAULT_N_JOBS
@contextmanager
def parallel_backend(backend, n_jobs=-1, **backend_params):
"""Change the default backend used by Parallel inside a with block.
If ``backend`` is a string it must match a previously registered
implementation using the ``register_parallel_backend`` function.
Alternatively backend can be passed directly as an instance.
By default all available workers will be used (``n_jobs=-1``) unless the
caller passes an explicit value for the ``n_jobs`` parameter.
This is an alternative to passing a ``backend='backend_name'`` argument to
the ``Parallel`` class constructor. It is particularly useful when calling
into library code that uses joblib internally but does not expose the
backend argument in its own API.
>>> from operator import neg
>>> with parallel_backend('threading'):
... print(Parallel()(delayed(neg)(i + 1) for i in range(5)))
...
[-1, -2, -3, -4, -5]
Warning: this function is experimental and subject to change in a future
version of joblib.
.. versionadded:: 0.10
"""
if isinstance(backend, _basestring):
backend = BACKENDS[backend](**backend_params)
old_backend_and_jobs = getattr(_backend, 'backend_and_jobs', None)
try:
_backend.backend_and_jobs = (backend, n_jobs)
# return the backend instance to make it easier to write tests
yield backend, n_jobs
finally:
if old_backend_and_jobs is None:
if getattr(_backend, 'backend_and_jobs', None) is not None:
del _backend.backend_and_jobs
else:
_backend.backend_and_jobs = old_backend_and_jobs
# Under Linux or OS X the default start method of multiprocessing
# can cause third party libraries to crash. Under Python 3.4+ it is possible
# to set an environment variable to switch the default start method from
# 'fork' to 'forkserver' or 'spawn' to avoid this issue albeit at the cost
# of causing semantic changes and some additional pool instantiation overhead.
if hasattr(mp, 'get_context'):
method = os.environ.get('JOBLIB_START_METHOD', '').strip() or None
DEFAULT_MP_CONTEXT = mp.get_context(method=method)
else:
DEFAULT_MP_CONTEXT = None
class BatchedCalls(object):
"""Wrap a sequence of (func, args, kwargs) tuples as a single callable"""
def __init__(self, iterator_slice):
self.items = list(iterator_slice)
self._size = len(self.items)
def __call__(self):
return [func(*args, **kwargs) for func, args, kwargs in self.items]
def __len__(self):
return self._size
###############################################################################
# CPU count that works also when multiprocessing has been disabled via
# the JOBLIB_MULTIPROCESSING environment variable
def cpu_count():
"""Return the number of CPUs."""
if mp is None:
return 1
return mp.cpu_count()
###############################################################################
# For verbosity
def _verbosity_filter(index, verbose):
""" Returns False for indices increasingly apart, the distance
depending on the value of verbose.
We use a lag increasing as the square of index
"""
if not verbose:
return True
elif verbose > 10:
return False
if index == 0:
return False
verbose = .5 * (11 - verbose) ** 2
scale = sqrt(index / verbose)
next_scale = sqrt((index + 1) / verbose)
return (int(next_scale) == int(scale))
###############################################################################
def delayed(function, check_pickle=True):
"""Decorator used to capture the arguments of a function.
Pass `check_pickle=False` when:
- performing a possibly repeated check is too costly and has been done
already once outside of the call to delayed.
- when used in conjunction `Parallel(backend='threading')`.
"""
# Try to pickle the input function, to catch the problems early when
# using with multiprocessing:
if check_pickle:
pickle.dumps(function)
def delayed_function(*args, **kwargs):
return function, args, kwargs
try:
delayed_function = functools.wraps(function)(delayed_function)
except AttributeError:
" functools.wraps fails on some callable objects "
return delayed_function
###############################################################################
class BatchCompletionCallBack(object):
"""Callback used by joblib.Parallel's multiprocessing backend.
This callable is executed by the parent process whenever a worker process
has returned the results of a batch of tasks.
It is used for progress reporting, to update estimate of the batch
processing duration and to schedule the next batch of tasks to be
processed.
"""
def __init__(self, dispatch_timestamp, batch_size, parallel):
self.dispatch_timestamp = dispatch_timestamp
self.batch_size = batch_size
self.parallel = parallel
def __call__(self, out):
self.parallel.n_completed_tasks += self.batch_size
this_batch_duration = time.time() - self.dispatch_timestamp
self.parallel._backend.batch_completed(self.batch_size,
this_batch_duration)
self.parallel.print_progress()
if self.parallel._original_iterator is not None:
self.parallel.dispatch_next()
###############################################################################
def register_parallel_backend(name, factory, make_default=False):
"""Register a new Parallel backend factory.
The new backend can then be selected by passing its name as the backend
argument to the Parallel class. Moreover, the default backend can be
overwritten globally by setting make_default=True.
The factory can be any callable that takes no argument and return an
instance of ``ParallelBackendBase``.
Warning: this function is experimental and subject to change in a future
version of joblib.
.. versionadded:: 0.10
"""
BACKENDS[name] = factory
if make_default:
global DEFAULT_BACKEND
DEFAULT_BACKEND = name
def effective_n_jobs(n_jobs=-1):
"""Determine the number of jobs that can actually run in parallel
n_jobs is the number of workers requested by the callers.
Passing n_jobs=-1 means requesting all available workers for instance
matching the number of CPU cores on the worker host(s).
This method should return a guesstimate of the number of workers that can
actually perform work concurrently with the currently enabled default
backend. The primary use case is to make it possible for the caller to know
in how many chunks to slice the work.
In general working on larger data chunks is more efficient (less
scheduling overhead and better use of CPU cache prefetching heuristics)
as long as all the workers have enough work to do.
Warning: this function is experimental and subject to change in a future
version of joblib.
.. versionadded:: 0.10
"""
backend, _ = get_active_backend()
return backend.effective_n_jobs(n_jobs=n_jobs)
###############################################################################
class Parallel(Logger):
''' Helper class for readable parallel mapping.
Parameters
-----------
n_jobs: int, default: 1
The maximum number of concurrently running jobs, such as the number
of Python worker processes when backend="multiprocessing"
or the size of the thread-pool when backend="threading".
If -1 all CPUs are used. If 1 is given, no parallel computing code
is used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all
CPUs but one are used.
backend: str, ParallelBackendBase instance or None, \
default: 'multiprocessing'
Specify the parallelization backend implementation.
Supported backends are:
- "multiprocessing" used by default, can induce some
communication and memory overhead when exchanging input and
output data with the worker Python processes.
- "threading" is a very low-overhead backend but it suffers
from the Python Global Interpreter Lock if the called function
relies a lot on Python objects. "threading" is mostly useful
when the execution bottleneck is a compiled extension that
explicitly releases the GIL (for instance a Cython loop wrapped
in a "with nogil" block or an expensive call to a library such
as NumPy).
- finally, you can register backends by calling
register_parallel_backend. This will allow you to implement
a backend of your liking.
verbose: int, optional
The verbosity level: if non zero, progress messages are
printed. Above 50, the output is sent to stdout.
The frequency of the messages increases with the verbosity level.
If it more than 10, all iterations are reported.
timeout: float, optional
Timeout limit for each task to complete. If any task takes longer
a TimeOutError will be raised. Only applied when n_jobs != 1
pre_dispatch: {'all', integer, or expression, as in '3*n_jobs'}
The number of batches (of tasks) to be pre-dispatched.
Default is '2*n_jobs'. When batch_size="auto" this is reasonable
default and the multiprocessing workers should never starve.
batch_size: int or 'auto', default: 'auto'
The number of atomic tasks to dispatch at once to each
worker. When individual evaluations are very fast, multiprocessing
can be slower than sequential computation because of the overhead.
Batching fast computations together can mitigate this.
The ``'auto'`` strategy keeps track of the time it takes for a batch
to complete, and dynamically adjusts the batch size to keep the time
on the order of half a second, using a heuristic. The initial batch
size is 1.
``batch_size="auto"`` with ``backend="threading"`` will dispatch
batches of a single task at a time as the threading backend has
very little overhead and using larger batch size has not proved to
bring any gain in that case.
temp_folder: str, optional
Folder to be used by the pool for memmaping large arrays
for sharing memory with worker processes. If None, this will try in
order:
- a folder pointed by the JOBLIB_TEMP_FOLDER environment
variable,
- /dev/shm if the folder exists and is writable: this is a
RAMdisk filesystem available by default on modern Linux
distributions,
- the default system temporary folder that can be
overridden with TMP, TMPDIR or TEMP environment
variables, typically /tmp under Unix operating systems.
Only active when backend="multiprocessing".
max_nbytes int, str, or None, optional, 1M by default
Threshold on the size of arrays passed to the workers that
triggers automated memory mapping in temp_folder. Can be an int
in Bytes, or a human-readable string, e.g., '1M' for 1 megabyte.
Use None to disable memmaping of large arrays.
Only active when backend="multiprocessing".
mmap_mode: {None, 'r+', 'r', 'w+', 'c'}
Memmapping mode for numpy arrays passed to workers.
See 'max_nbytes' parameter documentation for more details.
Notes
-----
This object uses the multiprocessing module to compute in
parallel the application of a function to many different
arguments. The main functionality it brings in addition to
using the raw multiprocessing API are (see examples for details):
* More readable code, in particular since it avoids
constructing list of arguments.
* Easier debugging:
- informative tracebacks even when the error happens on
the client side
- using 'n_jobs=1' enables to turn off parallel computing
for debugging without changing the codepath
- early capture of pickling errors
* An optional progress meter.
* Interruption of multiprocesses jobs with 'Ctrl-C'
* Flexible pickling control for the communication to and from
the worker processes.
* Ability to use shared memory efficiently with worker
processes for large numpy-based datastructures.
Examples
--------
A simple example:
>>> from math import sqrt
>>> from sklearn.externals.joblib import Parallel, delayed
>>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10))
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
Reshaping the output when the function has several return
values:
>>> from math import modf
>>> from sklearn.externals.joblib import Parallel, delayed
>>> r = Parallel(n_jobs=1)(delayed(modf)(i/2.) for i in range(10))
>>> res, i = zip(*r)
>>> res
(0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5)
>>> i
(0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0)
The progress meter: the higher the value of `verbose`, the more
messages:
>>> from time import sleep
>>> from sklearn.externals.joblib import Parallel, delayed
>>> r = Parallel(n_jobs=2, verbose=5)(delayed(sleep)(.1) for _ in range(10)) #doctest: +SKIP
[Parallel(n_jobs=2)]: Done 1 out of 10 | elapsed: 0.1s remaining: 0.9s
[Parallel(n_jobs=2)]: Done 3 out of 10 | elapsed: 0.2s remaining: 0.5s
[Parallel(n_jobs=2)]: Done 6 out of 10 | elapsed: 0.3s remaining: 0.2s
[Parallel(n_jobs=2)]: Done 9 out of 10 | elapsed: 0.5s remaining: 0.1s
[Parallel(n_jobs=2)]: Done 10 out of 10 | elapsed: 0.5s finished
Traceback example, note how the line of the error is indicated
as well as the values of the parameter passed to the function that
triggered the exception, even though the traceback happens in the
child process:
>>> from heapq import nlargest
>>> from sklearn.externals.joblib import Parallel, delayed
>>> Parallel(n_jobs=2)(delayed(nlargest)(2, n) for n in (range(4), 'abcde', 3)) #doctest: +SKIP
#...
---------------------------------------------------------------------------
Sub-process traceback:
---------------------------------------------------------------------------
TypeError Mon Nov 12 11:37:46 2012
PID: 12934 Python 2.7.3: /usr/bin/python
...........................................................................
/usr/lib/python2.7/heapq.pyc in nlargest(n=2, iterable=3, key=None)
419 if n >= size:
420 return sorted(iterable, key=key, reverse=True)[:n]
421
422 # When key is none, use simpler decoration
423 if key is None:
--> 424 it = izip(iterable, count(0,-1)) # decorate
425 result = _nlargest(n, it)
426 return map(itemgetter(0), result) # undecorate
427
428 # General case, slowest method
TypeError: izip argument #1 must support iteration
___________________________________________________________________________
Using pre_dispatch in a producer/consumer situation, where the
data is generated on the fly. Note how the producer is first
called 3 times before the parallel loop is initiated, and then
called to generate new data on the fly. In this case the total
number of iterations cannot be reported in the progress messages:
>>> from math import sqrt
>>> from sklearn.externals.joblib import Parallel, delayed
>>> def producer():
... for i in range(6):
... print('Produced %s' % i)
... yield i
>>> out = Parallel(n_jobs=2, verbose=100, pre_dispatch='1.5*n_jobs')(
... delayed(sqrt)(i) for i in producer()) #doctest: +SKIP
Produced 0
Produced 1
Produced 2
[Parallel(n_jobs=2)]: Done 1 jobs | elapsed: 0.0s
Produced 3
[Parallel(n_jobs=2)]: Done 2 jobs | elapsed: 0.0s
Produced 4
[Parallel(n_jobs=2)]: Done 3 jobs | elapsed: 0.0s
Produced 5
[Parallel(n_jobs=2)]: Done 4 jobs | elapsed: 0.0s
[Parallel(n_jobs=2)]: Done 5 out of 6 | elapsed: 0.0s remaining: 0.0s
[Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed: 0.0s finished
'''
def __init__(self, n_jobs=1, backend=None, verbose=0, timeout=None,
pre_dispatch='2 * n_jobs', batch_size='auto',
temp_folder=None, max_nbytes='1M', mmap_mode='r'):
active_backend, default_n_jobs = get_active_backend()
if backend is None and n_jobs == 1:
# If we are under a parallel_backend context manager, look up
# the default number of jobs and use that instead:
n_jobs = default_n_jobs
self.n_jobs = n_jobs
self.verbose = verbose
self.timeout = timeout
self.pre_dispatch = pre_dispatch
if isinstance(max_nbytes, _basestring):
max_nbytes = memstr_to_bytes(max_nbytes)
self._backend_args = dict(
max_nbytes=max_nbytes,
mmap_mode=mmap_mode,
temp_folder=temp_folder,
verbose=max(0, self.verbose - 50),
)
if DEFAULT_MP_CONTEXT is not None:
self._backend_args['context'] = DEFAULT_MP_CONTEXT
if backend is None:
backend = active_backend
elif isinstance(backend, ParallelBackendBase):
# Use provided backend as is
pass
elif hasattr(backend, 'Pool') and hasattr(backend, 'Lock'):
# Make it possible to pass a custom multiprocessing context as
# backend to change the start method to forkserver or spawn or
# preload modules on the forkserver helper process.
self._backend_args['context'] = backend
backend = MultiprocessingBackend()
else:
try:
backend_factory = BACKENDS[backend]
except KeyError:
raise ValueError("Invalid backend: %s, expected one of %r"
% (backend, sorted(BACKENDS.keys())))
backend = backend_factory()
if (batch_size == 'auto' or isinstance(batch_size, Integral) and
batch_size > 0):
self.batch_size = batch_size
else:
raise ValueError(
"batch_size must be 'auto' or a positive integer, got: %r"
% batch_size)
self._backend = backend
self._output = None
self._jobs = list()
self._managed_backend = False
# This lock is used coordinate the main thread of this process with
# the async callback thread of our the pool.
self._lock = threading.Lock()
def __enter__(self):
self._managed_backend = True
self._initialize_backend()
return self
def __exit__(self, exc_type, exc_value, traceback):
self._terminate_backend()
self._managed_backend = False
def _initialize_backend(self):
"""Build a process or thread pool and return the number of workers"""
try:
n_jobs = self._backend.configure(n_jobs=self.n_jobs, parallel=self,
**self._backend_args)
if self.timeout is not None and not self._backend.supports_timeout:
warnings.warn(
'The backend class {!r} does not support timeout. '
"You have set 'timeout={}' in Parallel but "
"the 'timeout' parameter will not be used.".format(
self._backend.__class__.__name__,
self.timeout))
except FallbackToBackend as e:
# Recursively initialize the backend in case of requested fallback.
self._backend = e.backend
n_jobs = self._initialize_backend()
return n_jobs
def _effective_n_jobs(self):
if self._backend:
return self._backend.effective_n_jobs(self.n_jobs)
return 1
def _terminate_backend(self):
if self._backend is not None:
self._backend.terminate()
def _dispatch(self, batch):
"""Queue the batch for computing, with or without multiprocessing
WARNING: this method is not thread-safe: it should be only called
indirectly via dispatch_one_batch.
"""
# If job.get() catches an exception, it closes the queue:
if self._aborting:
return
self.n_dispatched_tasks += len(batch)
self.n_dispatched_batches += 1
dispatch_timestamp = time.time()
cb = BatchCompletionCallBack(dispatch_timestamp, len(batch), self)
job = self._backend.apply_async(batch, callback=cb)
self._jobs.append(job)
def dispatch_next(self):
"""Dispatch more data for parallel processing
This method is meant to be called concurrently by the multiprocessing
callback. We rely on the thread-safety of dispatch_one_batch to protect
against concurrent consumption of the unprotected iterator.
"""
if not self.dispatch_one_batch(self._original_iterator):
self._iterating = False
self._original_iterator = None
def dispatch_one_batch(self, iterator):
"""Prefetch the tasks for the next batch and dispatch them.
The effective size of the batch is computed here.
If there are no more jobs to dispatch, return False, else return True.
The iterator consumption and dispatching is protected by the same
lock so calling this function should be thread safe.
"""
if self.batch_size == 'auto':
batch_size = self._backend.compute_batch_size()
else:
# Fixed batch size strategy
batch_size = self.batch_size
with self._lock:
tasks = BatchedCalls(itertools.islice(iterator, batch_size))
if len(tasks) == 0:
# No more tasks available in the iterator: tell caller to stop.
return False
else:
self._dispatch(tasks)
return True
def _print(self, msg, msg_args):
"""Display the message on stout or stderr depending on verbosity"""
# XXX: Not using the logger framework: need to
# learn to use logger better.
if not self.verbose:
return
if self.verbose < 50:
writer = sys.stderr.write
else:
writer = sys.stdout.write
msg = msg % msg_args
writer('[%s]: %s\n' % (self, msg))
def print_progress(self):
"""Display the process of the parallel execution only a fraction
of time, controlled by self.verbose.
"""
if not self.verbose:
return
elapsed_time = time.time() - self._start_time
# Original job iterator becomes None once it has been fully
# consumed : at this point we know the total number of jobs and we are
# able to display an estimation of the remaining time based on already
# completed jobs. Otherwise, we simply display the number of completed
# tasks.
if self._original_iterator is not None:
if _verbosity_filter(self.n_dispatched_batches, self.verbose):
return
self._print('Done %3i tasks | elapsed: %s',
(self.n_completed_tasks,
short_format_time(elapsed_time), ))
else:
index = self.n_completed_tasks
# We are finished dispatching
total_tasks = self.n_dispatched_tasks
# We always display the first loop
if not index == 0:
# Display depending on the number of remaining items
# A message as soon as we finish dispatching, cursor is 0
cursor = (total_tasks - index + 1 -
self._pre_dispatch_amount)
frequency = (total_tasks // self.verbose) + 1
is_last_item = (index + 1 == total_tasks)
if (is_last_item or cursor % frequency):
return
remaining_time = (elapsed_time / index) * \
(self.n_dispatched_tasks - index * 1.0)
# only display status if remaining time is greater or equal to 0
self._print('Done %3i out of %3i | elapsed: %s remaining: %s',
(index,
total_tasks,
short_format_time(elapsed_time),
short_format_time(remaining_time),
))
def retrieve(self):
self._output = list()
while self._iterating or len(self._jobs) > 0:
if len(self._jobs) == 0:
# Wait for an async callback to dispatch new jobs
time.sleep(0.01)
continue
# We need to be careful: the job list can be filling up as
# we empty it and Python list are not thread-safe by default hence
# the use of the lock
with self._lock:
job = self._jobs.pop(0)
try:
if getattr(self._backend, 'supports_timeout', False):
self._output.extend(job.get(timeout=self.timeout))
else:
self._output.extend(job.get())
except BaseException as exception:
# Note: we catch any BaseException instead of just Exception
# instances to also include KeyboardInterrupt.
# Stop dispatching any new job in the async callback thread
self._aborting = True
# If the backend allows it, cancel or kill remaining running
# tasks without waiting for the results as we will raise
# the exception we got back to the caller instead of returning
# any result.
backend = self._backend
if (backend is not None and
hasattr(backend, 'abort_everything')):
# If the backend is managed externally we need to make sure
# to leave it in a working state to allow for future jobs
# scheduling.
ensure_ready = self._managed_backend
backend.abort_everything(ensure_ready=ensure_ready)
if not isinstance(exception, TransportableException):
raise
else:
# Capture exception to add information on the local
# stack in addition to the distant stack
this_report = format_outer_frames(context=10,
stack_start=1)
report = """Multiprocessing exception:
%s
---------------------------------------------------------------------------
Sub-process traceback:
---------------------------------------------------------------------------
%s""" % (this_report, exception.message)
# Convert this to a JoblibException
exception_type = _mk_exception(exception.etype)[0]
exception = exception_type(report)
raise exception
def __call__(self, iterable):
if self._jobs:
raise ValueError('This Parallel instance is already running')
# A flag used to abort the dispatching of jobs in case an
# exception is found
self._aborting = False
if not self._managed_backend:
n_jobs = self._initialize_backend()
else:
n_jobs = self._effective_n_jobs()
iterator = iter(iterable)
pre_dispatch = self.pre_dispatch
if pre_dispatch == 'all' or n_jobs == 1:
# prevent further dispatch via multiprocessing callback thread
self._original_iterator = None
self._pre_dispatch_amount = 0
else:
self._original_iterator = iterator
if hasattr(pre_dispatch, 'endswith'):
pre_dispatch = eval(pre_dispatch)
self._pre_dispatch_amount = pre_dispatch = int(pre_dispatch)
# The main thread will consume the first pre_dispatch items and
# the remaining items will later be lazily dispatched by async
# callbacks upon task completions.
iterator = itertools.islice(iterator, pre_dispatch)
self._start_time = time.time()
self.n_dispatched_batches = 0
self.n_dispatched_tasks = 0
self.n_completed_tasks = 0
try:
# Only set self._iterating to True if at least a batch
# was dispatched. In particular this covers the edge
# case of Parallel used with an exhausted iterator.
while self.dispatch_one_batch(iterator):
self._iterating = True
else:
self._iterating = False
if pre_dispatch == "all" or n_jobs == 1:
# The iterable was consumed all at once by the above for loop.
# No need to wait for async callbacks to trigger to
# consumption.
self._iterating = False
self.retrieve()
# Make sure that we get a last message telling us we are done
elapsed_time = time.time() - self._start_time
self._print('Done %3i out of %3i | elapsed: %s finished',
(len(self._output), len(self._output),
short_format_time(elapsed_time)))
finally:
if not self._managed_backend:
self._terminate_backend()
self._jobs = list()
output = self._output
self._output = None
return output
def __repr__(self):
return '%s(n_jobs=%s)' % (self.__class__.__name__, self.n_jobs)
| herilalaina/scikit-learn | sklearn/externals/joblib/parallel.py | Python | bsd-3-clause | 33,164 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ovirt_job
short_description: Module to manage jobs in oVirt/RHV
version_added: "2.9"
author: "Martin Necas (@mnecas)"
description:
- "This module manage jobs in oVirt/RHV. It can also manage steps of the job."
options:
description:
description:
- "Description of the job."
required: true
state:
description:
- "Should the job be C(present)/C(absent)/C(failed)."
- "C(started) is alias for C(present). C(finished) is alias for C(absent). Same in the steps."
- "Note when C(finished)/C(failed) it will finish/fail all steps."
choices: ['present', 'absent', 'started', 'finished', 'failed']
default: present
steps:
description:
- "The steps of the job."
suboptions:
description:
description:
- "Description of the step."
required: true
state:
description:
- "Should the step be present/absent/failed."
- "Note when one step fail whole job will fail"
- "Note when all steps are finished it will finish job."
choices: ['present', 'absent', 'started', 'finished', 'failed']
default: present
type: list
extends_documentation_fragment: ovirt
'''
EXAMPLES = '''
# Examples don't contain auth parameter for simplicity,
# look at ovirt_auth module to see how to reuse authentication:
- name: Create job with two steps
ovirt_job:
description: job_name
steps:
- description: step_name_A
- description: step_name_B
- name: Finish one step
ovirt_job:
description: job_name
steps:
- description: step_name_A
state: finished
- name: When you fail one step whole job will stop
ovirt_job:
description: job_name
steps:
- description: step_name_B
state: failed
- name: Finish all steps
ovirt_job:
description: job_name
state: finished
'''
RETURN = '''
id:
description: ID of the job which is managed
returned: On success if job is found.
type: str
sample: 7de90f31-222c-436c-a1ca-7e655bd5b60c
job:
description: "Dictionary of all the job attributes. Job attributes can be found on your oVirt/RHV instance
at following url: http://ovirt.github.io/ovirt-engine-api-model/master/#types/job."
returned: On success if job is found.
type: dict
'''
import traceback
try:
import ovirtsdk4.types as otypes
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
equal,
get_id_by_name,
ovirt_full_argument_spec,
get_dict_of_struct,
)
def build_job(description):
return otypes.Job(
description=description,
status=otypes.JobStatus.STARTED,
external=True,
auto_cleared=True
)
def build_step(description, job_id):
return otypes.Step(
description=description,
type=otypes.StepEnum.UNKNOWN,
job=otypes.Job(
id=job_id
),
status=otypes.StepStatus.STARTED,
external=True,
)
def attach_steps(module, job_id, jobs_service):
changed = False
steps_service = jobs_service.job_service(job_id).steps_service()
if module.params.get('steps'):
for step in module.params.get('steps'):
step_entity = get_entity(steps_service, step.get('description'))
step_state = step.get('state', 'present')
if step_state in ['present', 'started']:
if step_entity is None:
steps_service.add(build_step(step.get('description'), job_id))
changed = True
if step_entity is not None and step_entity.status not in [otypes.StepStatus.FINISHED, otypes.StepStatus.FAILED]:
if step_state in ['absent', 'finished']:
steps_service.step_service(step_entity.id).end(succeeded=True)
changed = True
elif step_state == 'failed':
steps_service.step_service(step_entity.id).end(succeeded=False)
changed = True
return changed
def get_entity(service, description):
all_entities = service.list()
for entity in all_entities:
if entity.description == description and entity.status not in [otypes.StepStatus.FINISHED, otypes.JobStatus.FINISHED]:
return entity
def main():
argument_spec = ovirt_full_argument_spec(
state=dict(
choices=['present', 'absent', 'started', 'finished', 'failed'],
default='present',
),
description=dict(default=None),
steps=dict(default=None, type='list'),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=False,
)
check_sdk(module)
try:
auth = module.params.pop('auth')
connection = create_connection(auth)
jobs_service = connection.system_service().jobs_service()
state = module.params['state']
job = get_entity(jobs_service, module.params['description'])
changed = False
if state in ['present', 'started']:
if job is None:
job = jobs_service.add(build_job(module.params['description']))
changed = True
changed = attach_steps(module, job.id, jobs_service) or changed
if job is not None and job.status not in [otypes.JobStatus.FINISHED, otypes.JobStatus.FAILED]:
if state in ['absent', 'finished']:
jobs_service.job_service(job.id).end(succeeded=True)
changed = True
elif state == 'failed':
jobs_service.job_service(job.id).end(succeeded=False)
changed = True
ret = {
'changed': changed,
'id': getattr(job, 'id', None),
'job': get_dict_of_struct(
struct=job,
connection=connection,
fetch_nested=True,
attributes=module.params.get('nested_attributes'),
),
}
module.exit_json(**ret)
except Exception as e:
module.fail_json(msg=str(e), exception=traceback.format_exc())
finally:
connection.close(logout=auth.get('token') is None)
if __name__ == "__main__":
main()
| thaim/ansible | lib/ansible/modules/cloud/ovirt/ovirt_job.py | Python | mit | 7,379 |
/*
* 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
/*
*
* (C) Copyright IBM Corp. 1999 All Rights Reserved.
* Copyright 1997 The Open Group Research Institute. All rights reserved.
*/
package sun.security.krb5.internal;
import java.util.TimeZone;
import sun.security.util.*;
import sun.security.krb5.Config;
import sun.security.krb5.KrbException;
import sun.security.krb5.Asn1Exception;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.io.IOException;
/**
* Implements the ASN.1 KerberosTime type.
*
* <xmp>
* KerberosTime ::= GeneralizedTime -- with no fractional seconds
* </xmp>
*
* The timestamps used in Kerberos are encoded as GeneralizedTimes. A
* KerberosTime value shall not include any fractional portions of the
* seconds. As required by the DER, it further shall not include any
* separators, and it shall specify the UTC time zone (Z).
*
* <p>
* This definition reflects the Network Working Group RFC 4120
* specification available at
* <a href="http://www.ietf.org/rfc/rfc4120.txt">
* http://www.ietf.org/rfc/rfc4120.txt</a>.
*
* The implementation also includes the microseconds info so that the
* same class can be used as a precise timestamp in Authenticator etc.
*/
public class KerberosTime implements Cloneable {
private long kerberosTime; // milliseconds since epoch, a Date.getTime() value
private int microSeconds; // the last three digits of the microsecond value
// The time when this class is loaded. Used in setNow()
private static final long initMilli = System.currentTimeMillis();
private static final long initMicro = System.nanoTime() / 1000;
private static long syncTime;
private static boolean DEBUG = Krb5.DEBUG;
public static final boolean NOW = true;
public static final boolean UNADJUSTED_NOW = false;
public KerberosTime(long time) {
kerberosTime = time;
}
private KerberosTime(long time, int micro) {
kerberosTime = time;
microSeconds = micro;
}
public Object clone() {
return new KerberosTime(kerberosTime, microSeconds);
}
// This constructor is used in the native code
// src/windows/native/sun/security/krb5/NativeCreds.c
public KerberosTime(String time) throws Asn1Exception {
kerberosTime = toKerberosTime(time);
}
/**
* Constructs a KerberosTime object.
* @param encoding a DER-encoded data.
* @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.
* @exception IOException if an I/O error occurs while reading encoded data.
*/
public KerberosTime(DerValue encoding) throws Asn1Exception, IOException {
GregorianCalendar calendar = new GregorianCalendar();
Date temp = encoding.getGeneralizedTime();
kerberosTime = temp.getTime();
}
private static long toKerberosTime(String time) throws Asn1Exception {
// this method only used by KerberosTime class.
// ASN.1 GeneralizedTime format:
// "19700101000000Z"
// | | | | | | |
// 0 4 6 8 | | |
// 10 | |
// 12 |
// 14
if (time.length() != 15)
throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT);
if (time.charAt(14) != 'Z')
throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT);
int year = Integer.parseInt(time.substring(0, 4));
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear(); // so that millisecond is zero
calendar.set(year,
Integer.parseInt(time.substring(4, 6)) - 1,
Integer.parseInt(time.substring(6, 8)),
Integer.parseInt(time.substring(8, 10)),
Integer.parseInt(time.substring(10, 12)),
Integer.parseInt(time.substring(12, 14)));
//The Date constructor assumes the setting are local relative
//and converts the time to UTC before storing it. Since we
//want the internal representation to correspond to local
//and not UTC time we subtract the UTC time offset.
return (calendar.getTime().getTime());
}
// should be moved to sun.security.krb5.util class
public static String zeroPad(String s, int length) {
StringBuffer temp = new StringBuffer(s);
while (temp.length() < length)
temp.insert(0, '0');
return temp.toString();
}
public KerberosTime(Date time) {
kerberosTime = time.getTime(); // (time.getTimezoneOffset() * 60000L);
}
public KerberosTime(boolean initToNow) {
if (initToNow) {
setNow();
}
}
/**
* Returns a string representation of KerberosTime object.
* @return a string representation of this object.
*/
public String toGeneralizedTimeString() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.setTimeInMillis(kerberosTime);
return zeroPad(Integer.toString(calendar.get(Calendar.YEAR)), 4) +
zeroPad(Integer.toString(calendar.get(Calendar.MONTH) + 1), 2) +
zeroPad(Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)), 2) +
zeroPad(Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)), 2) +
zeroPad(Integer.toString(calendar.get(Calendar.MINUTE)), 2) +
zeroPad(Integer.toString(calendar.get(Calendar.SECOND)), 2) + 'Z';
}
/**
* Encodes this object to a byte array.
* @return a byte array of encoded data.
* @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.
* @exception IOException if an I/O error occurs while reading encoded data.
*/
public byte[] asn1Encode() throws Asn1Exception, IOException {
DerOutputStream out = new DerOutputStream();
out.putGeneralizedTime(this.toDate());
return out.toByteArray();
}
public long getTime() {
return kerberosTime;
}
public void setTime(Date time) {
kerberosTime = time.getTime(); // (time.getTimezoneOffset() * 60000L);
microSeconds = 0;
}
public void setTime(long time) {
kerberosTime = time;
microSeconds = 0;
}
public Date toDate() {
Date temp = new Date(kerberosTime);
temp.setTime(temp.getTime());
return temp;
}
public void setNow() {
long microElapsed = System.nanoTime() / 1000 - initMicro;
setTime(initMilli + microElapsed/1000);
microSeconds = (int)(microElapsed % 1000);
}
public int getMicroSeconds() {
Long temp_long = new Long((kerberosTime % 1000L) * 1000L);
return temp_long.intValue() + microSeconds;
}
public void setMicroSeconds(int usec) {
microSeconds = usec % 1000;
Integer temp_int = new Integer(usec);
long temp_long = temp_int.longValue() / 1000L;
kerberosTime = kerberosTime - (kerberosTime % 1000L) + temp_long;
}
public void setMicroSeconds(Integer usec) {
if (usec != null) {
microSeconds = usec.intValue() % 1000;
long temp_long = usec.longValue() / 1000L;
kerberosTime = kerberosTime - (kerberosTime % 1000L) + temp_long;
}
}
public boolean inClockSkew(int clockSkew) {
KerberosTime now = new KerberosTime(KerberosTime.NOW);
if (java.lang.Math.abs(kerberosTime - now.kerberosTime) >
clockSkew * 1000L)
return false;
return true;
}
public boolean inClockSkew() {
return inClockSkew(getDefaultSkew());
}
public boolean inClockSkew(int clockSkew, KerberosTime now) {
if (java.lang.Math.abs(kerberosTime - now.kerberosTime) >
clockSkew * 1000L)
return false;
return true;
}
public boolean inClockSkew(KerberosTime time) {
return inClockSkew(getDefaultSkew(), time);
}
public boolean greaterThanWRTClockSkew(KerberosTime time, int clockSkew) {
if ((kerberosTime - time.kerberosTime) > clockSkew * 1000L)
return true;
return false;
}
public boolean greaterThanWRTClockSkew(KerberosTime time) {
return greaterThanWRTClockSkew(time, getDefaultSkew());
}
public boolean greaterThan(KerberosTime time) {
return kerberosTime > time.kerberosTime ||
kerberosTime == time.kerberosTime &&
microSeconds > time.microSeconds;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof KerberosTime)) {
return false;
}
return kerberosTime == ((KerberosTime)obj).kerberosTime &&
microSeconds == ((KerberosTime)obj).microSeconds;
}
public int hashCode() {
int result = 37 * 17 + (int)(kerberosTime ^ (kerberosTime >>> 32));
return result * 17 + microSeconds;
}
public boolean isZero() {
return kerberosTime == 0 && microSeconds == 0;
}
public int getSeconds() {
Long temp_long = new Long(kerberosTime / 1000L);
return temp_long.intValue();
}
public void setSeconds(int sec) {
Integer temp_int = new Integer(sec);
kerberosTime = temp_int.longValue() * 1000L;
}
/**
* Parse (unmarshal) a kerberostime from a DER input stream. This form
* parsing might be used when expanding a value which is part of
* a constructed sequence and uses explicitly tagged type.
*
* @exception Asn1Exception on error.
* @param data the Der input stream value, which contains one or more marshaled value.
* @param explicitTag tag number.
* @param optional indicates if this data field is optional
* @return an instance of KerberosTime.
*
*/
public static KerberosTime parse(DerInputStream data, byte explicitTag, boolean optional) throws Asn1Exception, IOException {
if ((optional) && (((byte)data.peekByte() & (byte)0x1F)!= explicitTag))
return null;
DerValue der = data.getDerValue();
if (explicitTag != (der.getTag() & (byte)0x1F)) {
throw new Asn1Exception(Krb5.ASN1_BAD_ID);
}
else {
DerValue subDer = der.getData().getDerValue();
return new KerberosTime(subDer);
}
}
public static int getDefaultSkew() {
int tdiff = Krb5.DEFAULT_ALLOWABLE_CLOCKSKEW;
try {
Config c = Config.getInstance();
if ((tdiff = c.getDefaultIntValue("clockskew",
"libdefaults")) == Integer.MIN_VALUE) { //value is not defined
tdiff = Krb5.DEFAULT_ALLOWABLE_CLOCKSKEW;
}
} catch (KrbException e) {
if (DEBUG) {
System.out.println("Exception in getting clockskew from " +
"Configuration " +
"using default value " +
e.getMessage());
}
}
return tdiff;
}
public String toString() {
return toGeneralizedTimeString();
}
}
| rokn/Count_Words_2015 | testing/openjdk/jdk/src/share/classes/sun/security/krb5/internal/KerberosTime.java | Java | mit | 12,458 |
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*global */
/*
* Author: Zion Orent <zorent@ics.com>
* Copyright (c) 2014 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//Load Grove Moisture module
var grove_moisture = require('jsupm_grovemoisture');
// Instantiate a Grove Moisture sensor on analog pin A0
var myMoistureObj = new grove_moisture.GroveMoisture(0);
// Values (approximate):
// 0-300, sensor in air or dry soil
// 300-600, sensor in humid soil
// 600+, sensor in wet soil or submerged in water
// Read the value every second and print the corresponding moisture level
setInterval(function()
{
var result;
var moisture_val = parseInt(myMoistureObj.value());
if (moisture_val >= 0 && moisture_val < 300)
result = "Dry";
else if (moisture_val >= 300 && moisture_val < 600)
result = "Moist";
else
result = "Wet";
console.log("Moisture value: " + moisture_val + ", " + result);
}, 1000);
// Print message when exiting
process.on('SIGINT', function()
{
console.log("Exiting...");
process.exit(0);
});
| yoyojacky/upm | examples/javascript/grovemoisture.js | JavaScript | mit | 2,103 |
# flake8: NOQA
# "flake8: NOQA" to suppress warning "H104 File contains nothing but comments"
# TODO(okuta): Implement packbits
# TODO(okuta): Implement unpackbits
| tigerneil/chainer | cupy/binary/packing.py | Python | mit | 168 |
<?php
/**
* WPSEO plugin file.
*
* @package WPSEO\Admin\Views
*/
/**
* @var Yoast_Form $yform
*/
if ( ! defined( 'WPSEO_VERSION' ) ) {
header( 'Status: 403 Forbidden' );
header( 'HTTP/1.1 403 Forbidden' );
exit();
}
/* translators: %1$s expands to Yoast SEO */
$submit_button_value = sprintf( __( 'Export your %1$s settings', 'wordpress-seo' ), 'Yoast SEO' );
$wpseo_export_phrase = sprintf(
/* translators: %1$s expands to Yoast SEO */
__( 'Export your %1$s settings here, to import them again later or to import them on another site.', 'wordpress-seo' ),
'Yoast SEO'
);
?>
<p><?php echo esc_html( $wpseo_export_phrase ); ?></p>
<form
action="<?php echo esc_url( admin_url( 'admin.php?page=wpseo_tools&tool=import-export#top#wpseo-export' ) ); ?>"
method="post"
accept-charset="<?php echo esc_attr( get_bloginfo( 'charset' ) ); ?>">
<?php wp_nonce_field( WPSEO_Export::NONCE_ACTION, WPSEO_Export::NONCE_NAME ); ?>
<button type="submit" class="button button-primary" id="export-button"><?php echo esc_html( $submit_button_value ); ?></button>
</form>
| smpetrey/leahconstantine.com | web/app/plugins/wordpress-seo/admin/views/tabs/tool/wpseo-export.php | PHP | mit | 1,073 |
<?php
namespace Neos\Diff;
/**
* This file is part of the Neos.Diff package.
*
* (c) 2009 Chris Boulton <chris.boulton@interspire.com>
* Portions (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
/**
* Class Diff
*/
class Diff
{
/**
* @var array The "old" sequence to use as the basis for the comparison.
*/
private $a = null;
/**
* @var array The "new" sequence to generate the changes for.
*/
private $b = null;
/**
* @var array Array containing the generated opcodes for the differences between the two items.
*/
private $groupedCodes = null;
/**
* @var array Associative array of the default options available for the diff class and their default value.
*/
private $defaultOptions = [
'context' => 3,
'ignoreNewLines' => false,
'ignoreWhitespace' => false,
'ignoreCase' => false
];
/**
* @var array Array of the options that have been applied for generating the diff.
*/
private $options = [];
/**
* The constructor.
*
* @param array $a Array containing the lines of the first string to compare.
* @param array $b Array containing the lines for the second string to compare.
* @param array $options Options (see $defaultOptions in this class)
*/
public function __construct(array $a, array $b, array $options = [])
{
$this->a = $a;
$this->b = $b;
$this->options = array_merge($this->defaultOptions, $options);
}
/**
* Render a diff using the supplied rendering class and return it.
*
* @param Renderer\AbstractRenderer $renderer An instance of the rendering object to use for generating the diff.
* @return mixed The generated diff. Exact return value depends on the renderer used.
*/
public function render(Renderer\AbstractRenderer $renderer)
{
$renderer->diff = $this;
return $renderer->render();
}
/**
* Get a range of lines from $start to $end from the first comparison string
* and return them as an array. If no values are supplied, the entire string
* is returned. It's also possible to specify just one line to return only
* that line.
*
* @param int $start The starting number.
* @param int $end The ending number. If not supplied, only the item in $start will be returned.
* @return array Array of all of the lines between the specified range.
*/
public function getA($start = 0, $end = null)
{
if ($start == 0 && $end === null) {
return $this->a;
}
if ($end === null) {
$length = 1;
} else {
$length = $end - $start;
}
return array_slice($this->a, $start, $length);
}
/**
* Get a range of lines from $start to $end from the second comparison string
* and return them as an array. If no values are supplied, the entire string
* is returned. It's also possible to specify just one line to return only
* that line.
*
* @param int $start The starting number.
* @param int $end The ending number. If not supplied, only the item in $start will be returned.
* @return array Array of all of the lines between the specified range.
*/
public function getB($start = 0, $end = null)
{
if ($start == 0 && $end === null) {
return $this->b;
}
if ($end === null) {
$length = 1;
} else {
$length = $end - $start;
}
return array_slice($this->b, $start, $length);
}
/**
* Generate a list of the compiled and grouped opcodes for the differences between the
* two strings. Generally called by the renderer, this class instantiates the sequence
* matcher and performs the actual diff generation and return an array of the opcodes
* for it. Once generated, the results are cached in the diff class instance.
*
* @return array Array of the grouped opcodes for the generated diff.
*/
public function getGroupedOpcodes()
{
if (!is_null($this->groupedCodes)) {
return $this->groupedCodes;
}
$sequenceMatcher = new SequenceMatcher($this->a, $this->b, null, $this->options);
$this->groupedCodes = $sequenceMatcher->getGroupedOpcodes();
return $this->groupedCodes;
}
}
| dimaip/neos-development-collection | Neos.Diff/Classes/Diff.php | PHP | gpl-3.0 | 4,601 |
// Copyright John Maddock 2006.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Test real concept.
// real_concept is an archetype for User defined Real types.
// This file defines the features, constructors, operators, functions...
// that are essential to use mathematical and statistical functions.
// The template typename "RealType" is used where this type
// (as well as the normal built-in types, float, double & long double)
// can be used.
// That this is the minimum set is confirmed by use as a type
// in tests of all functions & distributions, for example:
// test_spots(0.F); & test_spots(0.); for float and double, but also
// test_spots(boost::math::concepts::real_concept(0.));
// NTL quad_float type is an example of a type meeting the requirements,
// but note minor additions are needed - see ntl.diff and documentation
// "Using With NTL - a High-Precision Floating-Point Library".
#ifndef BOOST_MATH_REAL_CONCEPT_HPP
#define BOOST_MATH_REAL_CONCEPT_HPP
#include <boost/config.hpp>
#include <boost/limits.hpp>
#include <boost/math/special_functions/round.hpp>
#include <boost/math/special_functions/trunc.hpp>
#include <boost/math/special_functions/modf.hpp>
#include <boost/math/tools/precision.hpp>
#include <boost/math/policies/policy.hpp>
#if defined(__SGI_STL_PORT)
# include <boost/math/tools/real_cast.hpp>
#endif
#include <ostream>
#include <istream>
#include <boost/config/no_tr1/cmath.hpp>
#include <math.h> // fmodl
#if defined(__SGI_STL_PORT) || defined(_RWSTD_VER) || defined(__LIBCOMO__)
# include <cstdio>
#endif
namespace boost{ namespace math{
namespace concepts
{
#ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
typedef double real_concept_base_type;
#else
typedef long double real_concept_base_type;
#endif
class real_concept
{
public:
// Constructors:
real_concept() : m_value(0){}
real_concept(char c) : m_value(c){}
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
real_concept(wchar_t c) : m_value(c){}
#endif
real_concept(unsigned char c) : m_value(c){}
real_concept(signed char c) : m_value(c){}
real_concept(unsigned short c) : m_value(c){}
real_concept(short c) : m_value(c){}
real_concept(unsigned int c) : m_value(c){}
real_concept(int c) : m_value(c){}
real_concept(unsigned long c) : m_value(c){}
real_concept(long c) : m_value(c){}
#if defined(__DECCXX) || defined(__SUNPRO_CC)
real_concept(unsigned long long c) : m_value(static_cast<real_concept_base_type>(c)){}
real_concept(long long c) : m_value(static_cast<real_concept_base_type>(c)){}
#elif defined(BOOST_HAS_LONG_LONG)
real_concept(boost::ulong_long_type c) : m_value(static_cast<real_concept_base_type>(c)){}
real_concept(boost::long_long_type c) : m_value(static_cast<real_concept_base_type>(c)){}
#elif defined(BOOST_HAS_MS_INT64)
real_concept(unsigned __int64 c) : m_value(static_cast<real_concept_base_type>(c)){}
real_concept(__int64 c) : m_value(static_cast<real_concept_base_type>(c)){}
#endif
real_concept(float c) : m_value(c){}
real_concept(double c) : m_value(c){}
real_concept(long double c) : m_value(c){}
// Assignment:
real_concept& operator=(char c) { m_value = c; return *this; }
real_concept& operator=(unsigned char c) { m_value = c; return *this; }
real_concept& operator=(signed char c) { m_value = c; return *this; }
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
real_concept& operator=(wchar_t c) { m_value = c; return *this; }
#endif
real_concept& operator=(short c) { m_value = c; return *this; }
real_concept& operator=(unsigned short c) { m_value = c; return *this; }
real_concept& operator=(int c) { m_value = c; return *this; }
real_concept& operator=(unsigned int c) { m_value = c; return *this; }
real_concept& operator=(long c) { m_value = c; return *this; }
real_concept& operator=(unsigned long c) { m_value = c; return *this; }
#ifdef BOOST_HAS_LONG_LONG
real_concept& operator=(boost::long_long_type c) { m_value = static_cast<real_concept_base_type>(c); return *this; }
real_concept& operator=(boost::ulong_long_type c) { m_value = static_cast<real_concept_base_type>(c); return *this; }
#endif
real_concept& operator=(float c) { m_value = c; return *this; }
real_concept& operator=(double c) { m_value = c; return *this; }
real_concept& operator=(long double c) { m_value = c; return *this; }
// Access:
real_concept_base_type value()const{ return m_value; }
// Member arithmetic:
real_concept& operator+=(const real_concept& other)
{ m_value += other.value(); return *this; }
real_concept& operator-=(const real_concept& other)
{ m_value -= other.value(); return *this; }
real_concept& operator*=(const real_concept& other)
{ m_value *= other.value(); return *this; }
real_concept& operator/=(const real_concept& other)
{ m_value /= other.value(); return *this; }
real_concept operator-()const
{ return -m_value; }
real_concept const& operator+()const
{ return *this; }
real_concept& operator++()
{ ++m_value; return *this; }
real_concept& operator--()
{ --m_value; return *this; }
private:
real_concept_base_type m_value;
};
// Non-member arithmetic:
inline real_concept operator+(const real_concept& a, const real_concept& b)
{
real_concept result(a);
result += b;
return result;
}
inline real_concept operator-(const real_concept& a, const real_concept& b)
{
real_concept result(a);
result -= b;
return result;
}
inline real_concept operator*(const real_concept& a, const real_concept& b)
{
real_concept result(a);
result *= b;
return result;
}
inline real_concept operator/(const real_concept& a, const real_concept& b)
{
real_concept result(a);
result /= b;
return result;
}
// Comparison:
inline bool operator == (const real_concept& a, const real_concept& b)
{ return a.value() == b.value(); }
inline bool operator != (const real_concept& a, const real_concept& b)
{ return a.value() != b.value();}
inline bool operator < (const real_concept& a, const real_concept& b)
{ return a.value() < b.value(); }
inline bool operator <= (const real_concept& a, const real_concept& b)
{ return a.value() <= b.value(); }
inline bool operator > (const real_concept& a, const real_concept& b)
{ return a.value() > b.value(); }
inline bool operator >= (const real_concept& a, const real_concept& b)
{ return a.value() >= b.value(); }
// Non-member functions:
inline real_concept acos(real_concept a)
{ return std::acos(a.value()); }
inline real_concept cos(real_concept a)
{ return std::cos(a.value()); }
inline real_concept asin(real_concept a)
{ return std::asin(a.value()); }
inline real_concept atan(real_concept a)
{ return std::atan(a.value()); }
inline real_concept atan2(real_concept a, real_concept b)
{ return std::atan2(a.value(), b.value()); }
inline real_concept ceil(real_concept a)
{ return std::ceil(a.value()); }
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
// I've seen std::fmod(long double) crash on some platforms
// so use fmodl instead:
#ifdef _WIN32_WCE
//
// Ugly workaround for macro fmodl:
//
inline long double call_fmodl(long double a, long double b)
{ return fmodl(a, b); }
inline real_concept fmod(real_concept a, real_concept b)
{ return call_fmodl(a.value(), b.value()); }
#else
inline real_concept fmod(real_concept a, real_concept b)
{ return fmodl(a.value(), b.value()); }
#endif
#endif
inline real_concept cosh(real_concept a)
{ return std::cosh(a.value()); }
inline real_concept exp(real_concept a)
{ return std::exp(a.value()); }
inline real_concept fabs(real_concept a)
{ return std::fabs(a.value()); }
inline real_concept abs(real_concept a)
{ return std::abs(a.value()); }
inline real_concept floor(real_concept a)
{ return std::floor(a.value()); }
inline real_concept modf(real_concept a, real_concept* ipart)
{
real_concept_base_type ip;
real_concept_base_type result = std::modf(a.value(), &ip);
*ipart = ip;
return result;
}
inline real_concept frexp(real_concept a, int* expon)
{ return std::frexp(a.value(), expon); }
inline real_concept ldexp(real_concept a, int expon)
{ return std::ldexp(a.value(), expon); }
inline real_concept log(real_concept a)
{ return std::log(a.value()); }
inline real_concept log10(real_concept a)
{ return std::log10(a.value()); }
inline real_concept tan(real_concept a)
{ return std::tan(a.value()); }
inline real_concept pow(real_concept a, real_concept b)
{ return std::pow(a.value(), b.value()); }
#if !defined(__SUNPRO_CC)
inline real_concept pow(real_concept a, int b)
{ return std::pow(a.value(), b); }
#else
inline real_concept pow(real_concept a, int b)
{ return std::pow(a.value(), static_cast<real_concept_base_type>(b)); }
#endif
inline real_concept sin(real_concept a)
{ return std::sin(a.value()); }
inline real_concept sinh(real_concept a)
{ return std::sinh(a.value()); }
inline real_concept sqrt(real_concept a)
{ return std::sqrt(a.value()); }
inline real_concept tanh(real_concept a)
{ return std::tanh(a.value()); }
//
// Conversion and truncation routines:
//
template <class Policy>
inline int iround(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::iround(v.value(), pol); }
inline int iround(const concepts::real_concept& v)
{ return boost::math::iround(v.value(), policies::policy<>()); }
template <class Policy>
inline long lround(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::lround(v.value(), pol); }
inline long lround(const concepts::real_concept& v)
{ return boost::math::lround(v.value(), policies::policy<>()); }
#ifdef BOOST_HAS_LONG_LONG
template <class Policy>
inline boost::long_long_type llround(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::llround(v.value(), pol); }
inline boost::long_long_type llround(const concepts::real_concept& v)
{ return boost::math::llround(v.value(), policies::policy<>()); }
#endif
template <class Policy>
inline int itrunc(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::itrunc(v.value(), pol); }
inline int itrunc(const concepts::real_concept& v)
{ return boost::math::itrunc(v.value(), policies::policy<>()); }
template <class Policy>
inline long ltrunc(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::ltrunc(v.value(), pol); }
inline long ltrunc(const concepts::real_concept& v)
{ return boost::math::ltrunc(v.value(), policies::policy<>()); }
#ifdef BOOST_HAS_LONG_LONG
template <class Policy>
inline boost::long_long_type lltrunc(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::lltrunc(v.value(), pol); }
inline boost::long_long_type lltrunc(const concepts::real_concept& v)
{ return boost::math::lltrunc(v.value(), policies::policy<>()); }
#endif
// Streaming:
template <class charT, class traits>
inline std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const real_concept& a)
{
return os << a.value();
}
template <class charT, class traits>
inline std::basic_istream<charT, traits>& operator>>(std::basic_istream<charT, traits>& is, real_concept& a)
{
#if defined(BOOST_MSVC) && defined(__SGI_STL_PORT)
//
// STLPort 5.1.4 has a problem reading long doubles from strings,
// see http://sourceforge.net/tracker/index.php?func=detail&aid=1811043&group_id=146814&atid=766244
//
double v;
is >> v;
a = v;
return is;
#elif defined(__SGI_STL_PORT) || defined(_RWSTD_VER) || defined(__LIBCOMO__)
std::string s;
real_concept_base_type d;
is >> s;
std::sscanf(s.c_str(), "%Lf", &d);
a = d;
return is;
#else
real_concept_base_type v;
is >> v;
a = v;
return is;
#endif
}
} // namespace concepts
namespace tools
{
template <>
inline concepts::real_concept max_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
return max_value<concepts::real_concept_base_type>();
}
template <>
inline concepts::real_concept min_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
return min_value<concepts::real_concept_base_type>();
}
template <>
inline concepts::real_concept log_max_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
return log_max_value<concepts::real_concept_base_type>();
}
template <>
inline concepts::real_concept log_min_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
return log_min_value<concepts::real_concept_base_type>();
}
template <>
inline concepts::real_concept epsilon<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
#ifdef __SUNPRO_CC
return std::numeric_limits<concepts::real_concept_base_type>::epsilon();
#else
return tools::epsilon<concepts::real_concept_base_type>();
#endif
}
template <>
inline int digits<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
// Assume number of significand bits is same as real_concept_base_type,
// unless std::numeric_limits<T>::is_specialized to provide digits.
return tools::digits<concepts::real_concept_base_type>();
// Note that if numeric_limits real concept is NOT specialized to provide digits10
// (or max_digits10) then the default precision of 6 decimal digits will be used
// by Boost test (giving misleading error messages like
// "difference between {9.79796} and {9.79796} exceeds 5.42101e-19%"
// and by Boost lexical cast and serialization causing loss of accuracy.
}
} // namespace tools
#if defined(__SGI_STL_PORT) || defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS)
//
// We shouldn't really need these type casts any more, but there are some
// STLport iostream bugs we work around by using them....
//
namespace tools
{
// real_cast converts from T to integer and narrower floating-point types.
// Convert from T to integer types.
template <>
inline unsigned int real_cast<unsigned int, concepts::real_concept>(concepts::real_concept r)
{
return static_cast<unsigned int>(r.value());
}
template <>
inline int real_cast<int, concepts::real_concept>(concepts::real_concept r)
{
return static_cast<int>(r.value());
}
template <>
inline long real_cast<long, concepts::real_concept>(concepts::real_concept r)
{
return static_cast<long>(r.value());
}
// Converts from T to narrower floating-point types, float, double & long double.
template <>
inline float real_cast<float, concepts::real_concept>(concepts::real_concept r)
{
return static_cast<float>(r.value());
}
template <>
inline double real_cast<double, concepts::real_concept>(concepts::real_concept r)
{
return static_cast<double>(r.value());
}
template <>
inline long double real_cast<long double, concepts::real_concept>(concepts::real_concept r)
{
return r.value();
}
} // STLPort
#endif
#if BOOST_WORKAROUND(BOOST_MSVC, <= 1310)
//
// For some strange reason ADL sometimes fails to find the
// correct overloads, unless we bring these declarations into scope:
//
using concepts::itrunc;
using concepts::iround;
#endif
} // namespace math
} // namespace boost
#endif // BOOST_MATH_REAL_CONCEPT_HPP
| Stevenwork/Innov_code | v0.9/innovApp/libboost_1_49_0/include/boost/math/concepts/real_concept.hpp | C++ | lgpl-3.0 | 15,306 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Model } from '../model';
import { GitExtension, Repository, API } from './git';
import { ApiRepository, ApiImpl } from './api1';
import { Event, EventEmitter } from 'vscode';
export function deprecated(_target: any, key: string, descriptor: any): void {
if (typeof descriptor.value !== 'function') {
throw new Error('not supported');
}
const fn = descriptor.value;
descriptor.value = function () {
console.warn(`Git extension API method '${key}' is deprecated.`);
return fn.apply(this, arguments);
};
}
export class GitExtensionImpl implements GitExtension {
enabled: boolean = false;
private _onDidChangeEnablement = new EventEmitter<boolean>();
readonly onDidChangeEnablement: Event<boolean> = this._onDidChangeEnablement.event;
private _model: Model | undefined = undefined;
set model(model: Model | undefined) {
this._model = model;
const enabled = !!model;
if (this.enabled === enabled) {
return;
}
this.enabled = enabled;
this._onDidChangeEnablement.fire(this.enabled);
}
get model(): Model | undefined {
return this._model;
}
constructor(model?: Model) {
if (model) {
this.enabled = true;
this._model = model;
}
}
@deprecated
async getGitPath(): Promise<string> {
if (!this._model) {
throw new Error('Git model not found');
}
return this._model.git.path;
}
@deprecated
async getRepositories(): Promise<Repository[]> {
if (!this._model) {
throw new Error('Git model not found');
}
return this._model.repositories.map(repository => new ApiRepository(repository));
}
getAPI(version: number): API {
if (!this._model) {
throw new Error('Git model not found');
}
if (version !== 1) {
throw new Error(`No API version ${version} found.`);
}
return new ApiImpl(this._model);
}
}
| jwren/intellij-community | plugins/textmate/lib/bundles/git/src/api/extension.ts | TypeScript | apache-2.0 | 2,148 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/grappler/costs/graph_memory.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/inputs/trivial_test_graph_input_yielder.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace grappler {
namespace {
class GraphMemoryTest : public ::testing::Test {
protected:
std::unordered_map<string, DeviceProperties> devices_;
public:
GraphMemoryTest() {
devices_["/CPU:0"].set_type("CPU");
devices_["/CPU:0"].set_num_cores(1);
devices_["/CPU:0"].set_frequency(1);
devices_["/CPU:0"].set_bandwidth(1);
devices_["/GPU:0"].set_type("GPU");
devices_["/GPU:0"].set_num_cores(1);
devices_["/GPU:0"].set_frequency(1);
devices_["/CPU:0"].set_bandwidth(1);
(*devices_["/GPU:0"].mutable_environment())["architecture"] = "3";
}
};
TEST_F(GraphMemoryTest, Basic) {
TrivialTestGraphInputYielder fake_input(4, 1, 10, false, {"/CPU:0"});
GrapplerItem item;
CHECK(fake_input.NextItem(&item));
item.feed.clear();
GraphMemory memory(item);
Status s = memory.InferStatically(devices_);
TF_CHECK_OK(s);
const GraphMemory::MemoryUsage& mem_usage =
memory.GetPeakMemoryUsage("/CPU:0");
EXPECT_EQ(120, mem_usage.used_memory);
std::set<string> tensors;
for (const auto& t : mem_usage.live_tensors) {
tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
// When the execution of the 'Sign' node completes, TF can start executing
// 'Sign_1' and release the memory used by 'x'. Since we can't be sure of
// the order in which this takes place, in the worst case the 3 tensors are in
// memory.
std::set<string> expected;
expected.insert("Sign:0");
expected.insert("Sign_1:0");
expected.insert("x:0");
EXPECT_EQ(expected, tensors);
}
TEST_F(GraphMemoryTest, UnknownBatchSize) {
TrivialTestGraphInputYielder fake_input(4, 1, -1, false, {"/CPU:0"});
GrapplerItem item;
CHECK(fake_input.NextItem(&item));
item.feed.clear();
GraphMemory memory(item);
Status s = memory.InferStatically(devices_);
TF_CHECK_OK(s);
// Same maths as before, except that batch size is unknown and therefore
// assumed to be one.
const GraphMemory::MemoryUsage& mem_usage =
memory.GetPeakMemoryUsage("/CPU:0");
EXPECT_EQ(16, mem_usage.used_memory);
std::set<string> tensors;
for (const auto& t : mem_usage.live_tensors) {
tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> expected;
expected.insert("Const/Const:0");
expected.insert("Sign:0");
expected.insert("x:0");
EXPECT_EQ(expected, tensors);
}
TEST_F(GraphMemoryTest, MultiDevice) {
TrivialTestGraphInputYielder fake_input(4, 2, 1024 * 1024, false,
{"/CPU:0", "/GPU:0"});
GrapplerItem item;
CHECK(fake_input.NextItem(&item));
item.feed.clear();
GraphMemory memory(item);
Status s = memory.InferStatically(devices_);
TF_CHECK_OK(s);
const GraphMemory::MemoryUsage& cpu_mem = memory.GetPeakMemoryUsage("/CPU:0");
EXPECT_EQ(16777216, cpu_mem.used_memory);
std::set<string> cpu_tensors;
for (const auto& t : cpu_mem.live_tensors) {
cpu_tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> cpu_expected;
cpu_expected.insert("Recv_Sign_1_0_on_/CPU_0:0");
cpu_expected.insert("Sign:0");
cpu_expected.insert("x:0");
cpu_expected.insert("AddN:0");
EXPECT_EQ(cpu_expected, cpu_tensors);
const GraphMemory::MemoryUsage& gpu_mem = memory.GetPeakMemoryUsage("/GPU:0");
EXPECT_EQ(16777216, gpu_mem.used_memory);
std::set<string> gpu_tensors;
for (const auto& t : gpu_mem.live_tensors) {
gpu_tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> gpu_expected;
gpu_expected.insert("Recv_AddN_0_on_/GPU_0:0");
gpu_expected.insert("Sign_1:0");
gpu_expected.insert("AddN_1:0");
gpu_expected.insert("AddN_3:0");
EXPECT_EQ(gpu_expected, gpu_tensors);
}
TEST_F(GraphMemoryTest, GpuSwapping) {
TrivialTestGraphInputYielder fake_input(4, 2, 1024 * 1024, false, {"/GPU:0"});
GrapplerItem item;
CHECK(fake_input.NextItem(&item));
item.feed.clear();
{
// Estimate the max memory usage for the graph.
GraphMemory memory(item);
Status s = memory.InferStatically(devices_);
TF_CHECK_OK(s);
const GraphMemory::MemoryUsage& gpu_mem =
memory.GetPeakMemoryUsage("/GPU:0");
EXPECT_EQ(20971520, gpu_mem.used_memory);
std::set<string> gpu_tensors;
for (const auto& t : gpu_mem.live_tensors) {
gpu_tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> gpu_expected;
gpu_expected.insert("Sign:0");
gpu_expected.insert("Sign_1:0");
gpu_expected.insert("AddN:0");
gpu_expected.insert("AddN_1:0");
gpu_expected.insert("AddN_2:0");
EXPECT_EQ(gpu_expected, gpu_tensors);
}
{
// Swap the first input to node AddN_1: its fanin (the square nodes) should
// not appear in the max cut anymore.
for (auto& node : *item.graph.mutable_node()) {
if (node.name() == "AddN_1") {
(*node.mutable_attr())["_swap_to_host"].mutable_list()->add_i(0);
}
}
GraphMemory memory(item);
Status s = memory.InferStatically(devices_);
TF_CHECK_OK(s);
const GraphMemory::MemoryUsage& new_gpu_mem =
memory.GetPeakMemoryUsage("/GPU:0");
EXPECT_EQ(20971520, new_gpu_mem.used_memory);
std::set<string> new_gpu_tensors;
for (const auto& t : new_gpu_mem.live_tensors) {
new_gpu_tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> new_gpu_expected;
new_gpu_expected.insert("AddN:0");
new_gpu_expected.insert("AddN_1:0");
new_gpu_expected.insert("AddN_2:0");
new_gpu_expected.insert("AddN_3:0");
new_gpu_expected.insert("AddN_4:0");
EXPECT_EQ(new_gpu_expected, new_gpu_tensors);
}
}
TEST_F(GraphMemoryTest, CtrlDependencies) {
// Build a simple graph with a control dependency.
Scope s = Scope::NewRootScope();
Output a = ops::Const(s.WithOpName("a").WithDevice("/CPU:0"), 10.0f, {3});
Output v =
ops::Variable(s.WithOpName("v").WithDevice("/CPU:0"), {3}, DT_FLOAT);
Output assign =
ops::Assign(s.WithOpName("assign").WithDevice("/CPU:0"), v, a);
ops::NoOp init(
s.WithOpName("init").WithDevice("/CPU:0").WithControlDependencies(
assign));
GrapplerItem item;
item.fetch.push_back("init");
TF_CHECK_OK(s.ToGraphDef(&item.graph));
GraphMemory memory(item);
Status status = memory.InferStatically(devices_);
TF_CHECK_OK(status);
const GraphMemory::MemoryUsage& mem = memory.GetPeakMemoryUsage("/CPU:0");
EXPECT_EQ(36, mem.used_memory);
std::set<string> tensors;
for (const auto& t : mem.live_tensors) {
tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> expected;
expected.insert("a:0");
expected.insert("v:0");
expected.insert("assign:0");
EXPECT_EQ(expected, tensors);
}
} // namespace
} // namespace grappler
} // namespace tensorflow
| sarvex/tensorflow | tensorflow/core/grappler/costs/graph_memory_test.cc | C++ | apache-2.0 | 7,766 |
// Copyright 2014 The Crashpad 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.
#include "util/mach/mach_message_server.h"
#include <string.h>
#include <limits>
#include "base/logging.h"
#include "base/mac/mach_logging.h"
#include "base/mac/scoped_mach_vm.h"
#include "util/mach/mach_message.h"
namespace crashpad {
namespace {
//! \brief Manages a dynamically-allocated buffer to be used for Mach messaging.
class MachMessageBuffer {
public:
MachMessageBuffer() : vm_() {}
~MachMessageBuffer() {}
//! \return A pointer to the buffer.
mach_msg_header_t* Header() const {
return reinterpret_cast<mach_msg_header_t*>(vm_.address());
}
//! \brief Ensures that this object has a buffer of exactly \a size bytes
//! available.
//!
//! If the existing buffer is a different size, it will be reallocated without
//! copying any of the old buffer’s contents to the new buffer. The contents
//! of the buffer are unspecified after this call, even if no reallocation is
//! performed.
kern_return_t Reallocate(vm_size_t size) {
// This test uses == instead of > so that a large reallocation to receive a
// large message doesn’t cause permanent memory bloat for the duration of
// a MachMessageServer::Run() loop.
if (size != vm_.size()) {
// reset() first, so that two allocations don’t exist simultaneously.
vm_.reset();
if (size) {
vm_address_t address;
kern_return_t kr =
vm_allocate(mach_task_self(),
&address,
size,
VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_MACH_MSG));
if (kr != KERN_SUCCESS) {
return kr;
}
vm_.reset(address, size);
}
}
#if !defined(NDEBUG)
// Regardless of whether the allocation was changed, scribble over the
// memory to make sure that nothing relies on zero-initialization or stale
// contents.
memset(Header(), 0x66, size);
#endif
return KERN_SUCCESS;
}
private:
base::mac::ScopedMachVM vm_;
DISALLOW_COPY_AND_ASSIGN(MachMessageBuffer);
};
// Wraps MachMessageWithDeadline(), using a MachMessageBuffer argument which
// will be resized to |receive_size| (after being page-rounded). MACH_RCV_MSG
// is always combined into |options|.
mach_msg_return_t MachMessageAllocateReceive(MachMessageBuffer* request,
mach_msg_option_t options,
mach_msg_size_t receive_size,
mach_port_name_t receive_port,
MachMessageDeadline deadline,
mach_port_name_t notify_port,
bool run_even_if_expired) {
mach_msg_size_t request_alloc = round_page(receive_size);
kern_return_t kr = request->Reallocate(request_alloc);
if (kr != KERN_SUCCESS) {
return kr;
}
return MachMessageWithDeadline(request->Header(),
options | MACH_RCV_MSG,
receive_size,
receive_port,
deadline,
notify_port,
run_even_if_expired);
}
} // namespace
// This method implements a server similar to 10.9.4
// xnu-2422.110.17/libsyscall/mach/mach_msg.c mach_msg_server_once(). The server
// callback function and |max_size| parameter have been replaced with a C++
// interface. The |persistent| parameter has been added, allowing this method to
// serve as a stand-in for mach_msg_server(). The |timeout_ms| parameter has
// been added, allowing this function to not block indefinitely.
//
// static
mach_msg_return_t MachMessageServer::Run(Interface* interface,
mach_port_t receive_port,
mach_msg_options_t options,
Persistent persistent,
ReceiveLarge receive_large,
mach_msg_timeout_t timeout_ms) {
options &= ~(MACH_RCV_MSG | MACH_SEND_MSG);
const MachMessageDeadline deadline =
MachMessageDeadlineFromTimeout(timeout_ms);
if (receive_large == kReceiveLargeResize) {
options |= MACH_RCV_LARGE;
} else {
options &= ~MACH_RCV_LARGE;
}
const mach_msg_size_t trailer_alloc = REQUESTED_TRAILER_SIZE(options);
const mach_msg_size_t expected_receive_size =
round_msg(interface->MachMessageServerRequestSize()) + trailer_alloc;
const mach_msg_size_t request_size = (receive_large == kReceiveLargeResize)
? round_page(expected_receive_size)
: expected_receive_size;
DCHECK_GE(request_size, sizeof(mach_msg_empty_rcv_t));
// mach_msg_server() and mach_msg_server_once() would consider whether
// |options| contains MACH_SEND_TRAILER and include MAX_TRAILER_SIZE in this
// computation if it does, but that option is ineffective on macOS.
const mach_msg_size_t reply_size = interface->MachMessageServerReplySize();
DCHECK_GE(reply_size, sizeof(mach_msg_empty_send_t));
const mach_msg_size_t reply_alloc = round_page(reply_size);
MachMessageBuffer request;
MachMessageBuffer reply;
bool received_any_request = false;
bool retry;
kern_return_t kr;
do {
retry = false;
kr = MachMessageAllocateReceive(&request,
options,
request_size,
receive_port,
deadline,
MACH_PORT_NULL,
!received_any_request);
if (kr == MACH_RCV_TOO_LARGE) {
switch (receive_large) {
case kReceiveLargeError:
break;
case kReceiveLargeIgnore:
// Try again, even in one-shot mode. The caller is expecting this
// method to take action on the first message in the queue, and has
// indicated that they want large messages to be ignored. The
// alternatives, which might involve returning MACH_MSG_SUCCESS,
// MACH_RCV_TIMED_OUT, or MACH_RCV_TOO_LARGE to a caller that
// specified one-shot behavior, all seem less correct than retrying.
MACH_LOG(WARNING, kr) << "mach_msg: ignoring large message";
retry = true;
continue;
case kReceiveLargeResize: {
mach_msg_size_t this_request_size = round_page(
round_msg(request.Header()->msgh_size) + trailer_alloc);
DCHECK_GT(this_request_size, request_size);
kr = MachMessageAllocateReceive(&request,
options & ~MACH_RCV_LARGE,
this_request_size,
receive_port,
deadline,
MACH_PORT_NULL,
!received_any_request);
break;
}
}
}
if (kr != MACH_MSG_SUCCESS) {
return kr;
}
received_any_request = true;
kr = reply.Reallocate(reply_alloc);
if (kr != KERN_SUCCESS) {
return kr;
}
mach_msg_header_t* request_header = request.Header();
mach_msg_header_t* reply_header = reply.Header();
bool destroy_complex_request = false;
interface->MachMessageServerFunction(
request_header, reply_header, &destroy_complex_request);
if (!(reply_header->msgh_bits & MACH_MSGH_BITS_COMPLEX)) {
// This only works if the reply message is not complex, because otherwise,
// the location of the RetCode field is not known. It should be possible
// to locate the RetCode field by looking beyond the descriptors in a
// complex reply message, but this is not currently done. This behavior
// has not proven itself necessary in practice, and it’s not done by
// mach_msg_server() or mach_msg_server_once() either.
mig_reply_error_t* reply_mig =
reinterpret_cast<mig_reply_error_t*>(reply_header);
if (reply_mig->RetCode == MIG_NO_REPLY) {
reply_header->msgh_remote_port = MACH_PORT_NULL;
} else if (reply_mig->RetCode != KERN_SUCCESS &&
request_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
destroy_complex_request = true;
}
}
if (destroy_complex_request &&
request_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
request_header->msgh_remote_port = MACH_PORT_NULL;
mach_msg_destroy(request_header);
}
if (reply_header->msgh_remote_port != MACH_PORT_NULL) {
// Avoid blocking indefinitely. This duplicates the logic in 10.9.5
// xnu-2422.115.4/libsyscall/mach/mach_msg.c mach_msg_server_once(),
// although the special provision for sending to a send-once right is not
// made, because kernel keeps sends to a send-once right on the fast path
// without considering the user-specified timeout. See 10.9.5
// xnu-2422.115.4/osfmk/ipc/ipc_mqueue.c ipc_mqueue_send().
const MachMessageDeadline send_deadline =
deadline == kMachMessageDeadlineWaitIndefinitely
? kMachMessageDeadlineNonblocking
: deadline;
kr = MachMessageWithDeadline(reply_header,
options | MACH_SEND_MSG,
0,
MACH_PORT_NULL,
send_deadline,
MACH_PORT_NULL,
true);
if (kr != MACH_MSG_SUCCESS) {
if (kr == MACH_SEND_INVALID_DEST ||
kr == MACH_SEND_TIMED_OUT ||
kr == MACH_SEND_INTERRUPTED) {
mach_msg_destroy(reply_header);
}
return kr;
}
}
} while (persistent == kPersistent || retry);
return kr;
}
} // namespace crashpad
| atom/crashpad | util/mach/mach_message_server.cc | C++ | apache-2.0 | 10,737 |
/*
* Copyright 2000-2015 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.codeInsight.daemon.impl.quickfix;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.roots.ExternalLibraryDescriptor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.DependencyScope;
import com.intellij.openapi.roots.JavaProjectModelModificationService;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.util.Consumer;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author nik
*/
class AddExternalLibraryToDependenciesQuickFix extends OrderEntryFix {
private final Module myCurrentModule;
private final PsiReference myReference;
private final ExternalLibraryDescriptor myLibraryDescriptor;
private final String myQualifiedClassName;
public AddExternalLibraryToDependenciesQuickFix(@NotNull Module currentModule,
@NotNull ExternalLibraryDescriptor libraryDescriptor, @NotNull PsiReference reference,
@Nullable String qualifiedClassName) {
myCurrentModule = currentModule;
myReference = reference;
myLibraryDescriptor = libraryDescriptor;
myQualifiedClassName = qualifiedClassName;
}
@Nls
@NotNull
@Override
public String getText() {
return "Add '" + myLibraryDescriptor.getPresentableName() + "' to classpath";
}
@Nls
@NotNull
@Override
public String getFamilyName() {
return getText();
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return !project.isDisposed() && !myCurrentModule.isDisposed();
}
@Override
public void invoke(@NotNull Project project, final Editor editor, PsiFile file) throws IncorrectOperationException {
DependencyScope scope = suggestScopeByLocation(myCurrentModule, myReference.getElement());
JavaProjectModelModificationService.getInstance(project).addDependency(myCurrentModule, myLibraryDescriptor, scope).done(
new Consumer<Void>() {
@Override
public void consume(Void aVoid) {
new WriteAction() {
protected void run(@NotNull final Result result) {
importClass(myCurrentModule, editor, myReference, myQualifiedClassName);
}
}.execute();
}
});
}
}
| MichaelNedzelsky/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExternalLibraryToDependenciesQuickFix.java | Java | apache-2.0 | 3,201 |
package com.alibaba.otter.canal.instance.manager;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import com.alibaba.otter.canal.common.CanalException;
import com.alibaba.otter.canal.common.alarm.CanalAlarmHandler;
import com.alibaba.otter.canal.common.alarm.LogAlarmHandler;
import com.alibaba.otter.canal.common.utils.JsonUtils;
import com.alibaba.otter.canal.common.zookeeper.ZkClientx;
import com.alibaba.otter.canal.filter.aviater.AviaterRegexFilter;
import com.alibaba.otter.canal.instance.core.CanalInstance;
import com.alibaba.otter.canal.instance.core.CanalInstanceSupport;
import com.alibaba.otter.canal.instance.manager.model.Canal;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.DataSourcing;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.HAMode;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.IndexMode;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.MetaMode;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.SourcingType;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.StorageMode;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.StorageScavengeMode;
import com.alibaba.otter.canal.meta.CanalMetaManager;
import com.alibaba.otter.canal.meta.MemoryMetaManager;
import com.alibaba.otter.canal.meta.PeriodMixedMetaManager;
import com.alibaba.otter.canal.meta.ZooKeeperMetaManager;
import com.alibaba.otter.canal.parse.CanalEventParser;
import com.alibaba.otter.canal.parse.ha.CanalHAController;
import com.alibaba.otter.canal.parse.ha.HeartBeatHAController;
import com.alibaba.otter.canal.parse.inbound.AbstractEventParser;
import com.alibaba.otter.canal.parse.inbound.group.GroupEventParser;
import com.alibaba.otter.canal.parse.inbound.mysql.LocalBinlogEventParser;
import com.alibaba.otter.canal.parse.inbound.mysql.MysqlEventParser;
import com.alibaba.otter.canal.parse.index.CanalLogPositionManager;
import com.alibaba.otter.canal.parse.index.FailbackLogPositionManager;
import com.alibaba.otter.canal.parse.index.MemoryLogPositionManager;
import com.alibaba.otter.canal.parse.index.MetaLogPositionManager;
import com.alibaba.otter.canal.parse.index.PeriodMixedLogPositionManager;
import com.alibaba.otter.canal.parse.index.ZooKeeperLogPositionManager;
import com.alibaba.otter.canal.parse.support.AuthenticationInfo;
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.ClientIdentity;
import com.alibaba.otter.canal.protocol.position.EntryPosition;
import com.alibaba.otter.canal.sink.CanalEventSink;
import com.alibaba.otter.canal.sink.entry.EntryEventSink;
import com.alibaba.otter.canal.sink.entry.group.GroupEventSink;
import com.alibaba.otter.canal.store.AbstractCanalStoreScavenge;
import com.alibaba.otter.canal.store.CanalEventStore;
import com.alibaba.otter.canal.store.memory.MemoryEventStoreWithBuffer;
import com.alibaba.otter.canal.store.model.BatchMode;
import com.alibaba.otter.canal.store.model.Event;
/**
* 单个canal实例,比如一个destination会独立一个实例
*
* @author jianghang 2012-7-11 下午09:26:51
* @version 1.0.0
*/
public class CanalInstanceWithManager extends CanalInstanceSupport implements CanalInstance {
private static final Logger logger = LoggerFactory.getLogger(CanalInstanceWithManager.class);
protected Long canalId; // 和manager交互唯一标示
protected String destination; // 队列名字
protected String filter; // 过滤表达式
protected CanalParameter parameters; // 对应参数
protected CanalMetaManager metaManager; // 消费信息管理器
protected CanalEventStore<Event> eventStore; // 有序队列
protected CanalEventParser eventParser; // 解析对应的数据信息
protected CanalEventSink<List<Entry>> eventSink; // 链接parse和store的桥接器
protected CanalAlarmHandler alarmHandler; // alarm报警机制
protected ZkClientx zkClientx;
public CanalInstanceWithManager(Canal canal){
this(canal, null);
}
public CanalInstanceWithManager(Canal canal, String filter){
this.parameters = canal.getCanalParameter();
this.canalId = canal.getId();
this.destination = canal.getName();
this.filter = filter;
logger.info("init CannalInstance for {}-{} with parameters:{}", canalId, destination, parameters);
// 初始化报警机制
initAlarmHandler();
// 初始化metaManager
initMetaManager();
// 初始化eventStore
initEventStore();
// 初始化eventSink
initEventSink();
// 初始化eventParser;
initEventParser();
// 基础工具,需要提前start,会有先订阅再根据filter条件启动paser的需求
if (!alarmHandler.isStart()) {
alarmHandler.start();
}
if (!metaManager.isStart()) {
metaManager.start();
}
logger.info("init successful....");
}
public void start() {
super.start();
// 初始化metaManager
logger.info("start CannalInstance for {}-{} with parameters:{}", canalId, destination, parameters);
if (!metaManager.isStart()) {
metaManager.start();
}
if (!alarmHandler.isStart()) {
alarmHandler.start();
}
if (!eventStore.isStart()) {
eventStore.start();
}
if (!eventSink.isStart()) {
eventSink.start();
}
if (!eventParser.isStart()) {
beforeStartEventParser(eventParser);
eventParser.start();
}
logger.info("start successful....");
}
public void stop() {
logger.info("stop CannalInstance for {}-{} ", new Object[] { canalId, destination });
if (eventParser.isStart()) {
eventParser.stop();
afterStopEventParser(eventParser);
}
if (eventSink.isStart()) {
eventSink.stop();
}
if (eventStore.isStart()) {
eventStore.stop();
}
if (metaManager.isStart()) {
metaManager.stop();
}
if (alarmHandler.isStart()) {
alarmHandler.stop();
}
// if (zkClientx != null) {
// zkClientx.close();
// }
super.stop();
logger.info("stop successful....");
}
public boolean subscribeChange(ClientIdentity identity) {
if (StringUtils.isNotEmpty(identity.getFilter())) {
AviaterRegexFilter aviaterFilter = new AviaterRegexFilter(identity.getFilter());
boolean isGroup = (eventParser instanceof GroupEventParser);
if (isGroup) {
// 处理group的模式
List<CanalEventParser> eventParsers = ((GroupEventParser) eventParser).getEventParsers();
for (CanalEventParser singleEventParser : eventParsers) {// 需要遍历启动
((AbstractEventParser) singleEventParser).setEventFilter(aviaterFilter);
}
} else {
((AbstractEventParser) eventParser).setEventFilter(aviaterFilter);
}
}
// filter的处理规则
// a. parser处理数据过滤处理
// b. sink处理数据的路由&分发,一份parse数据经过sink后可以分发为多份,每份的数据可以根据自己的过滤规则不同而有不同的数据
// 后续内存版的一对多分发,可以考虑
return true;
}
protected void afterStartEventParser(CanalEventParser eventParser) {
super.afterStartEventParser(eventParser);
// 读取一下历史订阅的filter信息
List<ClientIdentity> clientIdentitys = metaManager.listAllSubscribeInfo(destination);
for (ClientIdentity clientIdentity : clientIdentitys) {
subscribeChange(clientIdentity);
}
}
protected void initAlarmHandler() {
logger.info("init alarmHandler begin...");
alarmHandler = new LogAlarmHandler();
logger.info("init alarmHandler end! \n\t load CanalAlarmHandler:{} ", alarmHandler.getClass().getName());
}
protected void initMetaManager() {
logger.info("init metaManager begin...");
MetaMode mode = parameters.getMetaMode();
if (mode.isMemory()) {
metaManager = new MemoryMetaManager();
} else if (mode.isZookeeper()) {
metaManager = new ZooKeeperMetaManager();
((ZooKeeperMetaManager) metaManager).setZkClientx(getZkclientx());
} else if (mode.isMixed()) {
// metaManager = new MixedMetaManager();
metaManager = new PeriodMixedMetaManager();// 换用优化过的mixed, at
// 2012-09-11
// 设置内嵌的zk metaManager
ZooKeeperMetaManager zooKeeperMetaManager = new ZooKeeperMetaManager();
zooKeeperMetaManager.setZkClientx(getZkclientx());
((PeriodMixedMetaManager) metaManager).setZooKeeperMetaManager(zooKeeperMetaManager);
} else {
throw new CanalException("unsupport MetaMode for " + mode);
}
logger.info("init metaManager end! \n\t load CanalMetaManager:{} ", metaManager.getClass().getName());
}
protected void initEventStore() {
logger.info("init eventStore begin...");
StorageMode mode = parameters.getStorageMode();
if (mode.isMemory()) {
MemoryEventStoreWithBuffer memoryEventStore = new MemoryEventStoreWithBuffer();
memoryEventStore.setBufferSize(parameters.getMemoryStorageBufferSize());
memoryEventStore.setBufferMemUnit(parameters.getMemoryStorageBufferMemUnit());
memoryEventStore.setBatchMode(BatchMode.valueOf(parameters.getStorageBatchMode().name()));
memoryEventStore.setDdlIsolation(parameters.getDdlIsolation());
eventStore = memoryEventStore;
} else if (mode.isFile()) {
// 后续版本支持
throw new CanalException("unsupport MetaMode for " + mode);
} else if (mode.isMixed()) {
// 后续版本支持
throw new CanalException("unsupport MetaMode for " + mode);
} else {
throw new CanalException("unsupport MetaMode for " + mode);
}
if (eventStore instanceof AbstractCanalStoreScavenge) {
StorageScavengeMode scavengeMode = parameters.getStorageScavengeMode();
AbstractCanalStoreScavenge eventScavengeStore = (AbstractCanalStoreScavenge) eventStore;
eventScavengeStore.setDestination(destination);
eventScavengeStore.setCanalMetaManager(metaManager);
eventScavengeStore.setOnAck(scavengeMode.isOnAck());
eventScavengeStore.setOnFull(scavengeMode.isOnFull());
eventScavengeStore.setOnSchedule(scavengeMode.isOnSchedule());
if (scavengeMode.isOnSchedule()) {
eventScavengeStore.setScavengeSchedule(parameters.getScavengeSchdule());
}
}
logger.info("init eventStore end! \n\t load CanalEventStore:{}", eventStore.getClass().getName());
}
protected void initEventSink() {
logger.info("init eventSink begin...");
int groupSize = getGroupSize();
if (groupSize <= 1) {
eventSink = new EntryEventSink();
} else {
eventSink = new GroupEventSink(groupSize);
}
if (eventSink instanceof EntryEventSink) {
((EntryEventSink) eventSink).setFilterTransactionEntry(false);
((EntryEventSink) eventSink).setEventStore(getEventStore());
}
// if (StringUtils.isNotEmpty(filter)) {
// AviaterRegexFilter aviaterFilter = new AviaterRegexFilter(filter);
// ((AbstractCanalEventSink) eventSink).setFilter(aviaterFilter);
// }
logger.info("init eventSink end! \n\t load CanalEventSink:{}", eventSink.getClass().getName());
}
protected void initEventParser() {
logger.info("init eventParser begin...");
SourcingType type = parameters.getSourcingType();
List<List<DataSourcing>> groupDbAddresses = parameters.getGroupDbAddresses();
if (!CollectionUtils.isEmpty(groupDbAddresses)) {
int size = groupDbAddresses.get(0).size();// 取第一个分组的数量,主备分组的数量必须一致
List<CanalEventParser> eventParsers = new ArrayList<CanalEventParser>();
for (int i = 0; i < size; i++) {
List<InetSocketAddress> dbAddress = new ArrayList<InetSocketAddress>();
SourcingType lastType = null;
for (List<DataSourcing> groupDbAddress : groupDbAddresses) {
if (lastType != null && !lastType.equals(groupDbAddress.get(i).getType())) {
throw new CanalException(String.format("master/slave Sourcing type is unmatch. %s vs %s",
lastType,
groupDbAddress.get(i).getType()));
}
lastType = groupDbAddress.get(i).getType();
dbAddress.add(groupDbAddress.get(i).getDbAddress());
}
// 初始化其中的一个分组parser
eventParsers.add(doInitEventParser(lastType, dbAddress));
}
if (eventParsers.size() > 1) { // 如果存在分组,构造分组的parser
GroupEventParser groupEventParser = new GroupEventParser();
groupEventParser.setEventParsers(eventParsers);
this.eventParser = groupEventParser;
} else {
this.eventParser = eventParsers.get(0);
}
} else {
// 创建一个空数据库地址的parser,可能使用了tddl指定地址,启动的时候才会从tddl获取地址
this.eventParser = doInitEventParser(type, new ArrayList<InetSocketAddress>());
}
logger.info("init eventParser end! \n\t load CanalEventParser:{}", eventParser.getClass().getName());
}
private CanalEventParser doInitEventParser(SourcingType type, List<InetSocketAddress> dbAddresses) {
CanalEventParser eventParser;
if (type.isMysql()) {
MysqlEventParser mysqlEventParser = new MysqlEventParser();
mysqlEventParser.setDestination(destination);
// 编码参数
mysqlEventParser.setConnectionCharset(Charset.forName(parameters.getConnectionCharset()));
mysqlEventParser.setConnectionCharsetNumber(parameters.getConnectionCharsetNumber());
// 网络相关参数
mysqlEventParser.setDefaultConnectionTimeoutInSeconds(parameters.getDefaultConnectionTimeoutInSeconds());
mysqlEventParser.setSendBufferSize(parameters.getSendBufferSize());
mysqlEventParser.setReceiveBufferSize(parameters.getReceiveBufferSize());
// 心跳检查参数
mysqlEventParser.setDetectingEnable(parameters.getDetectingEnable());
mysqlEventParser.setDetectingSQL(parameters.getDetectingSQL());
mysqlEventParser.setDetectingIntervalInSeconds(parameters.getDetectingIntervalInSeconds());
// 数据库信息参数
mysqlEventParser.setSlaveId(parameters.getSlaveId());
if (!CollectionUtils.isEmpty(dbAddresses)) {
mysqlEventParser.setMasterInfo(new AuthenticationInfo(dbAddresses.get(0),
parameters.getDbUsername(),
parameters.getDbPassword(),
parameters.getDefaultDatabaseName()));
if (dbAddresses.size() > 1) {
mysqlEventParser.setStandbyInfo(new AuthenticationInfo(dbAddresses.get(1),
parameters.getDbUsername(),
parameters.getDbPassword(),
parameters.getDefaultDatabaseName()));
}
}
if (!CollectionUtils.isEmpty(parameters.getPositions())) {
EntryPosition masterPosition = JsonUtils.unmarshalFromString(parameters.getPositions().get(0),
EntryPosition.class);
// binlog位置参数
mysqlEventParser.setMasterPosition(masterPosition);
if (parameters.getPositions().size() > 1) {
EntryPosition standbyPosition = JsonUtils.unmarshalFromString(parameters.getPositions().get(0),
EntryPosition.class);
mysqlEventParser.setStandbyPosition(standbyPosition);
}
}
mysqlEventParser.setFallbackIntervalInSeconds(parameters.getFallbackIntervalInSeconds());
mysqlEventParser.setProfilingEnabled(false);
mysqlEventParser.setFilterTableError(parameters.getFilterTableError());
eventParser = mysqlEventParser;
} else if (type.isLocalBinlog()) {
LocalBinlogEventParser localBinlogEventParser = new LocalBinlogEventParser();
localBinlogEventParser.setDestination(destination);
localBinlogEventParser.setBufferSize(parameters.getReceiveBufferSize());
localBinlogEventParser.setConnectionCharset(Charset.forName(parameters.getConnectionCharset()));
localBinlogEventParser.setConnectionCharsetNumber(parameters.getConnectionCharsetNumber());
localBinlogEventParser.setDirectory(parameters.getLocalBinlogDirectory());
localBinlogEventParser.setProfilingEnabled(false);
localBinlogEventParser.setDetectingEnable(parameters.getDetectingEnable());
localBinlogEventParser.setDetectingIntervalInSeconds(parameters.getDetectingIntervalInSeconds());
localBinlogEventParser.setFilterTableError(parameters.getFilterTableError());
// 数据库信息,反查表结构时需要
if (!CollectionUtils.isEmpty(dbAddresses)) {
localBinlogEventParser.setMasterInfo(new AuthenticationInfo(dbAddresses.get(0),
parameters.getDbUsername(),
parameters.getDbPassword(),
parameters.getDefaultDatabaseName()));
}
eventParser = localBinlogEventParser;
} else if (type.isOracle()) {
throw new CanalException("unsupport SourcingType for " + type);
} else {
throw new CanalException("unsupport SourcingType for " + type);
}
// add transaction support at 2012-12-06
if (eventParser instanceof AbstractEventParser) {
AbstractEventParser abstractEventParser = (AbstractEventParser) eventParser;
abstractEventParser.setTransactionSize(parameters.getTransactionSize());
abstractEventParser.setLogPositionManager(initLogPositionManager());
abstractEventParser.setAlarmHandler(getAlarmHandler());
abstractEventParser.setEventSink(getEventSink());
if (StringUtils.isNotEmpty(filter)) {
AviaterRegexFilter aviaterFilter = new AviaterRegexFilter(filter);
abstractEventParser.setEventFilter(aviaterFilter);
}
// 设置黑名单
if (StringUtils.isNotEmpty(parameters.getBlackFilter())) {
AviaterRegexFilter aviaterFilter = new AviaterRegexFilter(parameters.getBlackFilter());
abstractEventParser.setEventBlackFilter(aviaterFilter);
}
}
if (eventParser instanceof MysqlEventParser) {
MysqlEventParser mysqlEventParser = (MysqlEventParser) eventParser;
// 初始化haController,绑定与eventParser的关系,haController会控制eventParser
CanalHAController haController = initHaController();
mysqlEventParser.setHaController(haController);
}
return eventParser;
}
protected CanalHAController initHaController() {
logger.info("init haController begin...");
HAMode haMode = parameters.getHaMode();
CanalHAController haController = null;
if (haMode.isHeartBeat()) {
haController = new HeartBeatHAController();
((HeartBeatHAController) haController).setDetectingRetryTimes(parameters.getDetectingRetryTimes());
((HeartBeatHAController) haController).setSwitchEnable(parameters.getHeartbeatHaEnable());
} else {
throw new CanalException("unsupport HAMode for " + haMode);
}
logger.info("init haController end! \n\t load CanalHAController:{}", haController.getClass().getName());
return haController;
}
protected CanalLogPositionManager initLogPositionManager() {
logger.info("init logPositionPersistManager begin...");
IndexMode indexMode = parameters.getIndexMode();
CanalLogPositionManager logPositionManager = null;
if (indexMode.isMemory()) {
logPositionManager = new MemoryLogPositionManager();
} else if (indexMode.isZookeeper()) {
logPositionManager = new ZooKeeperLogPositionManager();
((ZooKeeperLogPositionManager) logPositionManager).setZkClientx(getZkclientx());
} else if (indexMode.isMixed()) {
logPositionManager = new PeriodMixedLogPositionManager();
ZooKeeperLogPositionManager zooKeeperLogPositionManager = new ZooKeeperLogPositionManager();
zooKeeperLogPositionManager.setZkClientx(getZkclientx());
((PeriodMixedLogPositionManager) logPositionManager).setZooKeeperLogPositionManager(zooKeeperLogPositionManager);
} else if (indexMode.isMeta()) {
logPositionManager = new MetaLogPositionManager();
((MetaLogPositionManager) logPositionManager).setMetaManager(metaManager);
} else if (indexMode.isMemoryMetaFailback()) {
MemoryLogPositionManager primaryLogPositionManager = new MemoryLogPositionManager();
MetaLogPositionManager failbackLogPositionManager = new MetaLogPositionManager();
failbackLogPositionManager.setMetaManager(metaManager);
logPositionManager = new FailbackLogPositionManager();
((FailbackLogPositionManager) logPositionManager).setPrimary(primaryLogPositionManager);
((FailbackLogPositionManager) logPositionManager).setFailback(failbackLogPositionManager);
} else {
throw new CanalException("unsupport indexMode for " + indexMode);
}
logger.info("init logPositionManager end! \n\t load CanalLogPositionManager:{}", logPositionManager.getClass()
.getName());
return logPositionManager;
}
protected void startEventParserInternal(CanalEventParser eventParser, boolean isGroup) {
if (eventParser instanceof AbstractEventParser) {
AbstractEventParser abstractEventParser = (AbstractEventParser) eventParser;
abstractEventParser.setAlarmHandler(getAlarmHandler());
}
super.startEventParserInternal(eventParser, isGroup);
}
private int getGroupSize() {
List<List<DataSourcing>> groupDbAddresses = parameters.getGroupDbAddresses();
if (!CollectionUtils.isEmpty(groupDbAddresses)) {
return groupDbAddresses.get(0).size();
} else {
// 可能是基于tddl的启动
return 1;
}
}
private synchronized ZkClientx getZkclientx() {
// 做一下排序,保证相同的机器只使用同一个链接
List<String> zkClusters = new ArrayList<String>(parameters.getZkClusters());
Collections.sort(zkClusters);
return ZkClientx.getZkClient(StringUtils.join(zkClusters, ";"));
}
// =====================================
public String getDestination() {
return destination;
}
public CanalMetaManager getMetaManager() {
return metaManager;
}
public CanalEventStore<Event> getEventStore() {
return eventStore;
}
public CanalEventParser getEventParser() {
return eventParser;
}
public CanalEventSink<List<Entry>> getEventSink() {
return eventSink;
}
public CanalAlarmHandler getAlarmHandler() {
return alarmHandler;
}
public void setAlarmHandler(CanalAlarmHandler alarmHandler) {
this.alarmHandler = alarmHandler;
}
}
| yonglehou/canal | instance/manager/src/main/java/com/alibaba/otter/canal/instance/manager/CanalInstanceWithManager.java | Java | apache-2.0 | 25,518 |
/*******************************************************************************
* 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.sling.scripting.sightly.impl.engine.runtime;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.adapter.Adaptable;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.scripting.sightly.Record;
import org.apache.sling.scripting.sightly.render.AbstractRuntimeObjectModel;
public class SlingRuntimeObjectModel extends AbstractRuntimeObjectModel {
protected Object getProperty(Object target, Object propertyObj) {
String property = toString(propertyObj);
if (StringUtils.isEmpty(property)) {
throw new IllegalArgumentException("Invalid property name");
}
if (target == null) {
return null;
}
Object result = null;
if (target instanceof Map) {
result = getMapProperty((Map) target, property);
}
if (result == null && target instanceof Record) {
result = ((Record) target).getProperty(property);
}
if (result == null) {
result = getObjectProperty(target, property);
}
if (result == null && target instanceof Adaptable) {
ValueMap valueMap = ((Adaptable) target).adaptTo(ValueMap.class);
if (valueMap != null) {
result = valueMap.get(property);
}
}
return result;
}
}
| Nimco/sling | bundles/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/runtime/SlingRuntimeObjectModel.java | Java | apache-2.0 | 2,349 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.lang.xpath.xslt.psi.impl;
import com.intellij.psi.xml.XmlTag;
import org.intellij.lang.xpath.psi.XPathExpression;
import org.intellij.lang.xpath.xslt.psi.XsltApplyTemplates;
import org.intellij.lang.xpath.xslt.util.QNameUtil;
import org.intellij.lang.xpath.xslt.util.XsltCodeInsightUtil;
import org.jetbrains.annotations.Nullable;
import javax.xml.namespace.QName;
public class XsltApplyTemplatesImpl extends XsltTemplateInvocationBase implements XsltApplyTemplates {
protected XsltApplyTemplatesImpl(XmlTag target) {
super(target);
}
@Override
public String toString() {
return "XsltApplyTemplates[" + getSelect() + "]";
}
@Override
@Nullable
public XPathExpression getSelect() {
return XsltCodeInsightUtil.getXPathExpression(this, "select");
}
@Override
public QName getMode() {
final String mode = getTag().getAttributeValue("mode");
return mode != null ? QNameUtil.createQName(mode, getTag()) : null;
}
} | siosio/intellij-community | plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/psi/impl/XsltApplyTemplatesImpl.java | Java | apache-2.0 | 1,162 |
cask "vu" do
version "1.2,6,1523016199"
sha256 "a51884117a8e33339429a93a84c70eb82db46dc50ebe827ab7b7c9a0c6ced313"
url "https://dl.devmate.com/com.boriskarulin.vu/#{version.csv.second}/#{version.csv.third}/vu-#{version.csv.second}.dmg",
verified: "dl.devmate.com/com.boriskarulin.vu/"
name "vu"
desc "Instagram client"
homepage "https://datastills.com/vu/"
livecheck do
url "https://updates.devmate.com/com.boriskarulin.vu.xml"
strategy :sparkle do |item|
match = item.url.match(%r{/(\d+)/vu-(\d+(?:\.\d+)*)\.dmg}i)
next if match.blank?
"#{item.short_version},#{item.version},#{match[1]}"
end
end
depends_on macos: ">= :sierra"
app "vu.app"
end
| nrlquaker/homebrew-cask | Casks/vu.rb | Ruby | bsd-2-clause | 705 |
# -*- coding: utf-8 -*-
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Mathieu Blondel <mathieu@mblondel.org>
# Robert Layton <robertlayton@gmail.com>
# Andreas Mueller <amueller@ais.uni-bonn.de>
# Philippe Gervais <philippe.gervais@inria.fr>
# Lars Buitinck <larsmans@gmail.com>
# Joel Nothman <joel.nothman@gmail.com>
# License: BSD 3 clause
import itertools
import numpy as np
from scipy.spatial import distance
from scipy.sparse import csr_matrix
from scipy.sparse import issparse
from ..utils import check_array
from ..utils import gen_even_slices
from ..utils import gen_batches
from ..utils.fixes import partial
from ..utils.extmath import row_norms, safe_sparse_dot
from ..preprocessing import normalize
from ..externals.joblib import Parallel
from ..externals.joblib import delayed
from ..externals.joblib.parallel import cpu_count
from .pairwise_fast import _chi2_kernel_fast, _sparse_manhattan
# Utility Functions
def _return_float_dtype(X, Y):
"""
1. If dtype of X and Y is float32, then dtype float32 is returned.
2. Else dtype float is returned.
"""
if not issparse(X) and not isinstance(X, np.ndarray):
X = np.asarray(X)
if Y is None:
Y_dtype = X.dtype
elif not issparse(Y) and not isinstance(Y, np.ndarray):
Y = np.asarray(Y)
Y_dtype = Y.dtype
else:
Y_dtype = Y.dtype
if X.dtype == Y_dtype == np.float32:
dtype = np.float32
else:
dtype = np.float
return X, Y, dtype
def check_pairwise_arrays(X, Y, precomputed=False):
""" Set X and Y appropriately and checks inputs
If Y is None, it is set as a pointer to X (i.e. not a copy).
If Y is given, this does not happen.
All distance metrics should use this function first to assert that the
given parameters are correct and safe to use.
Specifically, this function first ensures that both X and Y are arrays,
then checks that they are at least two dimensional while ensuring that
their elements are floats. Finally, the function checks that the size
of the second dimension of the two arrays is equal, or the equivalent
check for a precomputed distance matrix.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
precomputed : bool
True if X is to be treated as precomputed distances to the samples in
Y.
Returns
-------
safe_X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
An array equal to X, guaranteed to be a numpy array.
safe_Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
An array equal to Y if Y was not None, guaranteed to be a numpy array.
If Y was None, safe_Y will be a pointer to X.
"""
X, Y, dtype = _return_float_dtype(X, Y)
if Y is X or Y is None:
X = Y = check_array(X, accept_sparse='csr', dtype=dtype)
else:
X = check_array(X, accept_sparse='csr', dtype=dtype)
Y = check_array(Y, accept_sparse='csr', dtype=dtype)
if precomputed:
if X.shape[1] != Y.shape[0]:
raise ValueError("Precomputed metric requires shape "
"(n_queries, n_indexed). Got (%d, %d) "
"for %d indexed." %
(X.shape[0], X.shape[1], Y.shape[0]))
elif X.shape[1] != Y.shape[1]:
raise ValueError("Incompatible dimension for X and Y matrices: "
"X.shape[1] == %d while Y.shape[1] == %d" % (
X.shape[1], Y.shape[1]))
return X, Y
def check_paired_arrays(X, Y):
""" Set X and Y appropriately and checks inputs for paired distances
All paired distance metrics should use this function first to assert that
the given parameters are correct and safe to use.
Specifically, this function first ensures that both X and Y are arrays,
then checks that they are at least two dimensional while ensuring that
their elements are floats. Finally, the function checks that the size
of the dimensions of the two arrays are equal.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
Returns
-------
safe_X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
An array equal to X, guaranteed to be a numpy array.
safe_Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
An array equal to Y if Y was not None, guaranteed to be a numpy array.
If Y was None, safe_Y will be a pointer to X.
"""
X, Y = check_pairwise_arrays(X, Y)
if X.shape != Y.shape:
raise ValueError("X and Y should be of same shape. They were "
"respectively %r and %r long." % (X.shape, Y.shape))
return X, Y
# Pairwise distances
def euclidean_distances(X, Y=None, Y_norm_squared=None, squared=False,
X_norm_squared=None):
"""
Considering the rows of X (and Y=X) as vectors, compute the
distance matrix between each pair of vectors.
For efficiency reasons, the euclidean distance between a pair of row
vector x and y is computed as::
dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y))
This formulation has two advantages over other ways of computing distances.
First, it is computationally efficient when dealing with sparse data.
Second, if one argument varies but the other remains unchanged, then
`dot(x, x)` and/or `dot(y, y)` can be pre-computed.
However, this is not the most precise way of doing this computation, and
the distance matrix returned by this function may not be exactly
symmetric as required by, e.g., ``scipy.spatial.distance`` functions.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples_1, n_features)
Y : {array-like, sparse matrix}, shape (n_samples_2, n_features)
Y_norm_squared : array-like, shape (n_samples_2, ), optional
Pre-computed dot-products of vectors in Y (e.g.,
``(Y**2).sum(axis=1)``)
squared : boolean, optional
Return squared Euclidean distances.
X_norm_squared : array-like, shape = [n_samples_1], optional
Pre-computed dot-products of vectors in X (e.g.,
``(X**2).sum(axis=1)``)
Returns
-------
distances : {array, sparse matrix}, shape (n_samples_1, n_samples_2)
Examples
--------
>>> from sklearn.metrics.pairwise import euclidean_distances
>>> X = [[0, 1], [1, 1]]
>>> # distance between rows of X
>>> euclidean_distances(X, X)
array([[ 0., 1.],
[ 1., 0.]])
>>> # get distance to origin
>>> euclidean_distances(X, [[0, 0]])
array([[ 1. ],
[ 1.41421356]])
See also
--------
paired_distances : distances betweens pairs of elements of X and Y.
"""
X, Y = check_pairwise_arrays(X, Y)
if X_norm_squared is not None:
XX = check_array(X_norm_squared)
if XX.shape == (1, X.shape[0]):
XX = XX.T
elif XX.shape != (X.shape[0], 1):
raise ValueError(
"Incompatible dimensions for X and X_norm_squared")
else:
XX = row_norms(X, squared=True)[:, np.newaxis]
if X is Y: # shortcut in the common case euclidean_distances(X, X)
YY = XX.T
elif Y_norm_squared is not None:
YY = check_array(Y_norm_squared)
if YY.shape != (1, Y.shape[0]):
raise ValueError(
"Incompatible dimensions for Y and Y_norm_squared")
else:
YY = row_norms(Y, squared=True)[np.newaxis, :]
distances = safe_sparse_dot(X, Y.T, dense_output=True)
distances *= -2
distances += XX
distances += YY
np.maximum(distances, 0, out=distances)
if X is Y:
# Ensure that distances between vectors and themselves are set to 0.0.
# This may not be the case due to floating point rounding errors.
distances.flat[::distances.shape[0] + 1] = 0.0
return distances if squared else np.sqrt(distances, out=distances)
def pairwise_distances_argmin_min(X, Y, axis=1, metric="euclidean",
batch_size=500, metric_kwargs=None):
"""Compute minimum distances between one point and a set of points.
This function computes for each row in X, the index of the row of Y which
is closest (according to the specified distance). The minimal distances are
also returned.
This is mostly equivalent to calling:
(pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis),
pairwise_distances(X, Y=Y, metric=metric).min(axis=axis))
but uses much less memory, and is faster for large arrays.
Parameters
----------
X, Y : {array-like, sparse matrix}
Arrays containing points. Respective shapes (n_samples1, n_features)
and (n_samples2, n_features)
batch_size : integer
To reduce memory consumption over the naive solution, data are
processed in batches, comprising batch_size rows of X and
batch_size rows of Y. The default value is quite conservative, but
can be changed for fine-tuning. The larger the number, the larger the
memory usage.
metric : string or callable, default 'euclidean'
metric to use for distance computation. Any metric from scikit-learn
or scipy.spatial.distance can be used.
If metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays as input and return one value indicating the
distance between them. This works for Scipy's metrics, but is less
efficient than passing the metric name as a string.
Distance matrices are not supported.
Valid values for metric are:
- from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
'manhattan']
- from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath',
'sqeuclidean', 'yule']
See the documentation for scipy.spatial.distance for details on these
metrics.
metric_kwargs : dict, optional
Keyword arguments to pass to specified metric function.
axis : int, optional, default 1
Axis along which the argmin and distances are to be computed.
Returns
-------
argmin : numpy.ndarray
Y[argmin[i], :] is the row in Y that is closest to X[i, :].
distances : numpy.ndarray
distances[i] is the distance between the i-th row in X and the
argmin[i]-th row in Y.
See also
--------
sklearn.metrics.pairwise_distances
sklearn.metrics.pairwise_distances_argmin
"""
dist_func = None
if metric in PAIRWISE_DISTANCE_FUNCTIONS:
dist_func = PAIRWISE_DISTANCE_FUNCTIONS[metric]
elif not callable(metric) and not isinstance(metric, str):
raise ValueError("'metric' must be a string or a callable")
X, Y = check_pairwise_arrays(X, Y)
if metric_kwargs is None:
metric_kwargs = {}
if axis == 0:
X, Y = Y, X
# Allocate output arrays
indices = np.empty(X.shape[0], dtype=np.intp)
values = np.empty(X.shape[0])
values.fill(np.infty)
for chunk_x in gen_batches(X.shape[0], batch_size):
X_chunk = X[chunk_x, :]
for chunk_y in gen_batches(Y.shape[0], batch_size):
Y_chunk = Y[chunk_y, :]
if dist_func is not None:
if metric == 'euclidean': # special case, for speed
d_chunk = safe_sparse_dot(X_chunk, Y_chunk.T,
dense_output=True)
d_chunk *= -2
d_chunk += row_norms(X_chunk, squared=True)[:, np.newaxis]
d_chunk += row_norms(Y_chunk, squared=True)[np.newaxis, :]
np.maximum(d_chunk, 0, d_chunk)
else:
d_chunk = dist_func(X_chunk, Y_chunk, **metric_kwargs)
else:
d_chunk = pairwise_distances(X_chunk, Y_chunk,
metric=metric, **metric_kwargs)
# Update indices and minimum values using chunk
min_indices = d_chunk.argmin(axis=1)
min_values = d_chunk[np.arange(chunk_x.stop - chunk_x.start),
min_indices]
flags = values[chunk_x] > min_values
indices[chunk_x][flags] = min_indices[flags] + chunk_y.start
values[chunk_x][flags] = min_values[flags]
if metric == "euclidean" and not metric_kwargs.get("squared", False):
np.sqrt(values, values)
return indices, values
def pairwise_distances_argmin(X, Y, axis=1, metric="euclidean",
batch_size=500, metric_kwargs=None):
"""Compute minimum distances between one point and a set of points.
This function computes for each row in X, the index of the row of Y which
is closest (according to the specified distance).
This is mostly equivalent to calling:
pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis)
but uses much less memory, and is faster for large arrays.
This function works with dense 2D arrays only.
Parameters
----------
X : array-like
Arrays containing points. Respective shapes (n_samples1, n_features)
and (n_samples2, n_features)
Y : array-like
Arrays containing points. Respective shapes (n_samples1, n_features)
and (n_samples2, n_features)
batch_size : integer
To reduce memory consumption over the naive solution, data are
processed in batches, comprising batch_size rows of X and
batch_size rows of Y. The default value is quite conservative, but
can be changed for fine-tuning. The larger the number, the larger the
memory usage.
metric : string or callable
metric to use for distance computation. Any metric from scikit-learn
or scipy.spatial.distance can be used.
If metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays as input and return one value indicating the
distance between them. This works for Scipy's metrics, but is less
efficient than passing the metric name as a string.
Distance matrices are not supported.
Valid values for metric are:
- from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
'manhattan']
- from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath',
'sqeuclidean', 'yule']
See the documentation for scipy.spatial.distance for details on these
metrics.
metric_kwargs : dict
keyword arguments to pass to specified metric function.
axis : int, optional, default 1
Axis along which the argmin and distances are to be computed.
Returns
-------
argmin : numpy.ndarray
Y[argmin[i], :] is the row in Y that is closest to X[i, :].
See also
--------
sklearn.metrics.pairwise_distances
sklearn.metrics.pairwise_distances_argmin_min
"""
if metric_kwargs is None:
metric_kwargs = {}
return pairwise_distances_argmin_min(X, Y, axis, metric, batch_size,
metric_kwargs)[0]
def manhattan_distances(X, Y=None, sum_over_features=True,
size_threshold=5e8):
""" Compute the L1 distances between the vectors in X and Y.
With sum_over_features equal to False it returns the componentwise
distances.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array_like
An array with shape (n_samples_X, n_features).
Y : array_like, optional
An array with shape (n_samples_Y, n_features).
sum_over_features : bool, default=True
If True the function returns the pairwise distance matrix
else it returns the componentwise L1 pairwise-distances.
Not supported for sparse matrix inputs.
size_threshold : int, default=5e8
Unused parameter.
Returns
-------
D : array
If sum_over_features is False shape is
(n_samples_X * n_samples_Y, n_features) and D contains the
componentwise L1 pairwise-distances (ie. absolute difference),
else shape is (n_samples_X, n_samples_Y) and D contains
the pairwise L1 distances.
Examples
--------
>>> from sklearn.metrics.pairwise import manhattan_distances
>>> manhattan_distances(3, 3)#doctest:+ELLIPSIS
array([[ 0.]])
>>> manhattan_distances(3, 2)#doctest:+ELLIPSIS
array([[ 1.]])
>>> manhattan_distances(2, 3)#doctest:+ELLIPSIS
array([[ 1.]])
>>> manhattan_distances([[1, 2], [3, 4]],\
[[1, 2], [0, 3]])#doctest:+ELLIPSIS
array([[ 0., 2.],
[ 4., 4.]])
>>> import numpy as np
>>> X = np.ones((1, 2))
>>> y = 2 * np.ones((2, 2))
>>> manhattan_distances(X, y, sum_over_features=False)#doctest:+ELLIPSIS
array([[ 1., 1.],
[ 1., 1.]]...)
"""
X, Y = check_pairwise_arrays(X, Y)
if issparse(X) or issparse(Y):
if not sum_over_features:
raise TypeError("sum_over_features=%r not supported"
" for sparse matrices" % sum_over_features)
X = csr_matrix(X, copy=False)
Y = csr_matrix(Y, copy=False)
D = np.zeros((X.shape[0], Y.shape[0]))
_sparse_manhattan(X.data, X.indices, X.indptr,
Y.data, Y.indices, Y.indptr,
X.shape[1], D)
return D
if sum_over_features:
return distance.cdist(X, Y, 'cityblock')
D = X[:, np.newaxis, :] - Y[np.newaxis, :, :]
D = np.abs(D, D)
return D.reshape((-1, X.shape[1]))
def cosine_distances(X, Y=None):
"""
Compute cosine distance between samples in X and Y.
Cosine distance is defined as 1.0 minus the cosine similarity.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array_like, sparse matrix
with shape (n_samples_X, n_features).
Y : array_like, sparse matrix (optional)
with shape (n_samples_Y, n_features).
Returns
-------
distance matrix : array
An array with shape (n_samples_X, n_samples_Y).
See also
--------
sklearn.metrics.pairwise.cosine_similarity
scipy.spatial.distance.cosine (dense matrices only)
"""
# 1.0 - cosine_similarity(X, Y) without copy
S = cosine_similarity(X, Y)
S *= -1
S += 1
return S
# Paired distances
def paired_euclidean_distances(X, Y):
"""
Computes the paired euclidean distances between X and Y
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Y : array-like, shape (n_samples, n_features)
Returns
-------
distances : ndarray (n_samples, )
"""
X, Y = check_paired_arrays(X, Y)
return row_norms(X - Y)
def paired_manhattan_distances(X, Y):
"""Compute the L1 distances between the vectors in X and Y.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Y : array-like, shape (n_samples, n_features)
Returns
-------
distances : ndarray (n_samples, )
"""
X, Y = check_paired_arrays(X, Y)
diff = X - Y
if issparse(diff):
diff.data = np.abs(diff.data)
return np.squeeze(np.array(diff.sum(axis=1)))
else:
return np.abs(diff).sum(axis=-1)
def paired_cosine_distances(X, Y):
"""
Computes the paired cosine distances between X and Y
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Y : array-like, shape (n_samples, n_features)
Returns
-------
distances : ndarray, shape (n_samples, )
Notes
------
The cosine distance is equivalent to the half the squared
euclidean distance if each sample is normalized to unit norm
"""
X, Y = check_paired_arrays(X, Y)
return .5 * row_norms(normalize(X) - normalize(Y), squared=True)
PAIRED_DISTANCES = {
'cosine': paired_cosine_distances,
'euclidean': paired_euclidean_distances,
'l2': paired_euclidean_distances,
'l1': paired_manhattan_distances,
'manhattan': paired_manhattan_distances,
'cityblock': paired_manhattan_distances}
def paired_distances(X, Y, metric="euclidean", **kwds):
"""
Computes the paired distances between X and Y.
Computes the distances between (X[0], Y[0]), (X[1], Y[1]), etc...
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : ndarray (n_samples, n_features)
Array 1 for distance computation.
Y : ndarray (n_samples, n_features)
Array 2 for distance computation.
metric : string or callable
The metric to use when calculating distance between instances in a
feature array. If metric is a string, it must be one of the options
specified in PAIRED_DISTANCES, including "euclidean",
"manhattan", or "cosine".
Alternatively, if metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays from X as input and return a value indicating
the distance between them.
Returns
-------
distances : ndarray (n_samples, )
Examples
--------
>>> from sklearn.metrics.pairwise import paired_distances
>>> X = [[0, 1], [1, 1]]
>>> Y = [[0, 1], [2, 1]]
>>> paired_distances(X, Y)
array([ 0., 1.])
See also
--------
pairwise_distances : pairwise distances.
"""
if metric in PAIRED_DISTANCES:
func = PAIRED_DISTANCES[metric]
return func(X, Y)
elif callable(metric):
# Check the matrix first (it is usually done by the metric)
X, Y = check_paired_arrays(X, Y)
distances = np.zeros(len(X))
for i in range(len(X)):
distances[i] = metric(X[i], Y[i])
return distances
else:
raise ValueError('Unknown distance %s' % metric)
# Kernels
def linear_kernel(X, Y=None):
"""
Compute the linear kernel between X and Y.
Read more in the :ref:`User Guide <linear_kernel>`.
Parameters
----------
X : array of shape (n_samples_1, n_features)
Y : array of shape (n_samples_2, n_features)
Returns
-------
Gram matrix : array of shape (n_samples_1, n_samples_2)
"""
X, Y = check_pairwise_arrays(X, Y)
return safe_sparse_dot(X, Y.T, dense_output=True)
def polynomial_kernel(X, Y=None, degree=3, gamma=None, coef0=1):
"""
Compute the polynomial kernel between X and Y::
K(X, Y) = (gamma <X, Y> + coef0)^degree
Read more in the :ref:`User Guide <polynomial_kernel>`.
Parameters
----------
X : ndarray of shape (n_samples_1, n_features)
Y : ndarray of shape (n_samples_2, n_features)
coef0 : int, default 1
degree : int, default 3
Returns
-------
Gram matrix : array of shape (n_samples_1, n_samples_2)
"""
X, Y = check_pairwise_arrays(X, Y)
if gamma is None:
gamma = 1.0 / X.shape[1]
K = safe_sparse_dot(X, Y.T, dense_output=True)
K *= gamma
K += coef0
K **= degree
return K
def sigmoid_kernel(X, Y=None, gamma=None, coef0=1):
"""
Compute the sigmoid kernel between X and Y::
K(X, Y) = tanh(gamma <X, Y> + coef0)
Read more in the :ref:`User Guide <sigmoid_kernel>`.
Parameters
----------
X : ndarray of shape (n_samples_1, n_features)
Y : ndarray of shape (n_samples_2, n_features)
coef0 : int, default 1
Returns
-------
Gram matrix: array of shape (n_samples_1, n_samples_2)
"""
X, Y = check_pairwise_arrays(X, Y)
if gamma is None:
gamma = 1.0 / X.shape[1]
K = safe_sparse_dot(X, Y.T, dense_output=True)
K *= gamma
K += coef0
np.tanh(K, K) # compute tanh in-place
return K
def rbf_kernel(X, Y=None, gamma=None):
"""
Compute the rbf (gaussian) kernel between X and Y::
K(x, y) = exp(-gamma ||x-y||^2)
for each pair of rows x in X and y in Y.
Read more in the :ref:`User Guide <rbf_kernel>`.
Parameters
----------
X : array of shape (n_samples_X, n_features)
Y : array of shape (n_samples_Y, n_features)
gamma : float
Returns
-------
kernel_matrix : array of shape (n_samples_X, n_samples_Y)
"""
X, Y = check_pairwise_arrays(X, Y)
if gamma is None:
gamma = 1.0 / X.shape[1]
K = euclidean_distances(X, Y, squared=True)
K *= -gamma
np.exp(K, K) # exponentiate K in-place
return K
def cosine_similarity(X, Y=None, dense_output=True):
"""Compute cosine similarity between samples in X and Y.
Cosine similarity, or the cosine kernel, computes similarity as the
normalized dot product of X and Y:
K(X, Y) = <X, Y> / (||X||*||Y||)
On L2-normalized data, this function is equivalent to linear_kernel.
Read more in the :ref:`User Guide <cosine_similarity>`.
Parameters
----------
X : ndarray or sparse array, shape: (n_samples_X, n_features)
Input data.
Y : ndarray or sparse array, shape: (n_samples_Y, n_features)
Input data. If ``None``, the output will be the pairwise
similarities between all samples in ``X``.
dense_output : boolean (optional), default True
Whether to return dense output even when the input is sparse. If
``False``, the output is sparse if both input arrays are sparse.
Returns
-------
kernel matrix : array
An array with shape (n_samples_X, n_samples_Y).
"""
# to avoid recursive import
X, Y = check_pairwise_arrays(X, Y)
X_normalized = normalize(X, copy=True)
if X is Y:
Y_normalized = X_normalized
else:
Y_normalized = normalize(Y, copy=True)
K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output)
return K
def additive_chi2_kernel(X, Y=None):
"""Computes the additive chi-squared kernel between observations in X and Y
The chi-squared kernel is computed between each pair of rows in X and Y. X
and Y have to be non-negative. This kernel is most commonly applied to
histograms.
The chi-squared kernel is given by::
k(x, y) = -Sum [(x - y)^2 / (x + y)]
It can be interpreted as a weighted difference per entry.
Read more in the :ref:`User Guide <chi2_kernel>`.
Notes
-----
As the negative of a distance, this kernel is only conditionally positive
definite.
Parameters
----------
X : array-like of shape (n_samples_X, n_features)
Y : array of shape (n_samples_Y, n_features)
Returns
-------
kernel_matrix : array of shape (n_samples_X, n_samples_Y)
References
----------
* Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C.
Local features and kernels for classification of texture and object
categories: A comprehensive study
International Journal of Computer Vision 2007
http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf
See also
--------
chi2_kernel : The exponentiated version of the kernel, which is usually
preferable.
sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation
to this kernel.
"""
if issparse(X) or issparse(Y):
raise ValueError("additive_chi2 does not support sparse matrices.")
X, Y = check_pairwise_arrays(X, Y)
if (X < 0).any():
raise ValueError("X contains negative values.")
if Y is not X and (Y < 0).any():
raise ValueError("Y contains negative values.")
result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype)
_chi2_kernel_fast(X, Y, result)
return result
def chi2_kernel(X, Y=None, gamma=1.):
"""Computes the exponential chi-squared kernel X and Y.
The chi-squared kernel is computed between each pair of rows in X and Y. X
and Y have to be non-negative. This kernel is most commonly applied to
histograms.
The chi-squared kernel is given by::
k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)])
It can be interpreted as a weighted difference per entry.
Read more in the :ref:`User Guide <chi2_kernel>`.
Parameters
----------
X : array-like of shape (n_samples_X, n_features)
Y : array of shape (n_samples_Y, n_features)
gamma : float, default=1.
Scaling parameter of the chi2 kernel.
Returns
-------
kernel_matrix : array of shape (n_samples_X, n_samples_Y)
References
----------
* Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C.
Local features and kernels for classification of texture and object
categories: A comprehensive study
International Journal of Computer Vision 2007
http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf
See also
--------
additive_chi2_kernel : The additive version of this kernel
sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation
to the additive version of this kernel.
"""
K = additive_chi2_kernel(X, Y)
K *= gamma
return np.exp(K, K)
# Helper functions - distance
PAIRWISE_DISTANCE_FUNCTIONS = {
# If updating this dictionary, update the doc in both distance_metrics()
# and also in pairwise_distances()!
'cityblock': manhattan_distances,
'cosine': cosine_distances,
'euclidean': euclidean_distances,
'l2': euclidean_distances,
'l1': manhattan_distances,
'manhattan': manhattan_distances,
'precomputed': None, # HACK: precomputed is always allowed, never called
}
def distance_metrics():
"""Valid metrics for pairwise_distances.
This function simply returns the valid pairwise distance metrics.
It exists to allow for a description of the mapping for
each of the valid strings.
The valid distance metrics, and the function they map to, are:
============ ====================================
metric Function
============ ====================================
'cityblock' metrics.pairwise.manhattan_distances
'cosine' metrics.pairwise.cosine_distances
'euclidean' metrics.pairwise.euclidean_distances
'l1' metrics.pairwise.manhattan_distances
'l2' metrics.pairwise.euclidean_distances
'manhattan' metrics.pairwise.manhattan_distances
============ ====================================
Read more in the :ref:`User Guide <metrics>`.
"""
return PAIRWISE_DISTANCE_FUNCTIONS
def _parallel_pairwise(X, Y, func, n_jobs, **kwds):
"""Break the pairwise matrix in n_jobs even slices
and compute them in parallel"""
if n_jobs < 0:
n_jobs = max(cpu_count() + 1 + n_jobs, 1)
if Y is None:
Y = X
if n_jobs == 1:
# Special case to avoid picklability checks in delayed
return func(X, Y, **kwds)
# TODO: in some cases, backend='threading' may be appropriate
fd = delayed(func)
ret = Parallel(n_jobs=n_jobs, verbose=0)(
fd(X, Y[s], **kwds)
for s in gen_even_slices(Y.shape[0], n_jobs))
return np.hstack(ret)
def _pairwise_callable(X, Y, metric, **kwds):
"""Handle the callable case for pairwise_{distances,kernels}
"""
X, Y = check_pairwise_arrays(X, Y)
if X is Y:
# Only calculate metric for upper triangle
out = np.zeros((X.shape[0], Y.shape[0]), dtype='float')
iterator = itertools.combinations(range(X.shape[0]), 2)
for i, j in iterator:
out[i, j] = metric(X[i], Y[j], **kwds)
# Make symmetric
# NB: out += out.T will produce incorrect results
out = out + out.T
# Calculate diagonal
# NB: nonzero diagonals are allowed for both metrics and kernels
for i in range(X.shape[0]):
x = X[i]
out[i, i] = metric(x, x, **kwds)
else:
# Calculate all cells
out = np.empty((X.shape[0], Y.shape[0]), dtype='float')
iterator = itertools.product(range(X.shape[0]), range(Y.shape[0]))
for i, j in iterator:
out[i, j] = metric(X[i], Y[j], **kwds)
return out
_VALID_METRICS = ['euclidean', 'l2', 'l1', 'manhattan', 'cityblock',
'braycurtis', 'canberra', 'chebyshev', 'correlation',
'cosine', 'dice', 'hamming', 'jaccard', 'kulsinski',
'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
'russellrao', 'seuclidean', 'sokalmichener',
'sokalsneath', 'sqeuclidean', 'yule', "wminkowski"]
def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds):
""" Compute the distance matrix from a vector array X and optional Y.
This method takes either a vector array or a distance matrix, and returns
a distance matrix. If the input is a vector array, the distances are
computed. If the input is a distances matrix, it is returned instead.
This method provides a safe way to take a distance matrix as input, while
preserving compatibility with many other algorithms that take a vector
array.
If Y is given (default is None), then the returned matrix is the pairwise
distance between the arrays from both X and Y.
Valid values for metric are:
- From scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
'manhattan']. These metrics support sparse matrix inputs.
- From scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis',
'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',
'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule']
See the documentation for scipy.spatial.distance for details on these
metrics. These metrics do not support sparse matrix inputs.
Note that in the case of 'cityblock', 'cosine' and 'euclidean' (which are
valid scipy.spatial.distance metrics), the scikit-learn implementation
will be used, which is faster and has support for sparse matrices (except
for 'cityblock'). For a verbose description of the metrics from
scikit-learn, see the __doc__ of the sklearn.pairwise.distance_metrics
function.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \
[n_samples_a, n_features] otherwise
Array of pairwise distances between samples, or a feature array.
Y : array [n_samples_b, n_features], optional
An optional second feature array. Only allowed if metric != "precomputed".
metric : string, or callable
The metric to use when calculating distance between instances in a
feature array. If metric is a string, it must be one of the options
allowed by scipy.spatial.distance.pdist for its metric parameter, or
a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS.
If metric is "precomputed", X is assumed to be a distance matrix.
Alternatively, if metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays from X as input and return a value indicating
the distance between them.
n_jobs : int
The number of jobs to use for the computation. This works by breaking
down the pairwise matrix into n_jobs even slices and computing them in
parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
`**kwds` : optional keyword parameters
Any further parameters are passed directly to the distance function.
If using a scipy.spatial.distance metric, the parameters are still
metric dependent. See the scipy docs for usage examples.
Returns
-------
D : array [n_samples_a, n_samples_a] or [n_samples_a, n_samples_b]
A distance matrix D such that D_{i, j} is the distance between the
ith and jth vectors of the given matrix X, if Y is None.
If Y is not None, then D_{i, j} is the distance between the ith array
from X and the jth array from Y.
"""
if (metric not in _VALID_METRICS and
not callable(metric) and metric != "precomputed"):
raise ValueError("Unknown metric %s. "
"Valid metrics are %s, or 'precomputed', or a "
"callable" % (metric, _VALID_METRICS))
if metric == "precomputed":
X, _ = check_pairwise_arrays(X, Y, precomputed=True)
return X
elif metric in PAIRWISE_DISTANCE_FUNCTIONS:
func = PAIRWISE_DISTANCE_FUNCTIONS[metric]
elif callable(metric):
func = partial(_pairwise_callable, metric=metric, **kwds)
else:
if issparse(X) or issparse(Y):
raise TypeError("scipy distance metrics do not"
" support sparse matrices.")
X, Y = check_pairwise_arrays(X, Y)
if n_jobs == 1 and X is Y:
return distance.squareform(distance.pdist(X, metric=metric,
**kwds))
func = partial(distance.cdist, metric=metric, **kwds)
return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
# Helper functions - distance
PAIRWISE_KERNEL_FUNCTIONS = {
# If updating this dictionary, update the doc in both distance_metrics()
# and also in pairwise_distances()!
'additive_chi2': additive_chi2_kernel,
'chi2': chi2_kernel,
'linear': linear_kernel,
'polynomial': polynomial_kernel,
'poly': polynomial_kernel,
'rbf': rbf_kernel,
'sigmoid': sigmoid_kernel,
'cosine': cosine_similarity, }
def kernel_metrics():
""" Valid metrics for pairwise_kernels
This function simply returns the valid pairwise distance metrics.
It exists, however, to allow for a verbose description of the mapping for
each of the valid strings.
The valid distance metrics, and the function they map to, are:
=============== ========================================
metric Function
=============== ========================================
'additive_chi2' sklearn.pairwise.additive_chi2_kernel
'chi2' sklearn.pairwise.chi2_kernel
'linear' sklearn.pairwise.linear_kernel
'poly' sklearn.pairwise.polynomial_kernel
'polynomial' sklearn.pairwise.polynomial_kernel
'rbf' sklearn.pairwise.rbf_kernel
'sigmoid' sklearn.pairwise.sigmoid_kernel
'cosine' sklearn.pairwise.cosine_similarity
=============== ========================================
Read more in the :ref:`User Guide <metrics>`.
"""
return PAIRWISE_KERNEL_FUNCTIONS
KERNEL_PARAMS = {
"additive_chi2": (),
"chi2": (),
"cosine": (),
"exp_chi2": frozenset(["gamma"]),
"linear": (),
"poly": frozenset(["gamma", "degree", "coef0"]),
"polynomial": frozenset(["gamma", "degree", "coef0"]),
"rbf": frozenset(["gamma"]),
"sigmoid": frozenset(["gamma", "coef0"]),
}
def pairwise_kernels(X, Y=None, metric="linear", filter_params=False,
n_jobs=1, **kwds):
"""Compute the kernel between arrays X and optional array Y.
This method takes either a vector array or a kernel matrix, and returns
a kernel matrix. If the input is a vector array, the kernels are
computed. If the input is a kernel matrix, it is returned instead.
This method provides a safe way to take a kernel matrix as input, while
preserving compatibility with many other algorithms that take a vector
array.
If Y is given (default is None), then the returned matrix is the pairwise
kernel between the arrays from both X and Y.
Valid values for metric are::
['rbf', 'sigmoid', 'polynomial', 'poly', 'linear', 'cosine']
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \
[n_samples_a, n_features] otherwise
Array of pairwise kernels between samples, or a feature array.
Y : array [n_samples_b, n_features]
A second feature array only if X has shape [n_samples_a, n_features].
metric : string, or callable
The metric to use when calculating kernel between instances in a
feature array. If metric is a string, it must be one of the metrics
in pairwise.PAIRWISE_KERNEL_FUNCTIONS.
If metric is "precomputed", X is assumed to be a kernel matrix.
Alternatively, if metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays from X as input and return a value indicating
the distance between them.
n_jobs : int
The number of jobs to use for the computation. This works by breaking
down the pairwise matrix into n_jobs even slices and computing them in
parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
filter_params: boolean
Whether to filter invalid parameters or not.
`**kwds` : optional keyword parameters
Any further parameters are passed directly to the kernel function.
Returns
-------
K : array [n_samples_a, n_samples_a] or [n_samples_a, n_samples_b]
A kernel matrix K such that K_{i, j} is the kernel between the
ith and jth vectors of the given matrix X, if Y is None.
If Y is not None, then K_{i, j} is the kernel between the ith array
from X and the jth array from Y.
Notes
-----
If metric is 'precomputed', Y is ignored and X is returned.
"""
if metric == "precomputed":
X, _ = check_pairwise_arrays(X, Y, precomputed=True)
return X
elif metric in PAIRWISE_KERNEL_FUNCTIONS:
if filter_params:
kwds = dict((k, kwds[k]) for k in kwds
if k in KERNEL_PARAMS[metric])
func = PAIRWISE_KERNEL_FUNCTIONS[metric]
elif callable(metric):
func = partial(_pairwise_callable, metric=metric, **kwds)
else:
raise ValueError("Unknown kernel %r" % metric)
return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
| mfjb/scikit-learn | sklearn/metrics/pairwise.py | Python | bsd-3-clause | 44,015 |
// 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;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Xunit;
namespace XDocumentTests.SDMSample
{
public class SDM_Element
{
/// <summary>
/// Validate behavior of XElement simple creation.
/// </summary>
[Fact]
public void CreateElementSimple()
{
const string ElementName = "Element";
XElement element;
// Test the constructor that takes only a name.
element = new XElement(ElementName);
Assert.Equal(ElementName, element.Name.ToString());
Assert.Throws<ArgumentNullException>(() => new XElement((XName)null));
}
/// <summary>
/// Validate behavior of XElement creation with content supplied.
/// </summary>
[Fact]
public void CreateElementWithContent()
{
// Test the constructor that takes a name and some content.
XElement level2Element = new XElement("Level2", "TextValue");
XAttribute attribute = new XAttribute("Attribute", "AttributeValue");
XCData cdata = new XCData("abcdefgh");
string someValue = "text";
XElement element = new XElement("Level1", level2Element, cdata, someValue, attribute);
Assert.Equal("Level1", element.Name.ToString());
Assert.Equal(
new XNode[] { level2Element, cdata, new XText(someValue) },
element.Nodes(),
XNode.EqualityComparer);
Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name));
Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value));
}
/// <summary>
/// Validate behavior of XElement creation with copy constructor.
/// </summary>
[Fact]
public void CreateElementCopy()
{
// With attributes
XElement level2Element = new XElement("Level2", "TextValue");
XAttribute attribute = new XAttribute("Attribute", "AttributeValue");
XCData cdata = new XCData("abcdefgh");
string someValue = "text";
XElement element = new XElement("Level1", level2Element, cdata, someValue, attribute);
XElement elementCopy = new XElement(element);
Assert.Equal("Level1", element.Name.ToString());
Assert.Equal(
new XNode[] { level2Element, cdata, new XText(someValue) },
elementCopy.Nodes(),
XNode.EqualityComparer);
Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name));
Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value));
// Without attributes
element = new XElement("Level1", level2Element, cdata, someValue);
elementCopy = new XElement(element);
Assert.Equal("Level1", element.Name.ToString());
Assert.Equal(
new XNode[] { level2Element, cdata, new XText(someValue) },
elementCopy.Nodes(),
XNode.EqualityComparer);
Assert.Empty(elementCopy.Attributes());
// Hsh codes of equal elements should be equal.
Assert.Equal(XNode.EqualityComparer.GetHashCode(element), XNode.EqualityComparer.GetHashCode(elementCopy));
// Null element is not allowed.
Assert.Throws<ArgumentNullException>(() => new XElement((XElement)null));
}
/// <summary>
/// Validate behavior of XElement creation from an XmlReader.
/// </summary>
[Fact]
public void CreateElementFromReader()
{
string xml = "<Level1 a1='1' a2='2'><Level2><![CDATA[12345678]]>text</Level2></Level1>";
string xml2 = "<Level1 />";
string xml3 = "<x><?xml version='1.0' encoding='utf-8'?></x>";
// With attributes
using (TextReader textReader = new StringReader(xml))
using (XmlReader xmlReader = XmlReader.Create(textReader))
{
xmlReader.Read();
XElement element = (XElement)XNode.ReadFrom(xmlReader);
Assert.Equal("Level1", element.Name.ToString());
Assert.Equal(new[] { "Level2" }, element.Elements().Select(x => x.Name.ToString()));
Assert.Equal(new[] { "a1", "a2" }, element.Attributes().Select(x => x.Name.ToString()));
Assert.Equal(new[] { "1", "2" }, element.Attributes().Select(x => x.Value));
Assert.Equal("12345678text", element.Element("Level2").Value);
}
// Without attributes
using (TextReader textReader = new StringReader(xml2))
using (XmlReader xmlReader = XmlReader.Create(textReader))
{
xmlReader.Read();
var element = (XElement)XNode.ReadFrom(xmlReader);
Assert.Equal("Level1", element.Name.ToString());
Assert.Empty(element.Elements());
Assert.Empty(element.Attributes());
Assert.Empty(element.Value);
}
// XmlReader in start state results in exception
using (TextReader textReader = new StringReader(xml))
using (XmlReader xmlReader = XmlReader.Create(textReader))
{
Assert.Throws<InvalidOperationException>(() => (XElement)XNode.ReadFrom(xmlReader));
}
// XmlReader not on an element results in exception.
using (TextReader textReader = new StringReader(xml))
using (XmlReader xmlReader = XmlReader.Create(textReader))
{
xmlReader.Read();
xmlReader.MoveToAttribute("a1");
Assert.Throws<InvalidOperationException>(() => (XElement)XNode.ReadFrom(xmlReader));
}
// Illegal xml triggers exception that is bubbled out.
using (TextReader textReader = new StringReader(xml3))
using (XmlReader xmlReader = XmlReader.Create(textReader))
{
xmlReader.Read();
Assert.Throws<XmlException>(() => (XElement)XNode.ReadFrom(xmlReader));
}
}
/// <summary>
/// Validate behavior of XElement EmptySequence method.
/// </summary>
[Fact]
public void ElementEmptyElementSequence()
{
Assert.Empty(XElement.EmptySequence);
Assert.Empty(XElement.EmptySequence);
}
/// <summary>
/// Validate behavior of XElement HasAttributes/HasElements properties.
/// </summary>
[Fact]
public void ElementHasAttributesAndElements()
{
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", new XAttribute("a", "value"));
XElement e3 = new XElement("x", new XElement("y"));
XElement e4 = new XElement("x", new XCData("cdata-value"));
Assert.False(e1.HasAttributes);
Assert.True(e2.HasAttributes);
Assert.False(e1.HasElements);
Assert.False(e2.HasElements);
Assert.True(e3.HasElements);
Assert.False(e4.HasElements);
}
/// <summary>
/// Validate behavior of the IsEmpty property.
/// </summary>
[Fact]
public void ElementIsEmpty()
{
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", 10);
XElement e3 = new XElement("x", string.Empty);
Assert.True(e1.IsEmpty);
Assert.False(e2.IsEmpty);
Assert.False(e3.IsEmpty);
}
/// <summary>
/// Validate behavior of the Value property on XElement.
/// </summary>
[Fact]
public void ElementValue()
{
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "value");
XElement e3 = new XElement("x", 100, 200);
XElement e4 = new XElement("x", 100, "value", 200);
XElement e5 = new XElement("x", string.Empty);
XElement e6 = new XElement("x", 1, string.Empty, 5);
XElement e7 = new XElement("x", new XElement("y", "inner1", new XElement("z", "foo"), "inner2"));
XElement e8 = new XElement("x", "text1", new XElement("y", "inner"), "text2");
XElement e9 = new XElement("x", "text1", new XText("abcd"), new XElement("y", "y"));
XElement e10 = new XElement("x", new XComment("my comment"));
Assert.Empty(e1.Value);
Assert.Equal("value", e2.Value);
Assert.Equal("100200", e3.Value);
Assert.Equal("100value200", e4.Value);
Assert.Empty(e5.Value);
Assert.Equal("15", e6.Value);
Assert.Equal("inner1fooinner2", e7.Value);
Assert.Equal("text1innertext2", e8.Value);
Assert.Equal("text1abcdy", e9.Value);
Assert.Empty(e10.Value);
Assert.Throws<ArgumentNullException>(() => e1.Value = null);
e1.Value = string.Empty;
e2.Value = "not-empty";
Assert.Empty(e1.Value);
Assert.Equal("not-empty", e2.Value);
}
/// <summary>
/// Validates the explicit string conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToString()
{
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", string.Empty);
XElement e3 = new XElement("x", "value");
Assert.Null((string)((XElement)null));
Assert.Empty((string)e1);
Assert.Empty((string)e2);
Assert.Equal("value", (string)e3);
}
/// <summary>
/// Validates the explicit boolean conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToBoolean()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (bool)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "true");
XElement e4 = new XElement("x", "false");
XElement e5 = new XElement("x", "0");
XElement e6 = new XElement("x", "1");
Assert.Throws<FormatException>(() => (bool)e1);
Assert.Throws<FormatException>(() => (bool)e2);
Assert.True((bool)e3);
Assert.False((bool)e4);
Assert.False((bool)e5);
Assert.True((bool)e6);
}
/// <summary>
/// Validates the explicit int32 conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToInt32()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (int)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "2147483648");
XElement e4 = new XElement("x", "5");
Assert.Throws<FormatException>(() => (int)e1);
Assert.Throws<FormatException>(() => (int)e2);
Assert.Throws<OverflowException>(() => (int)e3);
Assert.Equal(5, (int)e4);
}
/// <summary>
/// Validates the explicit uint32 conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToUInt32()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (uint)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "4294967296");
XElement e4 = new XElement("x", "5");
Assert.Throws<FormatException>(() => (uint)e1);
Assert.Throws<FormatException>(() => (uint)e2);
Assert.Throws<OverflowException>(() => (uint)e3);
Assert.Equal(5u, (uint)e4);
}
/// <summary>
/// Validates the explicit int64 conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToInt64()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (long)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "18446744073709551616");
XElement e4 = new XElement("x", "5");
Assert.Throws<FormatException>(() => (long)e1);
Assert.Throws<FormatException>(() => (long)e2);
Assert.Throws<OverflowException>(() => (long)e3);
Assert.Equal(5L, (long)e4);
}
/// <summary>
/// Validates the explicit uint64 conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToUInt64()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (ulong)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "18446744073709551616");
XElement e4 = new XElement("x", "5");
Assert.Throws<FormatException>(() => (ulong)e1);
Assert.Throws<FormatException>(() => (ulong)e2);
Assert.Throws<OverflowException>(() => (ulong)e3);
Assert.Equal(5UL, (ulong)e4);
}
/// <summary>
/// Validates the explicit float conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToFloat()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (float)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "5e+500");
XElement e4 = new XElement("x", "5.0");
Assert.Throws<FormatException>(() => (float)e1);
Assert.Throws<FormatException>(() => (float)e2);
Assert.Throws<OverflowException>(() => (float)e3);
Assert.Equal(5.0f, (float)e4);
}
/// <summary>
/// Validates the explicit double conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToDouble()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (double)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "5e+5000");
XElement e4 = new XElement("x", "5.0");
Assert.Throws<FormatException>(() => (double)e1);
Assert.Throws<FormatException>(() => (double)e2);
Assert.Throws<OverflowException>(() => (double)e3);
Assert.Equal(5.0, (double)e4);
}
/// <summary>
/// Validates the explicit decimal conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToDecimal()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (decimal)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "111111111111111111111111111111111111111111111111");
XElement e4 = new XElement("x", "5.0");
Assert.Throws<FormatException>(() => (decimal)e1);
Assert.Throws<FormatException>(() => (decimal)e2);
Assert.Throws<OverflowException>(() => (decimal)e3);
Assert.Equal(5.0m, (decimal)e4);
}
/// <summary>
/// Validates the explicit DateTime conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToDateTime()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (DateTime)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "1968-01-07");
Assert.Throws<FormatException>(() => (DateTime)e1);
Assert.Throws<FormatException>(() => (DateTime)e2);
Assert.Equal(new DateTime(1968, 1, 7), (DateTime)e3);
}
/// <summary>
/// Validates the explicit TimeSpan conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToTimeSpan()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (TimeSpan)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "PT1H2M3S");
Assert.Throws<FormatException>(() => (TimeSpan)e1);
Assert.Throws<FormatException>(() => (TimeSpan)e2);
Assert.Equal(new TimeSpan(1, 2, 3), (TimeSpan)e3);
}
/// <summary>
/// Validates the explicit guid conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToGuid()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (Guid)((XElement)null));
string guid = "2b67e9fb-97ad-4258-8590-8bc8c2d32df5";
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", guid);
Assert.Throws<FormatException>(() => (Guid)e1);
Assert.Throws<FormatException>(() => (Guid)e2);
Assert.Equal(new Guid(guid), (Guid)e3);
}
/// <summary>
/// Validates the explicit conversion operators on XElement
/// for nullable value types.
/// </summary>
[Fact]
public void ElementExplicitToNullables()
{
string guid = "cd8d69ed-fef9-4283-aaf4-216463e4496f";
bool? b = (bool?)new XElement("x", true);
int? i = (int?)new XElement("x", 5);
uint? u = (uint?)new XElement("x", 5);
long? l = (long?)new XElement("x", 5);
ulong? ul = (ulong?)new XElement("x", 5);
float? f = (float?)new XElement("x", 5);
double? n = (double?)new XElement("x", 5);
decimal? d = (decimal?)new XElement("x", 5);
DateTime? dt = (DateTime?)new XElement("x", "1968-01-07");
TimeSpan? ts = (TimeSpan?)new XElement("x", "PT1H2M3S");
Guid? g = (Guid?)new XElement("x", guid);
Assert.True(b.Value);
Assert.Equal(5, i.Value);
Assert.Equal(5u, u.Value);
Assert.Equal(5L, l.Value);
Assert.Equal(5uL, ul.Value);
Assert.Equal(5.0f, f.Value);
Assert.Equal(5.0, n.Value);
Assert.Equal(5.0m, d.Value);
Assert.Equal(new DateTime(1968, 1, 7), dt.Value);
Assert.Equal(new TimeSpan(1, 2, 3), ts.Value);
Assert.Equal(new Guid(guid), g.Value);
b = (bool?)((XElement)null);
i = (int?)((XElement)null);
u = (uint?)((XElement)null);
l = (long?)((XElement)null);
ul = (ulong?)((XElement)null);
f = (float?)((XElement)null);
n = (double?)((XElement)null);
d = (decimal?)((XElement)null);
dt = (DateTime?)((XElement)null);
ts = (TimeSpan?)((XElement)null);
g = (Guid?)((XElement)null);
Assert.Null(b);
Assert.Null(i);
Assert.Null(u);
Assert.Null(l);
Assert.Null(ul);
Assert.Null(f);
Assert.Null(n);
Assert.Null(d);
Assert.Null(dt);
Assert.Null(ts);
Assert.Null(g);
}
/// <summary>
/// Validate enumeration of element ancestors.
/// </summary>
[Fact]
public void ElementAncestors()
{
XElement level3 = new XElement("Level3");
XElement level2 = new XElement("Level2", level3);
XElement level1 = new XElement("Level1", level2);
XElement level0 = new XElement("Level1", level1);
Assert.Equal(new XElement[] { level2, level1, level0 }, level3.Ancestors(), XNode.EqualityComparer);
Assert.Equal(new XElement[] { level1, level0 }, level3.Ancestors("Level1"), XNode.EqualityComparer);
Assert.Empty(level3.Ancestors(null));
Assert.Equal(
new XElement[] { level3, level2, level1, level0 },
level3.AncestorsAndSelf(),
XNode.EqualityComparer);
Assert.Equal(new XElement[] { level3 }, level3.AncestorsAndSelf("Level3"), XNode.EqualityComparer);
Assert.Empty(level3.AncestorsAndSelf(null));
}
/// <summary>
/// Validate enumeration of element descendents.
/// </summary>
[Fact]
public void ElementDescendents()
{
XComment comment = new XComment("comment");
XElement level3 = new XElement("Level3");
XElement level2 = new XElement("Level2", level3);
XElement level1 = new XElement("Level1", level2, comment);
XElement level0 = new XElement("Level1", level1);
Assert.Equal(new XElement[] { level1, level2, level3 }, level1.DescendantsAndSelf(), XNode.EqualityComparer);
Assert.Equal(
new XNode[] { level0, level1, level2, level3, comment },
level0.DescendantNodesAndSelf(),
XNode.EqualityComparer);
Assert.Empty(level0.DescendantsAndSelf(null));
Assert.Equal(new XElement[] { level0, level1 }, level0.DescendantsAndSelf("Level1"), XNode.EqualityComparer);
}
/// <summary>
/// Validate enumeration of element attributes.
/// </summary>
[Fact]
public void ElementAttributes()
{
XElement e1 = new XElement("x");
XElement e2 = new XElement(
"x",
new XAttribute("a1", "1"),
new XAttribute("a2", "2"),
new XAttribute("a3", "3"),
new XAttribute("a4", "4"),
new XAttribute("a5", "5"));
XElement e3 = new XElement(
"x",
new XAttribute("a1", "1"),
new XAttribute("a2", "2"),
new XAttribute("a3", "3"));
Assert.Null(e1.Attribute("foo"));
Assert.Null(e2.Attribute("foo"));
Assert.Equal(e2.Attribute("a3").Name.ToString(), "a3");
Assert.Equal(e2.Attribute("a3").Value, "3");
Assert.Equal(new[] { "a1", "a2", "a3", "a4", "a5" }, e2.Attributes().Select(x => x.Name.ToString()));
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, e2.Attributes().Select(x => x.Value));
Assert.Equal(new[] { "a1" }, e2.Attributes("a1").Select(x => x.Name.ToString()));
Assert.Equal(new[] { "5" }, e2.Attributes("a5").Select(x => x.Value));
Assert.Empty(e2.Attributes(null));
e2.RemoveAttributes();
Assert.Empty(e2.Attributes());
// Removal of non-existent attribute
e1.SetAttributeValue("foo", null);
Assert.Empty(e1.Attributes());
// Add of non-existent attribute
e1.SetAttributeValue("foo", "foo-value");
Assert.Equal(e1.Attribute("foo").Name.ToString(), "foo");
Assert.Equal(e1.Attribute("foo").Value, "foo-value");
// Overwriting of existing attribute
e1.SetAttributeValue("foo", "noo-value");
Assert.Equal(e1.Attribute("foo").Name.ToString(), "foo");
Assert.Equal(e1.Attribute("foo").Value, "noo-value");
// Effective removal of existing attribute
e1.SetAttributeValue("foo", null);
Assert.Empty(e1.Attributes());
// These 3 are in a specific order to exercise the attribute removal code.
e3.SetAttributeValue("a2", null);
Assert.Equal(2, e3.Attributes().Count());
e3.SetAttributeValue("a3", null);
Assert.Equal(1, e3.Attributes().Count());
e3.SetAttributeValue("a1", null);
Assert.Empty(e3.Attributes());
}
/// <summary>
/// Validates remove methods on elements.
/// </summary>
[Fact]
public void ElementRemove()
{
XElement e = new XElement(
"x",
new XAttribute("a1", 1),
new XAttribute("a2", 2),
new XText("abcd"),
10,
new XElement("y", new XComment("comment")),
new XElement("z"));
Assert.Equal(5, e.DescendantNodesAndSelf().Count());
Assert.Equal(2, e.Attributes().Count());
e.RemoveAll();
Assert.Equal(1, e.DescendantNodesAndSelf().Count());
Assert.Empty(e.Attributes());
// Removing all from an already empty one.
e.RemoveAll();
Assert.Equal(1, e.DescendantNodesAndSelf().Count());
Assert.Empty(e.Attributes());
}
/// <summary>
/// Validate enumeration of the SetElementValue method on element/
/// </summary>
[Fact]
public void ElementSetElementValue()
{
XElement e1 = new XElement("x");
// Removal of non-existent element
e1.SetElementValue("foo", null);
Assert.Empty(e1.Elements());
// Add of non-existent element
e1.SetElementValue("foo", "foo-value");
Assert.Equal(new XElement[] { new XElement("foo", "foo-value") }, e1.Elements(), XNode.EqualityComparer);
// Overwriting of existing element
e1.SetElementValue("foo", "noo-value");
Assert.Equal(new XElement[] { new XElement("foo", "noo-value") }, e1.Elements(), XNode.EqualityComparer);
// Effective removal of existing element
e1.SetElementValue("foo", null);
Assert.Empty(e1.Elements());
}
/// <summary>
/// Tests XElement.GetDefaultNamespace().
/// </summary>
[Fact]
public void ElementGetDefaultNamespace()
{
XNamespace ns = XNamespace.Get("http://test");
XElement e = new XElement(ns + "foo");
XNamespace n = e.GetDefaultNamespace();
Assert.NotNull(n);
Assert.Equal(XNamespace.None, n);
e.SetAttributeValue("xmlns", ns);
n = e.GetDefaultNamespace();
Assert.NotNull(n);
Assert.Equal(ns, n);
}
/// <summary>
/// Tests XElement.GetNamespaceOfPrefix().
/// </summary>
[Fact]
public void ElementGetNamespaceOfPrefix()
{
XNamespace ns = XNamespace.Get("http://test");
XElement e = new XElement(ns + "foo");
Assert.Throws<ArgumentNullException>(() => e.GetNamespaceOfPrefix(null));
Assert.Throws<ArgumentException>(() => e.GetNamespaceOfPrefix(string.Empty));
XNamespace n = e.GetNamespaceOfPrefix("xmlns");
Assert.Equal("http://www.w3.org/2000/xmlns/", n.NamespaceName);
n = e.GetNamespaceOfPrefix("xml");
Assert.Equal("http://www.w3.org/XML/1998/namespace", n.NamespaceName);
n = e.GetNamespaceOfPrefix("myns");
Assert.Null(n);
XDocument doc = new XDocument(e);
e.SetAttributeValue("{http://www.w3.org/2000/xmlns/}myns", ns);
n = e.GetNamespaceOfPrefix("myns");
Assert.NotNull(n);
Assert.Equal(ns, n);
}
/// <summary>
/// Tests XElement.GetPrefixOfNamespace().
/// </summary>
[Fact]
public void ElementGetPrefixOfNamespace()
{
Assert.Throws<ArgumentNullException>(() => new XElement("foo").GetPrefixOfNamespace(null));
XNamespace ns = XNamespace.Get("http://test");
XElement e = new XElement(ns + "foo");
string prefix = e.GetPrefixOfNamespace(ns);
Assert.Null(prefix);
prefix = e.GetPrefixOfNamespace(XNamespace.Xmlns);
Assert.Equal("xmlns", prefix);
prefix = e.GetPrefixOfNamespace(XNamespace.Xml);
Assert.Equal("xml", prefix);
XElement parent = new XElement("parent", e);
parent.SetAttributeValue("{http://www.w3.org/2000/xmlns/}myns", ns);
prefix = e.GetPrefixOfNamespace(ns);
Assert.Equal("myns", prefix);
e = XElement.Parse("<foo:element xmlns:foo='http://xxx'></foo:element>");
prefix = e.GetPrefixOfNamespace("http://xxx");
Assert.Equal("foo", prefix);
e =
XElement.Parse(
"<foo:element xmlns:foo='http://foo' xmlns:bar='http://bar'><bar:element /></foo:element>");
prefix = e.GetPrefixOfNamespace("http://foo");
Assert.Equal("foo", prefix);
prefix = e.Element(XName.Get("{http://bar}element")).GetPrefixOfNamespace("http://foo");
Assert.Equal("foo", prefix);
prefix = e.Element(XName.Get("{http://bar}element")).GetPrefixOfNamespace("http://bar");
Assert.Equal("bar", prefix);
}
/// <summary>
/// Tests cases where we're exporting unqualified elements that have xmlns attributes.
/// In this specific scenario we expect XmlExceptions because the element itself
/// is written to an XmlWriter with the empty namespace, and then when the attribute
/// is written to the XmlWriter an exception occurs because the xmlns attribute
/// would cause a retroactive change to the namespace of the already-written element.
/// That is not allowed -- the element must be qualified.
/// </summary>
[Fact]
public void ElementWithXmlnsAttribute()
{
// And with just xmlns local name
XElement element = new XElement("MyElement", new XAttribute("xmlns", "http://tempuri/test"));
Assert.Throws<XmlException>(() => element.ToString());
// A qualified element name works.
element = new XElement("{http://tempuri/test}MyElement", new XAttribute("xmlns", "http://tempuri/test"));
Assert.Equal("<MyElement xmlns=\"http://tempuri/test\" />", element.ToString());
}
/// <summary>
/// Tests the Equals methods on XElement.
/// </summary>
[Fact]
public void ElementEquality()
{
XElement e1 = XElement.Parse("<x/>");
XElement e2 = XElement.Parse("<x/>");
XElement e3 = XElement.Parse("<x a='a'/>");
XElement e4 = XElement.Parse("<x>x</x>");
XElement e5 = XElement.Parse("<y/>");
// Internal method.
Assert.True(XNode.DeepEquals(e1, e1));
Assert.True(XNode.DeepEquals(e1, e2));
Assert.False(XNode.DeepEquals(e1, e3));
Assert.False(XNode.DeepEquals(e1, e4));
Assert.False(XNode.DeepEquals(e1, e5));
// object.Equals override
Assert.True(e1.Equals(e1));
Assert.False(e1.Equals(e2));
Assert.False(e1.Equals(e3));
Assert.False(e1.Equals(e4));
Assert.False(e1.Equals(e5));
Assert.False(e1.Equals(null));
Assert.False(e1.Equals("foo"));
// Hash codes. The most we can say is that identical elements
// should have the same hash codes.
XElement e1a = XElement.Parse("<x/>");
XElement e1b = XElement.Parse("<x/>");
XElement e2a = XElement.Parse("<x>abc</x>");
XElement e2b = XElement.Parse("<x>abc</x>");
XElement e3a = XElement.Parse("<x><y/></x>");
XElement e3b = XElement.Parse("<x><y/></x>");
XElement e4a = XElement.Parse("<x><y/><!--comment--></x>");
XElement e4b = XElement.Parse("<x><!--comment--><y/></x>");
XElement e5a = XElement.Parse("<x a='a'/>");
XElement e5b = XElement.Parse("<x a='a'/>");
int hash = XNode.EqualityComparer.GetHashCode(e1a);
Assert.Equal(XNode.EqualityComparer.GetHashCode(e1b), hash);
hash = XNode.EqualityComparer.GetHashCode(e2a);
Assert.Equal(XNode.EqualityComparer.GetHashCode(e2b), hash);
hash = XNode.EqualityComparer.GetHashCode(e3a);
Assert.Equal(XNode.EqualityComparer.GetHashCode(e3b), hash);
hash = XNode.EqualityComparer.GetHashCode(e4a);
Assert.Equal(XNode.EqualityComparer.GetHashCode(e4b), hash);
hash = XNode.EqualityComparer.GetHashCode(e5a);
Assert.Equal(XNode.EqualityComparer.GetHashCode(e5b), hash);
// Attribute comparison
e1 = XElement.Parse("<x a='a' />");
e2 = XElement.Parse("<x b='b' />");
e3 = XElement.Parse("<x a='a' b='b' />");
e4 = XElement.Parse("<x b='b' a='a' />");
e5 = XElement.Parse("<x a='b' />");
Assert.False(XNode.DeepEquals(e1, e2));
Assert.False(XNode.DeepEquals(e1, e3));
Assert.False(XNode.DeepEquals(e1, e4));
Assert.False(XNode.DeepEquals(e1, e5));
Assert.False(XNode.DeepEquals(e2, e3));
Assert.False(XNode.DeepEquals(e2, e4));
Assert.False(XNode.DeepEquals(e2, e5));
Assert.False(XNode.DeepEquals(e3, e4));
Assert.False(XNode.DeepEquals(e3, e5));
Assert.False(XNode.DeepEquals(e4, e5));
}
/// <summary>
/// Tests that an element appended as a child element during iteration of its new
/// parent's content is returned in iteration.
/// </summary>
[Fact]
public void ElementAppendedChildIsIterated()
{
XElement parent = new XElement("element", new XElement("child1"), new XElement("child2"));
bool b1 = false, b2 = false, b3 = false, b4 = false;
foreach (XElement child in parent.Elements())
{
switch (child.Name.LocalName)
{
case "child1":
b1 = true;
parent.Add(new XElement("extra1"));
break;
case "child2":
b2 = true;
parent.Add(new XElement("extra2"));
break;
case "extra1":
b3 = true;
break;
case "extra2":
b4 = true;
break;
default:
Assert.True(false, string.Format("Uexpected element '{0}'", child.Name));
break;
}
}
Assert.True(b1 || b2 || b3 || b4, "Appended child elements not included in parent iteration");
}
}
}
| dotnet-bot/corefx | src/System.Private.Xml.Linq/tests/SDMSample/SDMElement.cs | C# | mit | 37,040 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Grid\DataExtractor;
use Sylius\Component\Grid\Definition\Field;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
class PropertyAccessDataExtractor implements DataExtractorInterface
{
/**
* @var PropertyAccessorInterface
*/
private $propertyAccessor;
/**
* @param PropertyAccessorInterface $propertyAccessor
*/
public function __construct(PropertyAccessorInterface $propertyAccessor)
{
$this->propertyAccessor = $propertyAccessor;
}
/**
* {@inheritdoc}
*/
public function get(Field $field, $data)
{
return $this->propertyAccessor->getValue($data, $field->getPath());
}
}
| psyray/Sylius | src/Sylius/Component/Grid/DataExtractor/PropertyAccessDataExtractor.php | PHP | mit | 981 |
#!/usr/bin/env ruby
require 'soap/rpc/standaloneServer'
require 'calc2'
class CalcServer2 < SOAP::RPC::StandaloneServer
def on_init
servant = CalcService2.new
add_method(servant, 'set_value', 'newValue')
add_method(servant, 'get_value')
add_method_as(servant, '+', 'add', 'lhs')
add_method_as(servant, '-', 'sub', 'lhs')
add_method_as(servant, '*', 'multi', 'lhs')
add_method_as(servant, '/', 'div', 'lhs')
end
end
if $0 == __FILE__
status = CalcServer2.new('CalcServer', 'http://tempuri.org/calcService', '0.0.0.0', 17171).start
end
| cykod/Webiva | vendor/gems/soap4r-1.5.8/test/soap/calc/server2.rb | Ruby | mit | 571 |
/* eslint no-console: 0 */
var _ = require('underscore');
var files = require('./files.js');
var Console = require('./console.js').Console;
// This file implements "upgraders" --- functions which upgrade a Meteor app to
// a new version. Each upgrader has a name (registered in upgradersByName).
//
// You can test upgraders by running "meteor admin run-upgrader myupgradername".
//
// Upgraders are run automatically by "meteor update". It looks at the
// .meteor/.finished-upgraders file in the app and runs every upgrader listed
// here that is not in that file; then it appends their names to that file.
// Upgraders are run in the order they are listed in upgradersByName below.
//
// Upgraders receive a projectContext that has been fully prepared for build.
var printedNoticeHeaderThisProcess = false;
var maybePrintNoticeHeader = function () {
if (printedNoticeHeaderThisProcess)
return;
console.log();
console.log("-- Notice --");
console.log();
printedNoticeHeaderThisProcess = true;
};
// How to do package-specific notices:
// (a) A notice that occurs if a package is used indirectly or directly.
// if (projectContext.packageMap.getInfo('accounts-ui')) {
// console.log(
// "\n" +
// " Accounts UI has totally changed, yo.");
// }
//
// (b) A notice that occurs if a package is used directly.
// if (projectContext.projectConstraintsFile.getConstraint('accounts-ui')) {
// console.log(
// "\n" +
// " Accounts UI has totally changed, yo.");
// }
var upgradersByName = {
"notices-for-0.9.0": function (projectContext) {
maybePrintNoticeHeader();
var smartJsonPath =
files.pathJoin(projectContext.projectDir, 'smart.json');
if (files.exists(smartJsonPath)) {
// Meteorite apps:
console.log(
"0.9.0: Welcome to the new Meteor package system! You can now add any Meteor\n" +
" package to your app (from more than 1800 packages available on the\n" +
" Meteor Package Server) just by typing 'meteor add <packagename>', no\n" +
" Meteorite required.\n" +
"\n" +
" It looks like you have been using Meteorite with this project. To\n" +
" migrate your project automatically to the new system:\n" +
" (1) upgrade your Meteorite with 'npm install -g meteorite', then\n" +
" (2) run 'mrt migrate-app' inside the project.\n" +
" Having done this, you no longer need 'mrt' and can just use 'meteor'.\n");
} else {
// Non-Meteorite apps:
console.log(
"0.9.0: Welcome to the new Meteor package system! You can now add any Meteor\n" +
" package to your app (from more than 1800 packages available on the\n" +
" Meteor Package Server) just by typing 'meteor add <packagename>'. Check\n" +
" out the available packages by typing 'meteor search <term>' or by\n" +
" visiting atmospherejs.com.\n");
}
console.log();
},
"notices-for-0.9.1": function () {
maybePrintNoticeHeader();
console.log(
"0.9.1: Meteor 0.9.1 includes changes to the Blaze API, in preparation for 1.0.\n" +
" Many previously undocumented APIs are now public and documented. Most\n" +
" changes are backwards compatible, except that templates can no longer\n" +
" be named \"body\" or \"instance\".\n");
console.log();
},
// In 0.9.4, the platforms file contains "server" and "browser" as platforms,
// and before it only had "ios" and/or "android". We auto-fix that in
// PlatformList anyway, but we also need to pull platforms from the old
// cordova-platforms filename.
"0.9.4-platform-file": function (projectContext) {
var oldPlatformsPath =
files.pathJoin(projectContext.projectDir, ".meteor", "cordova-platforms");
try {
var oldPlatformsFile = files.readFile(oldPlatformsPath);
} catch (e) {
// If the file doesn't exist, there's no transition to do.
if (e && e.code === 'ENOENT')
return;
throw e;
}
var oldPlatforms = _.compact(_.map(
files.splitBufferToLines(oldPlatformsFile), files.trimSpaceAndComments));
// This method will automatically add "server" and "browser" and sort, etc.
projectContext.platformList.write(oldPlatforms);
files.unlink(oldPlatformsPath);
},
"notices-for-facebook-graph-api-2": function (projectContext) {
// Note: this will print if the app has facebook as a dependency, whether
// direct or indirect. (This is good, since most apps will be pulling it in
// indirectly via accounts-facebook.)
if (projectContext.packageMap.getInfo('facebook')) {
maybePrintNoticeHeader();
Console.info(
"This version of Meteor now uses version 2.2 of the Facebook API",
"for authentication, instead of 1.0. If you use additional Facebook",
"API methods beyond login, you may need to request new",
"permissions.\n\n",
"Facebook will automatically switch all apps to API",
"version 2.0 on April 30th, 2015. Please make sure to update your",
"application's permissions and API calls by that date.\n\n",
"For more details, see",
"https://github.com/meteor/meteor/wiki/Facebook-Graph-API-Upgrade",
Console.options({ bulletPoint: "1.0.5: " })
);
}
},
"1.2.0-standard-minifiers-package": function (projectContext) {
// Minifiers are extracted into a new package called "standard-minifiers"
projectContext.projectConstraintsFile.addConstraints(
['standard-minifiers']);
projectContext.projectConstraintsFile.writeIfModified();
}
////////////
// PLEASE. When adding new upgraders that print mesasges, follow the
// examples for 0.9.0 and 0.9.1 above. Specifically, formatting
// should be:
//
// 1.x.y: Lorem ipsum messages go here...
// ...and linewrapped on the right column
//
// (Or just use Console.info with bulletPoint)
////////////
};
exports.runUpgrader = function (projectContext, upgraderName) {
// This should only be called from the hidden run-upgrader command or by
// "meteor update" with an upgrader from one of our releases, so it's OK if
// error handling is just an exception.
if (! _.has(upgradersByName, upgraderName))
throw new Error("Unknown upgrader: " + upgraderName);
upgradersByName[upgraderName](projectContext);
};
exports.upgradersToRun = function (projectContext) {
var ret = [];
var finishedUpgraders = projectContext.finishedUpgraders.readUpgraders();
// This relies on the fact that Node guarantees object iteration ordering.
_.each(upgradersByName, function (func, name) {
if (! _.contains(finishedUpgraders, name)) {
ret.push(name);
}
});
return ret;
};
exports.allUpgraders = function () {
return _.keys(upgradersByName);
};
| arunoda/meteor | tools/upgraders.js | JavaScript | mit | 6,784 |
/*
* Copyright (C) 2012-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "FileItem.h"
#include "addons/include/xbmc_pvr_types.h"
#include "pvr/PVRManager.h"
#include "pvr/channels/PVRChannelGroupsContainer.h"
#include "pvr/recordings/PVRRecordings.h"
#include "pvr/timers/PVRTimers.h"
#include "utils/TextSearch.h"
#include "utils/log.h"
#include "EpgContainer.h"
#include "EpgSearchFilter.h"
using namespace EPG;
using namespace PVR;
void EpgSearchFilter::Reset()
{
m_strSearchTerm = "";
m_bIsCaseSensitive = false;
m_bSearchInDescription = false;
m_iGenreType = EPG_SEARCH_UNSET;
m_iGenreSubType = EPG_SEARCH_UNSET;
m_iMinimumDuration = EPG_SEARCH_UNSET;
m_iMaximumDuration = EPG_SEARCH_UNSET;
m_startDateTime.SetFromUTCDateTime(g_EpgContainer.GetFirstEPGDate());
m_endDateTime.SetFromUTCDateTime(g_EpgContainer.GetLastEPGDate());
m_bIncludeUnknownGenres = false;
m_bPreventRepeats = false;
/* pvr specific filters */
m_iChannelNumber = EPG_SEARCH_UNSET;
m_bFTAOnly = false;
m_iChannelGroup = EPG_SEARCH_UNSET;
m_bIgnorePresentTimers = true;
m_bIgnorePresentRecordings = true;
m_iUniqueBroadcastId = EPG_SEARCH_UNSET;
}
bool EpgSearchFilter::MatchGenre(const CEpgInfoTag &tag) const
{
bool bReturn(true);
if (m_iGenreType != EPG_SEARCH_UNSET)
{
bool bIsUnknownGenre(tag.GenreType() > EPG_EVENT_CONTENTMASK_USERDEFINED ||
tag.GenreType() < EPG_EVENT_CONTENTMASK_MOVIEDRAMA);
bReturn = ((m_bIncludeUnknownGenres && bIsUnknownGenre) || tag.GenreType() == m_iGenreType);
}
return bReturn;
}
bool EpgSearchFilter::MatchDuration(const CEpgInfoTag &tag) const
{
bool bReturn(true);
if (m_iMinimumDuration != EPG_SEARCH_UNSET)
bReturn = (tag.GetDuration() > m_iMinimumDuration * 60);
if (bReturn && m_iMaximumDuration != EPG_SEARCH_UNSET)
bReturn = (tag.GetDuration() < m_iMaximumDuration * 60);
return bReturn;
}
bool EpgSearchFilter::MatchStartAndEndTimes(const CEpgInfoTag &tag) const
{
return (tag.StartAsLocalTime() >= m_startDateTime && tag.EndAsLocalTime() <= m_endDateTime);
}
bool EpgSearchFilter::MatchSearchTerm(const CEpgInfoTag &tag) const
{
bool bReturn(true);
if (!m_strSearchTerm.empty())
{
CTextSearch search(m_strSearchTerm, m_bIsCaseSensitive, SEARCH_DEFAULT_OR);
bReturn = search.Search(tag.Title()) ||
search.Search(tag.PlotOutline());
}
return bReturn;
}
bool EpgSearchFilter::MatchBroadcastId(const CEpgInfoTag &tag) const
{
if (m_iUniqueBroadcastId != EPG_SEARCH_UNSET)
return (tag.UniqueBroadcastID() == m_iUniqueBroadcastId);
return true;
}
bool EpgSearchFilter::FilterEntry(const CEpgInfoTag &tag) const
{
return (MatchGenre(tag) &&
MatchBroadcastId(tag) &&
MatchDuration(tag) &&
MatchStartAndEndTimes(tag) &&
MatchSearchTerm(tag)) &&
(!tag.HasPVRChannel() ||
(MatchChannelType(tag) &&
MatchChannelNumber(tag) &&
MatchChannelGroup(tag) &&
(!m_bFTAOnly || !tag.ChannelTag()->IsEncrypted())));
}
int EpgSearchFilter::RemoveDuplicates(CFileItemList &results)
{
unsigned int iSize = results.Size();
for (unsigned int iResultPtr = 0; iResultPtr < iSize; iResultPtr++)
{
const CEpgInfoTagPtr epgentry_1(results.Get(iResultPtr)->GetEPGInfoTag());
if (!epgentry_1)
continue;
for (unsigned int iTagPtr = 0; iTagPtr < iSize; iTagPtr++)
{
if (iResultPtr == iTagPtr)
continue;
const CEpgInfoTagPtr epgentry_2(results.Get(iTagPtr)->GetEPGInfoTag());
if (!epgentry_2)
continue;
if (epgentry_1->Title() != epgentry_2->Title() ||
epgentry_1->Plot() != epgentry_2->Plot() ||
epgentry_1->PlotOutline() != epgentry_2->PlotOutline())
continue;
results.Remove(iTagPtr);
iResultPtr--;
iTagPtr--;
iSize--;
}
}
return iSize;
}
bool EpgSearchFilter::MatchChannelType(const CEpgInfoTag &tag) const
{
return (g_PVRManager.IsStarted() && tag.ChannelTag()->IsRadio() == m_bIsRadio);
}
bool EpgSearchFilter::MatchChannelNumber(const CEpgInfoTag &tag) const
{
bool bReturn(true);
if (m_iChannelNumber != EPG_SEARCH_UNSET && g_PVRManager.IsStarted())
{
CPVRChannelGroupPtr group = (m_iChannelGroup != EPG_SEARCH_UNSET) ? g_PVRChannelGroups->GetByIdFromAll(m_iChannelGroup) : g_PVRChannelGroups->GetGroupAllTV();
if (!group)
group = CPVRManager::GetInstance().ChannelGroups()->GetGroupAllTV();
bReturn = (m_iChannelNumber == (int) group->GetChannelNumber(tag.ChannelTag()));
}
return bReturn;
}
bool EpgSearchFilter::MatchChannelGroup(const CEpgInfoTag &tag) const
{
bool bReturn(true);
if (m_iChannelGroup != EPG_SEARCH_UNSET && g_PVRManager.IsStarted())
{
CPVRChannelGroupPtr group = g_PVRChannelGroups->GetByIdFromAll(m_iChannelGroup);
bReturn = (group && group->IsGroupMember(tag.ChannelTag()));
}
return bReturn;
}
int EpgSearchFilter::FilterRecordings(CFileItemList &results)
{
int iRemoved(0);
if (!g_PVRManager.IsStarted())
return iRemoved;
CFileItemList recordings;
g_PVRRecordings->GetAll(recordings);
// TODO inefficient!
CPVRRecordingPtr recording;
for (int iRecordingPtr = 0; iRecordingPtr < recordings.Size(); iRecordingPtr++)
{
recording = recordings.Get(iRecordingPtr)->GetPVRRecordingInfoTag();
if (!recording)
continue;
for (int iResultPtr = 0; iResultPtr < results.Size(); iResultPtr++)
{
const CEpgInfoTagPtr epgentry(results.Get(iResultPtr)->GetEPGInfoTag());
/* no match */
if (!epgentry ||
epgentry->Title() != recording->m_strTitle ||
epgentry->Plot() != recording->m_strPlot)
continue;
results.Remove(iResultPtr);
iResultPtr--;
++iRemoved;
}
}
return iRemoved;
}
int EpgSearchFilter::FilterTimers(CFileItemList &results)
{
int iRemoved(0);
if (!g_PVRManager.IsStarted())
return iRemoved;
std::vector<CFileItemPtr> timers = g_PVRTimers->GetActiveTimers();
// TODO inefficient!
for (unsigned int iTimerPtr = 0; iTimerPtr < timers.size(); iTimerPtr++)
{
CFileItemPtr fileItem = timers.at(iTimerPtr);
if (!fileItem || !fileItem->HasPVRTimerInfoTag())
continue;
CPVRTimerInfoTagPtr timer = fileItem->GetPVRTimerInfoTag();
if (!timer)
continue;
for (int iResultPtr = 0; iResultPtr < results.Size(); iResultPtr++)
{
const CEpgInfoTagPtr epgentry(results.Get(iResultPtr)->GetEPGInfoTag());
if (!epgentry ||
*epgentry->ChannelTag() != *timer->ChannelTag() ||
epgentry->StartAsUTC() < timer->StartAsUTC() ||
epgentry->EndAsUTC() > timer->EndAsUTC())
continue;
results.Remove(iResultPtr);
iResultPtr--;
++iRemoved;
}
}
return iRemoved;
}
| mikkle/xbmc | xbmc/epg/EpgSearchFilter.cpp | C++ | gpl-2.0 | 7,599 |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sqs-2012-11-05.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SQS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.SQS.Model.Internal.MarshallTransformations
{
/// <summary>
/// GetQueueUrl Request Marshaller
/// </summary>
public class GetQueueUrlRequestMarshaller : IMarshaller<IRequest, GetQueueUrlRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((GetQueueUrlRequest)input);
}
public IRequest Marshall(GetQueueUrlRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.SQS");
request.Parameters.Add("Action", "GetQueueUrl");
request.Parameters.Add("Version", "2012-11-05");
if(publicRequest != null)
{
if(publicRequest.IsSetQueueName())
{
request.Parameters.Add("QueueName", StringUtils.FromString(publicRequest.QueueName));
}
if(publicRequest.IsSetQueueOwnerAWSAccountId())
{
request.Parameters.Add("QueueOwnerAWSAccountId", StringUtils.FromString(publicRequest.QueueOwnerAWSAccountId));
}
}
return request;
}
}
} | ykbarros/aws-sdk-xamarin | AWS.XamarinSDK/AWSSDK_iOS/Amazon.SQS/Model/Model/Internal/MarshallTransformations/GetQueueUrlRequestMarshaller.cs | C# | apache-2.0 | 2,252 |
package org.apache.lucene.codecs.sep;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.Closeable;
import java.io.IOException;
import org.apache.lucene.store.DataInput;
/** Defines basic API for writing ints to an IndexOutput.
* IntBlockCodec interacts with this API. @see
* IntBlockReader
*
* @lucene.experimental */
public abstract class IntIndexInput implements Closeable {
public abstract Reader reader() throws IOException;
@Override
public abstract void close() throws IOException;
public abstract Index index() throws IOException;
/** Records a single skip-point in the {@link IntIndexInput.Reader}. */
public abstract static class Index {
public abstract void read(DataInput indexIn, boolean absolute) throws IOException;
/** Seeks primary stream to the last read offset */
public abstract void seek(IntIndexInput.Reader stream) throws IOException;
public abstract void copyFrom(Index other);
@Override
public abstract Index clone();
}
/** Reads int values. */
public abstract static class Reader {
/** Reads next single int */
public abstract int next() throws IOException;
}
}
| smartan/lucene | src/main/java/org/apache/lucene/codecs/sep/IntIndexInput.java | Java | apache-2.0 | 1,932 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.rest.messages.job.metrics;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonInclude;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
import javax.annotation.Nullable;
import static java.util.Objects.requireNonNull;
/**
* Response type for aggregated metrics. Contains the metric name and optionally the sum, average, minimum and maximum.
*/
public class AggregatedMetric {
private static final String FIELD_NAME_ID = "id";
private static final String FIELD_NAME_MIN = "min";
private static final String FIELD_NAME_MAX = "max";
private static final String FIELD_NAME_AVG = "avg";
private static final String FIELD_NAME_SUM = "sum";
@JsonProperty(value = FIELD_NAME_ID, required = true)
private final String id;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(FIELD_NAME_MIN)
private final Double min;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(FIELD_NAME_MAX)
private final Double max;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(FIELD_NAME_AVG)
private final Double avg;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(FIELD_NAME_SUM)
private final Double sum;
@JsonCreator
public AggregatedMetric(
final @JsonProperty(value = FIELD_NAME_ID, required = true) String id,
final @Nullable @JsonProperty(FIELD_NAME_MIN) Double min,
final @Nullable @JsonProperty(FIELD_NAME_MAX) Double max,
final @Nullable @JsonProperty(FIELD_NAME_AVG) Double avg,
final @Nullable @JsonProperty(FIELD_NAME_SUM) Double sum) {
this.id = requireNonNull(id, "id must not be null");
this.min = min;
this.max = max;
this.avg = avg;
this.sum = sum;
}
public AggregatedMetric(final @JsonProperty(value = FIELD_NAME_ID, required = true) String id) {
this(id, null, null, null, null);
}
@JsonIgnore
public String getId() {
return id;
}
@JsonIgnore
public Double getMin() {
return min;
}
@JsonIgnore
public Double getMax() {
return max;
}
@JsonIgnore
public Double getSum() {
return sum;
}
@JsonIgnore
public Double getAvg() {
return avg;
}
@Override
public String toString() {
return "AggregatedMetric{" +
"id='" + id + '\'' +
", mim='" + min + '\'' +
", max='" + max + '\'' +
", avg='" + avg + '\'' +
", sum='" + sum + '\'' +
'}';
}
}
| hequn8128/flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/job/metrics/AggregatedMetric.java | Java | apache-2.0 | 3,347 |
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"net/http"
"strings"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
)
// KubeletAuth implements AuthInterface
type KubeletAuth struct {
// authenticator identifies the user for requests to the Kubelet API
authenticator.Request
// authorizerAttributeGetter builds authorization.Attributes for a request to the Kubelet API
authorizer.RequestAttributesGetter
// authorizer determines whether a given authorization.Attributes is allowed
authorizer.Authorizer
}
// NewKubeletAuth returns a kubelet.AuthInterface composed of the given authenticator, attribute getter, and authorizer
func NewKubeletAuth(authenticator authenticator.Request, authorizerAttributeGetter authorizer.RequestAttributesGetter, authorizer authorizer.Authorizer) AuthInterface {
return &KubeletAuth{authenticator, authorizerAttributeGetter, authorizer}
}
func NewNodeAuthorizerAttributesGetter(nodeName types.NodeName) authorizer.RequestAttributesGetter {
return nodeAuthorizerAttributesGetter{nodeName: nodeName}
}
type nodeAuthorizerAttributesGetter struct {
nodeName types.NodeName
}
func isSubpath(subpath, path string) bool {
path = strings.TrimSuffix(path, "/")
return subpath == path || (strings.HasPrefix(subpath, path) && subpath[len(path)] == '/')
}
// GetRequestAttributes populates authorizer attributes for the requests to the kubelet API.
// Default attributes are: {apiVersion=v1,verb=<http verb from request>,resource=nodes,name=<node name>,subresource=proxy}
// More specific verb/resource is set for the following request patterns:
// /stats/* => verb=<api verb from request>, resource=nodes, name=<node name>, subresource=stats
// /metrics/* => verb=<api verb from request>, resource=nodes, name=<node name>, subresource=metrics
// /logs/* => verb=<api verb from request>, resource=nodes, name=<node name>, subresource=log
// /spec/* => verb=<api verb from request>, resource=nodes, name=<node name>, subresource=spec
func (n nodeAuthorizerAttributesGetter) GetRequestAttributes(u user.Info, r *http.Request) authorizer.Attributes {
apiVerb := ""
switch r.Method {
case "POST":
apiVerb = "create"
case "GET":
apiVerb = "get"
case "PUT":
apiVerb = "update"
case "PATCH":
apiVerb = "patch"
case "DELETE":
apiVerb = "delete"
}
requestPath := r.URL.Path
// Default attributes mirror the API attributes that would allow this access to the kubelet API
attrs := authorizer.AttributesRecord{
User: u,
Verb: apiVerb,
Namespace: "",
APIGroup: "",
APIVersion: "v1",
Resource: "nodes",
Subresource: "proxy",
Name: string(n.nodeName),
ResourceRequest: true,
Path: requestPath,
}
// Override subresource for specific paths
// This allows subdividing access to the kubelet API
switch {
case isSubpath(requestPath, statsPath):
attrs.Subresource = "stats"
case isSubpath(requestPath, metricsPath):
attrs.Subresource = "metrics"
case isSubpath(requestPath, logsPath):
// "log" to match other log subresources (pods/log, etc)
attrs.Subresource = "log"
case isSubpath(requestPath, specPath):
attrs.Subresource = "spec"
}
glog.V(5).Infof("Node request attributes: user=%#v attrs=%#v", attrs.GetUser(), attrs)
return attrs
}
| liyinan926/kubernetes | pkg/kubelet/server/auth.go | GO | apache-2.0 | 4,024 |
/*
* SSDPDeviceDescriptionParser
* Connect SDK
*
* Copyright (c) 2014 LG Electronics.
* Created by Hyun Kook Khang on 6 Jan 2015
*
* 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.connectsdk.discovery.provider.ssdp;
import java.util.HashMap;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SSDPDeviceDescriptionParser extends DefaultHandler {
public static final String TAG_DEVICE_TYPE = "deviceType";
public static final String TAG_FRIENDLY_NAME = "friendlyName";
public static final String TAG_MANUFACTURER = "manufacturer";
public static final String TAG_MANUFACTURER_URL = "manufacturerURL";
public static final String TAG_MODEL_DESCRIPTION = "modelDescription";
public static final String TAG_MODEL_NAME = "modelName";
public static final String TAG_MODEL_NUMBER = "modelNumber";
public static final String TAG_MODEL_URL = "modelURL";
public static final String TAG_SERIAL_NUMBER = "serialNumber";
public static final String TAG_UDN = "UDN";
public static final String TAG_UPC = "UPC";
public static final String TAG_ICON_LIST = "iconList";
public static final String TAG_SERVICE_LIST = "serviceList";
public static final String TAG_SEC_CAPABILITY = "sec:Capability";
public static final String TAG_PORT = "port";
public static final String TAG_LOCATION = "location";
String currentValue = null;
Icon currentIcon;
Service currentService;
SSDPDevice device;
Map<String, String> data;
public SSDPDeviceDescriptionParser(SSDPDevice device) {
this.device = device;
data = new HashMap<String, String>();
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentValue == null) {
currentValue = new String(ch, start, length);
}
else {
// append to existing string (needed for parsing character entities)
currentValue += new String(ch, start, length);
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (Icon.TAG.equals(qName)) {
currentIcon = new Icon();
} else if (Service.TAG.equals(qName)) {
currentService = new Service();
currentService.baseURL = device.baseURL;
} else if (TAG_SEC_CAPABILITY.equals(qName)) { // Samsung MultiScreen Capability
String port = null;
String location = null;
for (int i = 0; i < attributes.getLength(); i++) {
if (TAG_PORT.equals(attributes.getLocalName(i))) {
port = attributes.getValue(i);
}
else if (TAG_LOCATION.equals(attributes.getLocalName(i))) {
location = attributes.getValue(i);
}
}
if (port == null) {
device.serviceURI = String.format("%s%s", device.serviceURI, location);
}
else {
device.serviceURI = String.format("%s:%s%s", device.serviceURI, port, location);
}
}
currentValue = null;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
/* Parse device-specific information */
if (TAG_DEVICE_TYPE.equals(qName)) {
device.deviceType = currentValue;
} else if (TAG_FRIENDLY_NAME.equals(qName)) {
device.friendlyName = currentValue;
} else if (TAG_MANUFACTURER.equals(qName)) {
device.manufacturer = currentValue;
// } else if (TAG_MANUFACTURER_URL.equals(qName)) {
// device.manufacturerURL = currentValue;
} else if (TAG_MODEL_DESCRIPTION.equals(qName)) {
device.modelDescription = currentValue;
} else if (TAG_MODEL_NAME.equals(qName)) {
device.modelName = currentValue;
} else if (TAG_MODEL_NUMBER.equals(qName)) {
device.modelNumber = currentValue;
// } else if (TAG_MODEL_URL.equals(qName)) {
// device.modelURL = currentValue;
// } else if (TAG_SERIAL_NUMBER.equals(qName)) {
// device.serialNumber = currentValue;
} else if (TAG_UDN.equals(qName)) {
device.UDN = currentValue;
// } else if (TAG_UPC.equals(qName)) {
// device.UPC = currentValue;
}
// /* Parse icon-list information */
// else if (Icon.TAG_MIME_TYPE.equals(qName)) {
// currentIcon.mimetype = currentValue;
// } else if (Icon.TAG_WIDTH.equals(qName)) {
// currentIcon.width = currentValue;
// } else if (Icon.TAG_HEIGHT.equals(qName)) {
// currentIcon.height = currentValue;
// } else if (Icon.TAG_DEPTH.equals(qName)) {
// currentIcon.depth = currentValue;
// } else if (Icon.TAG_URL.equals(qName)) {
// currentIcon.url = currentValue;
// } else if (Icon.TAG.equals(qName)) {
// device.iconList.add(currentIcon);
// }
/* Parse service-list information */
else if (Service.TAG_SERVICE_TYPE.equals(qName)) {
currentService.serviceType = currentValue;
} else if (Service.TAG_SERVICE_ID.equals(qName)) {
currentService.serviceId = currentValue;
} else if (Service.TAG_SCPD_URL.equals(qName)) {
currentService.SCPDURL = currentValue;
} else if (Service.TAG_CONTROL_URL.equals(qName)) {
currentService.controlURL = currentValue;
} else if (Service.TAG_EVENTSUB_URL.equals(qName)) {
currentService.eventSubURL = currentValue;
} else if (Service.TAG.equals(qName)) {
device.serviceList.add(currentService);
}
data.put(qName, currentValue);
currentValue = null;
}
}
| AspiroTV/Connect-SDK-Android-Core | src/com/connectsdk/discovery/provider/ssdp/SSDPDeviceDescriptionParser.java | Java | apache-2.0 | 6,517 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.datatorrent.lib.util;
import java.util.AbstractMap;
/**
*
* A single KeyValPair for basic data passing, It is a write once, and read often model. <p>
* <br>
* Key and Value are to be treated as immutable objects.
*
* @param <K>
* @param <V>
* @since 0.3.2
*/
public class KeyValPair<K, V> extends AbstractMap.SimpleEntry<K, V>
{
private static final long serialVersionUID = 201301281547L;
/**
* Added default constructor for deserializer.
*/
private KeyValPair()
{
super(null, null);
}
/**
* Constructor
*
* @param k sets key
* @param v sets value
*/
public KeyValPair(K k, V v)
{
super(k, v);
}
}
| PramodSSImmaneni/apex-malhar | library/src/main/java/com/datatorrent/lib/util/KeyValPair.java | Java | apache-2.0 | 1,480 |
#include <exception>
#include <stdio.h>
int throws_exception_on_even (int value);
int intervening_function (int value);
int catches_exception (int value);
int
catches_exception (int value)
{
try
{
return intervening_function(value); // This is the line you should stop at for catch
}
catch (int value)
{
return value;
}
}
int
intervening_function (int value)
{
return throws_exception_on_even (2 * value);
}
int
throws_exception_on_even (int value)
{
printf ("Mod two works: %d.\n", value%2);
if (value % 2 == 0)
throw 30;
else
return value;
}
int
main ()
{
catches_exception (10); // Stop here
return 5;
}
| endlessm/chromium-browser | third_party/llvm/lldb/test/API/lang/cpp/exceptions/exceptions.cpp | C++ | bsd-3-clause | 696 |
// Copyright (c) 2011 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 "remoting/host/capture_scheduler.h"
#include <algorithm>
#include "base/logging.h"
#include "base/sys_info.h"
#include "base/time.h"
namespace {
// Number of samples to average the most recent capture and encode time
// over.
const int kStatisticsWindow = 3;
// The hard limit is 20fps or 50ms per recording cycle.
const int64 kMinimumRecordingDelay = 50;
// Controls how much CPU time we can use for encode and capture.
// Range of this value is between 0 to 1. 0 means using 0% of of all CPUs
// available while 1 means using 100% of all CPUs available.
const double kRecordingCpuConsumption = 0.5;
} // namespace
namespace remoting {
// We assume that the number of available cores is constant.
CaptureScheduler::CaptureScheduler()
: num_of_processors_(base::SysInfo::NumberOfProcessors()),
capture_time_(kStatisticsWindow),
encode_time_(kStatisticsWindow) {
DCHECK(num_of_processors_);
}
CaptureScheduler::~CaptureScheduler() {
}
base::TimeDelta CaptureScheduler::NextCaptureDelay() {
// Delay by an amount chosen such that if capture and encode times
// continue to follow the averages, then we'll consume the target
// fraction of CPU across all cores.
double delay =
(capture_time_.Average() + encode_time_.Average()) /
(kRecordingCpuConsumption * num_of_processors_);
if (delay < kMinimumRecordingDelay)
return base::TimeDelta::FromMilliseconds(kMinimumRecordingDelay);
return base::TimeDelta::FromMilliseconds(delay);
}
void CaptureScheduler::RecordCaptureTime(base::TimeDelta capture_time) {
capture_time_.Record(capture_time.InMilliseconds());
}
void CaptureScheduler::RecordEncodeTime(base::TimeDelta encode_time) {
encode_time_.Record(encode_time.InMilliseconds());
}
} // namespace remoting
| zcbenz/cefode-chromium | remoting/host/capture_scheduler.cc | C++ | bsd-3-clause | 1,951 |
require 'optparse'
require 'stringio'
module Spec
module Runner
class OptionParser < ::OptionParser
class << self
def parse(args, err, out)
parser = new(err, out)
parser.parse(args)
parser.options
end
def spec_command?
$0.split('/').last == 'spec'
end
end
attr_reader :options
OPTIONS = {
:pattern => ["-p", "--pattern [PATTERN]","Limit files loaded to those matching this pattern. Defaults to '**/*_spec.rb'",
"Separate multiple patterns with commas.",
"Applies only to directories named on the command line (files",
"named explicitly on the command line will be loaded regardless)."],
:diff => ["-D", "--diff [FORMAT]","Show diff of objects that are expected to be equal when they are not",
"Builtin formats: unified|u|context|c",
"You can also specify a custom differ class",
"(in which case you should also specify --require)"],
:colour => ["-c", "--colour", "--color", "Show coloured (red/green) output"],
:example => ["-e", "--example [NAME|FILE_NAME]", "Execute example(s) with matching name(s). If the argument is",
"the path to an existing file (typically generated by a previous",
"run using --format failing_examples:file.txt), then the examples",
"on each line of that file will be executed. If the file is empty,",
"all examples will be run (as if --example was not specified).",
" ",
"If the argument is not an existing file, then it is treated as",
"an example name directly, causing RSpec to run just the example",
"matching that name"],
:specification => ["-s", "--specification [NAME]", "DEPRECATED - use -e instead", "(This will be removed when autotest works with -e)"],
:line => ["-l", "--line LINE_NUMBER", Integer, "Execute example group or example at given line.",
"(does not work for dynamically generated examples)"],
:format => ["-f", "--format FORMAT[:WHERE]","Specifies what format to use for output. Specify WHERE to tell",
"the formatter where to write the output. All built-in formats",
"expect WHERE to be a file name, and will write to $stdout if it's",
"not specified. The --format option may be specified several times",
"if you want several outputs",
" ",
"Builtin formats:",
"silent|l : No output", "progress|p : Text-based progress bar",
"profile|o : Text-based progress bar with profiling of 10 slowest examples",
"specdoc|s : Code example doc strings",
"nested|n : Code example doc strings with nested groups indented",
"html|h : A nice HTML report",
"failing_examples|e : Write all failing examples - input for --example",
"failing_example_groups|g : Write all failing example groups - input for --example",
" ",
"FORMAT can also be the name of a custom formatter class",
"(in which case you should also specify --require to load it)"],
:require => ["-r", "--require FILE", "Require FILE before running specs",
"Useful for loading custom formatters or other extensions.",
"If this option is used it must come before the others"],
:backtrace => ["-b", "--backtrace", "Output full backtrace"],
:loadby => ["-L", "--loadby STRATEGY", "Specify the strategy by which spec files should be loaded.",
"STRATEGY can currently only be 'mtime' (File modification time)",
"By default, spec files are loaded in alphabetical order if --loadby",
"is not specified."],
:reverse => ["-R", "--reverse", "Run examples in reverse order"],
:timeout => ["-t", "--timeout FLOAT", "Interrupt and fail each example that doesn't complete in the",
"specified time"],
:heckle => ["-H", "--heckle CODE", "If all examples pass, this will mutate the classes and methods",
"identified by CODE little by little and run all the examples again",
"for each mutation. The intent is that for each mutation, at least",
"one example *should* fail, and RSpec will tell you if this is not the",
"case. CODE should be either Some::Module, Some::Class or",
"Some::Fabulous#method}"],
:dry_run => ["-d", "--dry-run", "Invokes formatters without executing the examples."],
:options_file => ["-O", "--options PATH", "Read options from a file"],
:generate_options => ["-G", "--generate-options PATH", "Generate an options file for --options"],
:runner => ["-U", "--runner RUNNER", "Use a custom Runner."],
:debug => ["-u", "--debugger", "Enable ruby-debugging."],
:drb => ["-X", "--drb", "Run examples via DRb. (For example against script/spec_server)"],
:drb_port => ["--port PORT", "Port for DRb server. (Ignored without --drb)"],
:version => ["-v", "--version", "Show version"],
:help => ["-h", "--help", "You're looking at it"]
}
def initialize(err, out)
super()
@error_stream = err
@out_stream = out
@options = Options.new(@error_stream, @out_stream)
@file_factory = File
self.banner = "Usage: spec (FILE(:LINE)?|DIRECTORY|GLOB)+ [options]"
self.separator ""
on(*OPTIONS[:pattern]) {|pattern| @options.filename_pattern = pattern}
on(*OPTIONS[:diff]) {|diff| @options.parse_diff(diff)}
on(*OPTIONS[:colour]) {@options.colour = true}
on(*OPTIONS[:example]) {|example| @options.parse_example(example)}
on(*OPTIONS[:specification]) {|example| @options.parse_example(example)}
on(*OPTIONS[:line]) {|line_number| @options.line_number = line_number.to_i}
on(*OPTIONS[:format]) {|format| @options.parse_format(format)}
on(*OPTIONS[:require]) {|requires| invoke_requires(requires)}
on(*OPTIONS[:backtrace]) {@options.backtrace_tweaker = NoisyBacktraceTweaker.new}
on(*OPTIONS[:loadby]) {|loadby| @options.loadby = loadby}
on(*OPTIONS[:reverse]) {@options.reverse = true}
on(*OPTIONS[:timeout]) {|timeout| @options.timeout = timeout.to_f}
on(*OPTIONS[:heckle]) {|heckle| @options.load_heckle_runner(heckle)}
on(*OPTIONS[:dry_run]) {@options.dry_run = true}
on(*OPTIONS[:options_file]) {|options_file|}
on(*OPTIONS[:generate_options]) {|options_file|}
on(*OPTIONS[:runner]) {|runner| @options.user_input_for_runner = runner}
on(*OPTIONS[:debug]) {@options.debug = true}
on(*OPTIONS[:drb]) {}
on(*OPTIONS[:drb_port]) {|port| @options.drb_port = port}
on(*OPTIONS[:version]) {parse_version}
on("--autospec") {@options.autospec = true}
on_tail(*OPTIONS[:help]) {parse_help}
end
def order!(argv, &blk)
@argv = argv.dup
@argv = (@argv.empty? & self.class.spec_command?) ? ['--help'] : @argv
# Parse options file first
parse_file_options(:options_file, :parse_options_file)
@options.argv = @argv.dup
return if parse_file_options(:generate_options, :write_options_file)
return if parse_drb
super(@argv) do |file|
if file =~ /^(.+):(\d+)$/
file = $1
@options.line_number = $2.to_i
end
@options.files << file
blk.call(file) if blk
end
@options
end
protected
def invoke_requires(requires)
requires.split(",").each do |file|
require file
end
end
def parse_file_options(option_name, action)
# Remove the file option and the argument before handling the file
options_file = nil
options_list = OPTIONS[option_name][0..1]
options_list[1].gsub!(" PATH", "")
options_list.each do |option|
if index = @argv.index(option)
@argv.delete_at(index)
options_file = @argv.delete_at(index)
end
end
if options_file.nil? &&
File.exist?('spec/spec.opts') &&
!@argv.any?{|a| a =~ /^\-/ }
options_file = 'spec/spec.opts'
end
if options_file
send(action, options_file)
return true
else
return false
end
end
def parse_options_file(options_file)
option_file_args = File.readlines(options_file).map {|l| l.chomp.split " "}.flatten
@argv.push(*option_file_args)
end
def write_options_file(options_file)
File.open(options_file, 'w') do |io|
io.puts @argv.join("\n")
end
@out_stream.puts "\nOptions written to #{options_file}. You can now use these options with:"
@out_stream.puts "spec --options #{options_file}"
@options.examples_should_not_be_run
end
def parse_drb
argv = @options.argv
is_drb = false
is_drb ||= argv.delete(OPTIONS[:drb][0])
is_drb ||= argv.delete(OPTIONS[:drb][1])
return false unless is_drb
if DrbCommandLine.run(self.class.parse(argv, @error_stream, @out_stream))
@options.examples_should_not_be_run
true
else
@error_stream.puts "Running specs locally:"
false
end
end
def parse_version
@out_stream.puts ::Spec::VERSION::SUMMARY
exit if stdout?
end
def parse_help
@out_stream.puts self
exit if stdout?
end
def stdout?
@out_stream == $stdout
end
end
end
end
| dnclabs/lockbox | vendor/plugins/rspec/lib/spec/runner/option_parser.rb | Ruby | bsd-3-clause | 11,779 |
// 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.Reflection.Metadata;
using System.Reflection.PortableExecutable;
namespace System.Reflection.TypeLoading.Ecma
{
/// <summary>
/// Base class for all Module objects created by a MetadataLoadContext and get its metadata from a PEReader.
/// </summary>
internal sealed partial class EcmaModule
{
internal unsafe InternalManifestResourceInfo GetInternalManifestResourceInfo(string resourceName)
{
MetadataReader reader = Reader;
InternalManifestResourceInfo result = new InternalManifestResourceInfo();
ManifestResourceHandleCollection manifestResources = reader.ManifestResources;
foreach (ManifestResourceHandle resourceHandle in manifestResources)
{
ManifestResource resource = resourceHandle.GetManifestResource(reader);
if (resource.Name.Equals(resourceName, reader))
{
result.Found = true;
if (resource.Implementation.IsNil)
{
checked
{
// Embedded data resource
result.ResourceLocation = ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile;
PEReader pe = _guardedPEReader.PEReader;
PEMemoryBlock resourceDirectory = pe.GetSectionData(pe.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress);
BlobReader blobReader = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset);
uint length = blobReader.ReadUInt32();
result.PointerToResource = blobReader.CurrentPointer;
// Length check the size of the resource to ensure it fits in the PE file section, note, this is only safe as its in a checked region
if (length + sizeof(int) > blobReader.Length)
throw new BadImageFormatException();
result.SizeOfResource = length;
}
}
else
{
if (resource.Implementation.Kind == HandleKind.AssemblyFile)
{
// Get file name
result.ResourceLocation = default;
AssemblyFile file = ((AssemblyFileHandle)resource.Implementation).GetAssemblyFile(reader);
result.FileName = file.Name.GetString(reader);
if (file.ContainsMetadata)
{
EcmaModule module = (EcmaModule)Assembly.GetModule(result.FileName);
if (module == null)
throw new BadImageFormatException(SR.Format(SR.ManifestResourceInfoReferencedBadModule, result.FileName));
result = module.GetInternalManifestResourceInfo(resourceName);
}
}
else if (resource.Implementation.Kind == HandleKind.AssemblyReference)
{
// Resolve assembly reference
result.ResourceLocation = ResourceLocation.ContainedInAnotherAssembly;
RoAssemblyName destinationAssemblyName = ((AssemblyReferenceHandle)resource.Implementation).ToRoAssemblyName(reader);
result.ReferencedAssembly = Loader.ResolveAssembly(destinationAssemblyName);
}
}
}
}
return result;
}
}
}
| ViktorHofer/corefx | src/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Modules/Ecma/EcmaModule.ManifestResources.cs | C# | mit | 4,067 |
var _ = require('underscore');
var os = require('os');
var utils = require('./utils.js');
/* Meteor's current architecture scheme defines the following virtual
* machine types, which are defined by specifying what is promised by
* the host enviroment:
*
* browser.w3c
* A web browser compliant with modern standards. This is
* intentionally a broad definition. In the coming years, as web
* standards evolve, we will likely tighten it up.
*
* browser.ie[678]
* Old versions of Internet Explorer (not sure yet exactly which
* versions to distinguish -- maybe 6 and 8?)
*
* os.linux.x86_32
* os.linux.x86_64
* Linux on Intel x86 architecture. x86_64 means a system that can
* run 64-bit images, furnished with 64-bit builds of shared
* libraries (there is no guarantee that 32-bit builds of shared
* libraries will be available). x86_32 means a system that can run
* 32-bit images, furnished with 32-bit builds of shared libraries.
* Additionally, if a package contains shared libraries (for use by
* other packages), then if the package is built for x86_64, it
* should contain a 64-bit version of the library, and likewise for
* 32-bit.
*
* Operationally speaking, if you worked at it, under this
* definition it would be possible to build a Linux system that can
* run both x86_64 and x86_32 images (eg, by using a 64-bit kernel
* and making sure that both versions of all relevant libraries were
* installed). But we require such a host to decide whether it is
* x86_64 or x86_32, and stick with it. You can't load a combination
* of packages from each and expect them to work together, because
* if they contain shared libraries they all need to have the same
* architecture.
*
* Basically the punchline is: if you installed the 32-bit version
* of Ubuntu, you've got a os.linux.x86_32 system and you will
* use exclusively os.linux.x86_32 packages, and likewise
* 64-bit. They are two parallel universes and which one you're in
* is determined by which version of Red Hat or Ubuntu you
* installed.
*
* os.osx.x86_64
* OS X (technically speaking, Darwin) on Intel x86 architecture,
* with a kernel capable of loading 64-bit images, and 64-bit builds
* of shared libraries available. If a os.osx.x86_64 package
* contains a shared library, it is only required to provide a
* 64-bit version of the library (it is not required to provide a
* fat binary with both 32-bit and 64-bit builds).
*
* Note that in modern Darwin, both the 32 and 64 bit versions of
* the kernel can load 64-bit images, and the Apple-supplied shared
* libraries are fat binaries that include both 32-bit and 64-bit
* builds in a single file. So it is technically fine (but
* discouraged) for a os.osx.x86_64 to include a 32-bit
* executable, if it only uses the system's shared libraries, but
* you'll run into problems if shared libraries from other packages
* are used.
*
* There is no os.osx.x86_32. Our experience is that such
* hardware is virtually extinct. Meteor has never supported it and
* nobody has asked for it.
*
* os.windows.x86_32
* This is 32 and 64 bit Windows. It seems like there is not much of
* a benefit to using 64 bit Node on Windows, and 32 bit works properly
* even on 64 bit systems.
*
* To be (more but far from completely) precise, the ABI for os.*
* architectures includes a CPU type, a mode in which the code will be
* run (eg, 64 bit), an executable file format (eg, ELF), a promise to
* make any shared libraries available in a particular architecture,
* and promise to set up the shared library search path
* "appropriately". In the future it will also include some guarantees
* about the directory layout in the environment, eg, location of a
* directory where temporary files may be freely written. It does not
* include any syscalls (beyond those used by code that customarily is
* statically linked into every executable built on a platform, eg,
* exit(2)). It does not guarantee the presence of any particular
* shared libraries or programs (including any particular shell or
* traditional tools like 'grep' or 'find').
*
* To model the shared libraries that are required on a system (and
* the particular versions that are required), and to model
* dependencies on command-line programs like 'bash' and 'grep', the
* idea is to have a package named something like 'posix-base' that
* rolls up a reasonable base environment (including such modern
* niceties as libopenssl) and is supplied by the container. This
* allows it to be versioned, unlike architectures, which we hope to
* avoid versioning.
*
* Q: What does "x86" mean?
* A: It refers to the traditional Intel architecture, which
* originally surfaced in CPUs such as the 8086 and the 80386. Those
* of us who are older should remember that the last time that Intel
* used this branding was the 80486, introduced in 1989, and that
* today, parts that use this architecture bear names like "Core",
* "Atom", and "Phenom", with no "86" it sight. We use it in the
* architecture name anyway because we don't want to depart too far
* from Linux's architecture names.
*
* Q: Why do we call it "x86_32" instead of the customary "i386" or
* "i686"?
* A: We wanted to have one name for 32-bit and one name for 64-bit,
* rather than several names for each that are virtual synonyms for
* each (eg, x86_64 vs amd64 vs ia64, i386 vs i686 vs x86). For the
* moment anyway, we're willing to adopt a "one size fits all"
* attitude to get there (no ability to have separate builds for 80386
* CPUs that don't support Pentium Pro extensions, for example --
* you'll have to do runtime detection if you need that). And as long
* as we have to pick a name, we wanted to pick one that was super
* clear (it is not obvious to many people that "i686" means "32-bit
* Intel", because why should it be?) and didn't imply too close of an
* equivalence to the precise meanings that other platforms may assign
* to some of these strings.
*/
// Returns the fully qualified arch of this host -- something like
// "os.linux.x86_32" or "os.osx.x86_64". Must be called inside
// a fiber. Throws an error if it's not a supported architecture.
//
// If you change this, also change scripts/admin/launch-meteor
var _host = null; // memoize
var host = function () {
if (! _host) {
var run = function (...args) {
var result = utils.execFileSync(args[0], args.slice(1)).stdout;
if (! result) {
throw new Error("can't get arch with " + args.join(" ") + "?");
}
return result.replace(/\s*$/, ''); // trailing whitespace
};
var platform = os.platform();
if (platform === "darwin") {
// Can't just test uname -m = x86_64, because Snow Leopard can
// return other values.
if (run('uname', '-p') !== "i386" ||
run('sysctl', '-n', 'hw.cpu64bit_capable') !== "1") {
throw new Error("Only 64-bit Intel processors are supported on OS X");
}
_host = "os.osx.x86_64";
}
else if (platform === "linux") {
var machine = run('uname', '-m');
if (_.contains(["i386", "i686", "x86"], machine)) {
_host = "os.linux.x86_32";
} else if (_.contains(["x86_64", "amd64", "ia64"], machine)) {
_host = "os.linux.x86_64";
} else {
throw new Error("Unsupported architecture: " + machine);
}
}
else if (platform === "win32") {
// We also use 32 bit builds on 64 bit Windows architectures.
_host = "os.windows.x86_32";
} else {
throw new Error("Unsupported operating system: " + platform);
}
}
return _host;
};
// True if `host` (an architecture name such as 'os.linux.x86_64') can run
// programs of architecture `program` (which might be something like 'os',
// 'os.linux', or 'os.linux.x86_64').
//
// `host` and `program` are just mnemonics -- `host` does not
// necessariy have to be a fully qualified architecture name. This
// function just checks to see if `program` describes a set of
// enviroments that is a (non-strict) superset of `host`.
var matches = function (host, program) {
return host.substr(0, program.length) === program &&
(host.length === program.length ||
host.substr(program.length, 1) === ".");
};
// Like `supports`, but instead taken an array of possible
// architectures as its second argument. Returns the most specific
// match, or null if none match. Throws an error if `programs`
// contains exact duplicates.
var mostSpecificMatch = function (host, programs) {
var seen = {};
var best = null;
_.each(programs, function (p) {
if (seen[p]) {
throw new Error("Duplicate architecture: " + p);
}
seen[p] = true;
if (archinfo.matches(host, p) &&
(! best || p.length > best.length)) {
best = p;
}
});
return best;
};
// `programs` is a set of architectures (as an array of string, which
// may contain duplicates). Determine if there exists any architecture
// that is compatible with all of the architectures in the set. If so,
// returns the least specific such architecture. Otherwise (the
// architectures are disjoin) raise an exception.
//
// For example, for 'os' and 'os.osx', return 'os.osx'. For 'os' and
// 'os.linux.x86_64', return 'os.linux.x86_64'. For 'os' and 'browser', throw an
// exception.
var leastSpecificDescription = function (programs) {
if (programs.length === 0) {
return '';
}
// Find the longest string
var longest = _.max(programs, function (p) { return p.length; });
// If everything else in the list is compatible with the longest,
// then it must be the most specific, and if everything is
// compatible with the most specific then it must be the least
// specific compatible description.
_.each(programs, function (p) {
if (! archinfo.matches(longest, p)) {
throw new Error("Incompatible architectures: '" + p + "' and '" +
longest + "'");
}
});
return longest;
};
var withoutSpecificOs = function (arch) {
if (arch.substr(0, 3) === 'os.') {
return 'os';
}
return arch;
};
var archinfo = exports;
_.extend(archinfo, {
host: host,
matches: matches,
mostSpecificMatch: mostSpecificMatch,
leastSpecificDescription: leastSpecificDescription,
withoutSpecificOs: withoutSpecificOs
});
| lpinto93/meteor | tools/utils/archinfo.js | JavaScript | mit | 10,422 |
module.exports = {
justNow: "ligenu",
secondsAgo: "{{time}} sekunder siden",
aMinuteAgo: "et minut siden",
minutesAgo: "{{time}} minutter siden",
anHourAgo: "en time siden",
hoursAgo: "{{time}} timer siden",
aDayAgo: "i går",
daysAgo: "{{time}} dage siden",
aWeekAgo: "en uge siden",
weeksAgo: "{{time}} uger siden",
aMonthAgo: "en måned siden",
monthsAgo: "{{time}} måneder siden",
aYearAgo: "et år siden",
yearsAgo: "{{time}} år siden",
overAYearAgo: "over et år siden",
secondsFromNow: "om {{time}} sekunder",
aMinuteFromNow: "om et minut",
minutesFromNow: "om {{time}} minutter",
anHourFromNow: "om en time",
hoursFromNow: "om {{time}} timer",
aDayFromNow: "i morgen",
daysFromNow: "om {{time}} dage",
aWeekFromNow: "om en uge",
weeksFromNow: "om {{time}} uger",
aMonthFromNow: "om en måned",
monthsFromNow: "om {{time}} måneder",
aYearFromNow: "om et år",
yearsFromNow: "om {{time}} år",
overAYearFromNow: "om over et år"
}
| joegesualdo/dotfiles | npm-global/lib/node_modules/npm/node_modules/tiny-relative-date/translations/da.js | JavaScript | mit | 998 |
<?php
/*
* This file is part of the Assetic package, an OpenSky project.
*
* (c) 2010-2011 OpenSky Project Inc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Assetic\Asset;
use Assetic\Filter\FilterInterface;
/**
* An asset has a mutable URL and content and can be loaded and dumped.
*
* @author Kris Wallsmith <kris.wallsmith@gmail.com>
*/
interface AssetInterface
{
/**
* Ensures the current asset includes the supplied filter.
*
* @param FilterInterface $filter A filter
*/
function ensureFilter(FilterInterface $filter);
/**
* Returns an array of filters currently applied.
*
* @return array An array of filters
*/
function getFilters();
/**
* Loads the asset into memory and applies load filters.
*
* You may provide an additional filter to apply during load.
*
* @param FilterInterface $additionalFilter An additional filter
*/
function load(FilterInterface $additionalFilter = null);
/**
* Applies dump filters and returns the asset as a string.
*
* You may provide an additional filter to apply during dump.
*
* Dumping an asset should not change its state.
*
* If the current asset has not been loaded yet, it should be
* automatically loaded at this time.
*
* @param FilterInterface $additionalFilter An additional filter
*
* @return string The filtered content of the current asset
*/
function dump(FilterInterface $additionalFilter = null);
/**
* Returns the loaded content of the current asset.
*
* @return string The content
*/
function getContent();
/**
* Sets the content of the current asset.
*
* Filters can use this method to change the content of the asset.
*
* @param string $content The asset content
*/
function setContent($content);
/**
* Returns an absolute path or URL to the source asset's root directory.
*
* This value should be an absolute path to a directory in the filesystem,
* an absolute URL with no path, or null.
*
* For example:
*
* * '/path/to/web'
* * 'http://example.com'
* * null
*
* @return string|null The asset's root
*/
function getSourceRoot();
/**
* Returns the relative path for the source asset.
*
* This value can be combined with the asset's source root (if both are
* non-null) to get something compatible with file_get_contents().
*
* For example:
*
* * 'js/main.js'
* * 'main.js'
* * null
*
* @return string|null The source asset path
*/
function getSourcePath();
/**
* Returns the URL for the current asset.
*
* @return string|null A web URL where the asset will be dumped
*/
function getTargetPath();
/**
* Sets the URL for the current asset.
*
* @param string $targetPath A web URL where the asset will be dumped
*/
function setTargetPath($targetPath);
/**
* Returns the time the current asset was last modified.
*
* @return integer|null A UNIX timestamp
*/
function getLastModified();
}
| VelvetMirror/doctrine | vendor/assetic/src/Assetic/Asset/AssetInterface.php | PHP | mit | 3,333 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Globalization;
using System.Net.NetworkInformation;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
namespace System.Net
{
[Serializable]
public class WebProxy : IWebProxy, ISerializable
{
private ArrayList _bypassList;
private Regex[] _regExBypassList;
public WebProxy() : this((Uri)null, false, null, null) { }
public WebProxy(Uri Address) : this(Address, false, null, null) { }
public WebProxy(Uri Address, bool BypassOnLocal) : this(Address, BypassOnLocal, null, null) { }
public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList) : this(Address, BypassOnLocal, BypassList, null) { }
public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
{
this.Address = Address;
this.Credentials = Credentials;
this.BypassProxyOnLocal = BypassOnLocal;
if (BypassList != null)
{
_bypassList = new ArrayList(BypassList);
UpdateRegExList(true);
}
}
public WebProxy(string Host, int Port)
: this(new Uri("http://" + Host + ":" + Port.ToString(CultureInfo.InvariantCulture)), false, null, null)
{
}
public WebProxy(string Address)
: this(CreateProxyUri(Address), false, null, null)
{
}
public WebProxy(string Address, bool BypassOnLocal)
: this(CreateProxyUri(Address), BypassOnLocal, null, null)
{
}
public WebProxy(string Address, bool BypassOnLocal, string[] BypassList)
: this(CreateProxyUri(Address), BypassOnLocal, BypassList, null)
{
}
public WebProxy(string Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
: this(CreateProxyUri(Address), BypassOnLocal, BypassList, Credentials)
{
}
public Uri Address { get; set; }
public bool BypassProxyOnLocal { get; set; }
public string[] BypassList
{
get { return _bypassList != null ? (string[])_bypassList.ToArray(typeof(string)) : Array.Empty<string>(); }
set
{
_bypassList = new ArrayList(value);
UpdateRegExList(true);
}
}
public ArrayList BypassArrayList => _bypassList ?? (_bypassList = new ArrayList());
public ICredentials Credentials { get; set; }
public bool UseDefaultCredentials
{
get { return Credentials == CredentialCache.DefaultCredentials; }
set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
}
public Uri GetProxy(Uri destination)
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
return IsBypassed(destination) ? destination : Address;
}
private static Uri CreateProxyUri(string address) =>
address == null ? null :
address.IndexOf("://") == -1 ? new Uri("http://" + address) :
new Uri(address);
private void UpdateRegExList(bool canThrow)
{
Regex[] regExBypassList = null;
ArrayList bypassList = _bypassList;
try
{
if (bypassList != null && bypassList.Count > 0)
{
regExBypassList = new Regex[bypassList.Count];
for (int i = 0; i < bypassList.Count; i++)
{
regExBypassList[i] = new Regex((string)bypassList[i], RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
}
}
catch
{
if (!canThrow)
{
_regExBypassList = null;
return;
}
throw;
}
// Update field here, as it could throw earlier in the loop
_regExBypassList = regExBypassList;
}
private bool IsMatchInBypassList(Uri input)
{
UpdateRegExList(false);
if (_regExBypassList != null)
{
string matchUriString = input.IsDefaultPort ?
input.Scheme + "://" + input.Host :
input.Scheme + "://" + input.Host + ":" + input.Port.ToString();
foreach (Regex r in _regExBypassList)
{
if (r.IsMatch(matchUriString))
{
return true;
}
}
}
return false;
}
private bool IsLocal(Uri host)
{
string hostString = host.Host;
IPAddress hostAddress;
if (IPAddress.TryParse(hostString, out hostAddress))
{
return IPAddress.IsLoopback(hostAddress) || IsAddressLocal(hostAddress);
}
// No dot? Local.
int dot = hostString.IndexOf('.');
if (dot == -1)
{
return true;
}
// If it matches the primary domain, it's local. (Whether or not the hostname matches.)
string local = "." + IPGlobalProperties.GetIPGlobalProperties().DomainName;
return
local.Length == (hostString.Length - dot) &&
string.Compare(local, 0, hostString, dot, local.Length, StringComparison.OrdinalIgnoreCase) == 0;
}
private static bool IsAddressLocal(IPAddress ipAddress)
{
// Perf note: The .NET Framework caches this and then uses network change notifications to track
// whether the set should be recomputed. We could consider doing the same if this is observed as
// a bottleneck, but that tracking has its own costs.
IPAddress[] localAddresses = Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList; // TODO: Use synchronous GetHostEntry when available
for (int i = 0; i < localAddresses.Length; i++)
{
if (ipAddress.Equals(localAddresses[i]))
{
return true;
}
}
return false;
}
public bool IsBypassed(Uri host)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
return
Address == null ||
host.IsLoopback ||
(BypassProxyOnLocal && IsLocal(host)) ||
IsMatchInBypassList(host);
}
protected WebProxy(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
BypassProxyOnLocal = serializationInfo.GetBoolean("_BypassOnLocal");
Address = (Uri)serializationInfo.GetValue("_ProxyAddress", typeof(Uri));
_bypassList = (ArrayList)serializationInfo.GetValue("_BypassList", typeof(ArrayList));
UseDefaultCredentials = serializationInfo.GetBoolean("_UseDefaultCredentials");
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData(serializationInfo, streamingContext);
}
protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
serializationInfo.AddValue("_BypassOnLocal", BypassProxyOnLocal);
serializationInfo.AddValue("_ProxyAddress", Address);
serializationInfo.AddValue("_BypassList", _bypassList);
serializationInfo.AddValue("_UseDefaultCredentials", UseDefaultCredentials);
}
[Obsolete("This method has been deprecated. Please use the proxy selected for you by default. http://go.microsoft.com/fwlink/?linkid=14202")]
public static WebProxy GetDefaultProxy()
{
// The .NET Framework here returns a proxy that fetches IE settings and
// executes JavaScript to determine the correct proxy.
throw new PlatformNotSupportedException();
}
}
}
| Petermarcu/corefx | src/System.Net.WebProxy/src/System/Net/WebProxy.cs | C# | mit | 8,613 |
<?php
namespace Drupal\Core;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Utility\UnroutedUrlAssemblerInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Defines an object that holds information about a URL.
*/
class Url {
use DependencySerializationTrait;
/**
* The URL generator.
*
* @var \Drupal\Core\Routing\UrlGeneratorInterface
*/
protected $urlGenerator;
/**
* The unrouted URL assembler.
*
* @var \Drupal\Core\Utility\UnroutedUrlAssemblerInterface
*/
protected $urlAssembler;
/**
* The access manager
*
* @var \Drupal\Core\Access\AccessManagerInterface
*/
protected $accessManager;
/**
* The route name.
*
* @var string
*/
protected $routeName;
/**
* The route parameters.
*
* @var array
*/
protected $routeParameters = array();
/**
* The URL options.
*
* See \Drupal\Core\Url::fromUri() for details on the options.
*
* @var array
*/
protected $options = array();
/**
* Indicates whether this object contains an external URL.
*
* @var bool
*/
protected $external = FALSE;
/**
* Indicates whether this URL is for a URI without a Drupal route.
*
* @var bool
*/
protected $unrouted = FALSE;
/**
* The non-route URI.
*
* Only used if self::$unrouted is TRUE.
*
* @var string
*/
protected $uri;
/**
* Stores the internal path, if already requested by getInternalPath().
*
* @var string
*/
protected $internalPath;
/**
* Constructs a new Url object.
*
* In most cases, use Url::fromRoute() or Url::fromUri() rather than
* constructing Url objects directly in order to avoid ambiguity and make your
* code more self-documenting.
*
* @param string $route_name
* The name of the route
* @param array $route_parameters
* (optional) An associative array of parameter names and values.
* @param array $options
* See \Drupal\Core\Url::fromUri() for details.
*
* @see static::fromRoute()
* @see static::fromUri()
*
* @todo Update this documentation for non-routed URIs in
* https://www.drupal.org/node/2346787
*/
public function __construct($route_name, $route_parameters = array(), $options = array()) {
$this->routeName = $route_name;
$this->routeParameters = $route_parameters;
$this->options = $options;
}
/**
* Creates a new Url object for a URL that has a Drupal route.
*
* This method is for URLs that have Drupal routes (that is, most pages
* generated by Drupal). For non-routed local URIs relative to the base
* path (like robots.txt) use Url::fromUri() with the base: scheme.
*
* @param string $route_name
* The name of the route
* @param array $route_parameters
* (optional) An associative array of route parameter names and values.
* @param array $options
* See \Drupal\Core\Url::fromUri() for details.
*
* @return \Drupal\Core\Url
* A new Url object for a routed (internal to Drupal) URL.
*
* @see \Drupal\Core\Url::fromUserInput()
* @see \Drupal\Core\Url::fromUri()
*/
public static function fromRoute($route_name, $route_parameters = array(), $options = array()) {
return new static($route_name, $route_parameters, $options);
}
/**
* Creates a new URL object from a route match.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
*
* @return $this
*/
public static function fromRouteMatch(RouteMatchInterface $route_match) {
if ($route_match->getRouteObject()) {
return new static($route_match->getRouteName(), $route_match->getRawParameters()->all());
}
else {
throw new \InvalidArgumentException('Route required');
}
}
/**
* Creates a Url object for a relative URI reference submitted by user input.
*
* Use this method to create a URL for user-entered paths that may or may not
* correspond to a valid Drupal route.
*
* @param string $user_input
* User input for a link or path. The first character must be one of the
* following characters:
* - '/': A path within the current site. This path might be to a Drupal
* route (e.g., '/admin'), to a file (e.g., '/README.txt'), or to
* something processed by a non-Drupal script (e.g.,
* '/not/a/drupal/page'). If the path matches a Drupal route, then the
* URL generation will include Drupal's path processors (e.g.,
* language-prefixing and aliasing). Otherwise, the URL generation will
* just append the passed-in path to Drupal's base path.
* - '?': A query string for the current page or resource.
* - '#': A fragment (jump-link) on the current page or resource.
* This helps reduce ambiguity for user-entered links and paths, and
* supports user interfaces where users may normally use auto-completion
* to search for existing resources, but also may type one of these
* characters to link to (e.g.) a specific path on the site.
* (With regard to the URI specification, the user input is treated as a
* @link https://tools.ietf.org/html/rfc3986#section-4.2 relative URI reference @endlink
* where the relative part is of type
* @link https://tools.ietf.org/html/rfc3986#section-3.3 path-abempty @endlink.)
* @param array $options
* (optional) An array of options. See Url::fromUri() for details.
*
* @return static
* A new Url object based on user input.
*
* @throws \InvalidArgumentException
* Thrown when the user input does not begin with one of the following
* characters: '/', '?', or '#'.
*/
public static function fromUserInput($user_input, $options = []) {
// Ensuring one of these initial characters also enforces that what is
// passed is a relative URI reference rather than an absolute URI,
// because these are URI reserved characters that a scheme name may not
// start with.
if ((strpos($user_input, '/') !== 0) && (strpos($user_input, '#') !== 0) && (strpos($user_input, '?') !== 0)) {
throw new \InvalidArgumentException("The user-entered string '$user_input' must begin with a '/', '?', or '#'.");
}
// fromUri() requires an absolute URI, so prepend the appropriate scheme
// name.
return static::fromUri('internal:' . $user_input, $options);
}
/**
* Creates a new Url object from a URI.
*
* This method is for generating URLs for URIs that:
* - do not have Drupal routes: both external URLs and unrouted local URIs
* like base:robots.txt
* - do have a Drupal route but have a custom scheme to simplify linking.
* Currently, there is only the entity: scheme (This allows URIs of the
* form entity:{entity_type}/{entity_id}. For example: entity:node/1
* resolves to the entity.node.canonical route with a node parameter of 1.)
*
* For URLs that have Drupal routes (that is, most pages generated by Drupal),
* use Url::fromRoute().
*
* @param string $uri
* The URI of the resource including the scheme. For user input that may
* correspond to a Drupal route, use internal: for the scheme. For paths
* that are known not to be handled by the Drupal routing system (such as
* static files), use base: for the scheme to get a link relative to the
* Drupal base path (like the <base> HTML element). For a link to an entity
* you may use entity:{entity_type}/{entity_id} URIs. The internal: scheme
* should be avoided except when processing actual user input that may or
* may not correspond to a Drupal route. Normally use Url::fromRoute() for
* code linking to any any Drupal page.
* @param array $options
* (optional) An associative array of additional URL options, with the
* following elements:
* - 'query': An array of query key/value-pairs (without any URL-encoding)
* to append to the URL.
* - 'fragment': A fragment identifier (named anchor) to append to the URL.
* Do not include the leading '#' character.
* - 'absolute': Defaults to FALSE. Whether to force the output to be an
* absolute link (beginning with http:). Useful for links that will be
* displayed outside the site, such as in an RSS feed.
* - 'attributes': An associative array of HTML attributes that will be
* added to the anchor tag if you use the \Drupal\Core\Link class to make
* the link.
* - 'language': An optional language object used to look up the alias
* for the URL. If $options['language'] is omitted, it defaults to the
* current language for the language type LanguageInterface::TYPE_URL.
* - 'https': Whether this URL should point to a secure location. If not
* defined, the current scheme is used, so the user stays on HTTP or HTTPS
* respectively. TRUE enforces HTTPS and FALSE enforces HTTP.
*
* @return \Drupal\Core\Url
* A new Url object with properties depending on the URI scheme. Call the
* access() method on this to do access checking.
*
* @throws \InvalidArgumentException
* Thrown when the passed in path has no scheme.
*
* @see \Drupal\Core\Url::fromRoute()
* @see \Drupal\Core\Url::fromUserInput()
*/
public static function fromUri($uri, $options = []) {
// parse_url() incorrectly parses base:number/... as hostname:port/...
// and not the scheme. Prevent that by prefixing the path with a slash.
if (preg_match('/^base:\d/', $uri)) {
$uri = str_replace('base:', 'base:/', $uri);
}
$uri_parts = parse_url($uri);
if ($uri_parts === FALSE) {
throw new \InvalidArgumentException("The URI '$uri' is malformed.");
}
if (empty($uri_parts['scheme'])) {
throw new \InvalidArgumentException("The URI '$uri' is invalid. You must use a valid URI scheme.");
}
$uri_parts += ['path' => ''];
// Discard empty fragment in $options for consistency with parse_url().
if (isset($options['fragment']) && strlen($options['fragment']) == 0) {
unset($options['fragment']);
}
// Extract query parameters and fragment and merge them into $uri_options,
// but preserve the original $options for the fallback case.
$uri_options = $options;
if (isset($uri_parts['fragment'])) {
$uri_options += ['fragment' => $uri_parts['fragment']];
unset($uri_parts['fragment']);
}
if (!empty($uri_parts['query'])) {
$uri_query = [];
parse_str($uri_parts['query'], $uri_query);
$uri_options['query'] = isset($uri_options['query']) ? $uri_options['query'] + $uri_query : $uri_query;
unset($uri_parts['query']);
}
if ($uri_parts['scheme'] === 'entity') {
$url = static::fromEntityUri($uri_parts, $uri_options, $uri);
}
elseif ($uri_parts['scheme'] === 'internal') {
$url = static::fromInternalUri($uri_parts, $uri_options);
}
elseif ($uri_parts['scheme'] === 'route') {
$url = static::fromRouteUri($uri_parts, $uri_options, $uri);
}
else {
$url = new static($uri, array(), $options);
if ($uri_parts['scheme'] !== 'base') {
$url->external = TRUE;
$url->setOption('external', TRUE);
}
$url->setUnrouted();
}
return $url;
}
/**
* Create a new Url object for entity URIs.
*
* @param array $uri_parts
* Parts from an URI of the form entity:{entity_type}/{entity_id} as from
* parse_url().
* @param array $options
* An array of options, see \Drupal\Core\Url::fromUri() for details.
* @param string $uri
* The original entered URI.
*
* @return \Drupal\Core\Url
* A new Url object for an entity's canonical route.
*
* @throws \InvalidArgumentException
* Thrown if the entity URI is invalid.
*/
protected static function fromEntityUri(array $uri_parts, array $options, $uri) {
list($entity_type_id, $entity_id) = explode('/', $uri_parts['path'], 2);
if ($uri_parts['scheme'] != 'entity' || $entity_id === '') {
throw new \InvalidArgumentException("The entity URI '$uri' is invalid. You must specify the entity id in the URL. e.g., entity:node/1 for loading the canonical path to node entity with id 1.");
}
return new static("entity.$entity_type_id.canonical", [$entity_type_id => $entity_id], $options);
}
/**
* Creates a new Url object for 'internal:' URIs.
*
* Important note: the URI minus the scheme can NOT simply be validated by a
* \Drupal\Core\Path\PathValidatorInterface implementation. The semantics of
* the 'internal:' URI scheme are different:
* - PathValidatorInterface accepts paths without a leading slash (e.g.
* 'node/add') as well as 2 special paths: '<front>' and '<none>', which are
* mapped to the correspondingly named routes.
* - 'internal:' URIs store paths with a leading slash that represents the
* root — i.e. the front page — (e.g. 'internal:/node/add'), and doesn't
* have any exceptions.
*
* To clarify, a few examples of path plus corresponding 'internal:' URI:
* - 'node/add' -> 'internal:/node/add'
* - 'node/add?foo=bar' -> 'internal:/node/add?foo=bar'
* - 'node/add#kitten' -> 'internal:/node/add#kitten'
* - '<front>' -> 'internal:/'
* - '<front>foo=bar' -> 'internal:/?foo=bar'
* - '<front>#kitten' -> 'internal:/#kitten'
* - '<none>' -> 'internal:'
* - '<none>foo=bar' -> 'internal:?foo=bar'
* - '<none>#kitten' -> 'internal:#kitten'
*
* Therefore, when using a PathValidatorInterface to validate 'internal:'
* URIs, we must map:
* - 'internal:' (path component is '') to the special '<none>' path
* - 'internal:/' (path component is '/') to the special '<front>' path
* - 'internal:/some-path' (path component is '/some-path') to 'some-path'
*
* @param array $uri_parts
* Parts from an URI of the form internal:{path} as from parse_url().
* @param array $options
* An array of options, see \Drupal\Core\Url::fromUri() for details.
*
* @return \Drupal\Core\Url
* A new Url object for a 'internal:' URI.
*
* @throws \InvalidArgumentException
* Thrown when the URI's path component doesn't have a leading slash.
*/
protected static function fromInternalUri(array $uri_parts, array $options) {
// Both PathValidator::getUrlIfValidWithoutAccessCheck() and 'base:' URIs
// only accept/contain paths without a leading slash, unlike 'internal:'
// URIs, for which the leading slash means "relative to Drupal root" and
// "relative to Symfony app root" (just like in Symfony/Drupal 8 routes).
if (empty($uri_parts['path'])) {
$uri_parts['path'] = '<none>';
}
elseif ($uri_parts['path'] === '/') {
$uri_parts['path'] = '<front>';
}
else {
if ($uri_parts['path'][0] !== '/') {
throw new \InvalidArgumentException("The internal path component '{$uri_parts['path']}' is invalid. Its path component must have a leading slash, e.g. internal:/foo.");
}
// Remove the leading slash.
$uri_parts['path'] = substr($uri_parts['path'], 1);
if (UrlHelper::isExternal($uri_parts['path'])) {
throw new \InvalidArgumentException("The internal path component '{$uri_parts['path']}' is external. You are not allowed to specify an external URL together with internal:/.");
}
}
$url = \Drupal::pathValidator()
->getUrlIfValidWithoutAccessCheck($uri_parts['path']) ?: static::fromUri('base:' . $uri_parts['path'], $options);
// Allow specifying additional options.
$url->setOptions($options + $url->getOptions());
return $url;
}
/**
* Creates a new Url object for 'route:' URIs.
*
* @param array $uri_parts
* Parts from an URI of the form route:{route_name};{route_parameters} as
* from parse_url(), where the path is the route name optionally followed by
* a ";" followed by route parameters in key=value format with & separators.
* @param array $options
* An array of options, see \Drupal\Core\Url::fromUri() for details.
* @param string $uri
* The original passed in URI.
*
* @return \Drupal\Core\Url
* A new Url object for a 'route:' URI.
*
* @throws \InvalidArgumentException
* Thrown when the route URI does not have a route name.
*/
protected static function fromRouteUri(array $uri_parts, array $options, $uri) {
$route_parts = explode(';', $uri_parts['path'], 2);
$route_name = $route_parts[0];
if ($route_name === '') {
throw new \InvalidArgumentException("The route URI '$uri' is invalid. You must have a route name in the URI. e.g., route:system.admin");
}
$route_parameters = [];
if (!empty($route_parts[1])) {
parse_str($route_parts[1], $route_parameters);
}
return new static($route_name, $route_parameters, $options);
}
/**
* Returns the Url object matching a request.
*
* SECURITY NOTE: The request path is not checked to be valid and accessible
* by the current user to allow storing and reusing Url objects by different
* users. The 'path.validator' service getUrlIfValid() method should be used
* instead of this one if validation and access check is desired. Otherwise,
* 'access_manager' service checkNamedRoute() method should be used on the
* router name and parameters stored in the Url object returned by this
* method.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object.
*
* @return static
* A Url object. Warning: the object is created even if the current user
* would get an access denied running the same request via the normal page
* flow.
*
* @throws \Drupal\Core\Routing\MatchingRouteNotFoundException
* Thrown when the request cannot be matched.
*/
public static function createFromRequest(Request $request) {
// We use the router without access checks because URL objects might be
// created and stored for different users.
$result = \Drupal::service('router.no_access_checks')->matchRequest($request);
$route_name = $result[RouteObjectInterface::ROUTE_NAME];
$route_parameters = $result['_raw_variables']->all();
return new static($route_name, $route_parameters);
}
/**
* Sets this Url to encapsulate an unrouted URI.
*
* @return $this
*/
protected function setUnrouted() {
$this->unrouted = TRUE;
// What was passed in as the route name is actually the URI.
// @todo Consider fixing this in https://www.drupal.org/node/2346787.
$this->uri = $this->routeName;
// Set empty route name and parameters.
$this->routeName = NULL;
$this->routeParameters = array();
return $this;
}
/**
* Generates a URI string that represents tha data in the Url object.
*
* The URI will typically have the scheme of route: even if the object was
* constructed using an entity: or internal: scheme. A internal: URI that
* does not match a Drupal route with be returned here with the base: scheme,
* and external URLs will be returned in their original form.
*
* @return string
* A URI representation of the Url object data.
*/
public function toUriString() {
if ($this->isRouted()) {
$uri = 'route:' . $this->routeName;
if ($this->routeParameters) {
$uri .= ';' . UrlHelper::buildQuery($this->routeParameters);
}
}
else {
$uri = $this->uri;
}
$query = !empty($this->options['query']) ? ('?' . UrlHelper::buildQuery($this->options['query'])) : '';
$fragment = isset($this->options['fragment']) && strlen($this->options['fragment']) ? '#' . $this->options['fragment'] : '';
return $uri . $query . $fragment;
}
/**
* Indicates if this Url is external.
*
* @return bool
*/
public function isExternal() {
return $this->external;
}
/**
* Indicates if this Url has a Drupal route.
*
* @return bool
*/
public function isRouted() {
return !$this->unrouted;
}
/**
* Returns the route name.
*
* @return string
*
* @throws \UnexpectedValueException.
* If this is a URI with no corresponding route.
*/
public function getRouteName() {
if ($this->unrouted) {
throw new \UnexpectedValueException('External URLs do not have an internal route name.');
}
return $this->routeName;
}
/**
* Returns the route parameters.
*
* @return array
*
* @throws \UnexpectedValueException.
* If this is a URI with no corresponding route.
*/
public function getRouteParameters() {
if ($this->unrouted) {
throw new \UnexpectedValueException('External URLs do not have internal route parameters.');
}
return $this->routeParameters;
}
/**
* Sets the route parameters.
*
* @param array $parameters
* The array of parameters.
*
* @return $this
*
* @throws \UnexpectedValueException.
* If this is a URI with no corresponding route.
*/
public function setRouteParameters($parameters) {
if ($this->unrouted) {
throw new \UnexpectedValueException('External URLs do not have route parameters.');
}
$this->routeParameters = $parameters;
return $this;
}
/**
* Sets a specific route parameter.
*
* @param string $key
* The key of the route parameter.
* @param mixed $value
* The route parameter.
*
* @return $this
*
* @throws \UnexpectedValueException.
* If this is a URI with no corresponding route.
*/
public function setRouteParameter($key, $value) {
if ($this->unrouted) {
throw new \UnexpectedValueException('External URLs do not have route parameters.');
}
$this->routeParameters[$key] = $value;
return $this;
}
/**
* Returns the URL options.
*
* @return array
* The array of options. See \Drupal\Core\Url::fromUri() for details on what
* it contains.
*/
public function getOptions() {
return $this->options;
}
/**
* Gets a specific option.
*
* See \Drupal\Core\Url::fromUri() for details on the options.
*
* @param string $name
* The name of the option.
*
* @return mixed
* The value for a specific option, or NULL if it does not exist.
*/
public function getOption($name) {
if (!isset($this->options[$name])) {
return NULL;
}
return $this->options[$name];
}
/**
* Sets the URL options.
*
* @param array $options
* The array of options. See \Drupal\Core\Url::fromUri() for details on what
* it contains.
*
* @return $this
*/
public function setOptions($options) {
$this->options = $options;
return $this;
}
/**
* Sets a specific option.
*
* See \Drupal\Core\Url::fromUri() for details on the options.
*
* @param string $name
* The name of the option.
* @param mixed $value
* The option value.
*
* @return $this
*/
public function setOption($name, $value) {
$this->options[$name] = $value;
return $this;
}
/**
* Returns the URI value for this Url object.
*
* Only to be used if self::$unrouted is TRUE.
*
* @return string
* A URI not connected to a route. May be an external URL.
*
* @throws \UnexpectedValueException
* Thrown when the URI was requested for a routed URL.
*/
public function getUri() {
if (!$this->unrouted) {
throw new \UnexpectedValueException('This URL has a Drupal route, so the canonical form is not a URI.');
}
return $this->uri;
}
/**
* Sets the value of the absolute option for this Url.
*
* @param bool $absolute
* (optional) Whether to make this Url absolute or not. Defaults to TRUE.
*
* @return $this
*/
public function setAbsolute($absolute = TRUE) {
$this->options['absolute'] = $absolute;
return $this;
}
/**
* Generates the string URL representation for this Url object.
*
* For an external URL, the string will contain the input plus any query
* string or fragment specified by the options array.
*
* If this Url object was constructed from a Drupal route or from an internal
* URI (URIs using the internal:, base:, or entity: schemes), the returned
* string will either be a relative URL like /node/1 or an absolute URL like
* http://example.com/node/1 depending on the options array, plus any
* specified query string or fragment.
*
* @param bool $collect_bubbleable_metadata
* (optional) Defaults to FALSE. When TRUE, both the generated URL and its
* associated bubbleable metadata are returned.
*
* @return string|\Drupal\Core\GeneratedUrl
* A string URL.
* When $collect_bubbleable_metadata is TRUE, a GeneratedUrl object is
* returned, containing the generated URL plus bubbleable metadata.
*/
public function toString($collect_bubbleable_metadata = FALSE) {
if ($this->unrouted) {
return $this->unroutedUrlAssembler()->assemble($this->getUri(), $this->getOptions(), $collect_bubbleable_metadata);
}
return $this->urlGenerator()->generateFromRoute($this->getRouteName(), $this->getRouteParameters(), $this->getOptions(), $collect_bubbleable_metadata);
}
/**
* Returns the route information for a render array.
*
* @return array
* An associative array suitable for a render array.
*/
public function toRenderArray() {
$render_array = [
'#url' => $this,
'#options' => $this->getOptions(),
];
if (!$this->unrouted) {
$render_array['#access_callback'] = [get_class(), 'renderAccess'];
}
return $render_array;
}
/**
* Returns the internal path (system path) for this route.
*
* This path will not include any prefixes, fragments, or query strings.
*
* @return string
* The internal path for this route.
*
* @throws \UnexpectedValueException.
* If this is a URI with no corresponding system path.
*/
public function getInternalPath() {
if ($this->unrouted) {
throw new \UnexpectedValueException('Unrouted URIs do not have internal representations.');
}
if (!isset($this->internalPath)) {
$this->internalPath = $this->urlGenerator()->getPathFromRoute($this->getRouteName(), $this->getRouteParameters());
}
return $this->internalPath;
}
/**
* Checks this Url object against applicable access check services.
*
* Determines whether the route is accessible or not.
*
* @param \Drupal\Core\Session\AccountInterface $account
* (optional) Run access checks for this account. Defaults to the current
* user.
*
* @return bool
* Returns TRUE if the user has access to the url, otherwise FALSE.
*/
public function access(AccountInterface $account = NULL) {
if ($this->isRouted()) {
return $this->accessManager()->checkNamedRoute($this->getRouteName(), $this->getRouteParameters(), $account);
}
return TRUE;
}
/**
* Checks a Url render element against applicable access check services.
*
* @param array $element
* A render element as returned from \Drupal\Core\Url::toRenderArray().
*
* @return bool
* Returns TRUE if the current user has access to the url, otherwise FALSE.
*/
public static function renderAccess(array $element) {
return $element['#url']->access();
}
/**
* @return \Drupal\Core\Access\AccessManagerInterface
*/
protected function accessManager() {
if (!isset($this->accessManager)) {
$this->accessManager = \Drupal::service('access_manager');
}
return $this->accessManager;
}
/**
* Gets the URL generator.
*
* @return \Drupal\Core\Routing\UrlGeneratorInterface
* The URL generator.
*/
protected function urlGenerator() {
if (!$this->urlGenerator) {
$this->urlGenerator = \Drupal::urlGenerator();
}
return $this->urlGenerator;
}
/**
* Gets the unrouted URL assembler for non-Drupal URLs.
*
* @return \Drupal\Core\Utility\UnroutedUrlAssemblerInterface
* The unrouted URL assembler.
*/
protected function unroutedUrlAssembler() {
if (!$this->urlAssembler) {
$this->urlAssembler = \Drupal::service('unrouted_url_assembler');
}
return $this->urlAssembler;
}
/**
* Sets the URL generator.
*
* @param \Drupal\Core\Routing\UrlGeneratorInterface
* (optional) The URL generator, specify NULL to reset it.
*
* @return $this
*/
public function setUrlGenerator(UrlGeneratorInterface $url_generator = NULL) {
$this->urlGenerator = $url_generator;
$this->internalPath = NULL;
return $this;
}
/**
* Sets the unrouted URL assembler.
*
* @param \Drupal\Core\Utility\UnroutedUrlAssemblerInterface
* The unrouted URL assembler.
*
* @return $this
*/
public function setUnroutedUrlAssembler(UnroutedUrlAssemblerInterface $url_assembler) {
$this->urlAssembler = $url_assembler;
return $this;
}
}
| 318io/318-io | expo/www/core/lib/Drupal/Core/Url.php | PHP | gpl-2.0 | 29,307 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qnetworkaccessfilebackend_p.h"
#include "qfileinfo.h"
#include "qurlinfo.h"
#include "qdir.h"
#include "private/qnoncontiguousbytedevice_p.h"
#include <QtCore/QCoreApplication>
QT_BEGIN_NAMESPACE
QNetworkAccessBackend *
QNetworkAccessFileBackendFactory::create(QNetworkAccessManager::Operation op,
const QNetworkRequest &request) const
{
// is it an operation we know of?
switch (op) {
case QNetworkAccessManager::GetOperation:
case QNetworkAccessManager::PutOperation:
break;
default:
// no, we can't handle this operation
return 0;
}
QUrl url = request.url();
if (url.scheme().compare(QLatin1String("qrc"), Qt::CaseInsensitive) == 0 || url.isLocalFile()) {
return new QNetworkAccessFileBackend;
} else if (!url.isEmpty() && url.authority().isEmpty()) {
// check if QFile could, in theory, open this URL via the file engines
// it has to be in the format:
// prefix:path/to/file
// or prefix:/path/to/file
//
// this construct here must match the one below in open()
QFileInfo fi(url.toString(QUrl::RemoveAuthority | QUrl::RemoveFragment | QUrl::RemoveQuery));
// On Windows and Symbian the drive letter is detected as the scheme.
if (fi.exists() && (url.scheme().isEmpty() || (url.scheme().length() == 1)))
qWarning("QNetworkAccessFileBackendFactory: URL has no schema set, use file:// for files");
if (fi.exists() || (op == QNetworkAccessManager::PutOperation && fi.dir().exists()))
return new QNetworkAccessFileBackend;
}
return 0;
}
QNetworkAccessFileBackend::QNetworkAccessFileBackend()
: uploadByteDevice(0), totalBytes(0), hasUploadFinished(false)
{
}
QNetworkAccessFileBackend::~QNetworkAccessFileBackend()
{
}
void QNetworkAccessFileBackend::open()
{
QUrl url = this->url();
if (url.host() == QLatin1String("localhost"))
url.setHost(QString());
#if !defined(Q_OS_WIN)
// do not allow UNC paths on Unix
if (!url.host().isEmpty()) {
// we handle only local files
error(QNetworkReply::ProtocolInvalidOperationError,
QCoreApplication::translate("QNetworkAccessFileBackend", "Request for opening non-local file %1").arg(url.toString()));
finished();
return;
}
#endif // !defined(Q_OS_WIN)
if (url.path().isEmpty())
url.setPath(QLatin1String("/"));
setUrl(url);
QString fileName = url.toLocalFile();
if (fileName.isEmpty()) {
if (url.scheme() == QLatin1String("qrc"))
fileName = QLatin1Char(':') + url.path();
else
fileName = url.toString(QUrl::RemoveAuthority | QUrl::RemoveFragment | QUrl::RemoveQuery);
}
file.setFileName(fileName);
if (operation() == QNetworkAccessManager::GetOperation) {
if (!loadFileInfo())
return;
}
QIODevice::OpenMode mode;
switch (operation()) {
case QNetworkAccessManager::GetOperation:
mode = QIODevice::ReadOnly;
break;
case QNetworkAccessManager::PutOperation:
mode = QIODevice::WriteOnly | QIODevice::Truncate;
uploadByteDevice = createUploadByteDevice();
QObject::connect(uploadByteDevice, SIGNAL(readyRead()), this, SLOT(uploadReadyReadSlot()));
QMetaObject::invokeMethod(this, "uploadReadyReadSlot", Qt::QueuedConnection);
break;
default:
Q_ASSERT_X(false, "QNetworkAccessFileBackend::open",
"Got a request operation I cannot handle!!");
return;
}
mode |= QIODevice::Unbuffered;
bool opened = file.open(mode);
// could we open the file?
if (!opened) {
QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Error opening %1: %2")
.arg(this->url().toString(), file.errorString());
// why couldn't we open the file?
// if we're opening for reading, either it doesn't exist, or it's access denied
// if we're opening for writing, not existing means it's access denied too
if (file.exists() || operation() == QNetworkAccessManager::PutOperation)
error(QNetworkReply::ContentAccessDenied, msg);
else
error(QNetworkReply::ContentNotFoundError, msg);
finished();
}
}
void QNetworkAccessFileBackend::uploadReadyReadSlot()
{
if (hasUploadFinished)
return;
forever {
qint64 haveRead;
const char *readPointer = uploadByteDevice->readPointer(-1, haveRead);
if (haveRead == -1) {
// EOF
hasUploadFinished = true;
file.flush();
file.close();
finished();
break;
} else if (haveRead == 0 || readPointer == 0) {
// nothing to read right now, we will be called again later
break;
} else {
qint64 haveWritten;
haveWritten = file.write(readPointer, haveRead);
if (haveWritten < 0) {
// write error!
QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Write error writing to %1: %2")
.arg(url().toString(), file.errorString());
error(QNetworkReply::ProtocolFailure, msg);
finished();
return;
} else {
uploadByteDevice->advanceReadPointer(haveWritten);
}
file.flush();
}
}
}
void QNetworkAccessFileBackend::closeDownstreamChannel()
{
if (operation() == QNetworkAccessManager::GetOperation) {
file.close();
}
}
void QNetworkAccessFileBackend::downstreamReadyWrite()
{
Q_ASSERT_X(operation() == QNetworkAccessManager::GetOperation, "QNetworkAccessFileBackend",
"We're being told to download data but operation isn't GET!");
readMoreFromFile();
}
bool QNetworkAccessFileBackend::loadFileInfo()
{
QFileInfo fi(file);
setHeader(QNetworkRequest::LastModifiedHeader, fi.lastModified());
setHeader(QNetworkRequest::ContentLengthHeader, fi.size());
// signal we're open
metaDataChanged();
if (fi.isDir()) {
error(QNetworkReply::ContentOperationNotPermittedError,
QCoreApplication::translate("QNetworkAccessFileBackend", "Cannot open %1: Path is a directory").arg(url().toString()));
finished();
return false;
}
return true;
}
bool QNetworkAccessFileBackend::readMoreFromFile()
{
qint64 wantToRead;
while ((wantToRead = nextDownstreamBlockSize()) > 0) {
// ### FIXME!!
// Obtain a pointer from the ringbuffer!
// Avoid extra copy
QByteArray data;
data.reserve(wantToRead);
qint64 actuallyRead = file.read(data.data(), wantToRead);
if (actuallyRead <= 0) {
// EOF or error
if (file.error() != QFile::NoError) {
QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Read error reading from %1: %2")
.arg(url().toString(), file.errorString());
error(QNetworkReply::ProtocolFailure, msg);
finished();
return false;
}
finished();
return true;
}
data.resize(actuallyRead);
totalBytes += actuallyRead;
QByteDataBuffer list;
list.append(data);
data.clear(); // important because of implicit sharing!
writeDownstreamData(list);
}
return true;
}
QT_END_NAMESPACE
| dulton/vlc-2.1.4.32.subproject-2013-update2 | win32/include/qt4/src/network/access/qnetworkaccessfilebackend.cpp | C++ | gpl-2.0 | 9,651 |
/*
* Copyright (C) 2015 RECRUIT LIFESTYLE CO., LTD.
*
* 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 jp.co.recruit_lifestyle.android.widget.character;
import android.graphics.Path;
/**
* @author amyu
*/
public class ButterflyPath {
public static Path getButterflyPath(float width, float[] centerPoint){
Path path = new Path();
path.moveTo(centerPoint[0] - width / 2 + 0.501f * width, centerPoint[1] - width / 2 + 0.666f * width);
path.cubicTo(
centerPoint[0] - width / 2 + 0.47f * width, centerPoint[1] - width / 2 + 0.668f * width,
centerPoint[0] - width / 2 + 0.48f * width, centerPoint[1] - width / 2 + 0.548f * width,
centerPoint[0] - width / 2 + 0.479f * width, centerPoint[1] - width / 2 + 0.545f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.478f * width, centerPoint[1] - width / 2 + 0.541f * width,
centerPoint[0] - width / 2 + 0.479f * width, centerPoint[1] - width / 2 + 0.534f * width,
centerPoint[0] - width / 2 + 0.478f * width, centerPoint[1] - width / 2 + 0.532f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.476f * width, centerPoint[1] - width / 2 + 0.529f * width,
centerPoint[0] - width / 2 + 0.467f * width, centerPoint[1] - width / 2 + 0.54f * width,
centerPoint[0] - width / 2 + 0.447f * width, centerPoint[1] - width / 2 + 0.572f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.427f * width, centerPoint[1] - width / 2 + 0.605f * width,
centerPoint[0] - width / 2 + 0.378f * width, centerPoint[1] - width / 2 + 0.729f * width,
centerPoint[0] - width / 2 + 0.369f * width, centerPoint[1] - width / 2 + 0.734f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.361f * width, centerPoint[1] - width / 2 + 0.739f * width,
centerPoint[0] - width / 2 + 0.352f * width, centerPoint[1] - width / 2 + 0.733f * width,
centerPoint[0] - width / 2 + 0.348f * width, centerPoint[1] - width / 2 + 0.733f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.344f * width, centerPoint[1] - width / 2 + 0.732f * width,
centerPoint[0] - width / 2 + 0.341f * width, centerPoint[1] - width / 2 + 0.739f * width,
centerPoint[0] - width / 2 + 0.341f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.341f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.319f * width, centerPoint[1] - width / 2 + 0.787f * width,
centerPoint[0] - width / 2 + 0.31f * width, centerPoint[1] - width / 2 + 0.785f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.302f * width, centerPoint[1] - width / 2 + 0.783f * width,
centerPoint[0] - width / 2 + 0.303f * width, centerPoint[1] - width / 2 + 0.757f * width,
centerPoint[0] - width / 2 + 0.295f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.287f * width, centerPoint[1] - width / 2 + 0.752f * width,
centerPoint[0] - width / 2 + 0.275f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.271f * width, centerPoint[1] - width / 2 + 0.77f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.266f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.266f * width, centerPoint[1] - width / 2 + 0.764f * width,
centerPoint[0] - width / 2 + 0.264f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.263f * width, centerPoint[1] - width / 2 + 0.745f * width,
centerPoint[0] - width / 2 + 0.262f * width, centerPoint[1] - width / 2 + 0.744f * width,
centerPoint[0] - width / 2 + 0.252f * width, centerPoint[1] - width / 2 + 0.743f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.241f * width, centerPoint[1] - width / 2 + 0.743f * width,
centerPoint[0] - width / 2 + 0.206f * width, centerPoint[1] - width / 2 + 0.774f * width,
centerPoint[0] - width / 2 + 0.188f * width, centerPoint[1] - width / 2 + 0.803f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.17f * width, centerPoint[1] - width / 2 + 0.832f * width,
centerPoint[0] - width / 2 + 0.119f * width, centerPoint[1] - width / 2 + 0.857f * width,
centerPoint[0] - width / 2 + 0.109f * width, centerPoint[1] - width / 2 + 0.844f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.098f * width, centerPoint[1] - width / 2 + 0.831f * width,
centerPoint[0] - width / 2 + 0.111f * width, centerPoint[1] - width / 2 + 0.82f * width,
centerPoint[0] - width / 2 + 0.126f * width, centerPoint[1] - width / 2 + 0.803f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.141f * width, centerPoint[1] - width / 2 + 0.786f * width,
centerPoint[0] - width / 2 + 0.175f * width, centerPoint[1] - width / 2 + 0.765f * width,
centerPoint[0] - width / 2 + 0.188f * width, centerPoint[1] - width / 2 + 0.757f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.2f * width, centerPoint[1] - width / 2 + 0.749f * width,
centerPoint[0] - width / 2 + 0.23f * width, centerPoint[1] - width / 2 + 0.723f * width,
centerPoint[0] - width / 2 + 0.241f * width, centerPoint[1] - width / 2 + 0.701f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.252f * width, centerPoint[1] - width / 2 + 0.678f * width,
centerPoint[0] - width / 2 + 0.234f * width, centerPoint[1] - width / 2 + 0.669f * width,
centerPoint[0] - width / 2 + 0.224f * width, centerPoint[1] - width / 2 + 0.663f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.214f * width, centerPoint[1] - width / 2 + 0.656f * width,
centerPoint[0] - width / 2 + 0.225f * width, centerPoint[1] - width / 2 + 0.641f * width,
centerPoint[0] - width / 2 + 0.229f * width, centerPoint[1] - width / 2 + 0.634f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.232f * width, centerPoint[1] - width / 2 + 0.628f * width,
centerPoint[0] - width / 2 + 0.23f * width, centerPoint[1] - width / 2 + 0.62f * width,
centerPoint[0] - width / 2 + 0.223f * width, centerPoint[1] - width / 2 + 0.616f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.215f * width, centerPoint[1] - width / 2 + 0.612f * width,
centerPoint[0] - width / 2 + 0.207f * width, centerPoint[1] - width / 2 + 0.599f * width,
centerPoint[0] - width / 2 + 0.208f * width, centerPoint[1] - width / 2 + 0.59f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.21f * width, centerPoint[1] - width / 2 + 0.582f * width,
centerPoint[0] - width / 2 + 0.213f * width, centerPoint[1] - width / 2 + 0.578f * width,
centerPoint[0] - width / 2 + 0.212f * width, centerPoint[1] - width / 2 + 0.574f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.211f * width, centerPoint[1] - width / 2 + 0.569f * width,
centerPoint[0] - width / 2 + 0.199f * width, centerPoint[1] - width / 2 + 0.562f * width,
centerPoint[0] - width / 2 + 0.196f * width, centerPoint[1] - width / 2 + 0.555f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.193f * width, centerPoint[1] - width / 2 + 0.549f * width,
centerPoint[0] - width / 2 + 0.215f * width, centerPoint[1] - width / 2 + 0.531f * width,
centerPoint[0] - width / 2 + 0.217f * width, centerPoint[1] - width / 2 + 0.529f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.219f * width, centerPoint[1] - width / 2 + 0.527f * width,
centerPoint[0] - width / 2 + 0.22f * width, centerPoint[1] - width / 2 + 0.517f * width,
centerPoint[0] - width / 2 + 0.221f * width, centerPoint[1] - width / 2 + 0.511f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.222f * width, centerPoint[1] - width / 2 + 0.505f * width,
centerPoint[0] - width / 2 + 0.257f * width, centerPoint[1] - width / 2 + 0.488f * width,
centerPoint[0] - width / 2 + 0.259f * width, centerPoint[1] - width / 2 + 0.486f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.262f * width, centerPoint[1] - width / 2 + 0.483f * width,
centerPoint[0] - width / 2 + 0.262f * width, centerPoint[1] - width / 2 + 0.478f * width,
centerPoint[0] - width / 2 + 0.251f * width, centerPoint[1] - width / 2 + 0.48f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.24f * width, centerPoint[1] - width / 2 + 0.482f * width,
centerPoint[0] - width / 2 + 0.216f * width, centerPoint[1] - width / 2 + 0.471f * width,
centerPoint[0] - width / 2 + 0.207f * width, centerPoint[1] - width / 2 + 0.463f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.198f * width, centerPoint[1] - width / 2 + 0.456f * width,
centerPoint[0] - width / 2 + 0.188f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.186f * width, centerPoint[1] - width / 2 + 0.425f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.184f * width, centerPoint[1] - width / 2 + 0.418f * width,
centerPoint[0] - width / 2 + 0.182f * width, centerPoint[1] - width / 2 + 0.414f * width,
centerPoint[0] - width / 2 + 0.176f * width, centerPoint[1] - width / 2 + 0.407f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.171f * width, centerPoint[1] - width / 2 + 0.401f * width,
centerPoint[0] - width / 2 + 0.17f * width, centerPoint[1] - width / 2 + 0.39f * width,
centerPoint[0] - width / 2 + 0.168f * width, centerPoint[1] - width / 2 + 0.385f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.166f * width, centerPoint[1] - width / 2 + 0.38f * width,
centerPoint[0] - width / 2 + 0.153f * width, centerPoint[1] - width / 2 + 0.364f * width,
centerPoint[0] - width / 2 + 0.149f * width, centerPoint[1] - width / 2 + 0.357f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.144f * width, centerPoint[1] - width / 2 + 0.35f * width,
centerPoint[0] - width / 2 + 0.146f * width, centerPoint[1] - width / 2 + 0.345f * width,
centerPoint[0] - width / 2 + 0.144f * width, centerPoint[1] - width / 2 + 0.34f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.143f * width, centerPoint[1] - width / 2 + 0.334f * width,
centerPoint[0] - width / 2 + 0.132f * width, centerPoint[1] - width / 2 + 0.322f * width,
centerPoint[0] - width / 2 + 0.129f * width, centerPoint[1] - width / 2 + 0.317f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.126f * width, centerPoint[1] - width / 2 + 0.311f * width,
centerPoint[0] - width / 2 + 0.125f * width, centerPoint[1] - width / 2 + 0.3f * width,
centerPoint[0] - width / 2 + 0.123f * width, centerPoint[1] - width / 2 + 0.297f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.121f * width, centerPoint[1] - width / 2 + 0.293f * width,
centerPoint[0] - width / 2 + 0.112f * width, centerPoint[1] - width / 2 + 0.277f * width,
centerPoint[0] - width / 2 + 0.11f * width, centerPoint[1] - width / 2 + 0.272f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.108f * width, centerPoint[1] - width / 2 + 0.268f * width,
centerPoint[0] - width / 2 + 0.104f * width, centerPoint[1] - width / 2 + 0.259f * width,
centerPoint[0] - width / 2 + 0.097f * width, centerPoint[1] - width / 2 + 0.251f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.091f * width, centerPoint[1] - width / 2 + 0.244f * width,
centerPoint[0] - width / 2 + 0.066f * width, centerPoint[1] - width / 2 + 0.2f * width,
centerPoint[0] - width / 2 + 0.061f * width, centerPoint[1] - width / 2 + 0.184f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.056f * width, centerPoint[1] - width / 2 + 0.168f * width,
centerPoint[0] - width / 2 + 0.073f * width, centerPoint[1] - width / 2 + 0.157f * width,
centerPoint[0] - width / 2 + 0.104f * width, centerPoint[1] - width / 2 + 0.153f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.136f * width, centerPoint[1] - width / 2 + 0.149f * width,
centerPoint[0] - width / 2 + 0.173f * width, centerPoint[1] - width / 2 + 0.162f * width,
centerPoint[0] - width / 2 + 0.223f * width, centerPoint[1] - width / 2 + 0.184f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.273f * width, centerPoint[1] - width / 2 + 0.206f * width,
centerPoint[0] - width / 2 + 0.316f * width, centerPoint[1] - width / 2 + 0.25f * width,
centerPoint[0] - width / 2 + 0.367f * width, centerPoint[1] - width / 2 + 0.3f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.418f * width, centerPoint[1] - width / 2 + 0.349f * width,
centerPoint[0] - width / 2 + 0.48f * width, centerPoint[1] - width / 2 + 0.462f * width,
centerPoint[0] - width / 2 + 0.482f * width, centerPoint[1] - width / 2 + 0.461f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.484f * width, centerPoint[1] - width / 2 + 0.461f * width,
centerPoint[0] - width / 2 + 0.482f * width, centerPoint[1] - width / 2 + 0.455f * width,
centerPoint[0] - width / 2 + 0.48f * width, centerPoint[1] - width / 2 + 0.449f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.478f * width, centerPoint[1] - width / 2 + 0.444f * width,
centerPoint[0] - width / 2 + 0.483f * width, centerPoint[1] - width / 2 + 0.436f * width,
centerPoint[0] - width / 2 + 0.483f * width, centerPoint[1] - width / 2 + 0.436f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.483f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.484f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.484f * width, centerPoint[1] - width / 2 + 0.433f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.484f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.481f * width, centerPoint[1] - width / 2 + 0.427f * width,
centerPoint[0] - width / 2 + 0.482f * width, centerPoint[1] - width / 2 + 0.421f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.483f * width, centerPoint[1] - width / 2 + 0.416f * width,
centerPoint[0] - width / 2 + 0.491f * width, centerPoint[1] - width / 2 + 0.414f * width,
centerPoint[0] - width / 2 + 0.491f * width, centerPoint[1] - width / 2 + 0.414f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.485f * width, centerPoint[1] - width / 2 + 0.406f * width,
centerPoint[0] - width / 2 + 0.401f * width, centerPoint[1] - width / 2 + 0.307f * width,
centerPoint[0] - width / 2 + 0.401f * width, centerPoint[1] - width / 2 + 0.307f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.394f * width, centerPoint[1] - width / 2 + 0.305f * width,
centerPoint[0] - width / 2 + 0.385f * width, centerPoint[1] - width / 2 + 0.294f * width,
centerPoint[0] - width / 2 + 0.387f * width, centerPoint[1] - width / 2 + 0.293f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.389f * width, centerPoint[1] - width / 2 + 0.292f * width,
centerPoint[0] - width / 2 + 0.392f * width, centerPoint[1] - width / 2 + 0.291f * width,
centerPoint[0] - width / 2 + 0.405f * width, centerPoint[1] - width / 2 + 0.305f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.418f * width, centerPoint[1] - width / 2 + 0.32f * width,
centerPoint[0] - width / 2 + 0.495f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.495f * width, centerPoint[1] - width / 2 + 0.413f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.495f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.498f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.5f * width, centerPoint[1] - width / 2 + 0.413f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.502f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.505f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.505f * width, centerPoint[1] - width / 2 + 0.413f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.505f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.582f * width, centerPoint[1] - width / 2 + 0.32f * width,
centerPoint[0] - width / 2 + 0.595f * width, centerPoint[1] - width / 2 + 0.305f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.608f * width, centerPoint[1] - width / 2 + 0.291f * width,
centerPoint[0] - width / 2 + 0.611f * width, centerPoint[1] - width / 2 + 0.292f * width,
centerPoint[0] - width / 2 + 0.613f * width, centerPoint[1] - width / 2 + 0.293f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.615f * width, centerPoint[1] - width / 2 + 0.294f * width,
centerPoint[0] - width / 2 + 0.606f * width, centerPoint[1] - width / 2 + 0.305f * width,
centerPoint[0] - width / 2 + 0.599f * width, centerPoint[1] - width / 2 + 0.307f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.599f * width, centerPoint[1] - width / 2 + 0.307f * width,
centerPoint[0] - width / 2 + 0.515f * width, centerPoint[1] - width / 2 + 0.406f * width,
centerPoint[0] - width / 2 + 0.509f * width, centerPoint[1] - width / 2 + 0.414f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.509f * width, centerPoint[1] - width / 2 + 0.414f * width,
centerPoint[0] - width / 2 + 0.517f * width, centerPoint[1] - width / 2 + 0.416f * width,
centerPoint[0] - width / 2 + 0.518f * width, centerPoint[1] - width / 2 + 0.421f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.519f * width, centerPoint[1] - width / 2 + 0.427f * width,
centerPoint[0] - width / 2 + 0.516f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.516f * width, centerPoint[1] - width / 2 + 0.433f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.516f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.517f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.517f * width, centerPoint[1] - width / 2 + 0.436f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.517f * width, centerPoint[1] - width / 2 + 0.436f * width,
centerPoint[0] - width / 2 + 0.522f * width, centerPoint[1] - width / 2 + 0.444f * width,
centerPoint[0] - width / 2 + 0.52f * width, centerPoint[1] - width / 2 + 0.449f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.518f * width, centerPoint[1] - width / 2 + 0.455f * width,
centerPoint[0] - width / 2 + 0.516f * width, centerPoint[1] - width / 2 + 0.461f * width,
centerPoint[0] - width / 2 + 0.518f * width, centerPoint[1] - width / 2 + 0.461f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.52f * width, centerPoint[1] - width / 2 + 0.462f * width,
centerPoint[0] - width / 2 + 0.582f * width, centerPoint[1] - width / 2 + 0.349f * width,
centerPoint[0] - width / 2 + 0.633f * width, centerPoint[1] - width / 2 + 0.3f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.684f * width, centerPoint[1] - width / 2 + 0.25f * width,
centerPoint[0] - width / 2 + 0.727f * width, centerPoint[1] - width / 2 + 0.206f * width,
centerPoint[0] - width / 2 + 0.777f * width, centerPoint[1] - width / 2 + 0.184f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.827f * width, centerPoint[1] - width / 2 + 0.162f * width,
centerPoint[0] - width / 2 + 0.864f * width, centerPoint[1] - width / 2 + 0.149f * width,
centerPoint[0] - width / 2 + 0.896f * width, centerPoint[1] - width / 2 + 0.153f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.927f * width, centerPoint[1] - width / 2 + 0.157f * width,
centerPoint[0] - width / 2 + 0.944f * width, centerPoint[1] - width / 2 + 0.168f * width,
centerPoint[0] - width / 2 + 0.939f * width, centerPoint[1] - width / 2 + 0.184f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.934f * width, centerPoint[1] - width / 2 + 0.2f * width,
centerPoint[0] - width / 2 + 0.909f * width, centerPoint[1] - width / 2 + 0.244f * width,
centerPoint[0] - width / 2 + 0.903f * width, centerPoint[1] - width / 2 + 0.251f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.896f * width, centerPoint[1] - width / 2 + 0.259f * width,
centerPoint[0] - width / 2 + 0.892f * width, centerPoint[1] - width / 2 + 0.268f * width,
centerPoint[0] - width / 2 + 0.89f * width, centerPoint[1] - width / 2 + 0.272f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.888f * width, centerPoint[1] - width / 2 + 0.277f * width,
centerPoint[0] - width / 2 + 0.879f * width, centerPoint[1] - width / 2 + 0.293f * width,
centerPoint[0] - width / 2 + 0.877f * width, centerPoint[1] - width / 2 + 0.297f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.875f * width, centerPoint[1] - width / 2 + 0.3f * width,
centerPoint[0] - width / 2 + 0.874f * width, centerPoint[1] - width / 2 + 0.311f * width,
centerPoint[0] - width / 2 + 0.871f * width, centerPoint[1] - width / 2 + 0.317f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.868f * width, centerPoint[1] - width / 2 + 0.322f * width,
centerPoint[0] - width / 2 + 0.857f * width, centerPoint[1] - width / 2 + 0.334f * width,
centerPoint[0] - width / 2 + 0.856f * width, centerPoint[1] - width / 2 + 0.34f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.854f * width, centerPoint[1] - width / 2 + 0.345f * width,
centerPoint[0] - width / 2 + 0.856f * width, centerPoint[1] - width / 2 + 0.35f * width,
centerPoint[0] - width / 2 + 0.851f * width, centerPoint[1] - width / 2 + 0.357f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.847f * width, centerPoint[1] - width / 2 + 0.364f * width,
centerPoint[0] - width / 2 + 0.834f * width, centerPoint[1] - width / 2 + 0.38f * width,
centerPoint[0] - width / 2 + 0.832f * width, centerPoint[1] - width / 2 + 0.385f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.83f * width, centerPoint[1] - width / 2 + 0.39f * width,
centerPoint[0] - width / 2 + 0.829f * width, centerPoint[1] - width / 2 + 0.401f * width,
centerPoint[0] - width / 2 + 0.824f * width, centerPoint[1] - width / 2 + 0.407f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.818f * width, centerPoint[1] - width / 2 + 0.414f * width,
centerPoint[0] - width / 2 + 0.816f * width, centerPoint[1] - width / 2 + 0.418f * width,
centerPoint[0] - width / 2 + 0.814f * width, centerPoint[1] - width / 2 + 0.425f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.812f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.802f * width, centerPoint[1] - width / 2 + 0.456f * width,
centerPoint[0] - width / 2 + 0.793f * width, centerPoint[1] - width / 2 + 0.463f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.784f * width, centerPoint[1] - width / 2 + 0.471f * width,
centerPoint[0] - width / 2 + 0.76f * width, centerPoint[1] - width / 2 + 0.482f * width,
centerPoint[0] - width / 2 + 0.749f * width, centerPoint[1] - width / 2 + 0.48f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.738f * width, centerPoint[1] - width / 2 + 0.478f * width,
centerPoint[0] - width / 2 + 0.738f * width, centerPoint[1] - width / 2 + 0.483f * width,
centerPoint[0] - width / 2 + 0.741f * width, centerPoint[1] - width / 2 + 0.486f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.743f * width, centerPoint[1] - width / 2 + 0.488f * width,
centerPoint[0] - width / 2 + 0.778f * width, centerPoint[1] - width / 2 + 0.505f * width,
centerPoint[0] - width / 2 + 0.779f * width, centerPoint[1] - width / 2 + 0.511f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.78f * width, centerPoint[1] - width / 2 + 0.517f * width,
centerPoint[0] - width / 2 + 0.781f * width, centerPoint[1] - width / 2 + 0.527f * width,
centerPoint[0] - width / 2 + 0.783f * width, centerPoint[1] - width / 2 + 0.529f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.785f * width, centerPoint[1] - width / 2 + 0.531f * width,
centerPoint[0] - width / 2 + 0.807f * width, centerPoint[1] - width / 2 + 0.549f * width,
centerPoint[0] - width / 2 + 0.804f * width, centerPoint[1] - width / 2 + 0.555f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.801f * width, centerPoint[1] - width / 2 + 0.562f * width,
centerPoint[0] - width / 2 + 0.789f * width, centerPoint[1] - width / 2 + 0.569f * width,
centerPoint[0] - width / 2 + 0.788f * width, centerPoint[1] - width / 2 + 0.574f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.787f * width, centerPoint[1] - width / 2 + 0.578f * width,
centerPoint[0] - width / 2 + 0.79f * width, centerPoint[1] - width / 2 + 0.582f * width,
centerPoint[0] - width / 2 + 0.792f * width, centerPoint[1] - width / 2 + 0.59f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.793f * width, centerPoint[1] - width / 2 + 0.599f * width,
centerPoint[0] - width / 2 + 0.785f * width, centerPoint[1] - width / 2 + 0.612f * width,
centerPoint[0] - width / 2 + 0.777f * width, centerPoint[1] - width / 2 + 0.616f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.77f * width, centerPoint[1] - width / 2 + 0.62f * width,
centerPoint[0] - width / 2 + 0.768f * width, centerPoint[1] - width / 2 + 0.628f * width,
centerPoint[0] - width / 2 + 0.771f * width, centerPoint[1] - width / 2 + 0.634f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.775f * width, centerPoint[1] - width / 2 + 0.641f * width,
centerPoint[0] - width / 2 + 0.786f * width, centerPoint[1] - width / 2 + 0.656f * width,
centerPoint[0] - width / 2 + 0.776f * width, centerPoint[1] - width / 2 + 0.663f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.766f * width, centerPoint[1] - width / 2 + 0.669f * width,
centerPoint[0] - width / 2 + 0.748f * width, centerPoint[1] - width / 2 + 0.678f * width,
centerPoint[0] - width / 2 + 0.759f * width, centerPoint[1] - width / 2 + 0.701f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.77f * width, centerPoint[1] - width / 2 + 0.723f * width,
centerPoint[0] - width / 2 + 0.8f * width, centerPoint[1] - width / 2 + 0.749f * width,
centerPoint[0] - width / 2 + 0.812f * width, centerPoint[1] - width / 2 + 0.757f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.825f * width, centerPoint[1] - width / 2 + 0.765f * width,
centerPoint[0] - width / 2 + 0.859f * width, centerPoint[1] - width / 2 + 0.786f * width,
centerPoint[0] - width / 2 + 0.874f * width, centerPoint[1] - width / 2 + 0.803f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.889f * width, centerPoint[1] - width / 2 + 0.82f * width,
centerPoint[0] - width / 2 + 0.902f * width, centerPoint[1] - width / 2 + 0.831f * width,
centerPoint[0] - width / 2 + 0.891f * width, centerPoint[1] - width / 2 + 0.844f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.881f * width, centerPoint[1] - width / 2 + 0.857f * width,
centerPoint[0] - width / 2 + 0.83f * width, centerPoint[1] - width / 2 + 0.832f * width,
centerPoint[0] - width / 2 + 0.812f * width, centerPoint[1] - width / 2 + 0.803f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.794f * width, centerPoint[1] - width / 2 + 0.774f * width,
centerPoint[0] - width / 2 + 0.759f * width, centerPoint[1] - width / 2 + 0.743f * width,
centerPoint[0] - width / 2 + 0.748f * width, centerPoint[1] - width / 2 + 0.743f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.738f * width, centerPoint[1] - width / 2 + 0.744f * width,
centerPoint[0] - width / 2 + 0.738f * width, centerPoint[1] - width / 2 + 0.745f * width,
centerPoint[0] - width / 2 + 0.736f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.734f * width, centerPoint[1] - width / 2 + 0.764f * width,
centerPoint[0] - width / 2 + 0.734f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.729f * width, centerPoint[1] - width / 2 + 0.77f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.725f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.713f * width, centerPoint[1] - width / 2 + 0.752f * width,
centerPoint[0] - width / 2 + 0.705f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.697f * width, centerPoint[1] - width / 2 + 0.757f * width,
centerPoint[0] - width / 2 + 0.698f * width, centerPoint[1] - width / 2 + 0.783f * width,
centerPoint[0] - width / 2 + 0.69f * width, centerPoint[1] - width / 2 + 0.785f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.681f * width, centerPoint[1] - width / 2 + 0.787f * width,
centerPoint[0] - width / 2 + 0.659f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.659f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.659f * width, centerPoint[1] - width / 2 + 0.739f * width,
centerPoint[0] - width / 2 + 0.656f * width, centerPoint[1] - width / 2 + 0.732f * width,
centerPoint[0] - width / 2 + 0.652f * width, centerPoint[1] - width / 2 + 0.733f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.648f * width, centerPoint[1] - width / 2 + 0.733f * width,
centerPoint[0] - width / 2 + 0.639f * width, centerPoint[1] - width / 2 + 0.739f * width,
centerPoint[0] - width / 2 + 0.631f * width, centerPoint[1] - width / 2 + 0.734f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.622f * width, centerPoint[1] - width / 2 + 0.729f * width,
centerPoint[0] - width / 2 + 0.573f * width, centerPoint[1] - width / 2 + 0.605f * width,
centerPoint[0] - width / 2 + 0.553f * width, centerPoint[1] - width / 2 + 0.572f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.533f * width, centerPoint[1] - width / 2 + 0.54f * width,
centerPoint[0] - width / 2 + 0.524f * width, centerPoint[1] - width / 2 + 0.529f * width,
centerPoint[0] - width / 2 + 0.522f * width, centerPoint[1] - width / 2 + 0.532f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.521f * width, centerPoint[1] - width / 2 + 0.534f * width,
centerPoint[0] - width / 2 + 0.522f * width, centerPoint[1] - width / 2 + 0.541f * width,
centerPoint[0] - width / 2 + 0.521f * width, centerPoint[1] - width / 2 + 0.545f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.52f * width, centerPoint[1] - width / 2 + 0.548f * width,
centerPoint[0] - width / 2 + 0.532f * width, centerPoint[1] - width / 2 + 0.668f * width,
centerPoint[0] - width / 2 + 0.501f * width, centerPoint[1] - width / 2 + 0.666f * width
);
return path;
}
}
| cheyiliu/test4XXX | test4ColoringLoading/src/jp/co/recruit_lifestyle/android/widget/character/ButterflyPath.java | Java | apache-2.0 | 33,662 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Mapping\Loader;
use Symfony\Component\Serializer\Exception\MappingException;
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
/**
* Calls multiple {@link LoaderInterface} instances in a chain.
*
* This class accepts multiple instances of LoaderInterface to be passed to the
* constructor. When {@link loadClassMetadata()} is called, the same method is called
* in <em>all</em> of these loaders, regardless of whether any of them was
* successful or not.
*
* @author Bernhard Schussek <bschussek@gmail.com>
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class LoaderChain implements LoaderInterface
{
private $loaders;
/**
* Accepts a list of LoaderInterface instances.
*
* @param LoaderInterface[] $loaders An array of LoaderInterface instances
*
* @throws MappingException If any of the loaders does not implement LoaderInterface
*/
public function __construct(array $loaders)
{
foreach ($loaders as $loader) {
if (!$loader instanceof LoaderInterface) {
throw new MappingException(sprintf('Class %s is expected to implement LoaderInterface', get_class($loader)));
}
}
$this->loaders = $loaders;
}
/**
* {@inheritdoc}
*/
public function loadClassMetadata(ClassMetadataInterface $metadata)
{
$success = false;
foreach ($this->loaders as $loader) {
$success = $loader->loadClassMetadata($metadata) || $success;
}
return $success;
}
/**
* @return LoaderInterface[]
*/
public function getLoaders()
{
return $this->loaders;
}
}
| MisterNono/camping | vendor/symfony/symfony/src/Symfony/Component/Serializer/Mapping/Loader/LoaderChain.php | PHP | apache-2.0 | 1,953 |
/*=============================================================================
Library: XNAT/Core
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include "ctkXnatObjectPrivate.h"
#include <QString>
//----------------------------------------------------------------------------
ctkXnatObjectPrivate::ctkXnatObjectPrivate()
: fetched(false)
, parent(0)
{
}
//----------------------------------------------------------------------------
ctkXnatObjectPrivate::~ctkXnatObjectPrivate()
{
}
| pieper/CTK | Libs/XNAT/Core/ctkXnatObjectPrivate.cpp | C++ | apache-2.0 | 1,167 |
module Metric::Processing
DERIVED_COLS = [
:derived_cpu_available,
:derived_cpu_reserved,
:derived_host_count_off,
:derived_host_count_on,
:derived_host_count_total,
:derived_memory_available,
:derived_memory_reserved,
:derived_memory_used,
:derived_host_sockets,
:derived_vm_allocated_disk_storage,
:derived_vm_count_off,
:derived_vm_count_on,
:derived_vm_count_total,
:derived_vm_numvcpus, # TODO: This is cpu_total_cores and needs to be renamed, but reports depend on the name :numvcpus
# See also #TODO on VimPerformanceState.capture
:derived_vm_used_disk_storage,
# TODO(lsmola) as described below, this field should be named derived_cpu_used
:cpu_usagemhz_rate_average
]
VALID_PROCESS_TARGETS = [
VmOrTemplate,
Container,
ContainerGroup,
ContainerNode,
ContainerProject,
ContainerReplicator,
ContainerService,
Host,
AvailabilityZone,
HostAggregate,
EmsCluster,
ExtManagementSystem,
MiqRegion,
MiqEnterprise
]
def self.process_derived_columns(obj, attrs, ts = nil)
unless VALID_PROCESS_TARGETS.any? { |t| obj.kind_of?(t) }
raise _("object %{name} is not one of %{items}") % {:name => obj,
:items => VALID_PROCESS_TARGETS.collect(&:name).join(", ")}
end
ts = attrs[:timestamp] if ts.nil?
state = obj.vim_performance_state_for_ts(ts)
total_cpu = state.total_cpu || 0
total_mem = state.total_mem || 0
result = {}
have_cpu_metrics = attrs[:cpu_usage_rate_average] || attrs[:cpu_usagemhz_rate_average]
have_mem_metrics = attrs[:mem_usage_absolute_average] || attrs[:derived_memory_used]
DERIVED_COLS.each do |col|
dummy, group, typ, mode = col.to_s.split("_")
case typ
when "available"
# Do not derive "available" values if there haven't been any usage
# values collected
if group == "cpu"
result[col] = total_cpu if have_cpu_metrics && total_cpu > 0
else
result[col] = total_mem if have_mem_metrics && total_mem > 0
end
when "allocated"
method = col.to_s.split("_")[1..-1].join("_")
result[col] = state.send(method) if state.respond_to?(method)
when "used"
if group == "cpu"
# TODO: This branch is never called because there isn't a column
# called derived_cpu_used. The callers, such as chargeback, generally
# use cpu_usagemhz_rate_average directly, and the column may not be
# needed, but perhaps should be added to normalize like is done for
# memory. The derivation here could then use cpu_usagemhz_rate_average
# directly if avaiable, otherwise do the calculation below.
result[col] = (attrs[:cpu_usage_rate_average] / 100 * total_cpu) unless total_cpu == 0 || attrs[:cpu_usage_rate_average].nil?
elsif group == "memory"
if attrs[:mem_usage_absolute_average].nil?
# If we can't get percentage usage, just used RAM in MB, lets compute percentage usage
attrs[:mem_usage_absolute_average] = 100.0 / total_mem * attrs[:derived_memory_used] if total_mem > 0 && !attrs[:derived_memory_used].nil?
else
# We have percentage usage of RAM, lets compute consumed RAM in MB
result[col] = (attrs[:mem_usage_absolute_average] / 100 * total_mem) unless total_mem == 0 || attrs[:mem_usage_absolute_average].nil?
end
else
method = col.to_s.split("_")[1..-1].join("_")
result[col] = state.send(method) if state.respond_to?(method)
end
when "rate"
if col.to_s == "cpu_usagemhz_rate_average" && attrs[:cpu_usagemhz_rate_average].blank?
# TODO(lsmola) for some reason, this column is used in chart, although from processing code above, it should
# be named derived_cpu_used. Investigate what is the right solution and make it right. For now lets fill
# the column shown in charts.
result[col] = (attrs[:cpu_usage_rate_average] / 100 * total_cpu) unless total_cpu == 0 || attrs[:cpu_usage_rate_average].nil?
end
when "reserved"
method = group == "cpu" ? :reserve_cpu : :reserve_mem
result[col] = state.send(method)
when "count"
method = [group, typ, mode].join("_")
result[col] = state.send(method)
when "numvcpus" # This is actually logical cpus. See note above.
# Do not derive "available" values if there haven't been any usage
# values collected
result[col] = state.numvcpus if have_cpu_metrics && state.try(:numvcpus).to_i > 0
when "sockets"
result[col] = state.host_sockets
end
end
result[:assoc_ids] = state.assoc_ids
result[:tag_names] = state.tag_names
result[:parent_host_id] = state.parent_host_id
result[:parent_storage_id] = state.parent_storage_id
result[:parent_ems_id] = state.parent_ems_id
result[:parent_ems_cluster_id] = state.parent_ems_cluster_id
result
end
def self.add_missing_intervals(obj, interval_name, start_time, end_time)
klass, meth = Metric::Helper.class_and_association_for_interval_name(interval_name)
scope = obj.send(meth).for_time_range(start_time, end_time)
scope = scope.where(:capture_interval_name => interval_name) if interval_name != "realtime"
extrapolate(klass, scope)
end
def self.extrapolate(klass, scope)
last_perf = {}
scope.order("timestamp, capture_interval_name").each do |perf|
interval = interval_name_to_interval(perf.capture_interval_name)
last_perf[interval] = perf if last_perf[interval].nil?
if (perf.timestamp - last_perf[interval].timestamp) <= interval
last_perf[interval] = perf
next
end
new_perf = create_new_metric(klass, last_perf[interval], perf, interval)
new_perf.save!
last_perf[interval] = perf
end
end
def self.create_new_metric(klass, last_perf, perf, interval)
attrs = last_perf.attributes
attrs.delete('id')
attrs['timestamp'] += interval
attrs['capture_interval'] = 0
new_perf = klass.new(attrs)
Metric::Rollup::ROLLUP_COLS.each do |c|
next if new_perf.send(c).nil? || perf.send(c).nil?
new_perf.send(c.to_s + "=", (new_perf.send(c) + perf.send(c)) / 2)
end
unless perf.assoc_ids.nil?
Metric::Rollup::ASSOC_KEYS.each do |assoc|
next if new_perf.assoc_ids.nil? || new_perf.assoc_ids[assoc].blank? || perf.assoc_ids[assoc].blank?
new_perf.assoc_ids[assoc][:on] ||= []
new_perf.assoc_ids[assoc][:off] ||= []
new_perf.assoc_ids[assoc][:on] = (new_perf.assoc_ids[assoc][:on] + perf.assoc_ids[assoc][:on]).uniq!
new_perf.assoc_ids[assoc][:off] = (new_perf.assoc_ids[assoc][:off] + perf.assoc_ids[assoc][:off]).uniq!
end
end
new_perf
end
private_class_method :extrapolate, :create_new_metric
def self.interval_name_to_interval(name)
case name
when "realtime" then 20
when "hourly" then 1.hour.to_i
when "daily" then 1.day.to_i
else raise _("unknown interval name: [%{name}]") % {:name => name}
end
end
end
| mfeifer/manageiq | app/models/metric/processing.rb | Ruby | apache-2.0 | 7,255 |
( function ( mw, $ ) {
mw.page = {};
// Client profile classes for <html>
// Allows for easy hiding/showing of JS or no-JS-specific UI elements
$( 'html' )
.addClass( 'client-js' )
.removeClass( 'client-nojs' );
$( function () {
// Initialize utilities as soon as the document is ready (mw.util.$content,
// messageBoxNew, profile, tooltip access keys, Table of contents toggle, ..).
// In the domready here instead of in mediawiki.page.ready to ensure that it gets enqueued
// before other modules hook into domready, so that mw.util.$content (defined by
// mw.util.init), is defined for them.
mw.util.init();
/**
* @event wikipage_content
* @member mw.hook
* @param {jQuery} $content
*/
mw.hook( 'wikipage.content' ).fire( $( '#mw-content-text' ) );
} );
}( mediaWiki, jQuery ) );
| BRL-CAD/web | wiki/resources/mediawiki.page/mediawiki.page.startup.js | JavaScript | bsd-2-clause | 826 |
//=================================================================================================
/*!
// \file src/mathtest/dvectdvecmult/VHbVDb.cpp
// \brief Source file for the VHbVDb dense vector/dense vector outer product math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/HybridVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvectdvecmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VHbVDb'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
typedef blaze::HybridVector<TypeB,128UL> VHb;
typedef blaze::DynamicVector<TypeB> VDb;
// Creator type definitions
typedef blazetest::Creator<VHb> CVHb;
typedef blazetest::Creator<VDb> CVDb;
// Running tests with small vectors
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=6UL; ++j ) {
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( i ), CVDb( j ) );
}
}
// Running tests with large vectors
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 67UL ), CVDb( 67UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 67UL ), CVDb( 127UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 127UL ), CVDb( 67UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 127UL ), CVDb( 127UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 64UL ), CVDb( 64UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 64UL ), CVDb( 128UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 128UL ), CVDb( 64UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 128UL ), CVDb( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector outer product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| yzxyzh/blaze-lib | blazetest/src/mathtest/dvectdvecmult/VHbVDb.cpp | C++ | bsd-3-clause | 4,422 |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.3/15.3.5/15.3.5.4/15.3.5.4_2-77gs.js
* @description Strict mode - checking access to strict function caller from non-strict function (non-strict function declaration called by strict Function constructor)
* @noStrict
*/
function f() {return gNonStrict();};
(function () {"use strict"; return Function("return f();")(); })();
function gNonStrict() {
return gNonStrict.caller;
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.3/15.3.5/15.3.5.4/15.3.5.4_2-77gs.js | JavaScript | bsd-3-clause | 476 |
//=================================================================================================
/*!
// \file src/mathtest/tdvecdvecmult/V4aV4b.cpp
// \brief Source file for the V4aV4b dense vector/dense vector inner product math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/StaticVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/tdvecdvecmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'V4aV4b'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
typedef blaze::StaticVector<TypeA,4UL> V4a;
typedef blaze::StaticVector<TypeB,4UL> V4b;
// Creator type definitions
typedef blazetest::Creator<V4a> CV4a;
typedef blazetest::Creator<V4b> CV4b;
// Running the tests
RUN_TDVECDVECMULT_OPERATION_TEST( CV4a(), CV4b() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector inner product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| honnibal/blaze-lib | blazetest/src/mathtest/tdvecdvecmult/V4aV4b.cpp | C++ | bsd-3-clause | 3,667 |
"""SCons.Scanner.IDL
This module implements the depenency scanner for IDL (Interface
Definition Language) files.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Scanner/IDL.py 4043 2009/02/23 09:06:45 scons"
import SCons.Node.FS
import SCons.Scanner
def IDLScan():
"""Return a prototype Scanner instance for scanning IDL source files"""
cs = SCons.Scanner.ClassicCPP("IDLScan",
"$IDLSUFFIXES",
"CPPPATH",
'^[ \t]*(?:#[ \t]*include|[ \t]*import)[ \t]+(<|")([^>"]+)(>|")')
return cs
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| mastbaum/rat-pac | python/SCons/Scanner/IDL.py | Python | bsd-3-clause | 1,852 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The [[Value]] property of the newly constructed object
* is set by following steps:
* 1. Call ToNumber(year)
* 2. Call ToNumber(month)
* 3. If date is supplied use ToNumber(date)
* 4. If hours is supplied use ToNumber(hours)
* 5. If minutes is supplied use ToNumber(minutes)
* 6. If seconds is supplied use ToNumber(seconds)
* 7. If ms is supplied use ToNumber(ms)
*
* @path ch15/15.9/15.9.3/S15.9.3.1_A4_T4.js
* @description 5 arguments, (year, month, date, hours, minutes)
*/
var myObj = function(val){
this.value = val;
this.valueOf = function(){throw "valueOf-"+this.value;};
this.toString = function(){throw "toString-"+this.value;};
};
//CHECK#1
try{
var x1 = new Date(new myObj(1), new myObj(2), new myObj(3), new myObj(4), new myObj(5));
$ERROR("#1: The 1st step is calling ToNumber(year)");
}
catch(e){
if(e !== "valueOf-1"){
$ERROR("#1: The 1st step is calling ToNumber(year)");
}
}
//CHECK#2
try{
var x2 = new Date(1, new myObj(2), new myObj(3), new myObj(4), new myObj(5));
$ERROR("#2: The 2nd step is calling ToNumber(month)");
}
catch(e){
if(e !== "valueOf-2"){
$ERROR("#2: The 2nd step is calling ToNumber(month)");
}
}
//CHECK#3
try{
var x3 = new Date(1, 2, new myObj(3), new myObj(4), new myObj(5));
$ERROR("#3: The 3rd step is calling ToNumber(date)");
}
catch(e){
if(e !== "valueOf-3"){
$ERROR("#3: The 3rd step is calling ToNumber(date)");
}
}
//CHECK#4
try{
var x4 = new Date(1, 2, 3, new myObj(4), new myObj(5));
$ERROR("#4: The 4th step is calling ToNumber(hours)");
}
catch(e){
if(e !== "valueOf-4"){
$ERROR("#4: The 4th step is calling ToNumber(hours)");
}
}
//CHECK#5
try{
var x5 = new Date(1, 2, 3, 4, new myObj(5));
$ERROR("#5: The 5th step is calling ToNumber(minutes)");
}
catch(e){
if(e !== "valueOf-5"){
$ERROR("#5: The 5th step is calling ToNumber(minutes)");
}
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.9/15.9.3/S15.9.3.1_A4_T4.js | JavaScript | bsd-3-clause | 1,950 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* Number.MIN_VALUE has the attribute DontEnum
*
* @path ch15/15.7/15.7.3/15.7.3.3/S15.7.3.3_A4.js
* @description Checking if enumerating Number.MIN_VALUE fails
*/
//CHECK#1
for(var x in Number) {
if(x === "MIN_VALUE") {
$ERROR('#1: Number.MIN_VALUE has the attribute DontEnum');
}
}
if (Number.propertyIsEnumerable('MIN_VALUE')) {
$ERROR('#2: Number.MIN_VALUE has the attribute DontEnum');
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.7/15.7.3/15.7.3.3/S15.7.3.3_A4.js | JavaScript | bsd-3-clause | 475 |
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <Array.hpp>
namespace opencl
{
template<typename T, bool is_color>
Array<T> meanshift(const Array<T> &in, const float &s_sigma, const float &c_sigma, const unsigned iter);
}
| marbre/arrayfire | src/backend/opencl/meanshift.hpp | C++ | bsd-3-clause | 519 |
//
// FPEnvironment_SUN.cpp
//
// $Id: //poco/1.4/Foundation/src/FPEnvironment_SUN.cpp#1 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include <math.h>
#include "Poco/FPEnvironment_SUN.h"
namespace Poco {
FPEnvironmentImpl::FPEnvironmentImpl()
{
_rnd = fpgetround();
_exc = fpgetmask();
}
FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env)
{
_rnd = env._rnd;
_exc = env._exc;
}
FPEnvironmentImpl::~FPEnvironmentImpl()
{
fpsetround(_rnd);
fpsetmask(_exc);
}
FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env)
{
_rnd = env._rnd;
_exc = env._exc;
return *this;
}
bool FPEnvironmentImpl::isInfiniteImpl(float value)
{
int cls = fpclass(value);
return cls == FP_PINF || cls == FP_NINF;
}
bool FPEnvironmentImpl::isInfiniteImpl(double value)
{
int cls = fpclass(value);
return cls == FP_PINF || cls == FP_NINF;
}
bool FPEnvironmentImpl::isInfiniteImpl(long double value)
{
int cls = fpclass(value);
return cls == FP_PINF || cls == FP_NINF;
}
bool FPEnvironmentImpl::isNaNImpl(float value)
{
return isnanf(value) != 0;
}
bool FPEnvironmentImpl::isNaNImpl(double value)
{
return isnan(value) != 0;
}
bool FPEnvironmentImpl::isNaNImpl(long double value)
{
return isnan((double) value) != 0;
}
float FPEnvironmentImpl::copySignImpl(float target, float source)
{
return (float) copysign(target, source);
}
double FPEnvironmentImpl::copySignImpl(double target, double source)
{
return (float) copysign(target, source);
}
long double FPEnvironmentImpl::copySignImpl(long double target, long double source)
{
return (source > 0 && target > 0) || (source < 0 && target < 0) ? target : -target;
}
void FPEnvironmentImpl::keepCurrentImpl()
{
fpsetround(_rnd);
fpsetmask(_exc);
}
void FPEnvironmentImpl::clearFlagsImpl()
{
fpsetsticky(0);
}
bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag)
{
return (fpgetsticky() & flag) != 0;
}
void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode)
{
fpsetround((fp_rnd) mode);
}
FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl()
{
return (FPEnvironmentImpl::RoundingModeImpl) fpgetround();
}
} // namespace Poco
| weinzierl-engineering/baos | thirdparty/poco/Foundation/src/FPEnvironment_SUN.cpp | C++ | mit | 2,352 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_admin
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
?>
<fieldset class="adminform">
<legend><?php echo JText::_('COM_ADMIN_PHP_INFORMATION'); ?></legend>
<?php echo $this->php_info; ?>
</fieldset>
| renebentes/joomla-3.x | administrator/components/com_admin/views/sysinfo/tmpl/default_phpinfo.php | PHP | gpl-2.0 | 422 |
/*
* Copyright (c) 2015, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package jdk.tools.jlink.internal;
import java.security.BasicPermission;
/**
* The permission required to use jlink API. The permission target_name is
* "jlink". e.g.: permission jdk.tools.jlink.plugins.JlinkPermission "jlink";
*
*/
public final class JlinkPermission extends BasicPermission {
private static final long serialVersionUID = -3687912306077727801L;
public JlinkPermission(String name) {
super(name);
}
}
| md-5/jdk10 | src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkPermission.java | Java | gpl-2.0 | 1,652 |
/**
* Copyright (c) 2009--2010 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.domain.action.kickstart;
/**
* KickstartInitiateAction
* @version $Rev$
*/
public class KickstartInitiateAction extends KickstartAction {
}
| shastah/spacewalk | java/code/src/com/redhat/rhn/domain/action/kickstart/KickstartInitiateAction.java | Java | gpl-2.0 | 798 |
<?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\Feed\Parser;
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Feed\Feed;
use Joomla\CMS\Feed\FeedEntry;
use Joomla\CMS\Feed\FeedLink;
use Joomla\CMS\Feed\FeedParser;
use Joomla\CMS\Feed\FeedPerson;
/**
* RSS Feed Parser class.
*
* @link http://cyber.law.harvard.edu/rss/rss.html
* @since 3.1.4
*/
class RssParser extends FeedParser
{
/**
* @var string The feed element name for the entry elements.
* @since 3.1.4
*/
protected $entryElementName = 'item';
/**
* @var string The feed format version.
* @since 3.1.4
*/
protected $version;
/**
* Method to handle the `<category>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleCategory(Feed $feed, \SimpleXMLElement $el)
{
// Get the data from the element.
$domain = (string) $el['domain'];
$category = (string) $el;
$feed->addCategory($category, $domain);
}
/**
* Method to handle the `<cloud>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleCloud(Feed $feed, \SimpleXMLElement $el)
{
$cloud = new \stdClass;
$cloud->domain = (string) $el['domain'];
$cloud->port = (string) $el['port'];
$cloud->path = (string) $el['path'];
$cloud->protocol = (string) $el['protocol'];
$cloud->registerProcedure = (string) $el['registerProcedure'];
$feed->cloud = $cloud;
}
/**
* Method to handle the `<copyright>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleCopyright(Feed $feed, \SimpleXMLElement $el)
{
$feed->copyright = (string) $el;
}
/**
* Method to handle the `<description>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleDescription(Feed $feed, \SimpleXMLElement $el)
{
$feed->description = (string) $el;
}
/**
* Method to handle the `<generator>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleGenerator(Feed $feed, \SimpleXMLElement $el)
{
$feed->generator = (string) $el;
}
/**
* Method to handle the `<image>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleImage(Feed $feed, \SimpleXMLElement $el)
{
// Create a feed link object for the image.
$image = new FeedLink(
(string) $el->url,
null,
'logo',
null,
(string) $el->title
);
// Populate extra fields if they exist.
$image->link = (string) $el->link;
$image->description = (string) $el->description;
$image->height = (string) $el->height;
$image->width = (string) $el->width;
$feed->image = $image;
}
/**
* Method to handle the `<language>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleLanguage(Feed $feed, \SimpleXMLElement $el)
{
$feed->language = (string) $el;
}
/**
* Method to handle the `<lastBuildDate>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleLastBuildDate(Feed $feed, \SimpleXMLElement $el)
{
$feed->updatedDate = (string) $el;
}
/**
* Method to handle the `<link>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleLink(Feed $feed, \SimpleXMLElement $el)
{
$link = new FeedLink;
$link->uri = (string) $el['href'];
$feed->link = $link;
}
/**
* Method to handle the `<managingEditor>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleManagingEditor(Feed $feed, \SimpleXMLElement $el)
{
$feed->author = $this->processPerson((string) $el);
}
/**
* Method to handle the `<skipDays>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleSkipDays(Feed $feed, \SimpleXMLElement $el)
{
// Initialise the array.
$days = array();
// Add all of the day values from the feed to the array.
foreach ($el->day as $day)
{
$days[] = (string) $day;
}
$feed->skipDays = $days;
}
/**
* Method to handle the `<skipHours>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleSkipHours(Feed $feed, \SimpleXMLElement $el)
{
// Initialise the array.
$hours = array();
// Add all of the day values from the feed to the array.
foreach ($el->hour as $hour)
{
$hours[] = (int) $hour;
}
$feed->skipHours = $hours;
}
/**
* Method to handle the `<pubDate>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handlePubDate(Feed $feed, \SimpleXMLElement $el)
{
$feed->publishedDate = (string) $el;
}
/**
* Method to handle the `<title>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleTitle(Feed $feed, \SimpleXMLElement $el)
{
$feed->title = (string) $el;
}
/**
* Method to handle the `<ttl>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleTtl(Feed $feed, \SimpleXMLElement $el)
{
$feed->ttl = (integer) $el;
}
/**
* Method to handle the `<webmaster>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleWebmaster(Feed $feed, \SimpleXMLElement $el)
{
// Get the tag contents and split it over the first space.
$tmp = (string) $el;
$tmp = explode(' ', $tmp, 2);
// This is really cheap parsing. Probably need to create a method to do this more robustly.
$name = null;
if (isset($tmp[1]))
{
$name = trim($tmp[1], ' ()');
}
$email = trim($tmp[0]);
$feed->addContributor($name, $email, null, 'webmaster');
}
/**
* Method to initialise the feed for parsing. Here we detect the version and advance the stream
* reader so that it is ready to parse feed elements.
*
* @return void
*
* @since 3.1.4
*/
protected function initialise()
{
// Read the version attribute.
$this->version = $this->stream->getAttribute('version');
// We want to move forward to the first element after the <channel> element.
$this->moveToNextElement('channel');
$this->moveToNextElement();
}
/**
* Method to handle a `<item>` element for the feed.
*
* @param FeedEntry $entry The FeedEntry object being built from the parsed feed entry.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function processFeedEntry(FeedEntry $entry, \SimpleXMLElement $el)
{
$entry->uri = (string) $el->link;
$entry->title = (string) $el->title;
$entry->publishedDate = (string) $el->pubDate;
$entry->updatedDate = (string) $el->pubDate;
$entry->content = (string) $el->description;
$entry->guid = (string) $el->guid;
$entry->isPermaLink = $entry->guid === '' || (string) $el->guid['isPermaLink'] === 'false' ? false : true;
$entry->comments = (string) $el->comments;
// Add the feed entry author if available.
$author = (string) $el->author;
if (!empty($author))
{
$entry->author = $this->processPerson($author);
}
// Add any categories to the entry.
foreach ($el->category as $category)
{
$entry->addCategory((string) $category, (string) $category['domain']);
}
// Add any enclosures to the entry.
foreach ($el->enclosure as $enclosure)
{
$link = new FeedLink(
(string) $enclosure['url'],
null,
(string) $enclosure['type'],
null,
null,
(int) $enclosure['length']
);
$entry->addLink($link);
}
}
/**
* Method to parse a string with person data and return a FeedPerson object.
*
* @param string $data The string to parse for a person.
*
* @return FeedPerson
*
* @since 3.1.4
*/
protected function processPerson($data)
{
// Create a new person object.
$person = new FeedPerson;
// This is really cheap parsing, but so far good enough. :)
$data = explode(' ', $data, 2);
if (isset($data[1]))
{
$person->name = trim($data[1], ' ()');
}
// Set the email for the person.
$person->email = trim($data[0]);
return $person;
}
}
| IOC/joomla3 | libraries/src/Feed/Parser/RssParser.php | PHP | gpl-2.0 | 11,247 |
// Copyright 2010 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "InputCommon/ControllerEmu/ControllerEmu.h"
#include <memory>
#include <mutex>
#include <string>
#include "Common/IniFile.h"
#include "InputCommon/ControlReference/ControlReference.h"
#include "InputCommon/ControllerEmu/Control/Control.h"
#include "InputCommon/ControllerEmu/ControlGroup/ControlGroup.h"
#include "InputCommon/ControllerEmu/ControlGroup/Extension.h"
#include "InputCommon/ControllerInterface/ControllerInterface.h"
namespace ControllerEmu
{
static std::recursive_mutex s_get_state_mutex;
EmulatedController::~EmulatedController() = default;
// This should be called before calling GetState() or State() on a control reference
// to prevent a race condition.
// This is a recursive mutex because UpdateReferences is recursive.
std::unique_lock<std::recursive_mutex> EmulatedController::GetStateLock()
{
std::unique_lock<std::recursive_mutex> lock(s_get_state_mutex);
return lock;
}
void EmulatedController::UpdateReferences(const ControllerInterface& devi)
{
const auto lock = GetStateLock();
m_default_device_is_connected = devi.HasConnectedDevice(m_default_device);
for (auto& ctrlGroup : groups)
{
for (auto& control : ctrlGroup->controls)
control->control_ref.get()->UpdateReference(devi, GetDefaultDevice());
// extension
if (ctrlGroup->type == GroupType::Extension)
{
for (auto& attachment : ((Extension*)ctrlGroup.get())->attachments)
attachment->UpdateReferences(devi);
}
}
}
bool EmulatedController::IsDefaultDeviceConnected() const
{
return m_default_device_is_connected;
}
const ciface::Core::DeviceQualifier& EmulatedController::GetDefaultDevice() const
{
return m_default_device;
}
void EmulatedController::SetDefaultDevice(const std::string& device)
{
ciface::Core::DeviceQualifier devq;
devq.FromString(device);
SetDefaultDevice(std::move(devq));
}
void EmulatedController::SetDefaultDevice(ciface::Core::DeviceQualifier devq)
{
m_default_device = std::move(devq);
for (auto& ctrlGroup : groups)
{
// extension
if (ctrlGroup->type == GroupType::Extension)
{
for (auto& ai : ((Extension*)ctrlGroup.get())->attachments)
{
ai->SetDefaultDevice(m_default_device);
}
}
}
}
void EmulatedController::LoadConfig(IniFile::Section* sec, const std::string& base)
{
std::string defdev = GetDefaultDevice().ToString();
if (base.empty())
{
sec->Get(base + "Device", &defdev, "");
SetDefaultDevice(defdev);
}
for (auto& cg : groups)
cg->LoadConfig(sec, defdev, base);
}
void EmulatedController::SaveConfig(IniFile::Section* sec, const std::string& base)
{
const std::string defdev = GetDefaultDevice().ToString();
if (base.empty())
sec->Set(/*std::string(" ") +*/ base + "Device", defdev, "");
for (auto& ctrlGroup : groups)
ctrlGroup->SaveConfig(sec, defdev, base);
}
void EmulatedController::LoadDefaults(const ControllerInterface& ciface)
{
// load an empty inifile section, clears everything
IniFile::Section sec;
LoadConfig(&sec);
const std::string& default_device_string = ciface.GetDefaultDeviceString();
if (!default_device_string.empty())
{
SetDefaultDevice(default_device_string);
}
}
} // namespace ControllerEmu
| delroth/dolphin | Source/Core/InputCommon/ControllerEmu/ControllerEmu.cpp | C++ | gpl-2.0 | 3,349 |
from sympy import *
from sympy.printing import print_ccode
from sympy.physics.vector import ReferenceFrame, gradient, divergence
from sympy.vector import CoordSysCartesian
R = ReferenceFrame('R');
x = R[0]; y = R[1];
a=-0.5; b=1.5;
visc=1e-1;
lambda_=(1/(2*visc)-sqrt(1/(4*visc**2)+4*pi**2));
print(" visc=%f" % visc)
u=[0,0]
u[0]=1-exp(lambda_*x)*cos(2*pi*y);
u[1]=lambda_/(2*pi)*exp(lambda_*x)*sin(2*pi*y);
p=(exp(3*lambda_)-exp(-lambda_))/(8*lambda_)-exp(2*lambda_*x)/2;
p=p - integrate(p, (x,a,b));
grad_p = gradient(p, R).to_matrix(R)
f0 = -divergence(visc*gradient(u[0], R), R) + grad_p[0];
f1 = -divergence(visc*gradient(u[1], R), R) + grad_p[1];
f2 = divergence(u[0]*R.x + u[1]*R.y, R);
print("\n * RHS:")
print(ccode(f0, assign_to = "values[0]"));
print(ccode(f1, assign_to = "values[1]"));
print(ccode(f2, assign_to = "values[2]"));
print("\n * ExactSolution:")
print(ccode(u[0], assign_to = "values[0]"));
print(ccode(u[1], assign_to = "values[1]"));
print(ccode(p, assign_to = "values[2]"));
print("")
print("pressure mean:", N(integrate(p,(x,a,b))))
| pesser/dealii | examples/step-55/reference.py | Python | lgpl-2.1 | 1,071 |
package store
import (
"strings"
"github.com/docker/swarmkit/api"
"github.com/docker/swarmkit/manager/state"
memdb "github.com/hashicorp/go-memdb"
)
const tableService = "service"
func init() {
register(ObjectStoreConfig{
Name: tableService,
Table: &memdb.TableSchema{
Name: tableService,
Indexes: map[string]*memdb.IndexSchema{
indexID: {
Name: indexID,
Unique: true,
Indexer: serviceIndexerByID{},
},
indexName: {
Name: indexName,
Unique: true,
Indexer: serviceIndexerByName{},
},
},
},
Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
var err error
snapshot.Services, err = FindServices(tx, All)
return err
},
Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
services, err := FindServices(tx, All)
if err != nil {
return err
}
for _, s := range services {
if err := DeleteService(tx, s.ID); err != nil {
return err
}
}
for _, s := range snapshot.Services {
if err := CreateService(tx, s); err != nil {
return err
}
}
return nil
},
ApplyStoreAction: func(tx Tx, sa *api.StoreAction) error {
switch v := sa.Target.(type) {
case *api.StoreAction_Service:
obj := v.Service
switch sa.Action {
case api.StoreActionKindCreate:
return CreateService(tx, obj)
case api.StoreActionKindUpdate:
return UpdateService(tx, obj)
case api.StoreActionKindRemove:
return DeleteService(tx, obj.ID)
}
}
return errUnknownStoreAction
},
NewStoreAction: func(c state.Event) (api.StoreAction, error) {
var sa api.StoreAction
switch v := c.(type) {
case state.EventCreateService:
sa.Action = api.StoreActionKindCreate
sa.Target = &api.StoreAction_Service{
Service: v.Service,
}
case state.EventUpdateService:
sa.Action = api.StoreActionKindUpdate
sa.Target = &api.StoreAction_Service{
Service: v.Service,
}
case state.EventDeleteService:
sa.Action = api.StoreActionKindRemove
sa.Target = &api.StoreAction_Service{
Service: v.Service,
}
default:
return api.StoreAction{}, errUnknownStoreAction
}
return sa, nil
},
})
}
type serviceEntry struct {
*api.Service
}
func (s serviceEntry) ID() string {
return s.Service.ID
}
func (s serviceEntry) Meta() api.Meta {
return s.Service.Meta
}
func (s serviceEntry) SetMeta(meta api.Meta) {
s.Service.Meta = meta
}
func (s serviceEntry) Copy() Object {
return serviceEntry{s.Service.Copy()}
}
func (s serviceEntry) EventCreate() state.Event {
return state.EventCreateService{Service: s.Service}
}
func (s serviceEntry) EventUpdate() state.Event {
return state.EventUpdateService{Service: s.Service}
}
func (s serviceEntry) EventDelete() state.Event {
return state.EventDeleteService{Service: s.Service}
}
// CreateService adds a new service to the store.
// Returns ErrExist if the ID is already taken.
func CreateService(tx Tx, s *api.Service) error {
// Ensure the name is not already in use.
if tx.lookup(tableService, indexName, strings.ToLower(s.Spec.Annotations.Name)) != nil {
return ErrNameConflict
}
return tx.create(tableService, serviceEntry{s})
}
// UpdateService updates an existing service in the store.
// Returns ErrNotExist if the service doesn't exist.
func UpdateService(tx Tx, s *api.Service) error {
// Ensure the name is either not in use or already used by this same Service.
if existing := tx.lookup(tableService, indexName, strings.ToLower(s.Spec.Annotations.Name)); existing != nil {
if existing.ID() != s.ID {
return ErrNameConflict
}
}
return tx.update(tableService, serviceEntry{s})
}
// DeleteService removes a service from the store.
// Returns ErrNotExist if the service doesn't exist.
func DeleteService(tx Tx, id string) error {
return tx.delete(tableService, id)
}
// GetService looks up a service by ID.
// Returns nil if the service doesn't exist.
func GetService(tx ReadTx, id string) *api.Service {
s := tx.get(tableService, id)
if s == nil {
return nil
}
return s.(serviceEntry).Service
}
// FindServices selects a set of services and returns them.
func FindServices(tx ReadTx, by By) ([]*api.Service, error) {
checkType := func(by By) error {
switch by.(type) {
case byName, byIDPrefix:
return nil
default:
return ErrInvalidFindBy
}
}
serviceList := []*api.Service{}
appendResult := func(o Object) {
serviceList = append(serviceList, o.(serviceEntry).Service)
}
err := tx.find(tableService, by, checkType, appendResult)
return serviceList, err
}
type serviceIndexerByID struct{}
func (si serviceIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
return fromArgs(args...)
}
func (si serviceIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
s, ok := obj.(serviceEntry)
if !ok {
panic("unexpected type passed to FromObject")
}
// Add the null character as a terminator
val := s.Service.ID + "\x00"
return true, []byte(val), nil
}
func (si serviceIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
return prefixFromArgs(args...)
}
type serviceIndexerByName struct{}
func (si serviceIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
return fromArgs(args...)
}
func (si serviceIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
s, ok := obj.(serviceEntry)
if !ok {
panic("unexpected type passed to FromObject")
}
// Add the null character as a terminator
return true, []byte(strings.ToLower(s.Spec.Annotations.Name) + "\x00"), nil
}
| jlebon/docker | vendor/src/github.com/docker/swarmkit/manager/state/store/services.go | GO | apache-2.0 | 5,558 |
/*
* Copyright (C) 2010 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 INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
#include "BrowserWindow.h"
#include "MiniBrowser.h"
#include <assert.h>
MiniBrowser::MiniBrowser()
: m_instance(0)
{
}
MiniBrowser& MiniBrowser::shared()
{
static MiniBrowser miniBrowser;
return miniBrowser;
}
void MiniBrowser::initialize(HINSTANCE instance)
{
assert(!m_instance);
m_instance = instance;
}
void MiniBrowser::createNewWindow()
{
static const wchar_t* kDefaultURLString = L"http://webkit.org/";
BrowserWindow* browserWindow = BrowserWindow::create();
browserWindow->createWindow(0, 0, 800, 600);
browserWindow->showWindow();
browserWindow->goToURL(kDefaultURLString);
}
void MiniBrowser::registerWindow(BrowserWindow* window)
{
m_browserWindows.insert(window);
}
void MiniBrowser::unregisterWindow(BrowserWindow* window)
{
m_browserWindows.erase(window);
if (m_browserWindows.empty())
::PostQuitMessage(0);
}
bool MiniBrowser::handleMessage(const MSG* message)
{
for (std::set<BrowserWindow*>::const_iterator it = m_browserWindows.begin(), end = m_browserWindows.end(); it != end; ++it) {
BrowserWindow* browserWindow = *it;
if (browserWindow->handleMessage(message))
return true;
}
return false;
}
| mogoweb/webkit_for_android5.1 | webkit/Tools/MiniBrowser/win/MiniBrowser.cpp | C++ | apache-2.0 | 2,604 |
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "ZlibStreamCompressor.h"
#include <folly/Bits.h>
#include <folly/io/Cursor.h>
using namespace folly;
using folly::IOBuf;
using std::unique_ptr;
// IOBuf uses 24 bytes of data for bookeeping purposes, so requesting for 4073
// bytes of data will be rounded up to an allocation of 1 page.
#ifndef NO_LIB_GFLAGS
DEFINE_int64(zlib_compressor_buffer_growth, 2024,
"The buffer growth size to use during IOBuf zlib deflation");
DEFINE_int64(zlib_compressor_buffer_minsize, 1024,
"The minimum buffer size to use before growing during IOBuf "
"zlib deflation");
#endif
namespace proxygen {
#ifdef NO_LIB_GFLAGS
int64_t FLAGS_zlib_compressor_buffer_growth = 2024;
int64_t FLAGS_zlib_compressor_buffer_minsize = 1024;
#endif
void ZlibStreamCompressor::init(ZlibCompressionType type, int32_t level) {
DCHECK(type_ == ZlibCompressionType::NONE)
<< "Attempt to re-initialize compression stream";
type_ = type;
level_ = level;
status_ = Z_OK;
zlibStream_.zalloc = Z_NULL;
zlibStream_.zfree = Z_NULL;
zlibStream_.opaque = Z_NULL;
zlibStream_.total_in = 0;
zlibStream_.next_in = Z_NULL;
zlibStream_.avail_in = 0;
zlibStream_.avail_out = 0;
zlibStream_.next_out = Z_NULL;
DCHECK(level_ >= Z_NO_COMPRESSION && level_ <= Z_BEST_COMPRESSION)
<< "Invalid Zlib compression level. level=" << level_;
switch (type_) {
case ZlibCompressionType::GZIP:
status_ = deflateInit2(&zlibStream_,
level_,
Z_DEFLATED,
static_cast<int32_t>(type),
MAX_MEM_LEVEL,
Z_DEFAULT_STRATEGY);
break;
case ZlibCompressionType::DEFLATE:
status_ = deflateInit(&zlibStream_, level);
break;
default:
DCHECK(false) << "Unsupported zlib compression type.";
break;
}
if (status_ != Z_OK) {
LOG(ERROR) << "error initializing zlib stream. r=" << status_ ;
}
}
ZlibStreamCompressor::ZlibStreamCompressor(ZlibCompressionType type, int level)
: status_(Z_OK) {
init(type, level);
}
ZlibStreamCompressor::~ZlibStreamCompressor() {
if (type_ != ZlibCompressionType::NONE) {
status_ = deflateEnd(&zlibStream_);
}
}
// Compress an IOBuf chain. Compress can be called multiple times and the
// Zlib stream will be synced after each call. trailer must be set to
// true on the final compression call.
std::unique_ptr<IOBuf> ZlibStreamCompressor::compress(const IOBuf* in,
bool trailer) {
const IOBuf* crtBuf{in};
size_t offset{0};
int flush{Z_NO_FLUSH};
auto out = IOBuf::create(FLAGS_zlib_compressor_buffer_growth);
auto appender = folly::io::Appender(out.get(),
FLAGS_zlib_compressor_buffer_growth);
auto chunkSize = FLAGS_zlib_compressor_buffer_minsize;
do {
// Advance to the next IOBuf if necessary
DCHECK_GE(crtBuf->length(), offset);
if (crtBuf->length() == offset) {
crtBuf = crtBuf->next();
if (crtBuf == in) {
// We hit the end of the IOBuf chain, and are done.
// Need to flush the stream
// Completely flush if the final call, otherwise flush state
if (trailer) {
flush = Z_FINISH;
} else {
flush = Z_SYNC_FLUSH;
}
} else {
// Prepare to process next buffer
offset = 0;
}
}
if (status_ == Z_STREAM_ERROR) {
LOG(ERROR) << "error compressing buffer. r=" << status_;
return nullptr;
}
const size_t origAvailIn = crtBuf->length() - offset;
zlibStream_.next_in = const_cast<uint8_t*>(crtBuf->data() + offset);
zlibStream_.avail_in = origAvailIn;
// Zlib may not write it's entire state on the first pass.
do {
appender.ensure(chunkSize);
zlibStream_.next_out = appender.writableData();
zlibStream_.avail_out = chunkSize;
status_ = deflate(&zlibStream_, flush);
// Move output buffer ahead
auto outMove = chunkSize - zlibStream_.avail_out;
appender.append(outMove);
} while (zlibStream_.avail_out == 0);
DCHECK(zlibStream_.avail_in == 0);
// Adjust the input offset ahead
auto inConsumed = origAvailIn - zlibStream_.avail_in;
offset += inConsumed;
} while (flush != Z_FINISH && flush != Z_SYNC_FLUSH);
return out;
}
}
| raphaelamorim/proxygen | proxygen/lib/utils/ZlibStreamCompressor.cpp | C++ | bsd-3-clause | 4,682 |
// stdafx.cpp : source file that includes just the standard includes
// KronFit.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| plliao/FASTEN | src/stdafx.cpp | C++ | mit | 294 |
// Type definitions for textr 0.3
// Project: https://github.com/shuvalov-anton/textr
// Definitions by: Adam Zerella <https://github.com/adamzerella>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
type TextrArgs = string | object;
interface textr {
/**
* Register new middleware and array of middlewares.
*/
use(...fn: any): textr;
/**
* Process given text by the middlewares.
*/
exec(text: string, options?: object): string;
/**
* List of registred middlewares.
*/
mws(): string[];
}
declare function textr(defaults?: TextrArgs): textr;
export = textr;
| markogresak/DefinitelyTyped | types/textr/index.d.ts | TypeScript | mit | 633 |
<?php
namespace Illuminate\Tests\Cookie\Middleware;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Router;
use PHPUnit\Framework\TestCase;
use Illuminate\Cookie\CookieJar;
use Illuminate\Events\Dispatcher;
use Illuminate\Routing\Controller;
use Illuminate\Container\Container;
use Illuminate\Encryption\Encrypter;
use Symfony\Component\HttpFoundation\Cookie;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Contracts\Encryption\Encrypter as EncrypterContract;
class EncryptCookiesTest extends TestCase
{
/**
* @var Router
*/
protected $router;
protected $setCookiePath = 'cookie/set';
protected $queueCookiePath = 'cookie/queue';
public function setUp()
{
parent::setUp();
$container = new Container;
$container->singleton(EncrypterContract::class, function () {
return new Encrypter(str_repeat('a', 16));
});
$this->router = new Router(new Dispatcher, $container);
}
public function testSetCookieEncryption()
{
$this->router->get($this->setCookiePath, [
'middleware' => 'Illuminate\Tests\Cookie\Middleware\EncryptCookiesTestMiddleware',
'uses' => 'Illuminate\Tests\Cookie\Middleware\EncryptCookiesTestController@setCookies',
]);
$response = $this->router->dispatch(Request::create($this->setCookiePath, 'GET'));
$cookies = $response->headers->getCookies();
$this->assertCount(2, $cookies);
$this->assertEquals('encrypted_cookie', $cookies[0]->getName());
$this->assertNotEquals('value', $cookies[0]->getValue());
$this->assertEquals('unencrypted_cookie', $cookies[1]->getName());
$this->assertEquals('value', $cookies[1]->getValue());
}
public function testQueuedCookieEncryption()
{
$this->router->get($this->queueCookiePath, [
'middleware' => ['Illuminate\Tests\Cookie\Middleware\EncryptCookiesTestMiddleware', 'Illuminate\Tests\Cookie\Middleware\AddQueuedCookiesToResponseTestMiddleware'],
'uses' => 'Illuminate\Tests\Cookie\Middleware\EncryptCookiesTestController@queueCookies',
]);
$response = $this->router->dispatch(Request::create($this->queueCookiePath, 'GET'));
$cookies = $response->headers->getCookies();
$this->assertCount(2, $cookies);
$this->assertEquals('encrypted_cookie', $cookies[0]->getName());
$this->assertNotEquals('value', $cookies[0]->getValue());
$this->assertEquals('unencrypted_cookie', $cookies[1]->getName());
$this->assertEquals('value', $cookies[1]->getValue());
}
}
class EncryptCookiesTestController extends Controller
{
public function setCookies()
{
$response = new Response;
$response->headers->setCookie(new Cookie('encrypted_cookie', 'value'));
$response->headers->setCookie(new Cookie('unencrypted_cookie', 'value'));
return $response;
}
public function queueCookies()
{
return new Response;
}
}
class EncryptCookiesTestMiddleware extends EncryptCookies
{
protected $except = [
'unencrypted_cookie',
];
}
class AddQueuedCookiesToResponseTestMiddleware extends AddQueuedCookiesToResponse
{
public function __construct()
{
$cookie = new CookieJar;
$cookie->queue(new Cookie('encrypted_cookie', 'value'));
$cookie->queue(new Cookie('unencrypted_cookie', 'value'));
$this->cookies = $cookie;
}
}
| guiwoda/framework | tests/Cookie/Middleware/EncryptCookiesTest.php | PHP | mit | 3,594 |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 96);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports) {
module.exports = jQuery;
/***/ }),
/***/ 1:
/***/ (function(module, exports) {
module.exports = {Foundation: window.Foundation};
/***/ }),
/***/ 2:
/***/ (function(module, exports) {
module.exports = {Plugin: window.Foundation.Plugin};
/***/ }),
/***/ 3:
/***/ (function(module, exports) {
module.exports = {rtl: window.Foundation.rtl, GetYoDigits: window.Foundation.GetYoDigits, transitionend: window.Foundation.transitionend};
/***/ }),
/***/ 30:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_core__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__foundation_core__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_sticky__ = __webpack_require__(60);
__WEBPACK_IMPORTED_MODULE_0__foundation_core__["Foundation"].plugin(__WEBPACK_IMPORTED_MODULE_1__foundation_sticky__["a" /* Sticky */], 'Sticky');
/***/ }),
/***/ 4:
/***/ (function(module, exports) {
module.exports = {Motion: window.Foundation.Motion, Move: window.Foundation.Move};
/***/ }),
/***/ 6:
/***/ (function(module, exports) {
module.exports = {MediaQuery: window.Foundation.MediaQuery};
/***/ }),
/***/ 60:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Sticky; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_util_triggers__ = __webpack_require__(7);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Sticky module.
* @module foundation.sticky
* @requires foundation.util.triggers
* @requires foundation.util.mediaQuery
*/
var Sticky = function (_Plugin) {
_inherits(Sticky, _Plugin);
function Sticky() {
_classCallCheck(this, Sticky);
return _possibleConstructorReturn(this, (Sticky.__proto__ || Object.getPrototypeOf(Sticky)).apply(this, arguments));
}
_createClass(Sticky, [{
key: '_setup',
/**
* Creates a new instance of a sticky thing.
* @class
* @param {jQuery} element - jQuery object to make sticky.
* @param {Object} options - options object passed when creating the element programmatically.
*/
value: function _setup(element, options) {
this.$element = element;
this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Sticky.defaults, this.$element.data(), options);
// Triggers init is idempotent, just need to make sure it is initialized
__WEBPACK_IMPORTED_MODULE_4__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a);
this._init();
}
/**
* Initializes the sticky element by adding classes, getting/setting dimensions, breakpoints and attributes
* @function
* @private
*/
}, {
key: '_init',
value: function _init() {
__WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["MediaQuery"]._init();
var $parent = this.$element.parent('[data-sticky-container]'),
id = this.$element[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["GetYoDigits"])(6, 'sticky'),
_this = this;
if ($parent.length) {
this.$container = $parent;
} else {
this.wasWrapped = true;
this.$element.wrap(this.options.container);
this.$container = this.$element.parent();
}
this.$container.addClass(this.options.containerClass);
this.$element.addClass(this.options.stickyClass).attr({ 'data-resize': id, 'data-mutate': id });
if (this.options.anchor !== '') {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + _this.options.anchor).attr({ 'data-mutate': id });
}
this.scrollCount = this.options.checkEvery;
this.isStuck = false;
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).one('load.zf.sticky', function () {
//We calculate the container height to have correct values for anchor points offset calculation.
_this.containerHeight = _this.$element.css("display") == "none" ? 0 : _this.$element[0].getBoundingClientRect().height;
_this.$container.css('height', _this.containerHeight);
_this.elemHeight = _this.containerHeight;
if (_this.options.anchor !== '') {
_this.$anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + _this.options.anchor);
} else {
_this._parsePoints();
}
_this._setSizes(function () {
var scroll = window.pageYOffset;
_this._calc(false, scroll);
//Unstick the element will ensure that proper classes are set.
if (!_this.isStuck) {
_this._removeSticky(scroll >= _this.topPoint ? false : true);
}
});
_this._events(id.split('-').reverse().join('-'));
});
}
/**
* If using multiple elements as anchors, calculates the top and bottom pixel values the sticky thing should stick and unstick on.
* @function
* @private
*/
}, {
key: '_parsePoints',
value: function _parsePoints() {
var top = this.options.topAnchor == "" ? 1 : this.options.topAnchor,
btm = this.options.btmAnchor == "" ? document.documentElement.scrollHeight : this.options.btmAnchor,
pts = [top, btm],
breaks = {};
for (var i = 0, len = pts.length; i < len && pts[i]; i++) {
var pt;
if (typeof pts[i] === 'number') {
pt = pts[i];
} else {
var place = pts[i].split(':'),
anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + place[0]);
pt = anchor.offset().top;
if (place[1] && place[1].toLowerCase() === 'bottom') {
pt += anchor[0].getBoundingClientRect().height;
}
}
breaks[i] = pt;
}
this.points = breaks;
return;
}
/**
* Adds event handlers for the scrolling element.
* @private
* @param {String} id - pseudo-random id for unique scroll event listener.
*/
}, {
key: '_events',
value: function _events(id) {
var _this = this,
scrollListener = this.scrollListener = 'scroll.zf.' + id;
if (this.isOn) {
return;
}
if (this.canStick) {
this.isOn = true;
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(scrollListener).on(scrollListener, function (e) {
if (_this.scrollCount === 0) {
_this.scrollCount = _this.options.checkEvery;
_this._setSizes(function () {
_this._calc(false, window.pageYOffset);
});
} else {
_this.scrollCount--;
_this._calc(false, window.pageYOffset);
}
});
}
this.$element.off('resizeme.zf.trigger').on('resizeme.zf.trigger', function (e, el) {
_this._eventsHandler(id);
});
this.$element.on('mutateme.zf.trigger', function (e, el) {
_this._eventsHandler(id);
});
if (this.$anchor) {
this.$anchor.on('mutateme.zf.trigger', function (e, el) {
_this._eventsHandler(id);
});
}
}
/**
* Handler for events.
* @private
* @param {String} id - pseudo-random id for unique scroll event listener.
*/
}, {
key: '_eventsHandler',
value: function _eventsHandler(id) {
var _this = this,
scrollListener = this.scrollListener = 'scroll.zf.' + id;
_this._setSizes(function () {
_this._calc(false);
if (_this.canStick) {
if (!_this.isOn) {
_this._events(id);
}
} else if (_this.isOn) {
_this._pauseListeners(scrollListener);
}
});
}
/**
* Removes event handlers for scroll and change events on anchor.
* @fires Sticky#pause
* @param {String} scrollListener - unique, namespaced scroll listener attached to `window`
*/
}, {
key: '_pauseListeners',
value: function _pauseListeners(scrollListener) {
this.isOn = false;
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(scrollListener);
/**
* Fires when the plugin is paused due to resize event shrinking the view.
* @event Sticky#pause
* @private
*/
this.$element.trigger('pause.zf.sticky');
}
/**
* Called on every `scroll` event and on `_init`
* fires functions based on booleans and cached values
* @param {Boolean} checkSizes - true if plugin should recalculate sizes and breakpoints.
* @param {Number} scroll - current scroll position passed from scroll event cb function. If not passed, defaults to `window.pageYOffset`.
*/
}, {
key: '_calc',
value: function _calc(checkSizes, scroll) {
if (checkSizes) {
this._setSizes();
}
if (!this.canStick) {
if (this.isStuck) {
this._removeSticky(true);
}
return false;
}
if (!scroll) {
scroll = window.pageYOffset;
}
if (scroll >= this.topPoint) {
if (scroll <= this.bottomPoint) {
if (!this.isStuck) {
this._setSticky();
}
} else {
if (this.isStuck) {
this._removeSticky(false);
}
}
} else {
if (this.isStuck) {
this._removeSticky(true);
}
}
}
/**
* Causes the $element to become stuck.
* Adds `position: fixed;`, and helper classes.
* @fires Sticky#stuckto
* @function
* @private
*/
}, {
key: '_setSticky',
value: function _setSticky() {
var _this = this,
stickTo = this.options.stickTo,
mrgn = stickTo === 'top' ? 'marginTop' : 'marginBottom',
notStuckTo = stickTo === 'top' ? 'bottom' : 'top',
css = {};
css[mrgn] = this.options[mrgn] + 'em';
css[stickTo] = 0;
css[notStuckTo] = 'auto';
this.isStuck = true;
this.$element.removeClass('is-anchored is-at-' + notStuckTo).addClass('is-stuck is-at-' + stickTo).css(css)
/**
* Fires when the $element has become `position: fixed;`
* Namespaced to `top` or `bottom`, e.g. `sticky.zf.stuckto:top`
* @event Sticky#stuckto
*/
.trigger('sticky.zf.stuckto:' + stickTo);
this.$element.on("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd", function () {
_this._setSizes();
});
}
/**
* Causes the $element to become unstuck.
* Removes `position: fixed;`, and helper classes.
* Adds other helper classes.
* @param {Boolean} isTop - tells the function if the $element should anchor to the top or bottom of its $anchor element.
* @fires Sticky#unstuckfrom
* @private
*/
}, {
key: '_removeSticky',
value: function _removeSticky(isTop) {
var stickTo = this.options.stickTo,
stickToTop = stickTo === 'top',
css = {},
anchorPt = (this.points ? this.points[1] - this.points[0] : this.anchorHeight) - this.elemHeight,
mrgn = stickToTop ? 'marginTop' : 'marginBottom',
notStuckTo = stickToTop ? 'bottom' : 'top',
topOrBottom = isTop ? 'top' : 'bottom';
css[mrgn] = 0;
css['bottom'] = 'auto';
if (isTop) {
css['top'] = 0;
} else {
css['top'] = anchorPt;
}
this.isStuck = false;
this.$element.removeClass('is-stuck is-at-' + stickTo).addClass('is-anchored is-at-' + topOrBottom).css(css)
/**
* Fires when the $element has become anchored.
* Namespaced to `top` or `bottom`, e.g. `sticky.zf.unstuckfrom:bottom`
* @event Sticky#unstuckfrom
*/
.trigger('sticky.zf.unstuckfrom:' + topOrBottom);
}
/**
* Sets the $element and $container sizes for plugin.
* Calls `_setBreakPoints`.
* @param {Function} cb - optional callback function to fire on completion of `_setBreakPoints`.
* @private
*/
}, {
key: '_setSizes',
value: function _setSizes(cb) {
this.canStick = __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["MediaQuery"].is(this.options.stickyOn);
if (!this.canStick) {
if (cb && typeof cb === 'function') {
cb();
}
}
var _this = this,
newElemWidth = this.$container[0].getBoundingClientRect().width,
comp = window.getComputedStyle(this.$container[0]),
pdngl = parseInt(comp['padding-left'], 10),
pdngr = parseInt(comp['padding-right'], 10);
if (this.$anchor && this.$anchor.length) {
this.anchorHeight = this.$anchor[0].getBoundingClientRect().height;
} else {
this._parsePoints();
}
this.$element.css({
'max-width': newElemWidth - pdngl - pdngr + 'px'
});
var newContainerHeight = this.$element[0].getBoundingClientRect().height || this.containerHeight;
if (this.$element.css("display") == "none") {
newContainerHeight = 0;
}
this.containerHeight = newContainerHeight;
this.$container.css({
height: newContainerHeight
});
this.elemHeight = newContainerHeight;
if (!this.isStuck) {
if (this.$element.hasClass('is-at-bottom')) {
var anchorPt = (this.points ? this.points[1] - this.$container.offset().top : this.anchorHeight) - this.elemHeight;
this.$element.css('top', anchorPt);
}
}
this._setBreakPoints(newContainerHeight, function () {
if (cb && typeof cb === 'function') {
cb();
}
});
}
/**
* Sets the upper and lower breakpoints for the element to become sticky/unsticky.
* @param {Number} elemHeight - px value for sticky.$element height, calculated by `_setSizes`.
* @param {Function} cb - optional callback function to be called on completion.
* @private
*/
}, {
key: '_setBreakPoints',
value: function _setBreakPoints(elemHeight, cb) {
if (!this.canStick) {
if (cb && typeof cb === 'function') {
cb();
} else {
return false;
}
}
var mTop = emCalc(this.options.marginTop),
mBtm = emCalc(this.options.marginBottom),
topPoint = this.points ? this.points[0] : this.$anchor.offset().top,
bottomPoint = this.points ? this.points[1] : topPoint + this.anchorHeight,
// topPoint = this.$anchor.offset().top || this.points[0],
// bottomPoint = topPoint + this.anchorHeight || this.points[1],
winHeight = window.innerHeight;
if (this.options.stickTo === 'top') {
topPoint -= mTop;
bottomPoint -= elemHeight + mTop;
} else if (this.options.stickTo === 'bottom') {
topPoint -= winHeight - (elemHeight + mBtm);
bottomPoint -= winHeight - mBtm;
} else {
//this would be the stickTo: both option... tricky
}
this.topPoint = topPoint;
this.bottomPoint = bottomPoint;
if (cb && typeof cb === 'function') {
cb();
}
}
/**
* Destroys the current sticky element.
* Resets the element to the top position first.
* Removes event listeners, JS-added css properties and classes, and unwraps the $element if the JS added the $container.
* @function
*/
}, {
key: '_destroy',
value: function _destroy() {
this._removeSticky(true);
this.$element.removeClass(this.options.stickyClass + ' is-anchored is-at-top').css({
height: '',
top: '',
bottom: '',
'max-width': ''
}).off('resizeme.zf.trigger').off('mutateme.zf.trigger');
if (this.$anchor && this.$anchor.length) {
this.$anchor.off('change.zf.sticky');
}
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(this.scrollListener);
if (this.wasWrapped) {
this.$element.unwrap();
} else {
this.$container.removeClass(this.options.containerClass).css({
height: ''
});
}
}
}]);
return Sticky;
}(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__["Plugin"]);
Sticky.defaults = {
/**
* Customizable container template. Add your own classes for styling and sizing.
* @option
* @type {string}
* @default '<div data-sticky-container></div>'
*/
container: '<div data-sticky-container></div>',
/**
* Location in the view the element sticks to. Can be `'top'` or `'bottom'`.
* @option
* @type {string}
* @default 'top'
*/
stickTo: 'top',
/**
* If anchored to a single element, the id of that element.
* @option
* @type {string}
* @default ''
*/
anchor: '',
/**
* If using more than one element as anchor points, the id of the top anchor.
* @option
* @type {string}
* @default ''
*/
topAnchor: '',
/**
* If using more than one element as anchor points, the id of the bottom anchor.
* @option
* @type {string}
* @default ''
*/
btmAnchor: '',
/**
* Margin, in `em`'s to apply to the top of the element when it becomes sticky.
* @option
* @type {number}
* @default 1
*/
marginTop: 1,
/**
* Margin, in `em`'s to apply to the bottom of the element when it becomes sticky.
* @option
* @type {number}
* @default 1
*/
marginBottom: 1,
/**
* Breakpoint string that is the minimum screen size an element should become sticky.
* @option
* @type {string}
* @default 'medium'
*/
stickyOn: 'medium',
/**
* Class applied to sticky element, and removed on destruction. Foundation defaults to `sticky`.
* @option
* @type {string}
* @default 'sticky'
*/
stickyClass: 'sticky',
/**
* Class applied to sticky container. Foundation defaults to `sticky-container`.
* @option
* @type {string}
* @default 'sticky-container'
*/
containerClass: 'sticky-container',
/**
* Number of scroll events between the plugin's recalculating sticky points. Setting it to `0` will cause it to recalc every scroll event, setting it to `-1` will prevent recalc on scroll.
* @option
* @type {number}
* @default -1
*/
checkEvery: -1
};
/**
* Helper function to calculate em values
* @param Number {em} - number of em's to calculate into pixels
*/
function emCalc(em) {
return parseInt(window.getComputedStyle(document.body, null).fontSize, 10) * em;
}
/***/ }),
/***/ 7:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Triggers; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__);
var MutationObserver = function () {
var prefixes = ['WebKit', 'Moz', 'O', 'Ms', ''];
for (var i = 0; i < prefixes.length; i++) {
if (prefixes[i] + 'MutationObserver' in window) {
return window[prefixes[i] + 'MutationObserver'];
}
}
return false;
}();
var triggers = function (el, type) {
el.data(type).split(' ').forEach(function (id) {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id)[type === 'close' ? 'trigger' : 'triggerHandler'](type + '.zf.trigger', [el]);
});
};
var Triggers = {
Listeners: {
Basic: {},
Global: {}
},
Initializers: {}
};
Triggers.Listeners.Basic = {
openListener: function () {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'open');
},
closeListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('close');
if (id) {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'close');
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('close.zf.trigger');
}
},
toggleListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle');
if (id) {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'toggle');
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('toggle.zf.trigger');
}
},
closeableListener: function (e) {
e.stopPropagation();
var animation = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('closable');
if (animation !== '') {
Foundation.Motion.animateOut(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), animation, function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('closed.zf');
});
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).fadeOut().trigger('closed.zf');
}
},
toggleFocusListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle-focus');
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id).triggerHandler('toggle.zf.trigger', [__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)]);
}
};
// Elements with [data-open] will reveal a plugin that supports it when clicked.
Triggers.Initializers.addOpenListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.openListener);
$elem.on('click.zf.trigger', '[data-open]', Triggers.Listeners.Basic.openListener);
};
// Elements with [data-close] will close a plugin that supports it when clicked.
// If used without a value on [data-close], the event will bubble, allowing it to close a parent component.
Triggers.Initializers.addCloseListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.closeListener);
$elem.on('click.zf.trigger', '[data-close]', Triggers.Listeners.Basic.closeListener);
};
// Elements with [data-toggle] will toggle a plugin that supports it when clicked.
Triggers.Initializers.addToggleListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.toggleListener);
$elem.on('click.zf.trigger', '[data-toggle]', Triggers.Listeners.Basic.toggleListener);
};
// Elements with [data-closable] will respond to close.zf.trigger events.
Triggers.Initializers.addCloseableListener = function ($elem) {
$elem.off('close.zf.trigger', Triggers.Listeners.Basic.closeableListener);
$elem.on('close.zf.trigger', '[data-closeable]', Triggers.Listeners.Basic.closeableListener);
};
// Elements with [data-toggle-focus] will respond to coming in and out of focus
Triggers.Initializers.addToggleFocusListener = function ($elem) {
$elem.off('focus.zf.trigger blur.zf.trigger', Triggers.Listeners.Basic.toggleFocusListener);
$elem.on('focus.zf.trigger blur.zf.trigger', '[data-toggle-focus]', Triggers.Listeners.Basic.toggleFocusListener);
};
// More Global/complex listeners and triggers
Triggers.Listeners.Global = {
resizeListener: function ($nodes) {
if (!MutationObserver) {
//fallback for IE 9
$nodes.each(function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('resizeme.zf.trigger');
});
}
//trigger all listening elements and signal a resize event
$nodes.attr('data-events', "resize");
},
scrollListener: function ($nodes) {
if (!MutationObserver) {
//fallback for IE 9
$nodes.each(function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('scrollme.zf.trigger');
});
}
//trigger all listening elements and signal a scroll event
$nodes.attr('data-events', "scroll");
},
closeMeListener: function (e, pluginId) {
var plugin = e.namespace.split('.')[0];
var plugins = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-' + plugin + ']').not('[data-yeti-box="' + pluginId + '"]');
plugins.each(function () {
var _this = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this);
_this.triggerHandler('close.zf.trigger', [_this]);
});
}
};
// Global, parses whole document.
Triggers.Initializers.addClosemeListener = function (pluginName) {
var yetiBoxes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-yeti-box]'),
plugNames = ['dropdown', 'tooltip', 'reveal'];
if (pluginName) {
if (typeof pluginName === 'string') {
plugNames.push(pluginName);
} else if (typeof pluginName === 'object' && typeof pluginName[0] === 'string') {
plugNames.concat(pluginName);
} else {
console.error('Plugin names must be strings');
}
}
if (yetiBoxes.length) {
var listeners = plugNames.map(function (name) {
return 'closeme.zf.' + name;
}).join(' ');
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(listeners).on(listeners, Triggers.Listeners.Global.closeMeListener);
}
};
function debounceGlobalListener(debounce, trigger, listener) {
var timer = void 0,
args = Array.prototype.slice.call(arguments, 3);
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(trigger).on(trigger, function (e) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
listener.apply(null, args);
}, debounce || 10); //default time to emit scroll event
});
}
Triggers.Initializers.addResizeListener = function (debounce) {
var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-resize]');
if ($nodes.length) {
debounceGlobalListener(debounce, 'resize.zf.trigger', Triggers.Listeners.Global.resizeListener, $nodes);
}
};
Triggers.Initializers.addScrollListener = function (debounce) {
var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-scroll]');
if ($nodes.length) {
debounceGlobalListener(debounce, 'scroll.zf.trigger', Triggers.Listeners.Global.scrollListener, $nodes);
}
};
Triggers.Initializers.addMutationEventsListener = function ($elem) {
if (!MutationObserver) {
return false;
}
var $nodes = $elem.find('[data-resize], [data-scroll], [data-mutate]');
//element callback
var listeningElementsMutation = function (mutationRecordsList) {
var $target = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(mutationRecordsList[0].target);
//trigger the event handler for the element depending on type
switch (mutationRecordsList[0].type) {
case "attributes":
if ($target.attr("data-events") === "scroll" && mutationRecordsList[0].attributeName === "data-events") {
$target.triggerHandler('scrollme.zf.trigger', [$target, window.pageYOffset]);
}
if ($target.attr("data-events") === "resize" && mutationRecordsList[0].attributeName === "data-events") {
$target.triggerHandler('resizeme.zf.trigger', [$target]);
}
if (mutationRecordsList[0].attributeName === "style") {
$target.closest("[data-mutate]").attr("data-events", "mutate");
$target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]);
}
break;
case "childList":
$target.closest("[data-mutate]").attr("data-events", "mutate");
$target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]);
break;
default:
return false;
//nothing
}
};
if ($nodes.length) {
//for each element that needs to listen for resizing, scrolling, or mutation add a single observer
for (var i = 0; i <= $nodes.length - 1; i++) {
var elementObserver = new MutationObserver(listeningElementsMutation);
elementObserver.observe($nodes[i], { attributes: true, childList: true, characterData: false, subtree: true, attributeFilter: ["data-events", "style"] });
}
}
};
Triggers.Initializers.addSimpleListeners = function () {
var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document);
Triggers.Initializers.addOpenListener($document);
Triggers.Initializers.addCloseListener($document);
Triggers.Initializers.addToggleListener($document);
Triggers.Initializers.addCloseableListener($document);
Triggers.Initializers.addToggleFocusListener($document);
};
Triggers.Initializers.addGlobalListeners = function () {
var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document);
Triggers.Initializers.addMutationEventsListener($document);
Triggers.Initializers.addResizeListener();
Triggers.Initializers.addScrollListener();
Triggers.Initializers.addClosemeListener();
};
Triggers.init = function ($, Foundation) {
if (typeof $.triggersInitialized === 'undefined') {
var $document = $(document);
if (document.readyState === "complete") {
Triggers.Initializers.addSimpleListeners();
Triggers.Initializers.addGlobalListeners();
} else {
$(window).on('load', function () {
Triggers.Initializers.addSimpleListeners();
Triggers.Initializers.addGlobalListeners();
});
}
$.triggersInitialized = true;
}
if (Foundation) {
Foundation.Triggers = Triggers;
// Legacy included to be backwards compatible for now.
Foundation.IHearYou = Triggers.Initializers.addGlobalListeners;
}
};
/***/ }),
/***/ 96:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(30);
/***/ })
/******/ }); | jeromelebleu/foundation-sites | dist/js/plugins/foundation.sticky.js | JavaScript | mit | 34,861 |
<?php
$type='TrueTypeUnicode';
$name='DejaVuSansCondensed-BoldOblique';
$desc=array('Ascent'=>928,'Descent'=>-236,'CapHeight'=>-46,'Flags'=>96,'FontBBox'=>'[-960 -385 1804 1121]','ItalicAngle'=>-11,'StemV'=>120,'MissingWidth'=>540);
$up=-63;
$ut=44;
$dw=540;
$cw=array(
0=>540,32=>313,33=>410,34=>469,35=>626,36=>626,37=>901,38=>785,39=>275,40=>411,
41=>411,42=>470,43=>754,44=>342,45=>374,46=>342,47=>329,48=>626,49=>626,50=>626,
51=>626,52=>626,53=>626,54=>626,55=>626,56=>626,57=>626,58=>360,59=>360,60=>754,
61=>754,62=>754,63=>522,64=>900,65=>696,66=>686,67=>660,68=>747,69=>615,70=>615,
71=>738,72=>753,73=>334,74=>334,75=>697,76=>573,77=>896,78=>753,79=>765,80=>659,
81=>765,82=>693,83=>648,84=>614,85=>730,86=>696,87=>993,88=>694,89=>651,90=>652,
91=>411,92=>329,93=>411,94=>754,95=>450,96=>450,97=>607,98=>644,99=>533,100=>644,
101=>610,102=>391,103=>644,104=>641,105=>308,106=>308,107=>598,108=>308,109=>938,110=>641,
111=>618,112=>644,113=>644,114=>444,115=>536,116=>430,117=>641,118=>586,119=>831,120=>580,
121=>586,122=>523,123=>641,124=>329,125=>641,126=>754,8364=>626,8218=>342,402=>391,8222=>580,
8230=>900,8224=>450,8225=>450,710=>450,8240=>1309,352=>648,8249=>371,338=>1050,381=>652,8216=>342,
8217=>342,8220=>580,8221=>580,8226=>575,8211=>450,8212=>900,732=>450,8482=>900,353=>536,8250=>371,
339=>984,382=>523,376=>651,160=>313,161=>410,162=>626,163=>626,164=>572,165=>626,166=>329,
167=>450,168=>450,169=>900,170=>507,171=>584,172=>754,173=>374,174=>900,175=>450,176=>450,
177=>754,178=>394,179=>394,180=>450,181=>662,182=>572,183=>342,184=>450,185=>394,186=>507,
187=>584,188=>932,189=>932,190=>932,191=>522,192=>696,193=>696,194=>696,195=>696,196=>696,
197=>696,198=>976,199=>660,200=>615,201=>615,202=>615,203=>615,204=>334,205=>334,206=>334,
207=>334,208=>760,209=>753,210=>765,211=>765,212=>765,213=>765,214=>765,215=>754,216=>765,
217=>730,218=>730,219=>730,220=>730,221=>651,222=>668,223=>647,224=>607,225=>607,226=>607,
227=>607,228=>607,229=>607,230=>943,231=>533,232=>610,233=>610,234=>610,235=>610,236=>308,
237=>308,238=>308,239=>308,240=>618,241=>641,242=>618,243=>618,244=>618,245=>618,246=>618,
247=>754,248=>618,249=>641,250=>641,251=>641,252=>641,253=>586,254=>644,255=>586,256=>696,
257=>607,258=>696,259=>607,260=>696,261=>607,262=>660,263=>533,264=>660,265=>533,266=>660,
267=>533,268=>660,269=>533,270=>747,271=>644,272=>760,273=>644,274=>615,275=>610,276=>615,
277=>610,278=>615,279=>610,280=>615,281=>610,282=>615,283=>610,284=>738,285=>644,286=>738,
287=>644,288=>738,289=>644,290=>738,291=>644,292=>753,293=>641,294=>876,295=>711,296=>334,
297=>308,298=>334,299=>308,300=>334,301=>308,302=>334,303=>308,304=>334,305=>308,306=>669,
307=>617,308=>334,309=>308,310=>697,311=>598,312=>598,313=>573,314=>308,315=>573,316=>308,
317=>573,318=>308,319=>573,320=>308,321=>594,322=>337,323=>753,324=>641,325=>753,326=>641,
327=>753,328=>641,329=>884,330=>753,331=>641,332=>765,333=>618,334=>765,335=>618,336=>765,
337=>618,340=>693,341=>444,342=>693,343=>444,344=>693,345=>444,346=>648,347=>536,348=>648,
349=>536,350=>648,351=>536,354=>614,355=>430,356=>614,357=>430,358=>614,359=>430,360=>730,
361=>641,362=>730,363=>641,364=>730,365=>641,366=>730,367=>641,368=>730,369=>641,370=>730,
371=>641,372=>993,373=>831,374=>651,375=>586,377=>652,378=>523,379=>652,380=>523,383=>391,
384=>644,385=>729,386=>686,387=>644,388=>686,389=>644,390=>660,391=>660,392=>533,393=>760,
394=>791,395=>686,396=>644,397=>618,398=>615,399=>765,400=>626,401=>615,403=>738,404=>713,
405=>940,406=>392,407=>350,408=>697,409=>598,410=>324,411=>532,412=>938,413=>753,414=>641,
415=>765,416=>765,417=>618,418=>1002,419=>866,420=>703,421=>644,422=>693,423=>648,424=>536,
425=>615,426=>497,427=>430,428=>636,429=>430,430=>614,431=>730,432=>641,433=>692,434=>732,
435=>717,436=>700,437=>652,438=>523,439=>695,440=>695,441=>576,442=>523,443=>626,444=>695,
445=>576,446=>515,447=>644,448=>334,449=>593,450=>489,451=>334,452=>1393,453=>1305,454=>1176,
455=>879,456=>881,457=>603,458=>1074,459=>1091,460=>957,461=>696,462=>607,463=>334,464=>308,
465=>765,466=>618,467=>730,468=>641,469=>730,470=>641,471=>730,472=>641,473=>730,474=>641,
475=>730,476=>641,477=>610,478=>696,479=>607,480=>696,481=>607,482=>976,483=>943,484=>738,
485=>644,486=>738,487=>644,488=>697,489=>598,490=>765,491=>618,492=>765,493=>618,494=>695,
495=>523,496=>308,497=>1393,498=>1305,499=>1176,500=>738,501=>644,502=>1160,503=>708,504=>753,
505=>641,506=>696,507=>607,508=>976,509=>943,510=>765,511=>618,512=>696,513=>607,514=>696,
515=>607,516=>615,517=>610,518=>615,519=>610,520=>334,521=>308,522=>334,523=>308,524=>765,
525=>618,526=>765,527=>618,528=>693,529=>444,530=>693,531=>444,532=>730,533=>641,534=>730,
535=>641,536=>648,537=>536,538=>614,539=>430,540=>621,541=>546,542=>753,543=>641,544=>753,
545=>778,546=>728,547=>593,548=>652,549=>523,550=>696,551=>607,552=>615,553=>610,554=>765,
555=>618,556=>765,557=>618,558=>765,559=>618,560=>765,561=>618,562=>651,563=>586,564=>442,
565=>780,566=>460,567=>308,568=>979,569=>979,570=>696,571=>660,572=>533,573=>573,574=>614,
575=>536,576=>523,577=>703,578=>553,579=>686,580=>730,581=>696,582=>615,583=>610,584=>334,
585=>308,586=>774,587=>712,588=>693,589=>444,590=>651,591=>586,592=>607,593=>644,594=>644,
595=>644,596=>533,597=>533,598=>712,599=>712,600=>610,601=>610,602=>788,603=>501,604=>490,
605=>696,606=>658,607=>308,608=>712,609=>644,610=>564,611=>661,612=>571,613=>641,614=>641,
615=>641,616=>491,617=>396,618=>491,619=>502,620=>624,621=>308,622=>757,623=>938,624=>938,
625=>938,626=>641,627=>713,628=>578,629=>618,630=>817,631=>613,632=>716,633=>484,634=>484,
635=>584,636=>444,637=>444,638=>536,639=>536,640=>578,641=>578,642=>536,643=>374,644=>391,
645=>544,646=>497,647=>430,648=>430,649=>828,650=>692,651=>603,652=>586,653=>831,654=>586,
655=>651,656=>624,657=>615,658=>576,659=>576,660=>515,661=>515,662=>515,663=>515,664=>765,
665=>569,666=>658,667=>616,668=>622,669=>308,670=>659,671=>485,672=>712,673=>515,674=>515,
675=>1040,676=>1093,677=>1039,678=>876,679=>691,680=>836,681=>923,682=>712,683=>702,684=>532,
685=>374,686=>609,687=>710,688=>410,689=>410,690=>197,691=>284,692=>284,693=>284,694=>369,
695=>532,696=>375,697=>271,698=>469,699=>342,700=>342,701=>342,702=>330,703=>330,704=>293,
705=>293,706=>450,707=>450,708=>450,709=>450,711=>450,712=>275,713=>450,714=>450,715=>450,
716=>275,717=>450,718=>450,719=>450,720=>303,721=>303,722=>330,723=>330,724=>450,725=>450,
726=>374,727=>295,728=>450,729=>450,730=>450,731=>450,733=>450,734=>315,735=>450,736=>370,
737=>197,738=>343,739=>371,740=>293,741=>450,742=>450,743=>450,744=>450,745=>450,748=>450,
749=>450,750=>580,755=>450,759=>450,768=>0,769=>0,770=>0,771=>0,772=>0,773=>0,
774=>0,775=>0,776=>0,777=>0,778=>0,779=>0,780=>0,781=>0,782=>0,783=>0,
784=>0,785=>0,786=>0,787=>0,788=>0,789=>0,790=>0,791=>0,792=>0,793=>0,
794=>0,795=>0,796=>0,797=>0,798=>0,799=>0,800=>0,801=>0,802=>0,803=>0,
804=>0,805=>0,806=>0,807=>0,808=>0,809=>0,810=>0,811=>0,812=>0,813=>0,
814=>0,815=>0,816=>0,817=>0,818=>0,819=>0,820=>0,821=>0,822=>0,823=>0,
824=>0,825=>0,826=>0,827=>0,828=>0,829=>0,830=>0,831=>0,832=>0,833=>0,
834=>0,835=>0,836=>0,837=>0,838=>0,839=>0,840=>0,841=>0,842=>0,843=>0,
844=>0,845=>0,846=>0,847=>0,849=>0,850=>0,851=>0,855=>0,856=>0,858=>0,
860=>0,861=>0,862=>0,863=>0,864=>0,865=>0,866=>0,880=>628,881=>508,882=>919,
883=>752,884=>271,885=>271,886=>753,887=>630,890=>450,891=>533,892=>495,893=>494,894=>360,
900=>397,901=>450,902=>717,903=>342,904=>761,905=>908,906=>507,908=>801,910=>882,911=>804,
912=>351,913=>696,914=>686,915=>573,916=>696,917=>615,918=>652,919=>753,920=>765,921=>334,
922=>697,923=>696,924=>896,925=>753,926=>568,927=>765,928=>753,929=>659,931=>615,932=>614,
933=>651,934=>765,935=>694,936=>765,937=>765,938=>334,939=>651,940=>618,941=>501,942=>641,
943=>351,944=>607,945=>618,946=>644,947=>613,948=>618,949=>501,950=>532,951=>641,952=>618,
953=>351,954=>639,955=>569,956=>662,957=>613,958=>532,959=>618,960=>712,961=>644,962=>533,
963=>701,964=>574,965=>607,966=>704,967=>580,968=>714,969=>782,970=>351,971=>607,972=>618,
973=>607,974=>782,975=>697,976=>585,977=>594,978=>671,979=>883,980=>671,981=>716,982=>782,
983=>669,984=>765,985=>618,986=>660,987=>533,988=>615,989=>444,990=>632,991=>593,992=>827,
993=>564,994=>983,995=>753,996=>749,997=>644,998=>835,999=>669,1000=>660,1001=>585,1002=>709,
1003=>604,1004=>677,1005=>644,1006=>614,1007=>531,1008=>669,1009=>644,1010=>533,1011=>308,1012=>765,
1013=>580,1014=>580,1015=>668,1016=>644,1017=>660,1018=>896,1019=>659,1020=>644,1021=>660,1022=>660,
1023=>628,1024=>615,1025=>615,1026=>791,1027=>573,1028=>660,1029=>648,1030=>334,1031=>334,1032=>334,
1033=>1039,1034=>1017,1035=>791,1036=>735,1037=>753,1038=>694,1039=>753,1040=>696,1041=>686,1042=>686,
1043=>573,1044=>801,1045=>615,1046=>1102,1047=>639,1048=>753,1049=>753,1050=>735,1051=>747,1052=>896,
1053=>753,1054=>765,1055=>753,1056=>659,1057=>660,1058=>614,1059=>694,1060=>892,1061=>694,1062=>835,
1063=>727,1064=>1112,1065=>1193,1066=>845,1067=>932,1068=>686,1069=>660,1070=>1056,1071=>693,1072=>607,
1073=>628,1074=>569,1075=>470,1076=>727,1077=>610,1078=>896,1079=>523,1080=>630,1081=>630,1082=>611,
1083=>659,1084=>735,1085=>622,1086=>618,1087=>622,1088=>644,1089=>533,1090=>521,1091=>586,1092=>893,
1093=>580,1094=>667,1095=>618,1096=>956,1097=>995,1098=>676,1099=>813,1100=>569,1101=>533,1102=>875,
1103=>578,1104=>610,1105=>610,1106=>642,1107=>470,1108=>533,1109=>536,1110=>308,1111=>308,1112=>308,
1113=>892,1114=>860,1115=>661,1116=>611,1117=>630,1118=>586,1119=>622,1120=>983,1121=>782,1122=>756,
1123=>662,1124=>911,1125=>755,1126=>893,1127=>749,1128=>1222,1129=>1009,1130=>765,1131=>618,1132=>1112,
1133=>906,1134=>626,1135=>501,1136=>967,1137=>955,1138=>765,1139=>618,1140=>765,1141=>625,1142=>765,
1143=>625,1144=>1033,1145=>939,1146=>967,1147=>776,1148=>1265,1149=>1055,1150=>983,1151=>782,1152=>660,
1153=>533,1154=>587,1155=>0,1156=>0,1157=>0,1158=>0,1159=>0,1160=>376,1161=>376,1162=>844,
1163=>725,1164=>686,1165=>550,1166=>662,1167=>646,1168=>573,1169=>470,1170=>599,1171=>488,1172=>709,
1173=>470,1174=>1102,1175=>896,1176=>639,1177=>523,1178=>697,1179=>611,1180=>735,1181=>611,1182=>735,
1183=>611,1184=>914,1185=>743,1186=>753,1187=>622,1188=>992,1189=>783,1190=>1129,1191=>880,1192=>851,
1193=>773,1194=>660,1195=>533,1196=>614,1197=>521,1198=>651,1199=>586,1200=>651,1201=>586,1202=>694,
1203=>580,1204=>993,1205=>901,1206=>727,1207=>618,1208=>727,1209=>618,1210=>727,1211=>641,1212=>923,
1213=>729,1214=>923,1215=>729,1216=>334,1217=>1102,1218=>896,1219=>700,1220=>566,1221=>839,1222=>724,
1223=>753,1224=>622,1225=>844,1226=>725,1227=>727,1228=>618,1229=>986,1230=>838,1231=>308,1232=>696,
1233=>607,1234=>696,1235=>607,1236=>976,1237=>943,1238=>615,1239=>610,1240=>765,1241=>610,1242=>765,
1243=>610,1244=>1102,1245=>896,1246=>639,1247=>523,1248=>695,1249=>576,1250=>753,1251=>630,1252=>753,
1253=>630,1254=>765,1255=>618,1256=>765,1257=>618,1258=>765,1259=>618,1260=>660,1261=>533,1262=>694,
1263=>586,1264=>694,1265=>586,1266=>694,1267=>586,1268=>727,1269=>618,1270=>573,1271=>470,1272=>932,
1273=>813,1274=>599,1275=>488,1276=>694,1277=>580,1278=>694,1279=>580,1280=>686,1281=>547,1282=>1043,
1283=>804,1284=>1007,1285=>828,1286=>745,1287=>624,1288=>1117,1289=>915,1290=>1160,1291=>912,1292=>755,
1293=>574,1294=>844,1295=>722,1296=>626,1297=>501,1298=>747,1299=>659,1300=>1157,1301=>963,1302=>958,
1303=>883,1304=>973,1305=>864,1306=>765,1307=>644,1308=>993,1309=>831,1312=>1123,1313=>920,1314=>1128,
1315=>880,1316=>861,1317=>726,1329=>886,1330=>730,1331=>886,1332=>886,1333=>730,1334=>699,1335=>730,
1336=>730,1337=>877,1338=>886,1339=>730,1340=>639,1341=>970,1342=>1022,1343=>730,1344=>639,1345=>681,
1346=>886,1347=>789,1348=>886,1349=>714,1350=>886,1351=>730,1352=>730,1353=>730,1354=>862,1355=>699,
1356=>886,1357=>730,1358=>886,1359=>648,1360=>730,1361=>714,1362=>805,1363=>765,1364=>842,1365=>765,
1366=>648,1369=>330,1370=>342,1371=>495,1372=>495,1373=>342,1374=>491,1375=>468,1377=>938,1378=>641,
1379=>779,1380=>781,1381=>641,1382=>735,1383=>588,1384=>641,1385=>729,1386=>735,1387=>641,1388=>448,
1389=>916,1390=>644,1391=>641,1392=>641,1393=>644,1394=>737,1395=>641,1396=>676,1397=>308,1398=>794,
1399=>502,1400=>641,1401=>502,1402=>938,1403=>502,1404=>777,1405=>641,1406=>732,1407=>938,1408=>641,
1409=>644,1410=>514,1411=>938,1412=>700,1413=>618,1414=>648,1415=>776,1417=>360,1418=>438,1456=>0,
1457=>0,1458=>0,1459=>0,1460=>0,1461=>0,1462=>0,1463=>0,1464=>0,1465=>0,1466=>0,
1467=>0,1468=>0,1469=>0,1470=>374,1471=>0,1472=>334,1473=>0,1474=>0,1475=>334,1478=>447,
1479=>0,1488=>676,1489=>605,1490=>483,1491=>589,1492=>641,1493=>308,1494=>442,1495=>641,1496=>651,
1497=>308,1498=>584,1499=>584,1500=>611,1501=>641,1502=>698,1503=>308,1504=>447,1505=>696,1506=>610,
1507=>646,1508=>618,1509=>565,1510=>676,1511=>656,1512=>584,1513=>854,1514=>676,1520=>598,1521=>598,
1522=>597,1523=>399,1524=>639,3647=>626,3713=>734,3714=>673,3716=>674,3719=>512,3720=>668,3722=>669,
3725=>685,3732=>635,3733=>633,3734=>672,3735=>737,3737=>657,3738=>654,3739=>654,3740=>830,3741=>744,
3742=>779,3743=>779,3745=>752,3746=>685,3747=>692,3749=>691,3751=>642,3754=>744,3755=>928,3757=>651,
3758=>705,3759=>840,3760=>620,3761=>0,3762=>549,3763=>549,3764=>0,3765=>0,3766=>0,3767=>0,
3768=>0,3769=>0,3771=>0,3772=>0,3773=>603,3776=>464,3777=>774,3778=>464,3779=>584,3780=>569,
3782=>683,3784=>0,3785=>0,3786=>0,3787=>0,3788=>0,3789=>0,3792=>694,3793=>694,3794=>624,
3795=>752,3796=>655,3797=>655,3798=>764,3799=>710,3800=>683,3801=>818,3804=>1227,3805=>1227,4256=>826,
4257=>669,4258=>665,4259=>753,4260=>584,4261=>696,4262=>771,4263=>800,4264=>477,4265=>570,4266=>771,
4267=>810,4268=>579,4269=>813,4270=>732,4271=>677,4272=>782,4273=>579,4274=>579,4275=>797,4276=>797,
4277=>660,4278=>587,4279=>579,4280=>582,4281=>579,4282=>710,4283=>812,4284=>570,4285=>557,4286=>579,
4287=>700,4288=>802,4289=>541,4290=>668,4291=>554,4292=>570,4293=>668,4304=>497,4305=>497,4306=>536,
4307=>734,4308=>505,4309=>506,4310=>497,4311=>744,4312=>497,4313=>488,4314=>967,4315=>506,4316=>507,
4317=>730,4318=>497,4319=>532,4320=>740,4321=>506,4322=>621,4323=>525,4324=>732,4325=>505,4326=>731,
4327=>506,4328=>506,4329=>507,4330=>568,4331=>506,4332=>506,4333=>497,4334=>506,4335=>506,4336=>501,
4337=>543,4338=>497,4339=>497,4340=>497,4341=>544,4342=>767,4343=>571,4344=>506,4345=>536,4346=>487,
4347=>615,4348=>331,5121=>696,5122=>696,5123=>696,5124=>696,5125=>814,5126=>814,5127=>814,5129=>814,
5130=>814,5131=>814,5132=>916,5133=>908,5134=>916,5135=>908,5136=>916,5137=>908,5138=>1034,5139=>1025,
5140=>1034,5141=>1025,5142=>814,5143=>1034,5144=>1028,5145=>1034,5146=>1028,5147=>814,5149=>278,5150=>476,
5151=>382,5152=>382,5153=>355,5154=>355,5155=>355,5156=>355,5157=>507,5158=>423,5159=>278,5160=>355,
5161=>355,5162=>355,5163=>1092,5164=>888,5165=>1094,5166=>1167,5167=>696,5168=>696,5169=>696,5170=>696,
5171=>797,5172=>797,5173=>797,5175=>797,5176=>797,5177=>797,5178=>916,5179=>908,5180=>916,5181=>908,
5182=>916,5183=>908,5184=>1034,5185=>1025,5186=>1034,5187=>1025,5188=>1034,5189=>1028,5190=>1034,5191=>1028,
5192=>797,5193=>518,5194=>206,5196=>730,5197=>730,5198=>730,5199=>730,5200=>734,5201=>734,5202=>734,
5204=>734,5205=>734,5206=>734,5207=>950,5208=>943,5209=>950,5210=>943,5211=>950,5212=>943,5213=>954,
5214=>949,5215=>954,5216=>949,5217=>954,5218=>946,5219=>954,5220=>946,5221=>954,5222=>435,5223=>904,
5224=>904,5225=>921,5226=>915,5227=>668,5228=>668,5229=>668,5230=>668,5231=>668,5232=>668,5233=>668,
5234=>668,5235=>668,5236=>926,5237=>877,5238=>882,5239=>877,5240=>882,5241=>877,5242=>926,5243=>877,
5244=>926,5245=>877,5246=>882,5247=>877,5248=>882,5249=>877,5250=>882,5251=>451,5252=>451,5253=>844,
5254=>844,5255=>844,5256=>844,5257=>668,5258=>668,5259=>668,5260=>668,5261=>668,5262=>668,5263=>668,
5264=>668,5265=>668,5266=>926,5267=>877,5268=>926,5269=>877,5270=>926,5271=>877,5272=>926,5273=>877,
5274=>926,5275=>877,5276=>926,5277=>877,5278=>926,5279=>877,5280=>926,5281=>451,5282=>451,5283=>563,
5284=>563,5285=>563,5286=>563,5287=>563,5288=>563,5289=>563,5290=>563,5291=>563,5292=>793,5293=>769,
5294=>777,5295=>786,5296=>777,5297=>786,5298=>793,5299=>786,5300=>793,5301=>786,5302=>777,5303=>786,
5304=>777,5305=>786,5306=>777,5307=>392,5308=>493,5309=>392,5312=>889,5313=>889,5314=>889,5315=>889,
5316=>838,5317=>838,5318=>838,5319=>838,5320=>838,5321=>1114,5322=>1122,5323=>1080,5324=>1105,5325=>1080,
5326=>1105,5327=>838,5328=>593,5329=>447,5330=>593,5331=>889,5332=>889,5333=>889,5334=>889,5335=>838,
5336=>838,5337=>838,5338=>838,5339=>838,5340=>1107,5341=>1122,5342=>1155,5343=>1105,5344=>1155,5345=>1105,
5346=>1105,5347=>1093,5348=>1105,5349=>1093,5350=>1155,5351=>1105,5352=>1155,5353=>1105,5354=>593,5356=>797,
5357=>657,5358=>657,5359=>657,5360=>657,5361=>657,5362=>657,5363=>657,5364=>657,5365=>657,5366=>897,
5367=>862,5368=>870,5369=>890,5370=>870,5371=>890,5372=>897,5373=>862,5374=>897,5375=>862,5376=>870,
5377=>890,5378=>870,5379=>890,5380=>870,5381=>443,5382=>414,5383=>443,5392=>831,5393=>831,5394=>831,
5395=>1022,5396=>1022,5397=>1022,5398=>1022,5399=>1088,5400=>1081,5401=>1088,5402=>1081,5403=>1088,5404=>1081,
5405=>1288,5406=>1278,5407=>1288,5408=>1278,5409=>1288,5410=>1278,5411=>1288,5412=>1278,5413=>671,5414=>698,
5415=>698,5416=>698,5417=>698,5418=>698,5419=>698,5420=>698,5421=>698,5422=>698,5423=>902,5424=>903,
5425=>911,5426=>896,5427=>911,5428=>896,5429=>902,5430=>903,5431=>902,5432=>903,5433=>911,5434=>896,
5435=>911,5436=>896,5437=>911,5438=>445,5440=>355,5441=>458,5442=>929,5443=>929,5444=>878,5445=>878,
5446=>878,5447=>878,5448=>659,5449=>659,5450=>659,5451=>659,5452=>659,5453=>659,5454=>902,5455=>863,
5456=>445,5458=>797,5459=>696,5460=>696,5461=>696,5462=>696,5463=>835,5464=>835,5465=>835,5466=>835,
5467=>1055,5468=>1028,5469=>542,5470=>730,5471=>730,5472=>730,5473=>730,5474=>730,5475=>730,5476=>734,
5477=>734,5478=>734,5479=>734,5480=>954,5481=>946,5482=>493,5492=>879,5493=>879,5494=>879,5495=>879,
5496=>879,5497=>879,5498=>879,5499=>556,5500=>753,5501=>458,5502=>1114,5503=>1114,5504=>1114,5505=>1114,
5506=>1114,5507=>1114,5508=>1114,5509=>890,5514=>879,5515=>879,5516=>879,5517=>879,5518=>1432,5519=>1432,
5520=>1432,5521=>1165,5522=>1165,5523=>1432,5524=>1432,5525=>763,5526=>1146,5536=>889,5537=>889,5538=>838,
5539=>838,5540=>838,5541=>838,5542=>593,5543=>698,5544=>698,5545=>698,5546=>698,5547=>698,5548=>698,
5549=>698,5550=>445,5551=>668,5598=>747,5601=>747,5702=>446,5703=>446,5742=>371,5743=>1114,5744=>1432,
5745=>1814,5746=>1814,5747=>1548,5748=>1510,5749=>1814,5750=>1814,7424=>586,7425=>750,7426=>943,7427=>547,
7428=>533,7429=>608,7430=>608,7431=>502,7432=>501,7433=>308,7434=>444,7435=>598,7436=>485,7437=>735,
7438=>630,7439=>618,7440=>533,7441=>594,7442=>594,7443=>594,7444=>984,7446=>618,7447=>618,7448=>500,
7449=>578,7450=>578,7451=>521,7452=>571,7453=>663,7454=>853,7455=>625,7456=>586,7457=>831,7458=>523,
7459=>581,7462=>485,7463=>586,7464=>622,7465=>500,7466=>703,7467=>659,7468=>438,7469=>615,7470=>432,
7472=>470,7473=>387,7474=>387,7475=>465,7476=>474,7477=>211,7478=>211,7479=>439,7480=>361,7481=>563,
7482=>474,7483=>474,7484=>481,7485=>458,7486=>415,7487=>436,7488=>387,7489=>460,7490=>625,7491=>412,
7492=>412,7493=>431,7494=>641,7495=>431,7496=>431,7497=>431,7498=>431,7499=>347,7500=>347,7501=>431,
7502=>197,7503=>438,7504=>597,7505=>410,7506=>439,7507=>372,7508=>439,7509=>439,7510=>431,7511=>349,
7512=>410,7513=>416,7514=>597,7515=>451,7517=>405,7518=>386,7519=>389,7520=>443,7521=>365,7522=>197,
7523=>284,7524=>410,7525=>451,7526=>405,7527=>386,7528=>405,7529=>443,7530=>365,7543=>644,7544=>474,
7547=>491,7549=>672,7557=>462,7579=>431,7580=>372,7581=>372,7582=>439,7583=>347,7584=>339,7585=>313,
7586=>431,7587=>410,7588=>312,7589=>253,7590=>312,7591=>312,7592=>388,7593=>293,7594=>296,7595=>333,
7596=>598,7597=>597,7598=>505,7599=>505,7600=>403,7601=>439,7602=>488,7603=>379,7604=>356,7605=>349,
7606=>524,7607=>444,7608=>359,7609=>405,7610=>451,7611=>375,7612=>471,7613=>422,7614=>409,7615=>382,
7620=>0,7621=>0,7622=>0,7623=>0,7624=>0,7625=>0,7680=>696,7681=>607,7682=>686,7683=>644,
7684=>686,7685=>644,7686=>686,7687=>644,7688=>660,7689=>533,7690=>747,7691=>644,7692=>747,7693=>644,
7694=>747,7695=>644,7696=>747,7697=>644,7698=>747,7699=>644,7700=>615,7701=>610,7702=>615,7703=>610,
7704=>615,7705=>610,7706=>615,7707=>610,7708=>615,7709=>610,7710=>615,7711=>391,7712=>738,7713=>644,
7714=>753,7715=>641,7716=>753,7717=>641,7718=>753,7719=>641,7720=>753,7721=>641,7722=>753,7723=>641,
7724=>334,7725=>308,7726=>334,7727=>308,7728=>697,7729=>598,7730=>697,7731=>598,7732=>697,7733=>598,
7734=>573,7735=>308,7736=>573,7737=>308,7738=>573,7739=>308,7740=>573,7741=>308,7742=>896,7743=>938,
7744=>896,7745=>938,7746=>896,7747=>938,7748=>753,7749=>641,7750=>753,7751=>641,7752=>753,7753=>641,
7754=>753,7755=>641,7756=>765,7757=>618,7758=>765,7759=>618,7760=>765,7761=>618,7762=>765,7763=>618,
7764=>659,7765=>644,7766=>659,7767=>644,7768=>693,7769=>444,7770=>693,7771=>444,7772=>693,7773=>444,
7774=>693,7775=>444,7776=>648,7777=>536,7778=>648,7779=>536,7780=>648,7781=>536,7782=>648,7783=>536,
7784=>648,7785=>536,7786=>614,7787=>430,7788=>614,7789=>430,7790=>614,7791=>430,7792=>614,7793=>430,
7794=>730,7795=>641,7796=>730,7797=>641,7798=>730,7799=>641,7800=>730,7801=>641,7802=>730,7803=>641,
7804=>696,7805=>586,7806=>696,7807=>586,7808=>993,7809=>831,7810=>993,7811=>831,7812=>993,7813=>831,
7814=>993,7815=>831,7816=>993,7817=>831,7818=>694,7819=>580,7820=>694,7821=>580,7822=>651,7823=>586,
7824=>652,7825=>523,7826=>652,7827=>523,7828=>652,7829=>523,7830=>641,7831=>430,7832=>831,7833=>586,
7834=>607,7835=>391,7836=>391,7837=>391,7838=>806,7839=>618,7840=>696,7841=>607,7842=>696,7843=>607,
7844=>696,7845=>607,7846=>696,7847=>607,7848=>696,7849=>607,7850=>696,7851=>607,7852=>696,7853=>607,
7854=>696,7855=>607,7856=>696,7857=>607,7858=>696,7859=>607,7860=>696,7861=>607,7862=>696,7863=>607,
7864=>615,7865=>610,7866=>615,7867=>610,7868=>615,7869=>610,7870=>615,7871=>610,7872=>615,7873=>610,
7874=>615,7875=>610,7876=>615,7877=>610,7878=>615,7879=>610,7880=>334,7881=>308,7882=>334,7883=>308,
7884=>765,7885=>618,7886=>765,7887=>618,7888=>765,7889=>618,7890=>765,7891=>618,7892=>765,7893=>618,
7894=>765,7895=>618,7896=>765,7897=>618,7898=>765,7899=>618,7900=>765,7901=>618,7902=>765,7903=>618,
7904=>765,7905=>618,7906=>765,7907=>618,7908=>730,7909=>641,7910=>730,7911=>641,7912=>730,7913=>641,
7914=>730,7915=>641,7916=>730,7917=>641,7918=>730,7919=>641,7920=>730,7921=>641,7922=>651,7923=>586,
7924=>651,7925=>586,7926=>651,7927=>586,7928=>651,7929=>586,7930=>857,7931=>579,7936=>618,7937=>618,
7938=>618,7939=>618,7940=>618,7941=>618,7942=>618,7943=>618,7944=>696,7945=>696,7946=>937,7947=>939,
7948=>841,7949=>866,7950=>751,7951=>773,7952=>501,7953=>501,7954=>501,7955=>501,7956=>501,7957=>501,
7960=>712,7961=>715,7962=>989,7963=>986,7964=>920,7965=>947,7968=>641,7969=>641,7970=>641,7971=>641,
7972=>641,7973=>641,7974=>641,7975=>641,7976=>851,7977=>856,7978=>1125,7979=>1125,7980=>1062,7981=>1085,
7982=>948,7983=>956,7984=>351,7985=>351,7986=>351,7987=>351,7988=>351,7989=>351,7990=>351,7991=>351,
7992=>435,7993=>440,7994=>699,7995=>707,7996=>641,7997=>664,7998=>544,7999=>544,8000=>618,8001=>618,
8002=>618,8003=>618,8004=>618,8005=>618,8008=>802,8009=>839,8010=>1099,8011=>1101,8012=>947,8013=>974,
8016=>607,8017=>607,8018=>607,8019=>607,8020=>607,8021=>607,8022=>607,8023=>607,8025=>837,8027=>1065,
8029=>1079,8031=>944,8032=>782,8033=>782,8034=>782,8035=>782,8036=>782,8037=>782,8038=>782,8039=>782,
8040=>817,8041=>862,8042=>1121,8043=>1126,8044=>968,8045=>994,8046=>925,8047=>968,8048=>618,8049=>618,
8050=>501,8051=>501,8052=>641,8053=>641,8054=>351,8055=>351,8056=>618,8057=>618,8058=>607,8059=>607,
8060=>782,8061=>782,8064=>618,8065=>618,8066=>618,8067=>618,8068=>618,8069=>618,8070=>618,8071=>618,
8072=>696,8073=>696,8074=>937,8075=>939,8076=>841,8077=>866,8078=>751,8079=>773,8080=>641,8081=>641,
8082=>641,8083=>641,8084=>641,8085=>641,8086=>641,8087=>641,8088=>851,8089=>856,8090=>1125,8091=>1125,
8092=>1062,8093=>1085,8094=>948,8095=>956,8096=>782,8097=>782,8098=>782,8099=>782,8100=>782,8101=>782,
8102=>782,8103=>782,8104=>817,8105=>862,8106=>1121,8107=>1126,8108=>968,8109=>994,8110=>925,8111=>968,
8112=>618,8113=>618,8114=>618,8115=>618,8116=>618,8118=>618,8119=>618,8120=>696,8121=>696,8122=>789,
8123=>717,8124=>696,8125=>450,8126=>450,8127=>450,8128=>450,8129=>450,8130=>641,8131=>641,8132=>641,
8134=>641,8135=>641,8136=>836,8137=>761,8138=>972,8139=>908,8140=>753,8141=>450,8142=>450,8143=>450,
8144=>351,8145=>351,8146=>351,8147=>351,8150=>351,8151=>351,8152=>334,8153=>334,8154=>559,8155=>507,
8157=>450,8158=>450,8159=>450,8160=>607,8161=>607,8162=>607,8163=>607,8164=>644,8165=>644,8166=>607,
8167=>607,8168=>651,8169=>651,8170=>918,8171=>882,8172=>754,8173=>450,8174=>450,8175=>450,8178=>782,
8179=>782,8180=>782,8182=>782,8183=>782,8184=>958,8185=>801,8186=>976,8187=>804,8188=>765,8189=>450,
8190=>450,8192=>450,8193=>900,8194=>450,8195=>900,8196=>296,8197=>225,8198=>150,8199=>626,8200=>342,
8201=>180,8202=>89,8203=>0,8204=>0,8205=>0,8206=>0,8207=>0,8208=>374,8209=>374,8210=>626,
8213=>900,8214=>450,8215=>450,8219=>342,8223=>591,8227=>575,8228=>342,8229=>616,8231=>313,8232=>0,
8233=>0,8234=>0,8235=>0,8236=>0,8237=>0,8238=>0,8239=>180,8241=>1717,8242=>237,8243=>402,
8244=>567,8245=>237,8246=>402,8247=>567,8248=>659,8251=>875,8252=>564,8253=>522,8254=>450,8255=>745,
8256=>745,8257=>296,8258=>920,8259=>450,8260=>150,8261=>411,8262=>411,8263=>927,8264=>746,8265=>746,
8266=>461,8267=>618,8268=>450,8269=>450,8270=>470,8271=>360,8272=>745,8273=>470,8274=>500,8275=>754,
8276=>745,8277=>754,8278=>615,8279=>731,8280=>754,8281=>754,8282=>342,8283=>784,8284=>754,8285=>342,
8286=>342,8287=>200,8288=>0,8289=>0,8290=>0,8291=>0,8292=>0,8298=>0,8299=>0,8300=>0,
8301=>0,8302=>0,8303=>0,8304=>394,8305=>197,8308=>394,8309=>394,8310=>394,8311=>394,8312=>394,
8313=>394,8314=>475,8315=>475,8316=>475,8317=>259,8318=>259,8319=>410,8320=>394,8321=>394,8322=>394,
8323=>394,8324=>394,8325=>394,8326=>394,8327=>394,8328=>394,8329=>394,8330=>475,8331=>475,8332=>475,
8333=>259,8334=>259,8336=>412,8337=>431,8338=>439,8339=>371,8340=>431,8352=>836,8353=>626,8354=>626,
8355=>626,8356=>626,8357=>938,8358=>753,8359=>1339,8360=>1084,8361=>993,8362=>768,8363=>626,8365=>626,
8366=>626,8367=>1252,8368=>626,8369=>626,8370=>626,8371=>626,8372=>773,8373=>626,8376=>626,8377=>626,
8400=>0,8401=>0,8406=>0,8407=>0,8411=>0,8412=>0,8417=>0,8448=>995,8449=>995,8450=>660,
8451=>1090,8452=>807,8453=>1002,8454=>1033,8455=>626,8456=>628,8457=>856,8459=>965,8460=>822,8461=>799,
8462=>641,8463=>641,8464=>537,8465=>627,8466=>771,8467=>424,8468=>876,8469=>753,8470=>1083,8471=>900,
8472=>627,8473=>675,8474=>765,8475=>844,8476=>732,8477=>721,8478=>807,8479=>639,8480=>917,8481=>1115,
8483=>751,8484=>679,8485=>560,8486=>765,8487=>692,8488=>686,8489=>272,8490=>697,8491=>696,8492=>835,
8493=>736,8494=>769,8495=>572,8496=>656,8497=>727,8498=>615,8499=>1065,8500=>418,8501=>714,8502=>658,
8503=>444,8504=>615,8505=>342,8506=>851,8507=>1232,8508=>710,8509=>663,8510=>589,8511=>776,8512=>756,
8513=>707,8514=>518,8515=>573,8516=>684,8517=>747,8518=>644,8519=>610,8520=>308,8521=>308,8523=>785,
8526=>492,8528=>932,8529=>932,8530=>1334,8531=>932,8532=>932,8533=>932,8534=>932,8535=>932,8536=>932,
8537=>932,8538=>932,8539=>932,8540=>932,8541=>932,8542=>932,8543=>554,8544=>334,8545=>593,8546=>851,
8547=>989,8548=>696,8549=>989,8550=>1247,8551=>1505,8552=>1008,8553=>694,8554=>1008,8555=>1266,8556=>573,
8557=>660,8558=>747,8559=>896,8560=>308,8561=>546,8562=>785,8563=>885,8564=>586,8565=>866,8566=>1104,
8567=>1342,8568=>872,8569=>580,8570=>872,8571=>1110,8572=>308,8573=>533,8574=>644,8575=>938,8576=>1160,
8577=>747,8578=>1160,8579=>660,8580=>533,8581=>660,8585=>932,8592=>754,8593=>754,8594=>754,8595=>754,
8596=>754,8597=>754,8598=>754,8599=>754,8600=>754,8601=>754,8602=>754,8603=>754,8604=>754,8605=>754,
8606=>754,8607=>754,8608=>754,8609=>754,8610=>754,8611=>754,8612=>754,8613=>754,8614=>754,8615=>754,
8616=>754,8617=>754,8618=>754,8619=>754,8620=>754,8621=>754,8622=>754,8623=>754,8624=>754,8625=>754,
8626=>754,8627=>754,8628=>754,8629=>754,8630=>754,8631=>754,8632=>754,8633=>754,8634=>754,8635=>754,
8636=>754,8637=>754,8638=>754,8639=>754,8640=>754,8641=>754,8642=>754,8643=>754,8644=>754,8645=>754,
8646=>754,8647=>754,8648=>754,8649=>754,8650=>754,8651=>754,8652=>754,8653=>754,8654=>754,8655=>754,
8656=>754,8657=>754,8658=>754,8659=>754,8660=>754,8661=>754,8662=>754,8663=>754,8664=>754,8665=>754,
8666=>754,8667=>754,8668=>754,8669=>754,8670=>754,8671=>754,8672=>754,8673=>754,8674=>754,8675=>754,
8676=>754,8677=>754,8678=>754,8679=>754,8680=>754,8681=>754,8682=>754,8683=>754,8684=>754,8685=>754,
8686=>754,8687=>754,8688=>754,8689=>754,8690=>754,8691=>754,8692=>754,8693=>754,8694=>754,8695=>754,
8696=>754,8697=>754,8698=>754,8699=>754,8700=>754,8701=>754,8702=>754,8703=>754,8704=>696,8705=>626,
8706=>489,8707=>615,8708=>615,8709=>771,8710=>627,8711=>627,8712=>807,8713=>807,8714=>675,8715=>807,
8716=>807,8717=>675,8718=>572,8719=>708,8720=>708,8721=>646,8722=>754,8723=>754,8724=>626,8725=>329,
8726=>626,8727=>754,8728=>563,8729=>342,8730=>600,8731=>600,8732=>600,8733=>641,8734=>750,8735=>754,
8736=>807,8737=>807,8738=>754,8739=>450,8740=>450,8741=>450,8742=>450,8743=>730,8744=>730,8745=>730,
8746=>730,8747=>549,8748=>835,8749=>1165,8750=>506,8751=>879,8752=>1181,8753=>506,8754=>506,8755=>506,
8756=>626,8757=>626,8758=>264,8759=>626,8760=>754,8761=>754,8762=>754,8763=>754,8764=>754,8765=>754,
8766=>754,8767=>754,8768=>337,8769=>754,8770=>754,8771=>754,8772=>754,8773=>754,8774=>754,8775=>754,
8776=>754,8777=>754,8778=>754,8779=>754,8780=>754,8781=>754,8782=>754,8783=>754,8784=>754,8785=>754,
8786=>754,8787=>754,8788=>956,8789=>956,8790=>754,8791=>754,8792=>754,8793=>754,8794=>754,8795=>754,
8796=>754,8797=>754,8798=>754,8799=>754,8800=>754,8801=>754,8802=>754,8803=>754,8804=>754,8805=>754,
8806=>754,8807=>754,8808=>756,8809=>756,8810=>942,8811=>942,8812=>450,8813=>754,8814=>754,8815=>754,
8816=>754,8817=>754,8818=>754,8819=>754,8820=>754,8821=>754,8822=>754,8823=>754,8824=>754,8825=>754,
8826=>754,8827=>754,8828=>754,8829=>754,8830=>754,8831=>754,8832=>754,8833=>754,8834=>754,8835=>754,
8836=>754,8837=>754,8838=>754,8839=>754,8840=>754,8841=>754,8842=>754,8843=>754,8844=>730,8845=>730,
8846=>730,8847=>754,8848=>754,8849=>754,8850=>754,8851=>716,8852=>716,8853=>754,8854=>754,8855=>754,
8856=>754,8857=>754,8858=>754,8859=>754,8860=>754,8861=>754,8862=>754,8863=>754,8864=>754,8865=>754,
8866=>822,8867=>822,8868=>822,8869=>822,8870=>488,8871=>488,8872=>822,8873=>822,8874=>822,8875=>822,
8876=>822,8877=>822,8878=>822,8879=>822,8880=>754,8881=>754,8882=>754,8883=>754,8884=>754,8885=>754,
8886=>900,8887=>900,8888=>754,8889=>754,8890=>488,8891=>730,8892=>730,8893=>730,8894=>754,8895=>754,
8896=>758,8897=>758,8898=>758,8899=>758,8900=>444,8901=>342,8902=>563,8903=>754,8904=>900,8905=>900,
8906=>900,8907=>900,8908=>900,8909=>754,8910=>730,8911=>730,8912=>754,8913=>754,8914=>754,8915=>754,
8916=>754,8917=>754,8918=>754,8919=>754,8920=>1280,8921=>1280,8922=>754,8923=>754,8924=>754,8925=>754,
8926=>754,8927=>754,8928=>754,8929=>754,8930=>754,8931=>754,8932=>754,8933=>754,8934=>754,8935=>754,
8936=>754,8937=>754,8938=>754,8939=>754,8940=>754,8941=>754,8942=>900,8943=>900,8944=>900,8945=>900,
8946=>1042,8947=>807,8948=>675,8949=>807,8950=>807,8951=>675,8952=>807,8953=>807,8954=>1042,8955=>807,
8956=>675,8957=>807,8958=>675,8959=>807,8960=>542,8961=>542,8962=>644,8963=>754,8964=>754,8965=>754,
8966=>754,8967=>439,8968=>411,8969=>411,8970=>411,8971=>411,8972=>728,8973=>728,8974=>728,8975=>728,
8976=>754,8977=>484,8984=>835,8985=>754,8988=>422,8989=>422,8990=>422,8991=>422,8992=>549,8993=>549,
8996=>1037,8997=>1037,8998=>1272,8999=>1037,9000=>1299,9003=>1272,9004=>786,9075=>351,9076=>644,9077=>782,
9082=>618,9085=>776,9095=>1037,9108=>786,9115=>450,9116=>450,9117=>450,9118=>450,9119=>450,9120=>450,
9121=>450,9122=>450,9123=>450,9124=>450,9125=>450,9126=>450,9127=>675,9128=>675,9129=>675,9130=>675,
9131=>675,9132=>675,9133=>675,9134=>549,9166=>754,9167=>850,9187=>786,9189=>692,9192=>626,9250=>644,
9251=>644,9312=>762,9313=>762,9314=>762,9315=>762,9316=>762,9317=>762,9318=>762,9319=>762,9320=>762,
9321=>762,9600=>692,9601=>692,9602=>692,9603=>692,9604=>692,9605=>692,9606=>692,9607=>692,9608=>692,
9609=>692,9610=>692,9611=>692,9612=>692,9613=>692,9614=>692,9615=>692,9616=>692,9617=>692,9618=>692,
9619=>692,9620=>692,9621=>692,9622=>692,9623=>692,9624=>692,9625=>692,9626=>692,9627=>692,9628=>692,
9629=>692,9630=>692,9631=>692,9632=>850,9633=>850,9634=>850,9635=>850,9636=>850,9637=>850,9638=>850,
9639=>850,9640=>850,9641=>850,9642=>610,9643=>610,9644=>850,9645=>850,9646=>495,9647=>495,9648=>692,
9649=>692,9650=>692,9651=>692,9652=>452,9653=>452,9654=>692,9655=>692,9656=>452,9657=>452,9658=>692,
9659=>692,9660=>692,9661=>692,9662=>452,9663=>452,9664=>692,9665=>692,9666=>452,9667=>452,9668=>692,
9669=>692,9670=>692,9671=>692,9672=>692,9673=>785,9674=>444,9675=>785,9676=>785,9677=>785,9678=>785,
9679=>785,9680=>785,9681=>785,9682=>785,9683=>785,9684=>785,9685=>785,9686=>474,9687=>474,9688=>756,
9689=>873,9690=>873,9691=>873,9692=>348,9693=>348,9694=>348,9695=>348,9696=>692,9697=>692,9698=>692,
9699=>692,9700=>692,9701=>692,9702=>575,9703=>850,9704=>850,9705=>850,9706=>850,9707=>850,9708=>692,
9709=>692,9710=>692,9711=>1007,9712=>850,9713=>850,9714=>850,9715=>850,9716=>785,9717=>785,9718=>785,
9719=>785,9720=>692,9721=>692,9722=>692,9723=>747,9724=>747,9725=>659,9726=>659,9727=>692,9728=>807,
9729=>900,9730=>807,9731=>807,9732=>807,9733=>807,9734=>807,9735=>515,9736=>806,9737=>807,9738=>799,
9739=>799,9740=>604,9741=>911,9742=>1121,9743=>1125,9744=>807,9745=>807,9746=>807,9747=>479,9748=>807,
9749=>807,9750=>807,9751=>807,9752=>807,9753=>807,9754=>807,9755=>807,9756=>807,9757=>548,9758=>807,
9759=>548,9760=>807,9761=>807,9762=>807,9763=>807,9764=>602,9765=>671,9766=>584,9767=>705,9768=>490,
9769=>807,9770=>807,9771=>807,9772=>639,9773=>807,9774=>807,9775=>807,9776=>807,9777=>807,9778=>807,
9779=>807,9780=>807,9781=>807,9782=>807,9783=>807,9784=>807,9785=>807,9786=>807,9787=>807,9788=>807,
9789=>807,9790=>807,9791=>552,9792=>659,9793=>659,9794=>807,9795=>807,9796=>807,9797=>807,9798=>807,
9799=>807,9800=>807,9801=>807,9802=>807,9803=>807,9804=>807,9805=>807,9806=>807,9807=>807,9808=>807,
9809=>807,9810=>807,9811=>807,9812=>807,9813=>807,9814=>807,9815=>807,9816=>807,9817=>807,9818=>807,
9819=>807,9820=>807,9821=>807,9822=>807,9823=>807,9824=>807,9825=>807,9826=>807,9827=>807,9828=>807,
9829=>807,9830=>807,9831=>807,9832=>807,9833=>424,9834=>574,9835=>807,9836=>807,9837=>424,9838=>321,
9839=>435,9840=>673,9841=>689,9842=>807,9843=>807,9844=>807,9845=>807,9846=>807,9847=>807,9848=>807,
9849=>807,9850=>807,9851=>807,9852=>807,9853=>807,9854=>807,9855=>807,9856=>782,9857=>782,9858=>782,
9859=>782,9860=>782,9861=>782,9862=>807,9863=>807,9864=>807,9865=>807,9866=>807,9867=>807,9868=>807,
9869=>807,9870=>807,9871=>807,9872=>807,9873=>807,9874=>807,9875=>807,9876=>807,9877=>487,9878=>807,
9879=>807,9880=>807,9881=>807,9882=>807,9883=>807,9884=>807,9888=>807,9889=>632,9890=>904,9891=>980,
9892=>1057,9893=>813,9894=>754,9895=>754,9896=>754,9897=>754,9898=>754,9899=>754,9900=>754,9901=>754,
9902=>754,9903=>754,9904=>759,9905=>754,9906=>659,9907=>659,9908=>659,9909=>659,9910=>765,9911=>659,
9912=>659,9920=>754,9921=>754,9922=>754,9923=>754,9985=>754,9986=>754,9987=>754,9988=>754,9990=>754,
9991=>754,9992=>754,9993=>754,9996=>754,9997=>754,9998=>754,9999=>754,10000=>754,10001=>754,10002=>754,
10003=>754,10004=>754,10005=>754,10006=>754,10007=>754,10008=>754,10009=>754,10010=>754,10011=>754,10012=>754,
10013=>754,10014=>754,10015=>754,10016=>754,10017=>754,10018=>754,10019=>754,10020=>754,10021=>754,10022=>754,
10023=>754,10025=>754,10026=>754,10027=>754,10028=>754,10029=>754,10030=>754,10031=>754,10032=>754,10033=>754,
10034=>754,10035=>754,10036=>754,10037=>754,10038=>754,10039=>754,10040=>754,10041=>754,10042=>754,10043=>754,
10044=>754,10045=>754,10046=>754,10047=>754,10048=>754,10049=>754,10050=>754,10051=>754,10052=>754,10053=>754,
10054=>754,10055=>754,10056=>754,10057=>754,10058=>754,10059=>754,10061=>807,10063=>807,10064=>807,10065=>807,
10066=>807,10070=>807,10072=>754,10073=>754,10074=>754,10075=>290,10076=>290,10077=>484,10078=>484,10081=>754,
10082=>754,10083=>754,10084=>754,10085=>754,10086=>754,10087=>754,10088=>754,10089=>754,10090=>754,10091=>754,
10092=>754,10093=>754,10094=>754,10095=>754,10096=>754,10097=>754,10098=>754,10099=>754,10100=>754,10101=>754,
10102=>762,10103=>762,10104=>762,10105=>762,10106=>762,10107=>762,10108=>762,10109=>762,10110=>762,10111=>762,
10112=>754,10113=>754,10114=>754,10115=>754,10116=>754,10117=>754,10118=>754,10119=>754,10120=>754,10121=>754,
10122=>754,10123=>754,10124=>754,10125=>754,10126=>754,10127=>754,10128=>754,10129=>754,10130=>754,10131=>754,
10132=>754,10136=>754,10137=>754,10138=>754,10139=>754,10140=>754,10141=>754,10142=>754,10143=>754,10144=>754,
10145=>754,10146=>754,10147=>754,10148=>754,10149=>754,10150=>754,10151=>754,10152=>754,10153=>754,10154=>754,
10155=>754,10156=>754,10157=>754,10158=>754,10159=>754,10161=>754,10162=>754,10163=>754,10164=>754,10165=>754,
10166=>754,10167=>754,10168=>754,10169=>754,10170=>754,10171=>754,10172=>754,10173=>754,10174=>754,10181=>411,
10182=>411,10208=>444,10214=>438,10215=>438,10216=>411,10217=>411,10218=>648,10219=>648,10224=>754,10225=>754,
10226=>754,10227=>754,10228=>1042,10229=>1290,10230=>1290,10231=>1290,10232=>1290,10233=>1290,10234=>1290,10235=>1290,
10236=>1290,10237=>1290,10238=>1290,10239=>1290,10240=>703,10241=>703,10242=>703,10243=>703,10244=>703,10245=>703,
10246=>703,10247=>703,10248=>703,10249=>703,10250=>703,10251=>703,10252=>703,10253=>703,10254=>703,10255=>703,
10256=>703,10257=>703,10258=>703,10259=>703,10260=>703,10261=>703,10262=>703,10263=>703,10264=>703,10265=>703,
10266=>703,10267=>703,10268=>703,10269=>703,10270=>703,10271=>703,10272=>703,10273=>703,10274=>703,10275=>703,
10276=>703,10277=>703,10278=>703,10279=>703,10280=>703,10281=>703,10282=>703,10283=>703,10284=>703,10285=>703,
10286=>703,10287=>703,10288=>703,10289=>703,10290=>703,10291=>703,10292=>703,10293=>703,10294=>703,10295=>703,
10296=>703,10297=>703,10298=>703,10299=>703,10300=>703,10301=>703,10302=>703,10303=>703,10304=>703,10305=>703,
10306=>703,10307=>703,10308=>703,10309=>703,10310=>703,10311=>703,10312=>703,10313=>703,10314=>703,10315=>703,
10316=>703,10317=>703,10318=>703,10319=>703,10320=>703,10321=>703,10322=>703,10323=>703,10324=>703,10325=>703,
10326=>703,10327=>703,10328=>703,10329=>703,10330=>703,10331=>703,10332=>703,10333=>703,10334=>703,10335=>703,
10336=>703,10337=>703,10338=>703,10339=>703,10340=>703,10341=>703,10342=>703,10343=>703,10344=>703,10345=>703,
10346=>703,10347=>703,10348=>703,10349=>703,10350=>703,10351=>703,10352=>703,10353=>703,10354=>703,10355=>703,
10356=>703,10357=>703,10358=>703,10359=>703,10360=>703,10361=>703,10362=>703,10363=>703,10364=>703,10365=>703,
10366=>703,10367=>703,10368=>703,10369=>703,10370=>703,10371=>703,10372=>703,10373=>703,10374=>703,10375=>703,
10376=>703,10377=>703,10378=>703,10379=>703,10380=>703,10381=>703,10382=>703,10383=>703,10384=>703,10385=>703,
10386=>703,10387=>703,10388=>703,10389=>703,10390=>703,10391=>703,10392=>703,10393=>703,10394=>703,10395=>703,
10396=>703,10397=>703,10398=>703,10399=>703,10400=>703,10401=>703,10402=>703,10403=>703,10404=>703,10405=>703,
10406=>703,10407=>703,10408=>703,10409=>703,10410=>703,10411=>703,10412=>703,10413=>703,10414=>703,10415=>703,
10416=>703,10417=>703,10418=>703,10419=>703,10420=>703,10421=>703,10422=>703,10423=>703,10424=>703,10425=>703,
10426=>703,10427=>703,10428=>703,10429=>703,10430=>703,10431=>703,10432=>703,10433=>703,10434=>703,10435=>703,
10436=>703,10437=>703,10438=>703,10439=>703,10440=>703,10441=>703,10442=>703,10443=>703,10444=>703,10445=>703,
10446=>703,10447=>703,10448=>703,10449=>703,10450=>703,10451=>703,10452=>703,10453=>703,10454=>703,10455=>703,
10456=>703,10457=>703,10458=>703,10459=>703,10460=>703,10461=>703,10462=>703,10463=>703,10464=>703,10465=>703,
10466=>703,10467=>703,10468=>703,10469=>703,10470=>703,10471=>703,10472=>703,10473=>703,10474=>703,10475=>703,
10476=>703,10477=>703,10478=>703,10479=>703,10480=>703,10481=>703,10482=>703,10483=>703,10484=>703,10485=>703,
10486=>703,10487=>703,10488=>703,10489=>703,10490=>703,10491=>703,10492=>703,10493=>703,10494=>703,10495=>703,
10502=>754,10503=>754,10506=>754,10507=>754,10560=>754,10561=>754,10627=>678,10628=>678,10702=>754,10703=>941,
10704=>941,10705=>900,10706=>900,10707=>900,10708=>900,10709=>900,10731=>444,10746=>754,10747=>754,10752=>900,
10753=>900,10754=>900,10764=>1495,10765=>506,10766=>506,10767=>506,10768=>506,10769=>506,10770=>506,10771=>506,
10772=>506,10773=>506,10774=>506,10775=>506,10776=>506,10777=>506,10778=>506,10779=>506,10780=>506,10799=>754,
10877=>754,10878=>754,10879=>754,10880=>754,10881=>754,10882=>754,10883=>754,10884=>754,10885=>754,10886=>754,
10887=>754,10888=>754,10889=>754,10890=>754,10891=>754,10892=>754,10893=>754,10894=>754,10895=>754,10896=>754,
10897=>754,10898=>754,10899=>754,10900=>754,10901=>754,10902=>754,10903=>754,10904=>754,10905=>754,10906=>754,
10907=>754,10908=>754,10909=>754,10910=>754,10911=>754,10912=>754,10926=>754,10927=>754,10928=>754,10929=>754,
10930=>754,10931=>754,10932=>754,10933=>754,10934=>754,10935=>754,10936=>754,10937=>754,10938=>754,11001=>754,
11002=>754,11008=>754,11009=>754,11010=>754,11011=>754,11012=>754,11013=>754,11014=>754,11015=>754,11016=>754,
11017=>754,11018=>754,11019=>754,11020=>754,11021=>754,11022=>754,11023=>754,11024=>754,11025=>754,11026=>850,
11027=>850,11028=>850,11029=>850,11030=>692,11031=>692,11032=>692,11033=>692,11034=>850,11039=>782,11040=>782,
11041=>786,11042=>786,11043=>786,11044=>1007,11091=>782,11092=>782,11360=>573,11361=>324,11362=>573,11363=>659,
11364=>693,11365=>607,11366=>430,11367=>860,11368=>641,11369=>697,11370=>598,11371=>652,11372=>523,11373=>774,
11374=>896,11375=>696,11376=>774,11377=>700,11378=>1099,11379=>950,11380=>586,11381=>628,11382=>508,11383=>704,
11385=>484,11386=>618,11387=>502,11388=>197,11389=>438,11390=>648,11391=>652,11800=>527,11810=>411,11811=>411,
11812=>411,11813=>411,11822=>522,19904=>807,19905=>807,19906=>807,19907=>807,19908=>807,19909=>807,19910=>807,
19911=>807,19912=>807,19913=>807,19914=>807,19915=>807,19916=>807,19917=>807,19918=>807,19919=>807,19920=>807,
19921=>807,19922=>807,19923=>807,19924=>807,19925=>807,19926=>807,19927=>807,19928=>807,19929=>807,19930=>807,
19931=>807,19932=>807,19933=>807,19934=>807,19935=>807,19936=>807,19937=>807,19938=>807,19939=>807,19940=>807,
19941=>807,19942=>807,19943=>807,19944=>807,19945=>807,19946=>807,19947=>807,19948=>807,19949=>807,19950=>807,
19951=>807,19952=>807,19953=>807,19954=>807,19955=>807,19956=>807,19957=>807,19958=>807,19959=>807,19960=>807,
19961=>807,19962=>807,19963=>807,19964=>807,19965=>807,19966=>807,19967=>807,42564=>648,42565=>536,42566=>392,
42567=>396,42572=>1265,42573=>1055,42576=>1110,42577=>924,42580=>1056,42581=>875,42582=>990,42583=>872,42594=>990,
42595=>846,42596=>986,42597=>823,42598=>1134,42599=>896,42600=>765,42601=>618,42602=>933,42603=>781,42604=>1266,
42605=>995,42606=>865,42634=>849,42635=>673,42636=>614,42637=>521,42644=>727,42645=>641,42760=>450,42761=>450,
42762=>450,42763=>450,42764=>450,42765=>450,42766=>450,42767=>450,42768=>450,42769=>450,42770=>450,42771=>450,
42772=>450,42773=>450,42774=>450,42779=>360,42780=>360,42781=>258,42782=>258,42783=>258,42786=>399,42787=>351,
42788=>486,42789=>486,42790=>753,42791=>641,42792=>928,42793=>771,42794=>626,42795=>501,42800=>502,42801=>536,
42802=>1214,42803=>946,42804=>1156,42805=>958,42806=>1120,42807=>947,42808=>971,42809=>830,42810=>971,42811=>830,
42812=>932,42813=>830,42814=>628,42815=>494,42822=>765,42823=>488,42824=>614,42825=>478,42826=>826,42827=>732,
42830=>1266,42831=>995,42832=>659,42833=>644,42834=>853,42835=>843,42838=>765,42839=>644,42852=>664,42853=>644,
42854=>664,42855=>644,42880=>573,42881=>308,42882=>753,42883=>641,42889=>360,42890=>356,42891=>410,42892=>275,
42893=>727,43003=>615,43004=>659,43005=>896,43006=>334,43007=>1192,61184=>194,61185=>218,61186=>240,61187=>249,
61188=>254,61189=>218,61190=>194,61191=>218,61192=>240,61193=>249,61194=>240,61195=>218,61196=>194,61197=>218,
61198=>240,61199=>249,61200=>240,61201=>218,61202=>194,61203=>218,61204=>254,61205=>249,61206=>240,61207=>218,
61208=>194,61209=>254,62917=>618,64256=>749,64257=>708,64258=>708,64259=>1024,64260=>1024,64261=>727,64262=>917,
64275=>1249,64276=>1245,64277=>1240,64278=>1245,64279=>1542,64285=>308,64286=>0,64287=>597,64288=>647,64289=>867,
64290=>801,64291=>889,64292=>867,64293=>844,64294=>889,64295=>889,64296=>878,64297=>754,64298=>854,64299=>854,
64300=>854,64301=>854,64302=>676,64303=>676,64304=>676,64305=>605,64306=>483,64307=>589,64308=>641,64309=>308,
64310=>442,64312=>651,64313=>420,64314=>584,64315=>584,64316=>611,64318=>698,64320=>447,64321=>696,64323=>646,
64324=>618,64326=>676,64327=>656,64328=>584,64329=>854,64330=>676,64331=>308,64332=>605,64333=>584,64334=>618,
64335=>585,65024=>0,65025=>0,65026=>0,65027=>0,65028=>0,65029=>0,65030=>0,65031=>0,65032=>0,
65033=>0,65034=>0,65035=>0,65036=>0,65037=>0,65038=>0,65039=>0,65056=>0,65057=>0,65058=>0,
65059=>0,65529=>0,65530=>0,65531=>0,65532=>0,65533=>1002);
$enc='';
$diff='';
$file='dejavusanscondensedbi.z';
$ctg='dejavusanscondensedbi.ctg.z';
$originalsize=543704;
// --- EOF --- | himan5050/hpbc | tcpdf/fonts/dejavusanscondensedbi.php | PHP | gpl-2.0 | 45,561 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "mutationofjb/widgets/imagewidget.h"
#include "graphics/managed_surface.h"
namespace MutationOfJB {
ImageWidget::ImageWidget(GuiScreen &gui, const Common::Rect &area, const Graphics::Surface &image) :
Widget(gui, area),
_image(image) {}
void ImageWidget::draw(Graphics::ManagedSurface &surface) {
surface.blitFrom(_image, Common::Point(_area.left, _area.top));
}
}
| alexbevi/scummvm | engines/mutationofjb/widgets/imagewidget.cpp | C++ | gpl-2.0 | 1,331 |
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ObjectMgr.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "zulgurub.h"
enum Yells
{
SAY_AGGRO = 0,
EMOTE_ZANZIL_ZOMBIES = 1, // ID - 96319 Zanzil's Resurrection Elixir
SAY_ZANZIL_ZOMBIES = 2, // ID - 96319 Zanzil's Resurrection Elixir
EMOTE_ZANZIL_GRAVEYARD_GAS = 3, // ID - 96338 Zanzil's Graveyard Gas
SAY_ZANZIL_GRAVEYARD_GAS = 4, // ID - 96338 Zanzil's Graveyard Gas
EMOTE_ZANZIL_BERSEKER = 5, // ID - 96316 Zanzil's Resurrection Elixir
SAY_ZANZIL_BERSEKER = 6, // ID - 96316 Zanzil's Resurrection Elixir
SAY_PLAYER_KILL = 7,
SAY_DEATH = 8
};
enum Spells
{
};
enum Events
{
};
class boss_zanzil : public CreatureScript
{
public:
boss_zanzil() : CreatureScript("boss_zanzil") { }
struct boss_zanzilAI : public BossAI
{
boss_zanzilAI(Creature* creature) : BossAI(creature, DATA_ZANZIL) { }
void Reset()
{
_Reset();
}
void EnterCombat(Unit* /*who*/)
{
_EnterCombat();
Talk(SAY_AGGRO);
}
void JustDied(Unit* /*killer*/)
{
_JustDied();
Talk(SAY_DEATH);
}
void KilledUnit(Unit* victim)
{
if (victim->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_PLAYER_KILL);
}
void UpdateAI(uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
/*
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
default:
break;
}
}
*/
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return GetZulGurubAI<boss_zanzilAI>(creature);
}
};
void AddSC_boss_zanzil()
{
new boss_zanzil();
}
| heros/multi_realm_cell | src/src_cata/server/scripts/EasternKingdoms/ZulGurub/boss_zanzil.cpp | C++ | gpl-2.0 | 3,051 |
<?php
/**
* @package Joomla.Site
* @subpackage Layout
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_BASE') or die;
extract($displayData);
/**
* Layout variables
* ------------------
* @param string $selector Unique DOM identifier for the modal. CSS id without #
* @param array $params Modal parameters. Default supported parameters:
* - title string The modal title
* - backdrop mixed A boolean select if a modal-backdrop element should be included (default = true)
* The string 'static' includes a backdrop which doesn't close the modal on click.
* - keyboard boolean Closes the modal when escape key is pressed (default = true)
* - closeButton boolean Display modal close button (default = true)
* - animation boolean Fade in from the top of the page (default = true)
* - footer string Optional markup for the modal footer
* - url string URL of a resource to be inserted as an <iframe> inside the modal body
* - height string height of the <iframe> containing the remote resource
* - width string width of the <iframe> containing the remote resource
* - bodyHeight int Optional height of the modal body in viewport units (vh)
* - modalWidth int Optional width of the modal in viewport units (vh)
* @param string $body Markup for the modal body. Appended after the <iframe> if the URL option is set
*
*/
$bodyClass = 'modal-body';
$bodyHeight = isset($params['bodyHeight']) ? round((int) $params['bodyHeight'], -1) : '';
if ($bodyHeight && $bodyHeight >= 20 && $bodyHeight < 90)
{
$bodyClass .= ' jviewport-height' . $bodyHeight;
}
?>
<div class="<?php echo $bodyClass; ?>">
<?php echo $body; ?>
</div>
| ciar4n/joomla-cms | layouts/joomla/modal/body.php | PHP | gpl-2.0 | 2,238 |
<?php
/*
* LibreNMS
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*
* @package LibreNMS
* @subpackage webui
* @link http://librenms.org
* @copyright 2017 LibreNMS
* @author LibreNMS Contributors
*/
$graph_type = 'sensor_temperature';
$unit = '°C';
$class = 'temperature';
require 'pages/health/sensors.inc.php';
| pheinrichs/librenms | html/pages/health/temperature.inc.php | PHP | gpl-3.0 | 648 |
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import os
from powerline.bindings.vim import buffer_name
def commandt(matcher_info):
name = buffer_name(matcher_info)
return name and os.path.basename(name) == b'GoToFile'
| gorczynski/dotfiles | vim/bundle/powerline/powerline/matchers/vim/plugin/commandt.py | Python | gpl-3.0 | 293 |
/*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* LICENSE: See LICENSE in the top level directory
* FILE: core/CCore.cpp
* PURPOSE: Base core class
* DEVELOPERS: Cecill Etheredge <ijsf@gmx.net>
* Chris McArthur <>
* Christian Myhre Lundheim <>
* Derek Abdine <>
* Ed Lyons <eai@opencoding.net>
* Jax <>
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
#include <game/CGame.h>
#include <Accctrl.h>
#include <Aclapi.h>
#include "Userenv.h" // This will enable SharedUtil::ExpandEnvString
#define ALLOC_STATS_MODULE_NAME "core"
#include "SharedUtil.hpp"
#include <clocale>
#include "CTimingCheckpoints.hpp"
#include "CModelCacheManager.h"
using SharedUtil::CalcMTASAPath;
using namespace std;
static float fTest = 1;
extern CCore* g_pCore;
bool g_bBoundsChecker = false;
BOOL AC_RestrictAccess( VOID )
{
EXPLICIT_ACCESS NewAccess;
PACL pTempDacl;
HANDLE hProcess;
DWORD dwFlags;
DWORD dwErr;
///////////////////////////////////////////////
// Get the HANDLE to the current process.
hProcess = GetCurrentProcess();
///////////////////////////////////////////////
// Setup which accesses we want to deny.
dwFlags = GENERIC_WRITE|PROCESS_ALL_ACCESS|WRITE_DAC|DELETE|WRITE_OWNER|READ_CONTROL;
///////////////////////////////////////////////
// Build our EXPLICIT_ACCESS structure.
BuildExplicitAccessWithName( &NewAccess, "CURRENT_USER", dwFlags, DENY_ACCESS, NO_INHERITANCE );
///////////////////////////////////////////////
// Create our Discretionary Access Control List.
if ( ERROR_SUCCESS != (dwErr = SetEntriesInAcl( 1, &NewAccess, NULL, &pTempDacl )) )
{
#ifdef DEBUG
// pConsole->Con_Printf("Error at SetEntriesInAcl(): %i", dwErr);
#endif
return FALSE;
}
////////////////////////////////////////////////
// Set the new DACL to our current process.
if ( ERROR_SUCCESS != (dwErr = SetSecurityInfo( hProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pTempDacl, NULL )) )
{
#ifdef DEBUG
// pConsole->Con_Printf("Error at SetSecurityInfo(): %i", dwErr);
#endif
return FALSE;
}
////////////////////////////////////////////////
// Free the DACL (see msdn on SetEntriesInAcl)
LocalFree( pTempDacl );
CloseHandle( hProcess );
return TRUE;
}
template<> CCore * CSingleton< CCore >::m_pSingleton = NULL;
CCore::CCore ( void )
{
// Initialize the global pointer
g_pCore = this;
#if !defined(MTA_DEBUG) && !defined(MTA_ALLOW_DEBUG)
AC_RestrictAccess ();
#endif
m_pConfigFile = NULL;
// Set our locale to the C locale, except for character handling which is the system's default
std::setlocale(LC_ALL,"C");
std::setlocale(LC_CTYPE,"");
// check LC_COLLATE is the old-time raw ASCII sort order
assert ( strcoll( "a", "B" ) > 0 );
// Parse the command line
const char* pszNoValOptions[] =
{
"window",
NULL
};
ParseCommandLine ( m_CommandLineOptions, m_szCommandLineArgs, pszNoValOptions );
// Load our settings and localization as early as possible
CreateXML ( );
g_pLocalization = new CLocalization;
// Create a logger instance.
m_pConsoleLogger = new CConsoleLogger ( );
// Create interaction objects.
m_pCommands = new CCommands;
m_pConnectManager = new CConnectManager;
// Create the GUI manager and the graphics lib wrapper
m_pLocalGUI = new CLocalGUI;
m_pGraphics = new CGraphics ( m_pLocalGUI );
g_pGraphics = m_pGraphics;
m_pGUI = NULL;
m_pWebCore = NULL;
// Create the mod manager
m_pModManager = new CModManager;
CCrashDumpWriter::SetHandlers();
m_pfnMessageProcessor = NULL;
m_pMessageBox = NULL;
m_bFirstFrame = true;
m_bIsOfflineMod = false;
m_bQuitOnPulse = false;
m_bDestroyMessageBox = false;
m_bCursorToggleControls = false;
m_bLastFocused = true;
m_bWaitToSetNick = false;
m_DiagnosticDebug = EDiagnosticDebug::NONE;
// Create our Direct3DData handler.
m_pDirect3DData = new CDirect3DData;
WriteDebugEvent ( "CCore::CCore" );
m_pKeyBinds = new CKeyBinds ( this );
m_pMouseControl = new CMouseControl();
// Create our hook objects.
//m_pFileSystemHook = new CFileSystemHook ( );
m_pDirect3DHookManager = new CDirect3DHookManager ( );
m_pDirectInputHookManager = new CDirectInputHookManager ( );
m_pMessageLoopHook = new CMessageLoopHook ( );
m_pSetCursorPosHook = new CSetCursorPosHook ( );
m_pTCPManager = new CTCPManager ( );
// Register internal commands.
RegisterCommands ( );
// Setup our hooks.
ApplyHooks ( );
// Reset the screenshot flag
bScreenShot = false;
//Create our current server and set the update time to zero
m_pCurrentServer = new CXfireServerInfo();
m_tXfireUpdate = 0;
// No initial fps limit
m_bDoneFrameRateLimit = false;
m_uiFrameRateLimit = 0;
m_uiServerFrameRateLimit = 0;
m_uiNewNickWaitFrames = 0;
m_iUnminimizeFrameCounter = 0;
m_bDidRecreateRenderTargets = false;
m_fMinStreamingMemory = 0;
m_fMaxStreamingMemory = 0;
m_bGettingIdleCallsFromMultiplayer = false;
m_bWindowsTimerEnabled = false;
}
CCore::~CCore ( void )
{
WriteDebugEvent ( "CCore::~CCore" );
// Delete the mod manager
delete m_pModManager;
SAFE_DELETE ( m_pMessageBox );
// Destroy early subsystems
m_bModulesLoaded = false;
DestroyNetwork ();
DestroyMultiplayer ();
DestroyGame ();
// Remove global events
g_pCore->m_pGUI->ClearInputHandlers( INPUT_CORE );
// Remove input hook
CMessageLoopHook::GetSingleton ( ).RemoveHook ( );
// Store core variables to cvars
CVARS_SET ( "console_pos", m_pLocalGUI->GetConsole ()->GetPosition () );
CVARS_SET ( "console_size", m_pLocalGUI->GetConsole ()->GetSize () );
// Delete interaction objects.
delete m_pCommands;
delete m_pConnectManager;
delete m_pDirect3DData;
// Delete hooks.
delete m_pSetCursorPosHook;
//delete m_pFileSystemHook;
delete m_pDirect3DHookManager;
delete m_pDirectInputHookManager;
delete m_pTCPManager;
// Delete the GUI manager
delete m_pLocalGUI;
delete m_pGraphics;
// Delete the web
delete m_pWebCore;
// Delete lazy subsystems
DestroyGUI ();
DestroyXML ();
// Delete keybinds
delete m_pKeyBinds;
// Delete Mouse Control
delete m_pMouseControl;
// Delete the logger
delete m_pConsoleLogger;
//Delete the Current Server
delete m_pCurrentServer;
// Delete last so calls to GetHookedWindowHandle do not crash
delete m_pMessageLoopHook;
}
eCoreVersion CCore::GetVersion ( void )
{
return MTACORE_20;
}
CConsoleInterface* CCore::GetConsole ( void )
{
return m_pLocalGUI->GetConsole ();
}
CCommandsInterface* CCore::GetCommands ( void )
{
return m_pCommands;
}
CGame* CCore::GetGame ( void )
{
return m_pGame;
}
CGraphicsInterface* CCore::GetGraphics ( void )
{
return m_pGraphics;
}
CModManagerInterface* CCore::GetModManager ( void )
{
return m_pModManager;
}
CMultiplayer* CCore::GetMultiplayer ( void )
{
return m_pMultiplayer;
}
CXMLNode* CCore::GetConfig ( void )
{
if ( !m_pConfigFile )
return NULL;
CXMLNode* pRoot = m_pConfigFile->GetRootNode ();
if ( !pRoot )
pRoot = m_pConfigFile->CreateRootNode ( CONFIG_ROOT );
return pRoot;
}
CGUI* CCore::GetGUI ( void )
{
return m_pGUI;
}
CNet* CCore::GetNetwork ( void )
{
return m_pNet;
}
CKeyBindsInterface* CCore::GetKeyBinds ( void )
{
return m_pKeyBinds;
}
CLocalGUI* CCore::GetLocalGUI ( void )
{
return m_pLocalGUI;
}
void CCore::SaveConfig ( void )
{
if ( m_pConfigFile )
{
CXMLNode* pBindsNode = GetConfig ()->FindSubNode ( CONFIG_NODE_KEYBINDS );
if ( !pBindsNode )
pBindsNode = GetConfig ()->CreateSubNode ( CONFIG_NODE_KEYBINDS );
m_pKeyBinds->SaveToXML ( pBindsNode );
GetVersionUpdater ()->SaveConfigToXML ();
GetServerCache ()->SaveServerCache ();
m_pConfigFile->Write ();
}
}
void CCore::ChatEcho ( const char* szText, bool bColorCoded )
{
CChat* pChat = m_pLocalGUI->GetChat ();
if ( pChat )
{
CColor color ( 255, 255, 255, 255 );
pChat->SetTextColor ( color );
}
// Echo it to the console and chat
m_pLocalGUI->EchoChat ( szText, bColorCoded );
if ( bColorCoded )
{
m_pLocalGUI->EchoConsole ( RemoveColorCodes( szText ) );
}
else
m_pLocalGUI->EchoConsole ( szText );
}
void CCore::DebugEcho ( const char* szText )
{
CDebugView * pDebugView = m_pLocalGUI->GetDebugView ();
if ( pDebugView )
{
CColor color ( 255, 255, 255, 255 );
pDebugView->SetTextColor ( color );
}
m_pLocalGUI->EchoDebug ( szText );
}
void CCore::DebugPrintf ( const char* szFormat, ... )
{
// Convert it to a string buffer
char szBuffer [1024];
va_list ap;
va_start ( ap, szFormat );
VSNPRINTF ( szBuffer, 1024, szFormat, ap );
va_end ( ap );
DebugEcho ( szBuffer );
}
void CCore::SetDebugVisible ( bool bVisible )
{
if ( m_pLocalGUI )
{
m_pLocalGUI->SetDebugViewVisible ( bVisible );
}
}
bool CCore::IsDebugVisible ( void )
{
if ( m_pLocalGUI )
return m_pLocalGUI->IsDebugViewVisible ();
else
return false;
}
void CCore::DebugEchoColor ( const char* szText, unsigned char R, unsigned char G, unsigned char B )
{
// Set the color
CDebugView * pDebugView = m_pLocalGUI->GetDebugView ();
if ( pDebugView )
{
CColor color ( R, G, B, 255 );
pDebugView->SetTextColor ( color );
}
m_pLocalGUI->EchoDebug ( szText );
}
void CCore::DebugPrintfColor ( const char* szFormat, unsigned char R, unsigned char G, unsigned char B, ... )
{
// Set the color
if ( szFormat )
{
// Convert it to a string buffer
char szBuffer [1024];
va_list ap;
va_start ( ap, B );
VSNPRINTF ( szBuffer, 1024, szFormat, ap );
va_end ( ap );
// Echo it to the console and chat
DebugEchoColor ( szBuffer, R, G, B );
}
}
void CCore::DebugClear ( void )
{
CDebugView * pDebugView = m_pLocalGUI->GetDebugView ();
if ( pDebugView )
{
pDebugView->Clear();
}
}
void CCore::ChatEchoColor ( const char* szText, unsigned char R, unsigned char G, unsigned char B, bool bColorCoded )
{
// Set the color
CChat* pChat = m_pLocalGUI->GetChat ();
if ( pChat )
{
CColor color ( R, G, B, 255 );
pChat->SetTextColor ( color );
}
// Echo it to the console and chat
m_pLocalGUI->EchoChat ( szText, bColorCoded );
if ( bColorCoded )
{
m_pLocalGUI->EchoConsole ( RemoveColorCodes( szText ) );
}
else
m_pLocalGUI->EchoConsole ( szText );
}
void CCore::ChatPrintf ( const char* szFormat, bool bColorCoded, ... )
{
// Convert it to a string buffer
char szBuffer [1024];
va_list ap;
va_start ( ap, bColorCoded );
VSNPRINTF ( szBuffer, 1024, szFormat, ap );
va_end ( ap );
// Echo it to the console and chat
ChatEcho ( szBuffer, bColorCoded );
}
void CCore::ChatPrintfColor ( const char* szFormat, bool bColorCoded, unsigned char R, unsigned char G, unsigned char B, ... )
{
// Set the color
if ( szFormat )
{
if ( m_pLocalGUI )
{
// Convert it to a string buffer
char szBuffer [1024];
va_list ap;
va_start ( ap, B );
VSNPRINTF ( szBuffer, 1024, szFormat, ap );
va_end ( ap );
// Echo it to the console and chat
ChatEchoColor ( szBuffer, R, G, B, bColorCoded );
}
}
}
void CCore::SetChatVisible ( bool bVisible )
{
if ( m_pLocalGUI )
{
m_pLocalGUI->SetChatBoxVisible ( bVisible );
}
}
bool CCore::IsChatVisible ( void )
{
if ( m_pLocalGUI )
{
return m_pLocalGUI->IsChatBoxVisible ();
}
return false;
}
void CCore::TakeScreenShot ( void )
{
bScreenShot = true;
}
void CCore::EnableChatInput ( char* szCommand, DWORD dwColor )
{
if ( m_pLocalGUI )
{
if ( m_pGame->GetSystemState () == 9 /* GS_PLAYING_GAME */ &&
m_pModManager->GetCurrentMod () != NULL &&
!IsOfflineMod () &&
!m_pGame->IsAtMenu () &&
!m_pLocalGUI->GetMainMenu ()->IsVisible () &&
!m_pLocalGUI->GetConsole ()->IsVisible () &&
!m_pLocalGUI->IsChatBoxInputEnabled () )
{
CChat* pChat = m_pLocalGUI->GetChat ();
pChat->SetCommand ( szCommand );
m_pLocalGUI->SetChatBoxInputEnabled ( true );
}
}
}
bool CCore::IsChatInputEnabled ( void )
{
if ( m_pLocalGUI )
{
return ( m_pLocalGUI->IsChatBoxInputEnabled () );
}
return false;
}
bool CCore::IsSettingsVisible ( void )
{
if ( m_pLocalGUI )
{
return ( m_pLocalGUI->GetMainMenu ()->GetSettingsWindow ()->IsVisible () );
}
return false;
}
bool CCore::IsMenuVisible ( void )
{
if ( m_pLocalGUI )
{
return ( m_pLocalGUI->GetMainMenu ()->IsVisible () );
}
return false;
}
bool CCore::IsCursorForcedVisible ( void )
{
if ( m_pLocalGUI )
{
return ( m_pLocalGUI->IsCursorForcedVisible () );
}
return false;
}
void CCore::ApplyConsoleSettings ( void )
{
CVector2D vec;
CConsole * pConsole = m_pLocalGUI->GetConsole ();
CVARS_GET ( "console_pos", vec );
pConsole->SetPosition ( vec );
CVARS_GET ( "console_size", vec );
pConsole->SetSize ( vec );
}
void CCore::ApplyGameSettings ( void )
{
bool bval;
int iVal;
CControllerConfigManager * pController = m_pGame->GetControllerConfigManager ();
CVARS_GET ( "invert_mouse", bval ); pController->SetMouseInverted ( bval );
CVARS_GET ( "fly_with_mouse", bval ); pController->SetFlyWithMouse ( bval );
CVARS_GET ( "steer_with_mouse", bval ); pController->SetSteerWithMouse ( bval );
CVARS_GET ( "classic_controls", bval ); pController->SetClassicControls ( bval );
CVARS_GET ( "volumetric_shadows", bval ); m_pGame->GetSettings ()->SetVolumetricShadowsEnabled ( bval );
CVARS_GET ( "aspect_ratio", iVal ); m_pGame->GetSettings ()->SetAspectRatio ( (eAspectRatio)iVal, CVARS_GET_VALUE < bool > ( "hud_match_aspect_ratio" ) );
CVARS_GET ( "grass", bval ); m_pGame->GetSettings ()->SetGrassEnabled ( bval );
CVARS_GET ( "heat_haze", bval ); m_pMultiplayer->SetHeatHazeEnabled ( bval );
CVARS_GET ( "fast_clothes_loading", iVal ); m_pMultiplayer->SetFastClothesLoading ( (CMultiplayer::EFastClothesLoading)iVal );
CVARS_GET ( "tyre_smoke_enabled", bval ); m_pMultiplayer->SetTyreSmokeEnabled ( bval );
pController->SetVerticalAimSensitivityRawValue( CVARS_GET_VALUE < float > ( "vertical_aim_sensitivity" ) );
}
void CCore::ApplyCommunityState ( void )
{
bool bLoggedIn = g_pCore->GetCommunity()->IsLoggedIn();
if ( bLoggedIn )
m_pLocalGUI->GetMainMenu ()->GetSettingsWindow()->OnLoginStateChange ( true );
}
void CCore::SetConnected ( bool bConnected )
{
m_pLocalGUI->GetMainMenu ( )->SetIsIngame ( bConnected );
UpdateIsWindowMinimized (); // Force update of stuff
}
bool CCore::IsConnected ( void )
{
return m_pLocalGUI->GetMainMenu ( )->GetIsIngame ();
}
bool CCore::Reconnect ( const char* szHost, unsigned short usPort, const char* szPassword, bool bSave, bool bForceInternalHTTPServer )
{
return m_pConnectManager->Reconnect ( szHost, usPort, szPassword, bSave, bForceInternalHTTPServer );
}
bool CCore::ShouldUseInternalHTTPServer( void )
{
return m_pConnectManager->ShouldUseInternalHTTPServer();
}
void CCore::SetOfflineMod ( bool bOffline )
{
m_bIsOfflineMod = bOffline;
}
const char* CCore::GetModInstallRoot ( const char* szModName )
{
m_strModInstallRoot = CalcMTASAPath ( PathJoin ( "mods", szModName ) );
return m_strModInstallRoot;
}
void CCore::ForceCursorVisible ( bool bVisible, bool bToggleControls )
{
m_bCursorToggleControls = bToggleControls;
m_pLocalGUI->ForceCursorVisible ( bVisible );
}
void CCore::SetMessageProcessor ( pfnProcessMessage pfnMessageProcessor )
{
m_pfnMessageProcessor = pfnMessageProcessor;
}
void CCore::ShowMessageBox ( const char* szTitle, const char* szText, unsigned int uiFlags, GUI_CALLBACK * ResponseHandler )
{
if ( m_pMessageBox )
delete m_pMessageBox;
// Create the message box
m_pMessageBox = m_pGUI->CreateMessageBox ( szTitle, szText, uiFlags );
if ( ResponseHandler ) m_pMessageBox->SetClickHandler ( *ResponseHandler );
// Make sure it doesn't auto-destroy, or we'll crash if the msgbox had buttons and the user clicks OK
m_pMessageBox->SetAutoDestroy ( false );
}
void CCore::RemoveMessageBox ( bool bNextFrame )
{
if ( bNextFrame )
{
m_bDestroyMessageBox = true;
}
else
{
if ( m_pMessageBox )
{
delete m_pMessageBox;
m_pMessageBox = NULL;
}
}
}
//
// Show message box with possibility of on-line help
//
void CCore::ShowErrorMessageBox( const SString& strTitle, SString strMessage, const SString& strTroubleLink )
{
if ( strTroubleLink.empty() )
{
CCore::GetSingleton ().ShowMessageBox ( strTitle, strMessage, MB_BUTTON_OK | MB_ICON_ERROR );
}
else
{
strMessage += "\n\n";
strMessage += _("Do you want to see some on-line help about this problem ?");
CQuestionBox* pQuestionBox = CCore::GetSingleton ().GetLocalGUI ()->GetMainMenu ()->GetQuestionWindow ();
pQuestionBox->Reset ();
pQuestionBox->SetTitle ( strTitle );
pQuestionBox->SetMessage ( strMessage );
pQuestionBox->SetButton ( 0, _("No") );
pQuestionBox->SetButton ( 1, _("Yes") );
pQuestionBox->SetCallback ( CCore::ErrorMessageBoxCallBack, new SString( strTroubleLink ) );
pQuestionBox->Show ();
}
}
//
// Show message box with possibility of on-line help
// + with net error code appended to message and trouble link
//
void CCore::ShowNetErrorMessageBox( const SString& strTitle, SString strMessage, SString strTroubleLink, bool bLinkRequiresErrorCode )
{
uint uiErrorCode = CCore::GetSingleton ().GetNetwork ()->GetExtendedErrorCode ();
if ( uiErrorCode != 0 )
{
// Do anti-virus check soon
SetApplicationSettingInt( "noav-user-says-skip", 1 );
strMessage += SString ( " \nCode: %08X", uiErrorCode );
if ( !strTroubleLink.empty() )
strTroubleLink += SString ( "&neterrorcode=%08X", uiErrorCode );
}
else
if ( bLinkRequiresErrorCode )
strTroubleLink = ""; // No link if no error code
AddReportLog( 7100, SString( "Core - NetError (%s) (%s)", *strTitle, *strMessage ) );
ShowErrorMessageBox( strTitle, strMessage, strTroubleLink );
}
//
// Callback used in CCore::ShowErrorMessageBox
//
void CCore::ErrorMessageBoxCallBack( void* pData, uint uiButton )
{
CCore::GetSingleton ().GetLocalGUI ()->GetMainMenu ()->GetQuestionWindow ()->Reset ();
SString* pstrTroubleLink = (SString*)pData;
if ( uiButton == 1 )
{
uint uiErrorCode = (uint)pData;
BrowseToSolution ( *pstrTroubleLink, EXIT_GAME_FIRST );
}
delete pstrTroubleLink;
}
//
// Check for disk space problems
// Returns false if low disk space, and dialog is being shown
//
bool CCore::CheckDiskSpace( uint uiResourcesPathMinMB, uint uiDataPathMinMB )
{
SString strDriveWithNoSpace = GetDriveNameWithNotEnoughSpace( uiResourcesPathMinMB, uiDataPathMinMB );
if ( !strDriveWithNoSpace.empty() )
{
SString strMessage( _("MTA:SA cannot continue because drive %s does not have enough space."), *strDriveWithNoSpace );
SString strTroubleLink( SString( "low-disk-space&drive=%s", *strDriveWithNoSpace.Left( 1 ) ) );
g_pCore->ShowErrorMessageBox ( _("Fatal error")+_E("CC43"), strMessage, strTroubleLink );
return false;
}
return true;
}
HWND CCore::GetHookedWindow ( void )
{
return CMessageLoopHook::GetSingleton ().GetHookedWindowHandle ();
}
void CCore::HideMainMenu ( void )
{
m_pLocalGUI->GetMainMenu ()->SetVisible ( false );
}
void CCore::HideQuickConnect ( void )
{
m_pLocalGUI->GetMainMenu ()->GetQuickConnectWindow()->SetVisible( false );
}
void CCore::ShowServerInfo ( unsigned int WindowType )
{
RemoveMessageBox ();
CServerInfo::GetSingletonPtr()->Show( (eWindowType)WindowType );
}
void CCore::ApplyHooks ( )
{
WriteDebugEvent ( "CCore::ApplyHooks" );
// Create our hooks.
m_pDirectInputHookManager->ApplyHook ( );
//m_pDirect3DHookManager->ApplyHook ( );
//m_pFileSystemHook->ApplyHook ( );
m_pSetCursorPosHook->ApplyHook ( );
// Redirect basic files.
//m_pFileSystemHook->RedirectFile ( "main.scm", "../../mta/gtafiles/main.scm" );
}
bool UsingAltD3DSetup()
{
static bool bAltStartup = GetApplicationSettingInt( "nvhacks", "optimus-alt-startup" ) ? true : false;
return bAltStartup;
}
void CCore::ApplyHooks2 ( )
{
WriteDebugEvent ( "CCore::ApplyHooks2" );
// Try this one a little later
if ( !UsingAltD3DSetup() )
m_pDirect3DHookManager->ApplyHook ( );
else
{
// Done a little later to get past the loading time required to decrypt the gta
// executable into memory...
if ( !CCore::GetSingleton ( ).AreModulesLoaded ( ) )
{
CCore::GetSingleton ( ).SetModulesLoaded ( true );
CCore::GetSingleton ( ).CreateNetwork ( );
CCore::GetSingleton ( ).CreateGame ( );
CCore::GetSingleton ( ).CreateMultiplayer ( );
CCore::GetSingleton ( ).CreateXML ( );
CCore::GetSingleton ( ).CreateGUI ( );
}
}
}
void CCore::ApplyHooks3( bool bEnable )
{
if ( bEnable )
CDirect3DHook9::GetSingletonPtr()->ApplyHook();
else
CDirect3DHook9::GetSingletonPtr()->RemoveHook();
}
void CCore::SetCenterCursor ( bool bEnabled )
{
if ( bEnabled )
m_pSetCursorPosHook->EnableSetCursorPos ();
else
m_pSetCursorPosHook->DisableSetCursorPos ();
}
////////////////////////////////////////////////////////////////////////
//
// LoadModule
//
// Attempt to load a module. Returns if successful.
// On failure, displays message box and terminates the current process.
//
////////////////////////////////////////////////////////////////////////
void LoadModule ( CModuleLoader& m_Loader, const SString& strName, const SString& strModuleName )
{
WriteDebugEvent ( "Loading " + strName.ToLower () );
// Ensure DllDirectory has not been changed
SString strDllDirectory = GetSystemDllDirectory();
if ( CalcMTASAPath ( "mta" ).CompareI ( strDllDirectory ) == false )
{
AddReportLog ( 3119, SString ( "DllDirectory wrong: DllDirectory:'%s' Path:'%s'", *strDllDirectory, *CalcMTASAPath ( "mta" ) ) );
SetDllDirectory( CalcMTASAPath ( "mta" ) );
}
// Save current directory (shouldn't change anyway)
SString strSavedCwd = GetSystemCurrentDirectory();
// Load approrpiate compilation-specific library.
#ifdef MTA_DEBUG
SString strModuleFileName = strModuleName + "_d.dll";
#else
SString strModuleFileName = strModuleName + ".dll";
#endif
m_Loader.LoadModule ( CalcMTASAPath ( PathJoin ( "mta", strModuleFileName ) ) );
if ( m_Loader.IsOk () == false )
{
SString strMessage( "Error loading %s module! (%s)", *strName.ToLower (), *m_Loader.GetLastErrorMessage () );
BrowseToSolution ( strModuleName + "-not-loadable", ASK_GO_ONLINE | TERMINATE_PROCESS, strMessage );
}
// Restore current directory
SetCurrentDirectory ( strSavedCwd );
WriteDebugEvent ( strName + " loaded." );
}
////////////////////////////////////////////////////////////////////////
//
// InitModule
//
// Attempt to initialize a loaded module. Returns if successful.
// On failure, displays message box and terminates the current process.
//
////////////////////////////////////////////////////////////////////////
template < class T, class U >
T* InitModule ( CModuleLoader& m_Loader, const SString& strName, const SString& strInitializer, U* pObj )
{
// Save current directory (shouldn't change anyway)
SString strSavedCwd = GetSystemCurrentDirectory();
// Get initializer function from DLL.
typedef T* (*PFNINITIALIZER) ( U* );
PFNINITIALIZER pfnInit = static_cast < PFNINITIALIZER > ( m_Loader.GetFunctionPointer ( strInitializer ) );
if ( pfnInit == NULL )
{
MessageBoxUTF8 ( 0, SString(_("%s module is incorrect!"),*strName), "Error"+_E("CC40"), MB_OK | MB_ICONEXCLAMATION | MB_TOPMOST );
TerminateProcess ( GetCurrentProcess (), 1 );
}
// If we have a valid initializer, call it.
T* pResult = pfnInit ( pObj );
// Restore current directory
SetCurrentDirectory ( strSavedCwd );
WriteDebugEvent ( strName + " initialized." );
return pResult;
}
////////////////////////////////////////////////////////////////////////
//
// CreateModule
//
// Attempt to load and initialize a module. Returns if successful.
// On failure, displays message box and terminates the current process.
//
////////////////////////////////////////////////////////////////////////
template < class T, class U >
T* CreateModule ( CModuleLoader& m_Loader, const SString& strName, const SString& strModuleName, const SString& strInitializer, U* pObj )
{
LoadModule ( m_Loader, strName, strModuleName );
return InitModule < T > ( m_Loader, strName, strInitializer, pObj );
}
void CCore::CreateGame ( )
{
m_pGame = CreateModule < CGame > ( m_GameModule, "Game", "game_sa", "GetGameInterface", this );
if ( m_pGame->GetGameVersion () >= VERSION_11 )
{
BrowseToSolution ( "downgrade", TERMINATE_PROCESS, "Only GTA:SA version 1.0 is supported!\n\nYou are now being redirected to a page where you can patch your version." );
}
}
void CCore::CreateMultiplayer ( )
{
m_pMultiplayer = CreateModule < CMultiplayer > ( m_MultiplayerModule, "Multiplayer", "multiplayer_sa", "InitMultiplayerInterface", this );
if ( m_pMultiplayer )
m_pMultiplayer->SetIdleHandler ( CCore::StaticIdleHandler );
}
void CCore::DeinitGUI ( void )
{
}
void CCore::InitGUI ( IDirect3DDevice9* pDevice )
{
m_pGUI = InitModule < CGUI > ( m_GUIModule, "GUI", "InitGUIInterface", pDevice );
// and set the screenshot path to this default library (screenshots shouldnt really be made outside mods)
std::string strScreenShotPath = CalcMTASAPath ( "screenshots" );
CVARS_SET ( "screenshot_path", strScreenShotPath );
CScreenShot::SetPath ( strScreenShotPath.c_str() );
}
void CCore::CreateGUI ( void )
{
LoadModule ( m_GUIModule, "GUI", "cgui" );
}
void CCore::DestroyGUI ( )
{
WriteDebugEvent ( "CCore::DestroyGUI" );
if ( m_pGUI )
{
m_pGUI = NULL;
}
m_GUIModule.UnloadModule ();
}
void CCore::CreateNetwork ( )
{
m_pNet = CreateModule < CNet > ( m_NetModule, "Network", "netc", "InitNetInterface", this );
// Network module compatibility check
typedef unsigned long (*PFNCHECKCOMPATIBILITY) ( unsigned long, unsigned long* );
PFNCHECKCOMPATIBILITY pfnCheckCompatibility = static_cast< PFNCHECKCOMPATIBILITY > ( m_NetModule.GetFunctionPointer ( "CheckCompatibility" ) );
if ( !pfnCheckCompatibility || !pfnCheckCompatibility ( MTA_DM_CLIENT_NET_MODULE_VERSION, NULL ) )
{
// net.dll doesn't like our version number
ulong ulNetModuleVersion = 0;
pfnCheckCompatibility ( 1, &ulNetModuleVersion );
SString strMessage( "Network module not compatible! (Expected 0x%x, got 0x%x)", MTA_DM_CLIENT_NET_MODULE_VERSION, ulNetModuleVersion );
BrowseToSolution ( "netc-not-compatible", ASK_GO_ONLINE | TERMINATE_PROCESS, strMessage );
}
// Set mta version for report log here
SetApplicationSetting ( "mta-version-ext", SString ( "%d.%d.%d-%d.%05d.%d.%03d"
,MTASA_VERSION_MAJOR
,MTASA_VERSION_MINOR
,MTASA_VERSION_MAINTENANCE
,MTASA_VERSION_TYPE
,MTASA_VERSION_BUILD
,m_pNet->GetNetRev ()
,m_pNet->GetNetRel ()
) );
char szSerial [ 64 ];
m_pNet->GetSerial ( szSerial, sizeof ( szSerial ) );
SetApplicationSetting ( "serial", szSerial );
}
void CCore::CreateXML ( )
{
if ( !m_pXML )
m_pXML = CreateModule < CXML > ( m_XMLModule, "XML", "xmll", "InitXMLInterface", *CalcMTASAPath ( "MTA" ) );
if ( !m_pConfigFile )
{
// Load config XML file
m_pConfigFile = m_pXML->CreateXML ( CalcMTASAPath ( MTA_CONFIG_PATH ) );
if ( !m_pConfigFile ) {
assert ( false );
return;
}
m_pConfigFile->Parse ();
}
// Load the keybinds (loads defaults if the subnode doesn't exist)
if ( m_pKeyBinds )
{
m_pKeyBinds->LoadFromXML ( GetConfig ()->FindSubNode ( CONFIG_NODE_KEYBINDS ) );
m_pKeyBinds->LoadDefaultCommands( false );
}
// Load XML-dependant subsystems
m_ClientVariables.Load ( );
}
void CCore::DestroyGame ( )
{
WriteDebugEvent ( "CCore::DestroyGame" );
if ( m_pGame )
{
m_pGame->Terminate ();
m_pGame = NULL;
}
m_GameModule.UnloadModule();
}
void CCore::DestroyMultiplayer ( )
{
WriteDebugEvent ( "CCore::DestroyMultiplayer" );
if ( m_pMultiplayer )
{
m_pMultiplayer = NULL;
}
m_MultiplayerModule.UnloadModule();
}
void CCore::DestroyXML ( )
{
WriteDebugEvent ( "CCore::DestroyXML" );
// Save and unload configuration
if ( m_pConfigFile ) {
SaveConfig ();
delete m_pConfigFile;
}
if ( m_pXML )
{
m_pXML = NULL;
}
m_XMLModule.UnloadModule();
}
void CCore::DestroyNetwork ( )
{
WriteDebugEvent ( "CCore::DestroyNetwork" );
if ( m_pNet )
{
m_pNet->Shutdown();
m_pNet = NULL;
}
m_NetModule.UnloadModule();
}
void CCore::InitialiseWeb ()
{
// Don't initialise webcore twice
if ( m_pWebCore )
return;
m_pWebCore = new CWebCore;
m_pWebCore->Initialise ();
}
void CCore::UpdateIsWindowMinimized ( void )
{
m_bIsWindowMinimized = IsIconic ( GetHookedWindow () ) ? true : false;
// Update CPU saver for when minimized and not connected
g_pCore->GetMultiplayer ()->SetIsMinimizedAndNotConnected ( m_bIsWindowMinimized && !IsConnected () );
g_pCore->GetMultiplayer ()->SetMirrorsEnabled ( !m_bIsWindowMinimized );
// Enable timer if not connected at least once
bool bEnableTimer = !m_bGettingIdleCallsFromMultiplayer;
if ( m_bWindowsTimerEnabled != bEnableTimer )
{
m_bWindowsTimerEnabled = bEnableTimer;
if ( bEnableTimer )
SetTimer( GetHookedWindow(), IDT_TIMER1, 50, (TIMERPROC) NULL );
else
KillTimer( GetHookedWindow(), IDT_TIMER1 );
}
}
bool CCore::IsWindowMinimized ( void )
{
return m_bIsWindowMinimized;
}
void CCore::DoPreFramePulse ( )
{
TIMING_CHECKPOINT( "+CorePreFrame" );
m_pKeyBinds->DoPreFramePulse ();
// Notify the mod manager
m_pModManager->DoPulsePreFrame ();
m_pLocalGUI->DoPulse ();
CCrashDumpWriter::UpdateCounters();
TIMING_CHECKPOINT( "-CorePreFrame" );
}
void CCore::DoPostFramePulse ( )
{
TIMING_CHECKPOINT( "+CorePostFrame1" );
if ( m_bQuitOnPulse )
Quit ();
if ( m_bDestroyMessageBox )
{
RemoveMessageBox ();
m_bDestroyMessageBox = false;
}
static bool bFirstPulse = true;
if ( bFirstPulse )
{
bFirstPulse = false;
// Validate CVARS
CClientVariables::GetSingleton().ValidateValues ();
// Apply all settings
ApplyConsoleSettings ();
ApplyGameSettings ();
m_pGUI->SelectInputHandlers( INPUT_CORE );
m_Community.Initialize ();
}
if ( m_pGame->GetSystemState () == 5 ) // GS_INIT_ONCE
{
WatchDogCompletedSection ( "L2" ); // gta_sa.set seems ok
WatchDogCompletedSection ( "L3" ); // No hang on startup
}
// This is the first frame in the menu?
if ( m_pGame->GetSystemState () == 7 ) // GS_FRONTEND
{
// Wait 250 frames more than the time it took to get status 7 (fade-out time)
static short WaitForMenu = 0;
// Do crash dump encryption while the credit screen is displayed
if ( WaitForMenu == 0 )
HandleCrashDumpEncryption();
// Cope with early finish
if ( m_pGame->HasCreditScreenFadedOut () )
WaitForMenu = 250;
if ( WaitForMenu >= 250 )
{
if ( m_bFirstFrame )
{
m_bFirstFrame = false;
// Disable vsync while it's all dark
m_pGame->DisableVSync ();
// Parse the command line
// Does it begin with mtasa://?
if ( m_szCommandLineArgs && strnicmp ( m_szCommandLineArgs, "mtasa://", 8 ) == 0 )
{
SString strArguments = GetConnectCommandFromURI ( m_szCommandLineArgs );
// Run the connect command
if ( strArguments.length () > 0 && !m_pCommands->Execute ( strArguments ) )
{
ShowMessageBox ( _("Error")+_E("CC41"), _("Error executing URL"), MB_BUTTON_OK | MB_ICON_ERROR );
}
}
else
{
// We want to load a mod?
const char* szOptionValue;
if ( szOptionValue = GetCommandLineOption( "l" ) )
{
// Try to load the mod
if ( !m_pModManager->Load ( szOptionValue, m_szCommandLineArgs ) )
{
SString strTemp ( _("Error running mod specified in command line ('%s')"), szOptionValue );
ShowMessageBox ( _("Error")+_E("CC42"), strTemp, MB_BUTTON_OK | MB_ICON_ERROR ); // Command line Mod load failed
}
}
// We want to connect to a server?
else if ( szOptionValue = GetCommandLineOption ( "c" ) )
{
CCommandFuncs::Connect ( szOptionValue );
}
}
}
}
else
{
WaitForMenu++;
}
if ( m_bWaitToSetNick && GetLocalGUI()->GetMainMenu()->IsVisible() && !GetLocalGUI()->GetMainMenu()->IsFading() )
{
if ( m_uiNewNickWaitFrames > 75 )
{
// Request a new nickname if we're waiting for one
GetLocalGUI()->GetMainMenu()->GetSettingsWindow()->RequestNewNickname();
m_bWaitToSetNick = false;
}
else
m_uiNewNickWaitFrames++;
}
}
if ( !IsFocused() && m_bLastFocused )
{
// Fix for #4948
m_pKeyBinds->CallAllGTAControlBinds ( CONTROL_BOTH, false );
m_bLastFocused = false;
}
else if ( IsFocused() && !m_bLastFocused )
{
m_bLastFocused = true;
}
GetJoystickManager ()->DoPulse (); // Note: This may indirectly call CMessageLoopHook::ProcessMessage
m_pKeyBinds->DoPostFramePulse ();
if ( m_pWebCore )
m_pWebCore->DoPulse ();
// Notify the mod manager and the connect manager
TIMING_CHECKPOINT( "-CorePostFrame1" );
m_pModManager->DoPulsePostFrame ();
TIMING_CHECKPOINT( "+CorePostFrame2" );
GetMemStats ()->Draw ();
GetGraphStats ()->Draw();
m_pConnectManager->DoPulse ();
m_Community.DoPulse ();
//XFire polling
if ( IsConnected() )
{
time_t ttime;
ttime = time ( NULL );
if ( ttime >= m_tXfireUpdate + XFIRE_UPDATE_RATE )
{
if ( m_pCurrentServer->IsSocketClosed() )
{
//Init our socket
m_pCurrentServer->Init();
}
//Get our xfire query reply
SString strReply = UpdateXfire( );
//If we Parsed or if the reply failed wait another XFIRE_UPDATE_RATE until trying again
if ( strReply == "ParsedQuery" || strReply == "NoReply" )
{
m_tXfireUpdate = time ( NULL );
//Close the socket
m_pCurrentServer->SocketClose();
}
}
}
//Set our update time to zero to ensure that the first xfire update happens instantly when joining
else
{
XfireSetCustomGameData ( 0, NULL, NULL );
if ( m_tXfireUpdate != 0 )
m_tXfireUpdate = 0;
}
TIMING_CHECKPOINT( "-CorePostFrame2" );
}
// Called after MOD is unloaded
void CCore::OnModUnload ( )
{
// reattach the global event
m_pGUI->SelectInputHandlers( INPUT_CORE );
// remove unused events
m_pGUI->ClearInputHandlers( INPUT_MOD );
// Ensure all these have been removed
m_pKeyBinds->RemoveAllFunctions ();
m_pKeyBinds->RemoveAllControlFunctions ();
// Reset client script frame rate limit
m_uiClientScriptFrameRateLimit = 0;
// Clear web whitelist
m_pWebCore->ResetFilter ();
}
void CCore::RegisterCommands ( )
{
//m_pCommands->Add ( "e", CCommandFuncs::Editor );
//m_pCommands->Add ( "clear", CCommandFuncs::Clear );
m_pCommands->Add ( "help", _("this help screen"), CCommandFuncs::Help );
m_pCommands->Add ( "exit", _("exits the application"), CCommandFuncs::Exit );
m_pCommands->Add ( "quit", _("exits the application"), CCommandFuncs::Exit );
m_pCommands->Add ( "ver", _("shows the version"), CCommandFuncs::Ver );
m_pCommands->Add ( "time", _("shows the time"), CCommandFuncs::Time );
m_pCommands->Add ( "showhud", _("shows the hud"), CCommandFuncs::HUD );
m_pCommands->Add ( "binds", _("shows all the binds"), CCommandFuncs::Binds );
m_pCommands->Add ( "serial", _("shows your serial"), CCommandFuncs::Serial );
#if 0
m_pCommands->Add ( "vid", "changes the video settings (id)", CCommandFuncs::Vid );
m_pCommands->Add ( "window", "enter/leave windowed mode", CCommandFuncs::Window );
m_pCommands->Add ( "load", "loads a mod (name args)", CCommandFuncs::Load );
m_pCommands->Add ( "unload", "unloads a mod (name)", CCommandFuncs::Unload );
#endif
m_pCommands->Add ( "connect", _("connects to a server (host port nick pass)"), CCommandFuncs::Connect );
m_pCommands->Add ( "reconnect", _("connects to a previous server"), CCommandFuncs::Reconnect );
m_pCommands->Add ( "bind", _("binds a key (key control)"), CCommandFuncs::Bind );
m_pCommands->Add ( "unbind", _("unbinds a key (key)"), CCommandFuncs::Unbind );
m_pCommands->Add ( "copygtacontrols", _("copies the default gta controls"), CCommandFuncs::CopyGTAControls );
m_pCommands->Add ( "screenshot", _("outputs a screenshot"), CCommandFuncs::ScreenShot );
m_pCommands->Add ( "saveconfig", _("immediately saves the config"), CCommandFuncs::SaveConfig );
m_pCommands->Add ( "cleardebug", _("clears the debug view"), CCommandFuncs::DebugClear );
m_pCommands->Add ( "chatscrollup", _("scrolls the chatbox upwards"), CCommandFuncs::ChatScrollUp );
m_pCommands->Add ( "chatscrolldown", _("scrolls the chatbox downwards"), CCommandFuncs::ChatScrollDown );
m_pCommands->Add ( "debugscrollup", _("scrolls the debug view upwards"), CCommandFuncs::DebugScrollUp );
m_pCommands->Add ( "debugscrolldown", _("scrolls the debug view downwards"), CCommandFuncs::DebugScrollDown );
m_pCommands->Add ( "test", "", CCommandFuncs::Test );
m_pCommands->Add ( "showmemstat", _("shows the memory statistics"), CCommandFuncs::ShowMemStat );
m_pCommands->Add ( "showframegraph", _("shows the frame timing graph"), CCommandFuncs::ShowFrameGraph );
m_pCommands->Add ( "jinglebells", "", CCommandFuncs::JingleBells );
#if defined(MTA_DEBUG) || defined(MTA_BETA)
m_pCommands->Add ( "fakelag", "", CCommandFuncs::FakeLag );
#endif
}
void CCore::SwitchRenderWindow ( HWND hWnd, HWND hWndInput )
{
assert ( 0 );
#if 0
// Make GTA windowed
m_pGame->GetSettings()->SetCurrentVideoMode(0);
// Get the destination window rectangle
RECT rect;
GetWindowRect ( hWnd, &rect );
// Size the GTA window size to the same size as the destination window rectangle
HWND hDeviceWindow = CDirect3DData::GetSingleton ().GetDeviceWindow ();
MoveWindow ( hDeviceWindow,
0,
0,
rect.right - rect.left,
rect.bottom - rect.top,
TRUE );
// Turn the GTA window into a child window of our static render container window
SetParent ( hDeviceWindow, hWnd );
SetWindowLong ( hDeviceWindow, GWL_STYLE, WS_VISIBLE | WS_CHILD );
#endif
}
bool CCore::IsValidNick ( const char* szNick )
{
// Grab the size of the nick. Check that it's within the player
size_t sizeNick = strlen(szNick);
if (sizeNick < MIN_PLAYER_NICK_LENGTH || sizeNick > MAX_PLAYER_NICK_LENGTH)
{
return false;
}
// Check that each character is valid (visible characters exluding space)
unsigned char ucTemp;
for (size_t i = 0; i < sizeNick; i++)
{
ucTemp = szNick[i];
if (ucTemp < 33 || ucTemp > 126)
{
return false;
}
}
// Nickname is valid, return true
return true;
}
void CCore::Quit ( bool bInstantly )
{
if ( bInstantly )
{
AddReportLog( 7101, "Core - Quit" );
// Show that we are quiting (for the crash dump filename)
SetApplicationSettingInt ( "last-server-ip", 1 );
WatchDogBeginSection( "Q0" ); // Allow loader to detect freeze on exit
// Destroy the client
CModManager::GetSingleton ().Unload ();
// Destroy ourself
delete CCore::GetSingletonPtr ();
WatchDogCompletedSection( "Q0" );
// Use TerminateProcess for now as exiting the normal way crashes
TerminateProcess ( GetCurrentProcess (), 0 );
//PostQuitMessage ( 0 );
}
else
{
m_bQuitOnPulse = true;
}
}
bool CCore::WasLaunchedWithConnectURI ( void )
{
if ( m_szCommandLineArgs && strnicmp ( m_szCommandLineArgs, "mtasa://", 8 ) == 0 )
return true;
return false;
}
void CCore::ParseCommandLine ( std::map < std::string, std::string > & options, const char*& szArgs, const char** pszNoValOptions )
{
std::set < std::string > noValOptions;
if ( pszNoValOptions )
{
while ( *pszNoValOptions )
{
noValOptions.insert ( *pszNoValOptions );
pszNoValOptions++;
}
}
const char* szCmdLine = GetCommandLine ();
char szCmdLineCopy[512];
STRNCPY ( szCmdLineCopy, szCmdLine, sizeof(szCmdLineCopy) );
char* pCmdLineEnd = szCmdLineCopy + strlen ( szCmdLineCopy );
char* pStart = szCmdLineCopy;
char* pEnd = pStart;
bool bInQuoted = false;
std::string strKey;
szArgs = NULL;
while ( pEnd != pCmdLineEnd )
{
pEnd = strchr ( pEnd + 1, ' ' );
if ( !pEnd )
pEnd = pCmdLineEnd;
if ( bInQuoted && *(pEnd - 1) == '"' )
bInQuoted = false;
else if ( *pStart == '"' )
bInQuoted = true;
if ( !bInQuoted )
{
*pEnd = 0;
if ( strKey.empty () )
{
if ( *pStart == '-' )
{
strKey = pStart + 1;
if ( noValOptions.find ( strKey ) != noValOptions.end () )
{
options [ strKey ] = "";
strKey.clear ();
}
}
else
{
szArgs = pStart - szCmdLineCopy + szCmdLine;
break;
}
}
else
{
if ( *pStart == '-' )
{
options [ strKey ] = "";
strKey = pStart + 1;
}
else
{
if ( *pStart == '"' )
pStart++;
if ( *(pEnd - 1) == '"' )
*(pEnd - 1) = 0;
options [ strKey ] = pStart;
strKey.clear ();
}
}
pStart = pEnd;
while ( pStart != pCmdLineEnd && *(++pStart) == ' ' );
pEnd = pStart;
}
}
}
const char* CCore::GetCommandLineOption ( const char* szOption )
{
std::map < std::string, std::string >::iterator it = m_CommandLineOptions.find ( szOption );
if ( it != m_CommandLineOptions.end () )
return it->second.c_str ();
else
return NULL;
}
SString CCore::GetConnectCommandFromURI ( const char* szURI )
{
unsigned short usPort;
std::string strHost, strNick, strPassword;
GetConnectParametersFromURI ( szURI, strHost, usPort, strNick, strPassword );
// Generate a string with the arguments to send to the mod IF we got a host
SString strDest;
if ( strHost.size() > 0 )
{
if ( strPassword.size() > 0 )
strDest.Format ( "connect %s %u %s %s", strHost.c_str (), usPort, strNick.c_str (), strPassword.c_str () );
else
strDest.Format ( "connect %s %u %s", strHost.c_str (), usPort, strNick.c_str () );
}
return strDest;
}
void CCore::GetConnectParametersFromURI ( const char* szURI, std::string &strHost, unsigned short &usPort, std::string &strNick, std::string &strPassword )
{
// Grab the length of the string
size_t sizeURI = strlen ( szURI );
// Parse it right to left
char szLeft [256];
szLeft [255] = 0;
char* szLeftIter = szLeft + 255;
char szRight [256];
szRight [255] = 0;
char* szRightIter = szRight + 255;
const char* szIterator = szURI + sizeURI;
bool bHitAt = false;
for ( ; szIterator >= szURI + 8; szIterator-- )
{
if ( !bHitAt && *szIterator == '@' )
{
bHitAt = true;
}
else
{
if ( bHitAt )
{
if ( szLeftIter > szLeft )
{
*(--szLeftIter) = *szIterator;
}
}
else
{
if ( szRightIter > szRight )
{
*(--szRightIter) = *szIterator;
}
}
}
}
// Parse the host/port
char szHost [64];
char szPort [12];
char* szHostIter = szHost;
char* szPortIter = szPort;
memset ( szHost, 0, sizeof(szHost) );
memset ( szPort, 0, sizeof(szPort) );
bool bIsInPort = false;
size_t sizeRight = strlen ( szRightIter );
for ( size_t i = 0; i < sizeRight; i++ )
{
if ( !bIsInPort && szRightIter [i] == ':' )
{
bIsInPort = true;
}
else
{
if ( bIsInPort )
{
if ( szPortIter < szPort + 11 )
{
*(szPortIter++) = szRightIter [i];
}
}
else
{
if ( szHostIter < szHost + 63 )
{
*(szHostIter++) = szRightIter [i];
}
}
}
}
// Parse the nickname / password
char szNickname [64];
char szPassword [64];
char* szNicknameIter = szNickname;
char* szPasswordIter = szPassword;
memset ( szNickname, 0, sizeof(szNickname) );
memset ( szPassword, 0, sizeof(szPassword) );
bool bIsInPassword = false;
size_t sizeLeft = strlen ( szLeftIter );
for ( size_t i = 0; i < sizeLeft; i++ )
{
if ( !bIsInPassword && szLeftIter [i] == ':' )
{
bIsInPassword = true;
}
else
{
if ( bIsInPassword )
{
if ( szPasswordIter < szPassword + 63 )
{
*(szPasswordIter++) = szLeftIter [i];
}
}
else
{
if ( szNicknameIter < szNickname + 63 )
{
*(szNicknameIter++) = szLeftIter [i];
}
}
}
}
// If we got any port, convert it to an integral type
usPort = 22003;
if ( strlen ( szPort ) > 0 )
{
usPort = static_cast < unsigned short > ( atoi ( szPort ) );
}
// Grab the nickname
if ( strlen ( szNickname ) > 0 )
{
strNick = szNickname;
}
else
{
CVARS_GET ( "nick", strNick );
}
strHost = szHost;
strPassword = szPassword;
}
void CCore::UpdateRecentlyPlayed()
{
//Get the current host and port
unsigned int uiPort;
std::string strHost;
CVARS_GET ( "host", strHost );
CVARS_GET ( "port", uiPort );
// Save the connection details into the recently played servers list
in_addr Address;
if ( CServerListItem::Parse ( strHost.c_str(), Address ) )
{
CServerBrowser* pServerBrowser = CCore::GetSingleton ().GetLocalGUI ()->GetMainMenu ()->GetServerBrowser ();
CServerList* pRecentList = pServerBrowser->GetRecentList ();
pRecentList->Remove ( Address, uiPort );
pRecentList->AddUnique ( Address, uiPort, true );
pServerBrowser->SaveRecentlyPlayedList();
if ( !m_pConnectManager->m_strLastPassword.empty() )
pServerBrowser->SetServerPassword ( strHost + ":" + SString("%u",uiPort), m_pConnectManager->m_strLastPassword );
}
//Save our configuration file
CCore::GetSingleton ().SaveConfig ();
}
void CCore::SetCurrentServer( in_addr Addr, unsigned short usGamePort )
{
//Set the current server info so we can query it with ASE for xfire
m_pCurrentServer->ChangeAddress( Addr, usGamePort );
}
SString CCore::UpdateXfire( void )
{
//Check if a current server exists
if ( m_pCurrentServer )
{
//Get the result from the Pulse method
std::string strResult = m_pCurrentServer->Pulse();
//Have we parsed the query this function call?
if ( strResult == "ParsedQuery" )
{
//Get our Nick from CVARS
std::string strNick;
CVARS_GET ( "nick", strNick );
//Format a player count
SString strPlayerCount("%i / %i", m_pCurrentServer->nPlayers, m_pCurrentServer->nMaxPlayers);
// Set as our custom date
SetXfireData( m_pCurrentServer->strName, m_pCurrentServer->strVersion, m_pCurrentServer->bPassworded, m_pCurrentServer->strGameMode, m_pCurrentServer->strMap, strNick, strPlayerCount );
}
//Return the result
return strResult;
}
return "";
}
void CCore::SetXfireData ( std::string strServerName, std::string strVersion, bool bPassworded, std::string strGamemode, std::string strMap, std::string strPlayerName, std::string strPlayerCount )
{
if ( XfireIsLoaded () )
{
//Set our "custom data"
const char *szKey[7], *szValue[7];
szKey[0] = "Server Name";
szValue[0] = strServerName.c_str();
szKey[1] = "Server Version";
szValue[1] = strVersion.c_str();
szKey[2] = "Passworded";
szValue[2] = bPassworded ? "Yes" : "No";
szKey[3] = "Gamemode";
szValue[3] = strGamemode.c_str();
szKey[4] = "Map";
szValue[4] = strMap.c_str();
szKey[5] = "Player Name";
szValue[5] = strPlayerName.c_str();
szKey[6] = "Player Count";
szValue[6] = strPlayerCount.c_str();
XfireSetCustomGameData ( 7, szKey, szValue );
}
}
//
// Recalculate FPS limit to use
//
// Uses client rate from config
// Uses client rate from script
// Uses server rate from argument, or last time if not supplied
//
void CCore::RecalculateFrameRateLimit ( uint uiServerFrameRateLimit, bool bLogToConsole )
{
// Save rate from server if valid
if ( uiServerFrameRateLimit != -1 )
m_uiServerFrameRateLimit = uiServerFrameRateLimit;
// Start with value set by the server
m_uiFrameRateLimit = m_uiServerFrameRateLimit;
// Apply client config setting
uint uiClientConfigRate;
g_pCore->GetCVars ()->Get ( "fps_limit", uiClientConfigRate );
// Lowest wins (Although zero is highest)
if ( ( m_uiFrameRateLimit == 0 || uiClientConfigRate < m_uiFrameRateLimit ) && uiClientConfigRate > 0 )
m_uiFrameRateLimit = uiClientConfigRate;
// Apply client script setting
uint uiClientScriptRate = m_uiClientScriptFrameRateLimit;
// Lowest wins (Although zero is highest)
if ( ( m_uiFrameRateLimit == 0 || uiClientScriptRate < m_uiFrameRateLimit ) && uiClientScriptRate > 0 )
m_uiFrameRateLimit = uiClientScriptRate;
// Print new limits to the console
if ( bLogToConsole )
{
SString strStatus ( "Server FPS limit: %d", m_uiServerFrameRateLimit );
if ( m_uiFrameRateLimit != m_uiServerFrameRateLimit )
strStatus += SString ( " (Using %d)", m_uiFrameRateLimit );
CCore::GetSingleton ().GetConsole ()->Print( strStatus );
}
}
//
// Change client rate as set by script
//
void CCore::SetClientScriptFrameRateLimit ( uint uiClientScriptFrameRateLimit )
{
m_uiClientScriptFrameRateLimit = uiClientScriptFrameRateLimit;
RecalculateFrameRateLimit( -1, false );
}
//
// Make sure the frame rate limit has been applied since the last call
//
void CCore::EnsureFrameRateLimitApplied ( void )
{
if ( !m_bDoneFrameRateLimit )
{
ApplyFrameRateLimit ();
}
m_bDoneFrameRateLimit = false;
}
//
// Do FPS limiting
//
// This is called once a frame even if minimized
//
void CCore::ApplyFrameRateLimit ( uint uiOverrideRate )
{
TIMING_CHECKPOINT( "-CallIdle1" );
ms_TimingCheckpoints.EndTimingCheckpoints ();
// Frame rate limit stuff starts here
m_bDoneFrameRateLimit = true;
uint uiUseRate = uiOverrideRate != -1 ? uiOverrideRate : m_uiFrameRateLimit;
TIMING_GRAPH("Limiter");
if ( uiUseRate < 1 )
return DoReliablePulse ();
if ( m_DiagnosticDebug != EDiagnosticDebug::D3D_6732 )
Sleep( 1 ); // Make frame rate smoother maybe
// Calc required time in ms between frames
const double dTargetTimeToUse = 1000.0 / uiUseRate;
// Time now
double dTimeMs = GetTickCount32 ();
// Get delta time in ms since last frame
double dTimeUsed = dTimeMs - m_dLastTimeMs;
// Apply any over/underrun carried over from the previous frame
dTimeUsed += m_dPrevOverrun;
if ( dTimeUsed < dTargetTimeToUse )
{
// Have time spare - maybe eat some of that now
double dSpare = dTargetTimeToUse - dTimeUsed;
double dUseUpNow = dSpare - dTargetTimeToUse * 0.2f;
if ( dUseUpNow >= 1 )
Sleep( static_cast < DWORD > ( floor ( dUseUpNow ) ) );
// Redo timing calcs
dTimeMs = GetTickCount32 ();
dTimeUsed = dTimeMs - m_dLastTimeMs;
dTimeUsed += m_dPrevOverrun;
}
// Update over/underrun for next frame
m_dPrevOverrun = dTimeUsed - dTargetTimeToUse;
// Limit carry over
m_dPrevOverrun = Clamp ( dTargetTimeToUse * -0.9f, m_dPrevOverrun, dTargetTimeToUse * 0.1f );
m_dLastTimeMs = dTimeMs;
DoReliablePulse ();
TIMING_GRAPH("FrameEnd");
TIMING_GRAPH("");
}
//
// DoReliablePulse
//
// This is called once a frame even if minimized
//
void CCore::DoReliablePulse ( void )
{
ms_TimingCheckpoints.BeginTimingCheckpoints ();
TIMING_CHECKPOINT( "+CallIdle2" );
UpdateIsWindowMinimized ();
// Non frame rate limit stuff
if ( IsWindowMinimized () )
m_iUnminimizeFrameCounter = 4; // Tell script we have unminimized after a short delay
UpdateModuleTickCount64 ();
}
//
// Debug timings
//
bool CCore::IsTimingCheckpoints ( void )
{
return ms_TimingCheckpoints.IsTimingCheckpoints ();
}
void CCore::OnTimingCheckpoint ( const char* szTag )
{
ms_TimingCheckpoints.OnTimingCheckpoint ( szTag );
}
void CCore::OnTimingDetail ( const char* szTag )
{
ms_TimingCheckpoints.OnTimingDetail ( szTag );
}
//
// OnDeviceRestore
//
void CCore::OnDeviceRestore ( void )
{
m_iUnminimizeFrameCounter = 4; // Tell script we have restored after 4 frames to avoid double sends
m_bDidRecreateRenderTargets = true;
}
//
// OnPreFxRender
//
void CCore::OnPreFxRender ( void )
{
// Don't do nothing if nothing won't be drawn
if ( !CGraphics::GetSingleton ().HasMaterialLine3DQueueItems () )
return;
CGraphics::GetSingleton ().EnteringMTARenderZone();
CGraphics::GetSingleton ().DrawMaterialLine3DQueue ();
CGraphics::GetSingleton ().LeavingMTARenderZone();
}
//
// OnPreHUDRender
//
void CCore::OnPreHUDRender ( void )
{
IDirect3DDevice9* pDevice = CGraphics::GetSingleton ().GetDevice ();
// Handle saving depth buffer
CGraphics::GetSingleton ().GetRenderItemManager ()->SaveReadableDepthBuffer();
CGraphics::GetSingleton ().EnteringMTARenderZone();
// Maybe capture screen and other stuff
CGraphics::GetSingleton ().GetRenderItemManager ()->DoPulse ();
// Handle script stuffs
if ( m_iUnminimizeFrameCounter && --m_iUnminimizeFrameCounter == 0 )
{
m_pModManager->DoPulsePreHUDRender ( true, m_bDidRecreateRenderTargets );
m_bDidRecreateRenderTargets = false;
}
else
m_pModManager->DoPulsePreHUDRender ( false, false );
// Restore in case script forgets
CGraphics::GetSingleton ().GetRenderItemManager ()->RestoreDefaultRenderTarget ();
// Draw pre-GUI primitives
CGraphics::GetSingleton ().DrawPreGUIQueue ();
CGraphics::GetSingleton ().LeavingMTARenderZone();
}
//
// CCore::CalculateStreamingMemoryRange
//
// Streaming memory range based on system installed memory:
//
// System RAM MB min max
// 512 = 64 96
// 1024 = 96 128
// 2048 = 128 256
//
// Also:
// Max should be no more than 2 * installed video memory
// Min should be no more than 1 * installed video memory
// Max should be no less than 96MB
// Gap between min and max should be no less than 32MB
//
void CCore::CalculateStreamingMemoryRange ( void )
{
// Only need to do this once
if ( m_fMinStreamingMemory != 0 )
return;
// Get system info
int iSystemRamMB = static_cast < int > ( GetWMITotalPhysicalMemory () / 1024LL / 1024LL );
int iVideoMemoryMB = g_pDeviceState->AdapterState.InstalledMemoryKB / 1024;
// Calc min and max from lookup table
SSamplePoint < float > minPoints[] = { {512, 64}, {1024, 96}, {2048, 128} };
SSamplePoint < float > maxPoints[] = { {512, 96}, {1024, 128}, {2048, 256} };
float fMinAmount = EvalSamplePosition < float > ( minPoints, NUMELMS ( minPoints ), iSystemRamMB );
float fMaxAmount = EvalSamplePosition < float > ( maxPoints, NUMELMS ( maxPoints ), iSystemRamMB );
// Apply cap dependant on video memory
fMaxAmount = Min ( fMaxAmount, iVideoMemoryMB * 2.f );
fMinAmount = Min ( fMinAmount, iVideoMemoryMB * 1.f );
// Apply 96MB lower limit
fMaxAmount = Max ( fMaxAmount, 96.f );
// Apply gap limit
fMinAmount = fMaxAmount - Max ( fMaxAmount - fMinAmount, 32.f );
m_fMinStreamingMemory = fMinAmount;
m_fMaxStreamingMemory = fMaxAmount;
}
//
// GetMinStreamingMemory
//
uint CCore::GetMinStreamingMemory ( void )
{
CalculateStreamingMemoryRange ();
#ifdef MTA_DEBUG
return 1;
#endif
return m_fMinStreamingMemory;
}
//
// GetMaxStreamingMemory
//
uint CCore::GetMaxStreamingMemory ( void )
{
CalculateStreamingMemoryRange ();
return m_fMaxStreamingMemory;
}
//
// OnCrashAverted
//
void CCore::OnCrashAverted ( uint uiId )
{
CCrashDumpWriter::OnCrashAverted ( uiId );
}
//
// OnEnterCrashZone
//
void CCore::OnEnterCrashZone ( uint uiId )
{
CCrashDumpWriter::OnEnterCrashZone ( uiId );
}
//
// LogEvent
//
void CCore::LogEvent ( uint uiDebugId, const char* szType, const char* szContext, const char* szBody, uint uiAddReportLogId )
{
if ( uiAddReportLogId )
AddReportLog ( uiAddReportLogId, SString ( "%s - %s", szContext, szBody ) );
if ( GetDebugIdEnabled ( uiDebugId ) )
{
CCrashDumpWriter::LogEvent ( szType, szContext, szBody );
OutputDebugLine ( SString ( "[LogEvent] %d %s %s %s", uiDebugId, szType, szContext, szBody ) );
}
}
//
// GetDebugIdEnabled
//
bool CCore::GetDebugIdEnabled ( uint uiDebugId )
{
static CFilterMap debugIdFilterMap ( GetVersionUpdater ()->GetDebugFilterString () );
return ( uiDebugId == 0 ) || !debugIdFilterMap.IsFiltered ( uiDebugId );
}
EDiagnosticDebugType CCore::GetDiagnosticDebug ( void )
{
return m_DiagnosticDebug;
}
void CCore::SetDiagnosticDebug ( EDiagnosticDebugType value )
{
m_DiagnosticDebug = value;
}
CModelCacheManager* CCore::GetModelCacheManager ( void )
{
if ( !m_pModelCacheManager )
m_pModelCacheManager = NewModelCacheManager ();
return m_pModelCacheManager;
}
void CCore::AddModelToPersistentCache ( ushort usModelId )
{
return GetModelCacheManager ()->AddModelToPersistentCache ( usModelId );
}
void CCore::StaticIdleHandler ( void )
{
g_pCore->IdleHandler ();
}
// Gets called every game loop, after GTA has been loaded for the first time
void CCore::IdleHandler ( void )
{
m_bGettingIdleCallsFromMultiplayer = true;
HandleIdlePulse();
}
// Gets called every 50ms, before GTA has been loaded for the first time
void CCore::WindowsTimerHandler ( void )
{
if ( !m_bGettingIdleCallsFromMultiplayer )
HandleIdlePulse();
}
// Always called, even if minimized
void CCore::HandleIdlePulse ( void )
{
UpdateIsWindowMinimized();
if ( IsWindowMinimized() )
{
DoPreFramePulse();
DoPostFramePulse();
}
if ( m_pModManager->GetCurrentMod() )
m_pModManager->GetCurrentMod()->IdleHandler();
}
//
// Handle encryption of Windows crash dump files
//
void CCore::HandleCrashDumpEncryption( void )
{
const int iMaxFiles = 10;
SString strDumpDirPath = CalcMTASAPath( "mta\\dumps" );
SString strDumpDirPrivatePath = PathJoin( strDumpDirPath, "private" );
SString strDumpDirPublicPath = PathJoin( strDumpDirPath, "public" );
MakeSureDirExists( strDumpDirPrivatePath + "/" );
MakeSureDirExists( strDumpDirPublicPath + "/" );
SString strMessage = "Dump files in this directory are encrypted and copied to 'dumps\\public' during startup\n\n";
FileSave( PathJoin( strDumpDirPrivatePath, "README.txt" ), strMessage );
// Move old dumps to the private folder
{
std::vector < SString > legacyList = FindFiles( PathJoin( strDumpDirPath, "*.dmp" ), true, false );
for ( uint i = 0 ; i < legacyList.size() ; i++ )
{
const SString& strFilename = legacyList[i];
SString strSrcPathFilename = PathJoin( strDumpDirPath, strFilename );
SString strDestPathFilename = PathJoin( strDumpDirPrivatePath, strFilename );
FileRename( strSrcPathFilename, strDestPathFilename );
}
}
// Limit number of files in the private folder
{
std::vector < SString > privateList = FindFiles( PathJoin( strDumpDirPrivatePath, "*.dmp" ), true, false, true );
for ( int i = 0 ; i < (int)privateList.size() - iMaxFiles ; i++ )
FileDelete( PathJoin( strDumpDirPrivatePath, privateList[i] ) );
}
// Copy and encrypt private files to public if they don't already exist
{
std::vector < SString > privateList = FindFiles( PathJoin( strDumpDirPrivatePath, "*.dmp" ), true, false );
for ( uint i = 0 ; i < privateList.size() ; i++ )
{
const SString& strPrivateFilename = privateList[i];
SString strPublicFilename = ExtractBeforeExtension( strPrivateFilename ) + ".rsa." + ExtractExtension( strPrivateFilename );
SString strPrivatePathFilename = PathJoin( strDumpDirPrivatePath, strPrivateFilename );
SString strPublicPathFilename = PathJoin( strDumpDirPublicPath, strPublicFilename );
if ( !FileExists( strPublicPathFilename ) )
{
GetNetwork()->EncryptDumpfile( strPrivatePathFilename, strPublicPathFilename );
}
}
}
// Limit number of files in the public folder
{
std::vector < SString > publicList = FindFiles( PathJoin( strDumpDirPublicPath, "*.dmp" ), true, false, true );
for ( int i = 0 ; i < (int)publicList.size() - iMaxFiles ; i++ )
FileDelete( PathJoin( strDumpDirPublicPath, publicList[i] ) );
}
// And while we are here, limit number of items in core.log as well
{
SString strCoreLogPathFilename = CalcMTASAPath( "mta\\core.log" );
SString strFileContents;
FileLoad( strCoreLogPathFilename, strFileContents );
SString strDelmiter = "** -- Unhandled exception -- **";
std::vector < SString > parts;
strFileContents.Split( strDelmiter, parts );
if ( parts.size() > iMaxFiles )
{
strFileContents = strDelmiter + strFileContents.Join( strDelmiter, parts, parts.size() - iMaxFiles );
FileSave( strCoreLogPathFilename, strFileContents );
}
}
}
//
// Flag to make sure stuff only gets done when everything is ready
//
void CCore::SetModulesLoaded( bool bLoaded )
{
m_bModulesLoaded = bLoaded;
}
bool CCore::AreModulesLoaded( void )
{
return m_bModulesLoaded;
}
//
// Handle dummy progress when game seems stalled
//
int ms_iDummyProgressTimerCounter = 0;
void CALLBACK TimerProc( void* lpParametar, BOOLEAN TimerOrWaitFired )
{
ms_iDummyProgressTimerCounter++;
}
//
// Refresh progress output
//
void CCore::UpdateDummyProgress( int iValue, const char* szType )
{
if ( iValue != -1 )
{
m_iDummyProgressValue = iValue;
m_strDummyProgressType = szType;
}
if ( m_DummyProgressTimerHandle == NULL )
{
// Using this timer is quicker than checking tick count with every call to UpdateDummyProgress()
::CreateTimerQueueTimer( &m_DummyProgressTimerHandle, NULL, TimerProc, this, DUMMY_PROGRESS_ANIMATION_INTERVAL, DUMMY_PROGRESS_ANIMATION_INTERVAL, WT_EXECUTEINTIMERTHREAD );
}
if ( !ms_iDummyProgressTimerCounter )
return;
ms_iDummyProgressTimerCounter = 0;
// Compose message with amount
SString strMessage;
if ( m_iDummyProgressValue )
strMessage = SString( "%d%s", m_iDummyProgressValue, *m_strDummyProgressType );
CGraphics::GetSingleton().SetProgressMessage( strMessage );
}
//
// Do SetCursorPos if allowed
//
void CCore::CallSetCursorPos( int X, int Y )
{
if ( CCore::GetSingleton ( ).IsFocused ( ) && !CLocalGUI::GetSingleton ( ).IsMainMenuVisible ( ) )
m_pLocalGUI->SetCursorPos ( X, Y );
}
bool CCore::GetRequiredDisplayResolution( int& iOutWidth, int& iOutHeight, int& iOutColorBits, int& iOutAdapterIndex, bool& bOutAllowUnsafeResolutions )
{
CVARS_GET( "show_unsafe_resolutions", bOutAllowUnsafeResolutions );
return GetVideoModeManager()->GetRequiredDisplayResolution( iOutWidth, iOutHeight, iOutColorBits, iOutAdapterIndex );
}
bool CCore::GetDeviceSelectionEnabled( void )
{
return GetApplicationSettingInt ( "device-selection-disabled" ) ? false : true;
}
void CCore::NotifyRenderingGrass( bool bIsRenderingGrass )
{
m_bIsRenderingGrass = bIsRenderingGrass;
CDirect3DEvents9::CloseActiveShader();
}
| BozhkoAlexander/mtasa-blue | MTA10/core/CCore.cpp | C++ | gpl-3.0 | 69,554 |
/* md5.cc
Jeremy Barnes, 25 October 2012
Copyright (c) 2012 Datacratic. All rights reserved.
*/
#include "hash.h"
#include "string_functions.h"
#include <boost/algorithm/string.hpp>
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include "crypto++/sha.h"
#include "crypto++/md5.h"
#include "crypto++/hmac.h"
#include "crypto++/base64.h"
using namespace std;
namespace ML {
std::string md5HashToHex(const std::string & str)
{
return md5HashToHex(str.c_str(), str.length());
}
std::string md5HashToHex(const char * buf, size_t nBytes)
{
typedef CryptoPP::Weak::MD5 Hash;
size_t digestLen = Hash::DIGESTSIZE;
byte digest[digestLen];
Hash hash;
hash.CalculateDigest(digest, (byte *)buf, nBytes);
string md5;
for (unsigned i = 0; i < digestLen; ++i) {
md5 += ML::format("%02x", digest[i]);
}
return md5;
}
std::string md5HashToBase64(const std::string & str)
{
return md5HashToBase64(str.c_str(), str.length());
}
std::string md5HashToBase64(const char * buf, size_t nBytes)
{
typedef CryptoPP::Weak::MD5 Hash;
size_t digestLen = Hash::DIGESTSIZE;
byte digest[digestLen];
Hash hash;
hash.CalculateDigest(digest, (byte *)buf, nBytes);
// base64
char outBuf[256];
CryptoPP::Base64Encoder baseEncoder;
baseEncoder.Put(digest, digestLen);
baseEncoder.MessageEnd();
size_t got = baseEncoder.Get((byte *)outBuf, 256);
outBuf[got] = 0;
//cerr << "got " << got << " characters" << endl;
return boost::trim_copy(std::string(outBuf));
}
std::string hmacSha1Base64(const std::string & stringToSign,
const std::string & privateKey)
{
typedef CryptoPP::SHA1 Hash;
size_t digestLen = Hash::DIGESTSIZE;
byte digest[digestLen];
CryptoPP::HMAC<Hash> hmac((byte *)privateKey.c_str(), privateKey.length());
hmac.CalculateDigest(digest,
(byte *)stringToSign.c_str(),
stringToSign.length());
// base64
char outBuf[256];
CryptoPP::Base64Encoder baseEncoder;
baseEncoder.Put(digest, digestLen);
baseEncoder.MessageEnd();
size_t got = baseEncoder.Get((byte *)outBuf, 256);
outBuf[got] = 0;
string base64digest(outBuf, outBuf + got - 1);
return base64digest;
}
std::string hmacSha256Base64(const std::string & stringToSign,
const std::string & privateKey)
{
typedef CryptoPP::SHA256 Hash;
size_t digestLen = Hash::DIGESTSIZE;
byte digest[digestLen];
CryptoPP::HMAC<Hash> hmac((byte *)privateKey.c_str(), privateKey.length());
hmac.CalculateDigest(digest,
(byte *)stringToSign.c_str(),
stringToSign.length());
// base64
char outBuf[256];
CryptoPP::Base64Encoder baseEncoder;
baseEncoder.Put(digest, digestLen);
baseEncoder.MessageEnd();
size_t got = baseEncoder.Get((byte *)outBuf, 256);
outBuf[got] = 0;
string base64digest(outBuf, outBuf + got - 1);
return base64digest;
}
} // namespace ML
| WitchKing-Helkar/rtbkit | jml/utils/hash.cc | C++ | apache-2.0 | 3,112 |
(function() {
'use strict';
Polymer({
is: 'iron-overlay-backdrop',
properties: {
/**
* Returns true if the backdrop is opened.
*/
opened: {
reflectToAttribute: true,
type: Boolean,
value: false,
observer: '_openedChanged'
}
},
listeners: {
'transitionend': '_onTransitionend'
},
created: function() {
// Used to cancel previous requestAnimationFrame calls when opened changes.
this.__openedRaf = null;
},
attached: function() {
this.opened && this._openedChanged(this.opened);
},
/**
* Appends the backdrop to document body if needed.
*/
prepare: function() {
if (this.opened && !this.parentNode) {
Polymer.dom(document.body).appendChild(this);
}
},
/**
* Shows the backdrop.
*/
open: function() {
this.opened = true;
},
/**
* Hides the backdrop.
*/
close: function() {
this.opened = false;
},
/**
* Removes the backdrop from document body if needed.
*/
complete: function() {
if (!this.opened && this.parentNode === document.body) {
Polymer.dom(this.parentNode).removeChild(this);
}
},
_onTransitionend: function(event) {
if (event && event.target === this) {
this.complete();
}
},
/**
* @param {boolean} opened
* @private
*/
_openedChanged: function(opened) {
if (opened) {
// Auto-attach.
this.prepare();
} else {
// Animation might be disabled via the mixin or opacity custom property.
// If it is disabled in other ways, it's up to the user to call complete.
var cs = window.getComputedStyle(this);
if (cs.transitionDuration === '0s' || cs.opacity == 0) {
this.complete();
}
}
if (!this.isAttached) {
return;
}
// Always cancel previous requestAnimationFrame.
if (this.__openedRaf) {
window.cancelAnimationFrame(this.__openedRaf);
this.__openedRaf = null;
}
// Force relayout to ensure proper transitions.
this.scrollTop = this.scrollTop;
this.__openedRaf = window.requestAnimationFrame(function() {
this.__openedRaf = null;
this.toggleClass('opened', this.opened);
}.bind(this));
}
});
})(); | axinging/chromium-crosswalk | third_party/polymer/v1_0/components-chromium/iron-overlay-behavior/iron-overlay-backdrop-extracted.js | JavaScript | bsd-3-clause | 2,415 |
'use strict';
$(function () {
//Simple implementation of direct chat contact pane toggle (TEMPORARY)
$('[data-widget="chat-pane-toggle"]').click(function(){
$("#myDirectChat").toggleClass('direct-chat-contacts-open');
});
/* ChartJS
* -------
* Here we will create a few charts using ChartJS
*/
//-----------------------
//- MONTHLY SALES CHART -
//-----------------------
// Get context with jQuery - using jQuery's .get() method.
var salesChartCanvas = $("#salesChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
var salesChart = new Chart(salesChartCanvas);
var salesChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "Electronics",
fillColor: "rgb(210, 214, 222)",
strokeColor: "rgb(210, 214, 222)",
pointColor: "rgb(210, 214, 222)",
pointStrokeColor: "#c1c7d1",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgb(220,220,220)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Digital Goods",
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "rgba(60,141,188,1)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(60,141,188,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var salesChartOptions = {
//Boolean - If we should show the scale at all
showScale: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: false,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.3,
//Boolean - Whether to show a dot for each point
pointDot: false,
//Number - Radius of each point dot in pixels
pointDotRadius: 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a color
datasetFill: true,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%=datasets[i].label%></li><%}%></ul>",
//Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
//Boolean - whether to make the chart responsive to window resizing
responsive: true
};
//Create the line chart
salesChart.Line(salesChartData, salesChartOptions);
//---------------------------
//- END MONTHLY SALES CHART -
//---------------------------
//-------------
//- PIE CHART -
//-------------
// Get context with jQuery - using jQuery's .get() method.
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = [
{
value: 700,
color: "#f56954",
highlight: "#f56954",
label: "Chrome"
},
{
value: 500,
color: "#00a65a",
highlight: "#00a65a",
label: "IE"
},
{
value: 400,
color: "#f39c12",
highlight: "#f39c12",
label: "FireFox"
},
{
value: 600,
color: "#00c0ef",
highlight: "#00c0ef",
label: "Safari"
},
{
value: 300,
color: "#3c8dbc",
highlight: "#3c8dbc",
label: "Opera"
},
{
value: 100,
color: "#d2d6de",
highlight: "#d2d6de",
label: "Navigator"
}
];
var pieOptions = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke: true,
//String - The colour of each segment stroke
segmentStrokeColor: "#fff",
//Number - The width of each segment stroke
segmentStrokeWidth: 2,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout: 50, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect
animationEasing: "easeOutBounce",
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false,
//Boolean - whether to make the chart responsive to window resizing
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
//String - A tooltip template
tooltipTemplate: "<%=value %> <%=label%> users"
};
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
pieChart.Doughnut(PieData, pieOptions);
//-----------------
//- END PIE CHART -
//-----------------
/* jVector Maps
* ------------
* Create a world map with markers
*/
$('#world-map-markers').vectorMap({
map: 'world_mill_en',
normalizeFunction: 'polynomial',
hoverOpacity: 0.7,
hoverColor: false,
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: 'rgba(210, 214, 222, 1)',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
},
hover: {
"fill-opacity": 0.7,
cursor: 'pointer'
},
selected: {
fill: 'yellow'
},
selectedHover: {
}
},
markerStyle: {
initial: {
fill: '#00a65a',
stroke: '#111'
}
},
markers: [
{latLng: [41.90, 12.45], name: 'Vatican City'},
{latLng: [43.73, 7.41], name: 'Monaco'},
{latLng: [-0.52, 166.93], name: 'Nauru'},
{latLng: [-8.51, 179.21], name: 'Tuvalu'},
{latLng: [43.93, 12.46], name: 'San Marino'},
{latLng: [47.14, 9.52], name: 'Liechtenstein'},
{latLng: [7.11, 171.06], name: 'Marshall Islands'},
{latLng: [17.3, -62.73], name: 'Saint Kitts and Nevis'},
{latLng: [3.2, 73.22], name: 'Maldives'},
{latLng: [35.88, 14.5], name: 'Malta'},
{latLng: [12.05, -61.75], name: 'Grenada'},
{latLng: [13.16, -61.23], name: 'Saint Vincent and the Grenadines'},
{latLng: [13.16, -59.55], name: 'Barbados'},
{latLng: [17.11, -61.85], name: 'Antigua and Barbuda'},
{latLng: [-4.61, 55.45], name: 'Seychelles'},
{latLng: [7.35, 134.46], name: 'Palau'},
{latLng: [42.5, 1.51], name: 'Andorra'},
{latLng: [14.01, -60.98], name: 'Saint Lucia'},
{latLng: [6.91, 158.18], name: 'Federated States of Micronesia'},
{latLng: [1.3, 103.8], name: 'Singapore'},
{latLng: [1.46, 173.03], name: 'Kiribati'},
{latLng: [-21.13, -175.2], name: 'Tonga'},
{latLng: [15.3, -61.38], name: 'Dominica'},
{latLng: [-20.2, 57.5], name: 'Mauritius'},
{latLng: [26.02, 50.55], name: 'Bahrain'},
{latLng: [0.33, 6.73], name: 'São Tomé and Príncipe'}
]
});
/* SPARKLINE CHARTS
* ----------------
* Create a inline charts with spark line
*/
//-----------------
//- SPARKLINE BAR -
//-----------------
$('.sparkbar').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'bar',
height: $this.data('height') ? $this.data('height') : '30',
barColor: $this.data('color')
});
});
//-----------------
//- SPARKLINE PIE -
//-----------------
$('.sparkpie').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'pie',
height: $this.data('height') ? $this.data('height') : '90',
sliceColors: $this.data('color')
});
});
//------------------
//- SPARKLINE LINE -
//------------------
$('.sparkline').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'line',
height: $this.data('height') ? $this.data('height') : '90',
width: '100%',
lineColor: $this.data('linecolor'),
fillColor: $this.data('fillcolor'),
spotColor: $this.data('spotcolor')
});
});
}); | johan--/ember-admin-dashboards | vendor/AdminLTE/dist/js/pages/dashboard2.js | JavaScript | mit | 9,137 |
/*
* Copyright (c) 1996, 2010, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package sun.awt.windows;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.peer.*;
import java.beans.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.List;
import sun.util.logging.PlatformLogger;
import sun.awt.*;
import sun.java2d.pipe.Region;
public class WWindowPeer extends WPanelPeer implements WindowPeer,
DisplayChangedListener
{
private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.windows.WWindowPeer");
private static final PlatformLogger screenLog = PlatformLogger.getLogger("sun.awt.windows.screen.WWindowPeer");
// we can't use WDialogPeer as blocker may be an instance of WPrintDialogPeer that
// extends WWindowPeer, not WDialogPeer
private WWindowPeer modalBlocker = null;
private boolean isOpaque;
private TranslucentWindowPainter painter;
/*
* A key used for storing a list of active windows in AppContext. The value
* is a list of windows, sorted by the time of activation: later a window is
* activated, greater its index is in the list.
*/
private final static StringBuffer ACTIVE_WINDOWS_KEY =
new StringBuffer("active_windows_list");
/*
* Listener for 'activeWindow' KFM property changes. It is added to each
* AppContext KFM. See ActiveWindowListener inner class below.
*/
private static PropertyChangeListener activeWindowListener =
new ActiveWindowListener();
/*
* The object is a listener for the AppContext.GUI_DISPOSED property.
*/
private final static PropertyChangeListener guiDisposedListener =
new GuiDisposedListener();
/*
* Called (on the Toolkit thread) before the appropriate
* WindowStateEvent is posted to the EventQueue.
*/
private WindowListener windowListener;
/**
* Initialize JNI field IDs
*/
private static native void initIDs();
static {
initIDs();
}
// WComponentPeer overrides
protected void disposeImpl() {
AppContext appContext = SunToolkit.targetToAppContext(target);
synchronized (appContext) {
List<WWindowPeer> l = (List<WWindowPeer>)appContext.get(ACTIVE_WINDOWS_KEY);
if (l != null) {
l.remove(this);
}
}
// Remove ourself from the Map of DisplayChangeListeners
GraphicsConfiguration gc = getGraphicsConfiguration();
((Win32GraphicsDevice)gc.getDevice()).removeDisplayChangedListener(this);
synchronized (getStateLock()) {
TranslucentWindowPainter currentPainter = painter;
if (currentPainter != null) {
currentPainter.flush();
// don't set the current one to null here; reduces the chances of
// MT issues (like NPEs)
}
}
super.disposeImpl();
}
// WindowPeer implementation
public void toFront() {
updateFocusableWindowState();
_toFront();
}
native void _toFront();
public native void toBack();
public native void setAlwaysOnTopNative(boolean value);
public void setAlwaysOnTop(boolean value) {
if ((value && ((Window)target).isVisible()) || !value) {
setAlwaysOnTopNative(value);
}
}
public void updateFocusableWindowState() {
setFocusableWindow(((Window)target).isFocusableWindow());
}
native void setFocusableWindow(boolean value);
// FramePeer & DialogPeer partial shared implementation
public void setTitle(String title) {
// allow a null title to pass as an empty string.
if (title == null) {
title = "";
}
_setTitle(title);
}
native void _setTitle(String title);
public void setResizable(boolean resizable) {
_setResizable(resizable);
}
public native void _setResizable(boolean resizable);
// Toolkit & peer internals
WWindowPeer(Window target) {
super(target);
}
void initialize() {
super.initialize();
updateInsets(insets_);
Font f = ((Window)target).getFont();
if (f == null) {
f = defaultFont;
((Window)target).setFont(f);
setFont(f);
}
// Express our interest in display changes
GraphicsConfiguration gc = getGraphicsConfiguration();
((Win32GraphicsDevice)gc.getDevice()).addDisplayChangedListener(this);
initActiveWindowsTracking((Window)target);
updateIconImages();
Shape shape = ((Window)target).getShape();
if (shape != null) {
applyShape(Region.getInstance(shape, null));
}
float opacity = ((Window)target).getOpacity();
if (opacity < 1.0f) {
setOpacity(opacity);
}
synchronized (getStateLock()) {
// default value of a boolean field is 'false', so set isOpaque to
// true here explicitly
this.isOpaque = true;
setOpaque(((Window)target).isOpaque());
}
}
native void createAwtWindow(WComponentPeer parent);
private volatile Window.Type windowType = Window.Type.NORMAL;
// This method must be called for Window, Dialog, and Frame before creating
// the hwnd
void preCreate(WComponentPeer parent) {
windowType = ((Window)target).getType();
}
void create(WComponentPeer parent) {
preCreate(parent);
createAwtWindow(parent);
}
// should be overriden in WDialogPeer
protected void realShow() {
super.show();
}
public void show() {
updateFocusableWindowState();
boolean alwaysOnTop = ((Window)target).isAlwaysOnTop();
// Fix for 4868278.
// If we create a window with a specific GraphicsConfig, and then move it with
// setLocation() or setBounds() to another one before its peer has been created,
// then calling Window.getGraphicsConfig() returns wrong config. That may lead
// to some problems like wrong-placed tooltips. It is caused by calling
// super.displayChanged() in WWindowPeer.displayChanged() regardless of whether
// GraphicsDevice was really changed, or not. So we need to track it here.
updateGC();
realShow();
updateMinimumSize();
if (((Window)target).isAlwaysOnTopSupported() && alwaysOnTop) {
setAlwaysOnTop(alwaysOnTop);
}
synchronized (getStateLock()) {
if (!isOpaque) {
updateWindow(true);
}
}
}
// Synchronize the insets members (here & in helper) with actual window
// state.
native void updateInsets(Insets i);
static native int getSysMinWidth();
static native int getSysMinHeight();
static native int getSysIconWidth();
static native int getSysIconHeight();
static native int getSysSmIconWidth();
static native int getSysSmIconHeight();
/**windows/classes/sun/awt/windows/
* Creates native icon from specified raster data and updates
* icon for window and all descendant windows that inherit icon.
* Raster data should be passed in the ARGB form.
* Note that raster data format was changed to provide support
* for XP icons with alpha-channel
*/
native void setIconImagesData(int[] iconRaster, int w, int h,
int[] smallIconRaster, int smw, int smh);
synchronized native void reshapeFrame(int x, int y, int width, int height);
public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
if (!focusAllowedFor()) {
return false;
}
return requestWindowFocus(cause == CausedFocusEvent.Cause.MOUSE_EVENT);
}
public native boolean requestWindowFocus(boolean isMouseEventCause);
public boolean focusAllowedFor() {
Window window = (Window)this.target;
if (!window.isVisible() ||
!window.isEnabled() ||
!window.isFocusableWindow())
{
return false;
}
if (isModalBlocked()) {
return false;
}
return true;
}
public void hide() {
WindowListener listener = windowListener;
if (listener != null) {
// We're not getting WINDOW_CLOSING from the native code when hiding
// the window programmatically. So, create it and notify the listener.
listener.windowClosing(new WindowEvent((Window)target, WindowEvent.WINDOW_CLOSING));
}
super.hide();
}
// WARNING: it's called on the Toolkit thread!
void preprocessPostEvent(AWTEvent event) {
if (event instanceof WindowEvent) {
WindowListener listener = windowListener;
if (listener != null) {
switch(event.getID()) {
case WindowEvent.WINDOW_CLOSING:
listener.windowClosing((WindowEvent)event);
break;
case WindowEvent.WINDOW_ICONIFIED:
listener.windowIconified((WindowEvent)event);
break;
}
}
}
}
synchronized void addWindowListener(WindowListener l) {
windowListener = AWTEventMulticaster.add(windowListener, l);
}
synchronized void removeWindowListener(WindowListener l) {
windowListener = AWTEventMulticaster.remove(windowListener, l);
}
public void updateMinimumSize() {
Dimension minimumSize = null;
if (((Component)target).isMinimumSizeSet()) {
minimumSize = ((Component)target).getMinimumSize();
}
if (minimumSize != null) {
int msw = getSysMinWidth();
int msh = getSysMinHeight();
int w = (minimumSize.width >= msw) ? minimumSize.width : msw;
int h = (minimumSize.height >= msh) ? minimumSize.height : msh;
setMinSize(w, h);
} else {
setMinSize(0, 0);
}
}
public void updateIconImages() {
java.util.List<Image> imageList = ((Window)target).getIconImages();
if (imageList == null || imageList.size() == 0) {
setIconImagesData(null, 0, 0, null, 0, 0);
} else {
int w = getSysIconWidth();
int h = getSysIconHeight();
int smw = getSysSmIconWidth();
int smh = getSysSmIconHeight();
DataBufferInt iconData = SunToolkit.getScaledIconData(imageList,
w, h);
DataBufferInt iconSmData = SunToolkit.getScaledIconData(imageList,
smw, smh);
if (iconData != null && iconSmData != null) {
setIconImagesData(iconData.getData(), w, h,
iconSmData.getData(), smw, smh);
} else {
setIconImagesData(null, 0, 0, null, 0, 0);
}
}
}
native void setMinSize(int width, int height);
/*
* ---- MODALITY SUPPORT ----
*/
/**
* Some modality-related code here because WFileDialogPeer, WPrintDialogPeer and
* WPageDialogPeer are descendants of WWindowPeer, not WDialogPeer
*/
public boolean isModalBlocked() {
return modalBlocker != null;
}
public void setModalBlocked(Dialog dialog, boolean blocked) {
synchronized (((Component)getTarget()).getTreeLock()) // State lock should always be after awtLock
{
// use WWindowPeer instead of WDialogPeer because of FileDialogs and PrintDialogs
WWindowPeer blockerPeer = (WWindowPeer)dialog.getPeer();
if (blocked)
{
modalBlocker = blockerPeer;
// handle native dialogs separately, as they may have not
// got HWND yet; modalEnable/modalDisable is called from
// their setHWnd() methods
if (blockerPeer instanceof WFileDialogPeer) {
((WFileDialogPeer)blockerPeer).blockWindow(this);
} else if (blockerPeer instanceof WPrintDialogPeer) {
((WPrintDialogPeer)blockerPeer).blockWindow(this);
} else {
modalDisable(dialog, blockerPeer.getHWnd());
}
} else {
modalBlocker = null;
if (blockerPeer instanceof WFileDialogPeer) {
((WFileDialogPeer)blockerPeer).unblockWindow(this);
} else if (blockerPeer instanceof WPrintDialogPeer) {
((WPrintDialogPeer)blockerPeer).unblockWindow(this);
} else {
modalEnable(dialog);
}
}
}
}
native void modalDisable(Dialog blocker, long blockerHWnd);
native void modalEnable(Dialog blocker);
/*
* Returns all the ever active windows from the current AppContext.
* The list is sorted by the time of activation, so the latest
* active window is always at the end.
*/
public static long[] getActiveWindowHandles() {
AppContext appContext = AppContext.getAppContext();
synchronized (appContext) {
List<WWindowPeer> l = (List<WWindowPeer>)appContext.get(ACTIVE_WINDOWS_KEY);
if (l == null) {
return null;
}
long[] result = new long[l.size()];
for (int j = 0; j < l.size(); j++) {
result[j] = l.get(j).getHWnd();
}
return result;
}
}
/*
* ----DISPLAY CHANGE SUPPORT----
*/
/*
* Called from native code when we have been dragged onto another screen.
*/
void draggedToNewScreen() {
SunToolkit.executeOnEventHandlerThread((Component)target,new Runnable()
{
public void run() {
displayChanged();
}
});
}
public void updateGC() {
int scrn = getScreenImOn();
if (screenLog.isLoggable(PlatformLogger.FINER)) {
log.finer("Screen number: " + scrn);
}
// get current GD
Win32GraphicsDevice oldDev = (Win32GraphicsDevice)winGraphicsConfig
.getDevice();
Win32GraphicsDevice newDev;
GraphicsDevice devs[] = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getScreenDevices();
// Occasionally during device addition/removal getScreenImOn can return
// a non-existing screen number. Use the default device in this case.
if (scrn >= devs.length) {
newDev = (Win32GraphicsDevice)GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice();
} else {
newDev = (Win32GraphicsDevice)devs[scrn];
}
// Set winGraphicsConfig to the default GC for the monitor this Window
// is now mostly on.
winGraphicsConfig = (Win32GraphicsConfig)newDev
.getDefaultConfiguration();
if (screenLog.isLoggable(PlatformLogger.FINE)) {
if (winGraphicsConfig == null) {
screenLog.fine("Assertion (winGraphicsConfig != null) failed");
}
}
// if on a different display, take off old GD and put on new GD
if (oldDev != newDev) {
oldDev.removeDisplayChangedListener(this);
newDev.addDisplayChangedListener(this);
}
AWTAccessor.getComponentAccessor().
setGraphicsConfiguration((Component)target, winGraphicsConfig);
}
/**
* From the DisplayChangedListener interface.
*
* This method handles a display change - either when the display settings
* are changed, or when the window has been dragged onto a different
* display.
* Called after a change in the display mode. This event
* triggers replacing the surfaceData object (since that object
* reflects the current display depth information, which has
* just changed).
*/
public void displayChanged() {
updateGC();
}
/**
* Part of the DisplayChangedListener interface: components
* do not need to react to this event
*/
public void paletteChanged() {
}
private native int getScreenImOn();
// Used in Win32GraphicsDevice.
public final native void setFullScreenExclusiveModeState(boolean state);
/*
* ----END DISPLAY CHANGE SUPPORT----
*/
public void grab() {
nativeGrab();
}
public void ungrab() {
nativeUngrab();
}
private native void nativeGrab();
private native void nativeUngrab();
private final boolean hasWarningWindow() {
return ((Window)target).getWarningString() != null;
}
boolean isTargetUndecorated() {
return true;
}
// These are the peer bounds. They get updated at:
// 1. the WWindowPeer.setBounds() method.
// 2. the native code (on WM_SIZE/WM_MOVE)
private volatile int sysX = 0;
private volatile int sysY = 0;
private volatile int sysW = 0;
private volatile int sysH = 0;
public native void repositionSecurityWarning();
@Override
public void setBounds(int x, int y, int width, int height, int op) {
sysX = x;
sysY = y;
sysW = width;
sysH = height;
super.setBounds(x, y, width, height, op);
}
@Override
public void print(Graphics g) {
// We assume we print the whole frame,
// so we expect no clip was set previously
Shape shape = AWTAccessor.getWindowAccessor().getShape((Window)target);
if (shape != null) {
g.setClip(shape);
}
super.print(g);
}
private void replaceSurfaceDataRecursively(Component c) {
if (c instanceof Container) {
for (Component child : ((Container)c).getComponents()) {
replaceSurfaceDataRecursively(child);
}
}
ComponentPeer cp = c.getPeer();
if (cp instanceof WComponentPeer) {
((WComponentPeer)cp).replaceSurfaceDataLater();
}
}
public final Graphics getTranslucentGraphics() {
synchronized (getStateLock()) {
return isOpaque ? null : painter.getBackBuffer(false).getGraphics();
}
}
@Override
public void setBackground(Color c) {
super.setBackground(c);
synchronized (getStateLock()) {
if (!isOpaque && ((Window)target).isVisible()) {
updateWindow(true);
}
}
}
private native void setOpacity(int iOpacity);
private float opacity = 1.0f;
public void setOpacity(float opacity) {
if (!((SunToolkit)((Window)target).getToolkit()).
isWindowOpacitySupported())
{
return;
}
if (opacity < 0.0f || opacity > 1.0f) {
throw new IllegalArgumentException(
"The value of opacity should be in the range [0.0f .. 1.0f].");
}
if (((this.opacity == 1.0f && opacity < 1.0f) ||
(this.opacity < 1.0f && opacity == 1.0f)) &&
!Win32GraphicsEnvironment.isVistaOS())
{
// non-Vista OS: only replace the surface data if opacity status
// changed (see WComponentPeer.isAccelCapable() for more)
replaceSurfaceDataRecursively((Component)getTarget());
}
this.opacity = opacity;
final int maxOpacity = 0xff;
int iOpacity = (int)(opacity * maxOpacity);
if (iOpacity < 0) {
iOpacity = 0;
}
if (iOpacity > maxOpacity) {
iOpacity = maxOpacity;
}
setOpacity(iOpacity);
synchronized (getStateLock()) {
if (!isOpaque && ((Window)target).isVisible()) {
updateWindow(true);
}
}
}
private native void setOpaqueImpl(boolean isOpaque);
public void setOpaque(boolean isOpaque) {
synchronized (getStateLock()) {
if (this.isOpaque == isOpaque) {
return;
}
}
Window target = (Window)getTarget();
if (!isOpaque) {
SunToolkit sunToolkit = (SunToolkit)target.getToolkit();
if (!sunToolkit.isWindowTranslucencySupported() ||
!sunToolkit.isTranslucencyCapable(target.getGraphicsConfiguration()))
{
return;
}
}
boolean isVistaOS = Win32GraphicsEnvironment.isVistaOS();
if (this.isOpaque != isOpaque && !isVistaOS) {
// non-Vista OS: only replace the surface data if the opacity
// status changed (see WComponentPeer.isAccelCapable() for more)
replaceSurfaceDataRecursively(target);
}
synchronized (getStateLock()) {
this.isOpaque = isOpaque;
setOpaqueImpl(isOpaque);
if (isOpaque) {
TranslucentWindowPainter currentPainter = painter;
if (currentPainter != null) {
currentPainter.flush();
painter = null;
}
} else {
painter = TranslucentWindowPainter.createInstance(this);
}
}
if (isVistaOS) {
// On Vista: setting the window non-opaque makes the window look
// rectangular, though still catching the mouse clicks within
// its shape only. To restore the correct visual appearance
// of the window (i.e. w/ the correct shape) we have to reset
// the shape.
Shape shape = ((Window)target).getShape();
if (shape != null) {
((Window)target).setShape(shape);
}
}
if (((Window)target).isVisible()) {
updateWindow(true);
}
}
public native void updateWindowImpl(int[] data, int width, int height);
public void updateWindow() {
updateWindow(false);
}
private void updateWindow(boolean repaint) {
Window w = (Window)target;
synchronized (getStateLock()) {
if (isOpaque || !w.isVisible() ||
(w.getWidth() <= 0) || (w.getHeight() <= 0))
{
return;
}
TranslucentWindowPainter currentPainter = painter;
if (currentPainter != null) {
currentPainter.updateWindow(repaint);
} else if (log.isLoggable(PlatformLogger.FINER)) {
log.finer("Translucent window painter is null in updateWindow");
}
}
}
/*
* The method maps the list of the active windows to the window's AppContext,
* then the method registers ActiveWindowListener, GuiDisposedListener listeners;
* it executes the initilialization only once per AppContext.
*/
private static void initActiveWindowsTracking(Window w) {
AppContext appContext = AppContext.getAppContext();
synchronized (appContext) {
List<WWindowPeer> l = (List<WWindowPeer>)appContext.get(ACTIVE_WINDOWS_KEY);
if (l == null) {
l = new LinkedList<WWindowPeer>();
appContext.put(ACTIVE_WINDOWS_KEY, l);
appContext.addPropertyChangeListener(AppContext.GUI_DISPOSED, guiDisposedListener);
KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
kfm.addPropertyChangeListener("activeWindow", activeWindowListener);
}
}
}
/*
* The GuiDisposedListener class listens for the AppContext.GUI_DISPOSED property,
* it removes the list of the active windows from the disposed AppContext and
* unregisters ActiveWindowListener listener.
*/
private static class GuiDisposedListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
boolean isDisposed = (Boolean)e.getNewValue();
if (isDisposed != true) {
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine(" Assertion (newValue != true) failed for AppContext.GUI_DISPOSED ");
}
}
AppContext appContext = AppContext.getAppContext();
synchronized (appContext) {
appContext.remove(ACTIVE_WINDOWS_KEY);
appContext.removePropertyChangeListener(AppContext.GUI_DISPOSED, this);
KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
kfm.removePropertyChangeListener("activeWindow", activeWindowListener);
}
}
}
/*
* Static inner class, listens for 'activeWindow' KFM property changes and
* updates the list of active windows per AppContext, so the latest active
* window is always at the end of the list. The list is stored in AppContext.
*/
private static class ActiveWindowListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
Window w = (Window)e.getNewValue();
if (w == null) {
return;
}
AppContext appContext = SunToolkit.targetToAppContext(w);
synchronized (appContext) {
WWindowPeer wp = (WWindowPeer)w.getPeer();
// add/move wp to the end of the list
List<WWindowPeer> l = (List<WWindowPeer>)appContext.get(ACTIVE_WINDOWS_KEY);
if (l != null) {
l.remove(wp);
l.add(wp);
}
}
}
}
}
| rokn/Count_Words_2015 | testing/openjdk/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java | Java | mit | 27,167 |
/*!
* Bootstrap v3.2.0 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') }
/* ========================================================================
* Bootstrap: transition.js v3.2.0
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.2.0
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.2.0'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.hasClass('alert') ? $this : $this.parent()
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.2.0
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.2.0'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
$el[val](data[state] == null ? this.options[state] : data[state])
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
e.preventDefault()
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', e.type == 'focus')
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.2.0
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element).on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused =
this.sliding =
this.interval =
this.$active =
this.$items = null
this.options.pause == 'hover' && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.2.0'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true
}
Carousel.prototype.keydown = function (e) {
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var delta = direction == 'prev' ? -1 : 1
var activeIndex = this.getItemIndex(active)
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var fallback = type == 'next' ? 'first' : 'last'
var that = this
if (!$next.length) {
if (!this.options.wrap) return
$next = this.$element.find('.item')[fallback]()
}
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
$(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
})
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.2.0
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.transitioning = null
if (this.options.parent) this.$parent = $(this.options.parent)
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.2.0'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var actives = this.$parent && this.$parent.find('> .panel > .in')
if (actives && actives.length) {
var hasData = actives.data('bs.collapse')
if (hasData && hasData.transitioning) return
Plugin.call(actives, 'hide')
hasData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.trigger('hidden.bs.collapse')
.removeClass('collapsing')
.addClass('collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && option == 'show') option = !option
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var href
var $this = $(this)
var target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
var $target = $(target)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
var parent = $this.attr('data-parent')
var $parent = parent && $(parent)
if (!data || !data.transitioning) {
if ($parent) $parent.find('[data-toggle="collapse"][data-parent="' + parent + '"]').not($this).addClass('collapsed')
$this.toggleClass('collapsed', $target.hasClass('in'))
}
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.2.0
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.2.0'
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger('shown.bs.dropdown', relatedTarget)
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27)/.test(e.keyCode)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive || (isActive && e.keyCode == 27)) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.divider):visible a'
var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
if (!$items.length) return
var index = $items.index($items.filter(':focus'))
if (e.keyCode == 38 && index > 0) index-- // up
if (e.keyCode == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
})
}
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle + ', [role="menu"], [role="listbox"]', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.2.0
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$backdrop =
this.isShown = null
this.scrollbarWidth = 0
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.2.0'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.$body.addClass('modal-open')
this.setScrollbar()
this.escape()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.$body.removeClass('modal-open')
this.resetScrollbar()
this.escape()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(this.$body)
this.$element.on('mousedown.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
Modal.prototype.checkScrollbar = function () {
if (document.body.clientWidth >= window.innerWidth) return
this.scrollbarWidth = this.scrollbarWidth || this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
if (this.scrollbarWidth) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', '')
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.2.0
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.2.0'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(document.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var $parent = this.$element.parent()
var parentDim = this.getPosition($parent)
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - parentDim.scroll > parentDim.height ? 'top' :
placement == 'top' && pos.top - parentDim.scroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < parentDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var arrowDelta = delta.left ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowPosition = delta.left ? 'left' : 'top'
var arrowOffsetPosition = delta.left ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], arrowPosition)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, position) {
this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function () {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
this.$element.removeAttr('aria-describedby')
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element.trigger('hidden.bs.' + that.type)
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var isSvg = window.SVGElement && el instanceof window.SVGElement
var elRect = el.getBoundingClientRect ? el.getBoundingClientRect() : null
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isSvg ? {} : {
width: isBody ? $(window).width() : $element.outerWidth(),
height: isBody ? $(window).height() : $element.outerHeight()
}
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
return (this.$tip = this.$tip || $(this.options.template))
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.validate = function () {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function () {
clearTimeout(this.timeout)
this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.2.0
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.2.0'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').empty()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
Popover.prototype.tip = function () {
if (!this.$tip) this.$tip = $(this.options.template)
return this.$tip
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.2.0
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
this.$body = $('body')
this.$scrollElement = $(element).is('body') ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', process)
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.2.0'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var offsetMethod = 'offset'
var offsetBase = 0
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
var self = this
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop <= offsets[0]) {
return activeTarget != (i = targets[0]) && this.activate(i)
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.2.0
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.VERSION = '3.2.0'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: previous
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
})
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.2.0
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin =
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.2.0'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && colliderTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = $('body').height()
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom) data.offset.bottom = data.offsetBottom
if (data.offsetTop) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
| Czarnodziej/final-omnislash | web/assetic/bootstrap_js.js | JavaScript | mit | 62,681 |
import { ColorPalette20 } from "../../";
export = ColorPalette20;
| markogresak/DefinitelyTyped | types/carbon__icons-react/lib/color-palette/20.d.ts | TypeScript | mit | 67 |
/**
* Copyright (c) 2010-2016, openHAB.org and others.
*
* 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.intertechno.internal;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Extension of the default OSGi bundle activator
*
* @author Till Klocke
* @since 1.4.0
*/
public final class CULIntertechnoActivator implements BundleActivator {
private static Logger logger = LoggerFactory.getLogger(CULIntertechnoActivator.class);
private static BundleContext context;
/**
* Called whenever the OSGi framework starts our bundle
*/
@Override
public void start(BundleContext bc) throws Exception {
context = bc;
logger.debug("CULIntertechno binding has been started.");
}
/**
* Called whenever the OSGi framework stops our bundle
*/
@Override
public void stop(BundleContext bc) throws Exception {
context = null;
logger.debug("CULIntertechno binding has been stopped.");
}
/**
* Returns the bundle context of this bundle
*
* @return the bundle context
*/
public static BundleContext getContext() {
return context;
}
}
| paolodenti/openhab | bundles/binding/org.openhab.binding.intertechno/src/main/java/org/openhab/binding/intertechno/internal/CULIntertechnoActivator.java | Java | epl-1.0 | 1,485 |
/*global $:false*/
define([
"manager",
"constants",
"lang",
"generator"
], function(manager, C, L, generator) {
"use strict";
/**
* @name Composite
* @description JS code for the Composite Data Type.
* @see DataType
* @namespace
*/
/* @private */
var MODULE_ID = "data-type-Composite";
var LANG = L.dataTypePlugins.Composite;
var _validate = function(rows) {
var visibleProblemRows = [];
var problemFields = [];
for (var i=0; i<rows.length; i++) {
if ($("#dtOption_" + rows[i]).val() === "") {
var visibleRowNum = generator.getVisibleRowOrderByRowNum(rows[i]);
visibleProblemRows.push(visibleRowNum);
problemFields.push($("#option_" + rows[i]));
}
}
var errors = [];
if (visibleProblemRows.length) {
errors.push({ els: problemFields, error: L.AlphaNumeric_incomplete_fields + " <b>" + visibleProblemRows.join(", ") + "</b>"});
}
return errors;
};
var _loadRow = function(rowNum, data) {
return {
execute: function() {
$("#dtExample_" + rowNum).val(data.example);
$("#dtOption_" + rowNum).val(data.option);
},
isComplete: function() { return $("#dtOption_" + rowNum).length > 0; }
};
};
var _saveRow = function(rowNum) {
return {
"example": $("#dtExample_" + rowNum).val(),
"option": $("#dtOption_" + rowNum).val()
};
};
manager.registerDataType(MODULE_ID, {
validate: _validate,
loadRow: _loadRow,
saveRow: _saveRow
});
});
| vivekmalikymca/generatedata | plugins/dataTypes/Composite/Composite.js | JavaScript | gpl-3.0 | 1,444 |
define(["../SimpleTheme", "./common"], function(SimpleTheme, themes){
themes.Minty = new SimpleTheme({
colors: [
"#80ccbb",
"#539e8b",
"#335f54",
"#8dd1c2",
"#68c5ad"
]
});
return themes.Minty;
});
| avz-cmf/zaboy-middleware | www/js/dojox/charting/themes/Minty.js | JavaScript | gpl-3.0 | 220 |
define(
({
"preview": "Anteprima"
})
);
| avz-cmf/zaboy-middleware | www/js/dojox/editor/plugins/nls/it/Preview.js | JavaScript | gpl-3.0 | 41 |
module SearchesHelper
def show_birthdays?
return false unless params[:birthday]
params[:birthday][:month].present? ||
params[:birthday][:day].present?
end
def show_testimonies?
params[:testimony].present?
end
def types_for_select
t('search.form.types').invert.to_a +
(Setting.get(:features, :custom_person_type) ? Person.custom_types : [])
end
def search_path(*args)
if params[:controller] == 'searches' and params[:family_id] and @family
family_search_path(*args)
else
super
end
end
end
| davidleach/onebody | app/helpers/searches_helper.rb | Ruby | agpl-3.0 | 557 |
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.indentation;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
/**
* Handler for try blocks.
*
* @author jrichard
*/
public class TryHandler extends BlockParentHandler {
/**
* Construct an instance of this handler with the given indentation check,
* abstract syntax tree, and parent handler.
*
* @param indentCheck the indentation check
* @param ast the abstract syntax tree
* @param parent the parent handler
*/
public TryHandler(IndentationCheck indentCheck,
DetailAST ast, AbstractExpressionHandler parent) {
super(indentCheck, "try", ast, parent);
}
@Override
public IndentLevel suggestedChildLevel(AbstractExpressionHandler child) {
if (child instanceof CatchHandler
|| child instanceof FinallyHandler) {
return getLevel();
}
return super.suggestedChildLevel(child);
}
}
| attatrol/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler.java | Java | lgpl-2.1 | 2,009 |
# 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
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.compute.base import NodeAuthPassword
ECSDriver = get_driver(Provider.ALIYUN_ECS)
region = 'cn-hangzhou'
your_access_key_id = ''
your_access_key_secret = ''
ecs = ECSDriver(your_access_key_id, your_access_key_secret, region=region)
sizes = ecs.list_sizes()
small = sizes[1]
locations = ecs.list_locations()
location = None
for each in locations:
if each.id == region:
location = each
break
if location is None:
print('could not find cn-qingdao location')
sys.exit(-1)
print(location.name)
images = ecs.list_images()
print('Found %d images' % len(images))
for each in images:
if 'ubuntu' in each.id.lower():
image = each
break
else:
image = images[0]
print('Use image %s' % image)
sgs = ecs.ex_list_security_groups()
print('Found %d security groups' % len(sgs))
if len(sgs) == 0:
sg = ecs.ex_create_security_group(description='test')
print('Create security group %s' % sg)
else:
sg = sgs[0].id
print('Use security group %s' % sg)
nodes = ecs.list_nodes()
print('Found %d nodes' % len(nodes))
if len(nodes) == 0:
print('Starting create a new node')
data_disk = {
'size': 5,
'category': ecs.disk_categories.CLOUD,
'disk_name': 'data_disk1',
'delete_with_instance': True}
auth = NodeAuthPassword('P@$$w0rd')
ex_internet_charge_type = ecs.internet_charge_types.BY_TRAFFIC
node = ecs.create_node(image=image, size=small, name='test',
ex_security_group_id=sg,
ex_internet_charge_type=ex_internet_charge_type,
ex_internet_max_bandwidth_out=1,
ex_data_disk=data_disk,
auth=auth)
print('Created node %s' % node)
nodes = ecs.list_nodes()
for each in nodes:
print('Found node %s' % each)
| StackPointCloud/libcloud | demos/example_aliyun_ecs.py | Python | apache-2.0 | 2,755 |
// 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.
#nullable disable
using System;
using System.Diagnostics;
using System.IO;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class TempDirectory
{
private readonly string _path;
private readonly TempRoot _root;
protected TempDirectory(TempRoot root)
: this(CreateUniqueDirectory(TempRoot.Root), root)
{
}
private TempDirectory(string path, TempRoot root)
{
Debug.Assert(path != null);
Debug.Assert(root != null);
_path = path;
_root = root;
}
private static string CreateUniqueDirectory(string basePath)
{
while (true)
{
string dir = System.IO.Path.Combine(basePath, Guid.NewGuid().ToString());
try
{
Directory.CreateDirectory(dir);
return dir;
}
catch (IOException)
{
// retry
}
}
}
public string Path
{
get { return _path; }
}
/// <summary>
/// Creates a file in this directory.
/// </summary>
/// <param name="name">File name.</param>
public TempFile CreateFile(string name)
{
string filePath = System.IO.Path.Combine(_path, name);
TempRoot.CreateStream(filePath, FileMode.CreateNew);
return _root.AddFile(new DisposableFile(filePath));
}
/// <summary>
/// Creates a file or opens an existing file in this directory.
/// </summary>
public TempFile CreateOrOpenFile(string name)
{
string filePath = System.IO.Path.Combine(_path, name);
TempRoot.CreateStream(filePath, FileMode.OpenOrCreate);
return _root.AddFile(new DisposableFile(filePath));
}
/// <summary>
/// Creates a file in this directory that is a copy of the specified file.
/// </summary>
public TempFile CopyFile(string originalPath, string name = null)
{
string filePath = System.IO.Path.Combine(_path, name ?? System.IO.Path.GetFileName(originalPath));
File.Copy(originalPath, filePath);
return _root.AddFile(new DisposableFile(filePath));
}
/// <summary>
/// Creates a subdirectory in this directory.
/// </summary>
/// <param name="name">Directory name or unrooted directory path.</param>
public TempDirectory CreateDirectory(string name)
{
string dirPath = System.IO.Path.Combine(_path, name);
Directory.CreateDirectory(dirPath);
return new TempDirectory(dirPath, _root);
}
public override string ToString()
{
return _path;
}
}
}
| brettfo/roslyn | src/Test/Utilities/Portable/TempFiles/TempDirectory.cs | C# | apache-2.0 | 3,117 |
<table id="<?php echo $id ?>" width="100%">
<?php if (isset($options['title'])): ?>
<tr><td bgcolor="<?php echo $op_color["core_color_5"] ?>">
<font color="<?php echo $op_color["core_color_25"] ?>"><?php echo $options['title'] ?></font><br>
</td></tr>
<?php else: ?>
<tr><td bgcolor="<?php echo $op_color["core_color_7"] ?>">
<hr color="<?php echo $op_color["core_color_12"] ?>">
</td></tr>
<?php endif; ?>
<?php foreach ($options['list'] as $key => $value): ?>
<tr><td bgcolor="<?php echo cycle_vars($id, $op_color["core_color_6"].','.$op_color["core_color_7"]) ?>">
<?php echo $options['list']->getRaw($key) ?><br>
</td></tr>
<?php if (!empty($options['border'])): ?>
<tr><td bgcolor="<?php echo $op_color["core_color_7"] ?>">
<hr color="<?php echo $op_color["core_color_12"] ?>">
</td></tr>
<?php endif; ?>
<?php endforeach; ?>
<?php if (isset($options['moreInfo'])): ?>
<tr><td align="right">
<?php foreach ($options['moreInfo'] as $key => $value): ?>
<?php echo $options['moreInfo']->getRaw($key) ?><br>
<?php endforeach; ?>
</td></tr>
<?php endif; ?>
</table>
<br>
| smart-e/lifemap | apps/mobile_frontend/templates/_partsListBox.php | PHP | apache-2.0 | 1,074 |
/*
* 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 sample.eventing;
import org.apache.axiom.om.OMElement;
public class ListnerService2 {
String name = "ListnerService2";
public void publish(OMElement param) throws Exception {
System.out.println("\n");
System.out.println("'" + name + "' got a new publication...");
System.out.println(param);
System.out.println("\n");
}
}
| Nipuni/wso2-axis2 | modules/samples/eventing/src/sample/eventing/ListnerService2.java | Java | apache-2.0 | 1,154 |
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
class MyArray extends Array { }
Object.prototype[Symbol.species] = MyArray;
delete Array[Symbol.species];
__v_1 = Math.pow(2, 31);
__v_2 = [];
__v_2[__v_1] = 31;
__v_4 = [];
__v_4[__v_1 - 2] = 33;
assertThrows(() => __v_2.concat(__v_4), RangeError);
| weolar/miniblink49 | v8_7_5/test/mjsunit/regress/regress-crbug-592340.js | JavaScript | apache-2.0 | 418 |
/*
* 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.wso2.andes.client.message;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import javax.jms.JMSException;
import javax.jms.MessageEOFException;
import javax.jms.MessageFormatException;
import javax.jms.MessageNotReadableException;
import javax.jms.MessageNotWriteableException;
import org.apache.mina.common.ByteBuffer;
import org.wso2.andes.AMQException;
import org.wso2.andes.framing.AMQShortString;
import org.wso2.andes.framing.BasicContentHeaderProperties;
/**
* @author Apache Software Foundation
*/
public abstract class AbstractBytesTypedMessage extends AbstractBytesMessage
{
protected static final byte BOOLEAN_TYPE = (byte) 1;
protected static final byte BYTE_TYPE = (byte) 2;
protected static final byte BYTEARRAY_TYPE = (byte) 3;
protected static final byte SHORT_TYPE = (byte) 4;
protected static final byte CHAR_TYPE = (byte) 5;
protected static final byte INT_TYPE = (byte) 6;
protected static final byte LONG_TYPE = (byte) 7;
protected static final byte FLOAT_TYPE = (byte) 8;
protected static final byte DOUBLE_TYPE = (byte) 9;
protected static final byte STRING_TYPE = (byte) 10;
protected static final byte NULL_STRING_TYPE = (byte) 11;
/**
* This is set when reading a byte array. The readBytes(byte[]) method supports multiple calls to read
* a byte array in multiple chunks, hence this is used to track how much is left to be read
*/
private int _byteArrayRemaining = -1;
AbstractBytesTypedMessage(AMQMessageDelegateFactory delegateFactory)
{
this(delegateFactory, null);
}
/**
* Construct a stream message with existing data.
*
* @param delegateFactory
* @param data the data that comprises this message. If data is null, you get a 1024 byte buffer that is
*/
AbstractBytesTypedMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data)
{
super(delegateFactory, data); // this instanties a content header
}
AbstractBytesTypedMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
{
super(delegate, data);
}
protected byte readWireType() throws MessageFormatException, MessageEOFException,
MessageNotReadableException
{
checkReadable();
checkAvailable(1);
return _data.get();
}
protected void writeTypeDiscriminator(byte type) throws MessageNotWriteableException
{
checkWritable();
_data.put(type);
_changedData = true;
}
protected boolean readBoolean() throws JMSException
{
int position = _data.position();
byte wireType = readWireType();
boolean result;
try
{
switch (wireType)
{
case BOOLEAN_TYPE:
checkAvailable(1);
result = readBooleanImpl();
break;
case STRING_TYPE:
checkAvailable(1);
result = Boolean.parseBoolean(readStringImpl());
break;
default:
_data.position(position);
throw new MessageFormatException("Unable to convert " + wireType + " to a boolean");
}
return result;
}
catch (RuntimeException e)
{
_data.position(position);
throw e;
}
}
private boolean readBooleanImpl()
{
return _data.get() != 0;
}
protected byte readByte() throws JMSException
{
int position = _data.position();
byte wireType = readWireType();
byte result;
try
{
switch (wireType)
{
case BYTE_TYPE:
checkAvailable(1);
result = readByteImpl();
break;
case STRING_TYPE:
checkAvailable(1);
result = Byte.parseByte(readStringImpl());
break;
default:
_data.position(position);
throw new MessageFormatException("Unable to convert " + wireType + " to a byte");
}
}
catch (RuntimeException e)
{
_data.position(position);
throw e;
}
return result;
}
private byte readByteImpl()
{
return _data.get();
}
protected short readShort() throws JMSException
{
int position = _data.position();
byte wireType = readWireType();
short result;
try
{
switch (wireType)
{
case SHORT_TYPE:
checkAvailable(2);
result = readShortImpl();
break;
case STRING_TYPE:
checkAvailable(1);
result = Short.parseShort(readStringImpl());
break;
case BYTE_TYPE:
checkAvailable(1);
result = readByteImpl();
break;
default:
_data.position(position);
throw new MessageFormatException("Unable to convert " + wireType + " to a short");
}
}
catch (RuntimeException e)
{
_data.position(position);
throw e;
}
return result;
}
private short readShortImpl()
{
return _data.getShort();
}
/**
* Note that this method reads a unicode character as two bytes from the stream
*
* @return the character read from the stream
* @throws javax.jms.JMSException
*/
protected char readChar() throws JMSException
{
int position = _data.position();
byte wireType = readWireType();
try
{
if(wireType == NULL_STRING_TYPE){
throw new NullPointerException();
}
if (wireType != CHAR_TYPE)
{
_data.position(position);
throw new MessageFormatException("Unable to convert " + wireType + " to a char");
}
else
{
checkAvailable(2);
return readCharImpl();
}
}
catch (RuntimeException e)
{
_data.position(position);
throw e;
}
}
private char readCharImpl()
{
return _data.getChar();
}
protected int readInt() throws JMSException
{
int position = _data.position();
byte wireType = readWireType();
int result;
try
{
switch (wireType)
{
case INT_TYPE:
checkAvailable(4);
result = readIntImpl();
break;
case SHORT_TYPE:
checkAvailable(2);
result = readShortImpl();
break;
case STRING_TYPE:
checkAvailable(1);
result = Integer.parseInt(readStringImpl());
break;
case BYTE_TYPE:
checkAvailable(1);
result = readByteImpl();
break;
default:
_data.position(position);
throw new MessageFormatException("Unable to convert " + wireType + " to an int");
}
return result;
}
catch (RuntimeException e)
{
_data.position(position);
throw e;
}
}
protected int readIntImpl()
{
return _data.getInt();
}
protected long readLong() throws JMSException
{
int position = _data.position();
byte wireType = readWireType();
long result;
try
{
switch (wireType)
{
case LONG_TYPE:
checkAvailable(8);
result = readLongImpl();
break;
case INT_TYPE:
checkAvailable(4);
result = readIntImpl();
break;
case SHORT_TYPE:
checkAvailable(2);
result = readShortImpl();
break;
case STRING_TYPE:
checkAvailable(1);
result = Long.parseLong(readStringImpl());
break;
case BYTE_TYPE:
checkAvailable(1);
result = readByteImpl();
break;
default:
_data.position(position);
throw new MessageFormatException("Unable to convert " + wireType + " to a long");
}
return result;
}
catch (RuntimeException e)
{
_data.position(position);
throw e;
}
}
private long readLongImpl()
{
return _data.getLong();
}
protected float readFloat() throws JMSException
{
int position = _data.position();
byte wireType = readWireType();
float result;
try
{
switch (wireType)
{
case FLOAT_TYPE:
checkAvailable(4);
result = readFloatImpl();
break;
case STRING_TYPE:
checkAvailable(1);
result = Float.parseFloat(readStringImpl());
break;
default:
_data.position(position);
throw new MessageFormatException("Unable to convert " + wireType + " to a float");
}
return result;
}
catch (RuntimeException e)
{
_data.position(position);
throw e;
}
}
private float readFloatImpl()
{
return _data.getFloat();
}
protected double readDouble() throws JMSException
{
int position = _data.position();
byte wireType = readWireType();
double result;
try
{
switch (wireType)
{
case DOUBLE_TYPE:
checkAvailable(8);
result = readDoubleImpl();
break;
case FLOAT_TYPE:
checkAvailable(4);
result = readFloatImpl();
break;
case STRING_TYPE:
checkAvailable(1);
result = Double.parseDouble(readStringImpl());
break;
default:
_data.position(position);
throw new MessageFormatException("Unable to convert " + wireType + " to a double");
}
return result;
}
catch (RuntimeException e)
{
_data.position(position);
throw e;
}
}
private double readDoubleImpl()
{
return _data.getDouble();
}
protected String readString() throws JMSException
{
int position = _data.position();
byte wireType = readWireType();
String result;
try
{
switch (wireType)
{
case STRING_TYPE:
checkAvailable(1);
result = readStringImpl();
break;
case NULL_STRING_TYPE:
result = null;
throw new NullPointerException("data is null");
case BOOLEAN_TYPE:
checkAvailable(1);
result = String.valueOf(readBooleanImpl());
break;
case LONG_TYPE:
checkAvailable(8);
result = String.valueOf(readLongImpl());
break;
case INT_TYPE:
checkAvailable(4);
result = String.valueOf(readIntImpl());
break;
case SHORT_TYPE:
checkAvailable(2);
result = String.valueOf(readShortImpl());
break;
case BYTE_TYPE:
checkAvailable(1);
result = String.valueOf(readByteImpl());
break;
case FLOAT_TYPE:
checkAvailable(4);
result = String.valueOf(readFloatImpl());
break;
case DOUBLE_TYPE:
checkAvailable(8);
result = String.valueOf(readDoubleImpl());
break;
case CHAR_TYPE:
checkAvailable(2);
result = String.valueOf(readCharImpl());
break;
default:
_data.position(position);
throw new MessageFormatException("Unable to convert " + wireType + " to a String");
}
return result;
}
catch (RuntimeException e)
{
_data.position(position);
throw e;
}
}
protected String readStringImpl() throws JMSException
{
try
{
return _data.getString(Charset.forName("UTF-8").newDecoder());
}
catch (CharacterCodingException e)
{
JMSException jmse = new JMSException("Error decoding byte stream as a UTF8 string: " + e);
jmse.setLinkedException(e);
jmse.initCause(e);
throw jmse;
}
}
protected int readBytes(byte[] bytes) throws JMSException
{
if (bytes == null)
{
throw new IllegalArgumentException("byte array must not be null");
}
checkReadable();
// first call
if (_byteArrayRemaining == -1)
{
// type discriminator checked separately so you get a MessageFormatException rather than
// an EOF even in the case where both would be applicable
checkAvailable(1);
byte wireType = readWireType();
if (wireType != BYTEARRAY_TYPE)
{
throw new MessageFormatException("Unable to convert " + wireType + " to a byte array");
}
checkAvailable(4);
int size = _data.getInt();
// length of -1 indicates null
if (size == -1)
{
return -1;
}
else
{
if (size > _data.remaining())
{
throw new MessageEOFException("Byte array has stated length " + size + " but message only contains " +
_data.remaining() + " bytes");
}
else
{
_byteArrayRemaining = size;
}
}
}
else if (_byteArrayRemaining == 0)
{
_byteArrayRemaining = -1;
return -1;
}
int returnedSize = readBytesImpl(bytes);
if (returnedSize < bytes.length)
{
_byteArrayRemaining = -1;
}
return returnedSize;
}
private int readBytesImpl(byte[] bytes)
{
int count = (_byteArrayRemaining >= bytes.length ? bytes.length : _byteArrayRemaining);
_byteArrayRemaining -= count;
if (count == 0)
{
return 0;
}
else
{
_data.get(bytes, 0, count);
return count;
}
}
protected Object readObject() throws JMSException
{
int position = _data.position();
byte wireType = readWireType();
Object result = null;
try
{
switch (wireType)
{
case BOOLEAN_TYPE:
checkAvailable(1);
result = readBooleanImpl();
break;
case BYTE_TYPE:
checkAvailable(1);
result = readByteImpl();
break;
case BYTEARRAY_TYPE:
checkAvailable(4);
int size = _data.getInt();
if (size == -1)
{
result = null;
}
else
{
_byteArrayRemaining = size;
byte[] bytesResult = new byte[size];
readBytesImpl(bytesResult);
result = bytesResult;
}
break;
case SHORT_TYPE:
checkAvailable(2);
result = readShortImpl();
break;
case CHAR_TYPE:
checkAvailable(2);
result = readCharImpl();
break;
case INT_TYPE:
checkAvailable(4);
result = readIntImpl();
break;
case LONG_TYPE:
checkAvailable(8);
result = readLongImpl();
break;
case FLOAT_TYPE:
checkAvailable(4);
result = readFloatImpl();
break;
case DOUBLE_TYPE:
checkAvailable(8);
result = readDoubleImpl();
break;
case NULL_STRING_TYPE:
result = null;
break;
case STRING_TYPE:
checkAvailable(1);
result = readStringImpl();
break;
}
return result;
}
catch (RuntimeException e)
{
_data.position(position);
throw e;
}
}
protected void writeBoolean(boolean b) throws JMSException
{
writeTypeDiscriminator(BOOLEAN_TYPE);
_data.put(b ? (byte) 1 : (byte) 0);
}
protected void writeByte(byte b) throws JMSException
{
writeTypeDiscriminator(BYTE_TYPE);
_data.put(b);
}
protected void writeShort(short i) throws JMSException
{
writeTypeDiscriminator(SHORT_TYPE);
_data.putShort(i);
}
protected void writeChar(char c) throws JMSException
{
writeTypeDiscriminator(CHAR_TYPE);
_data.putChar(c);
}
protected void writeInt(int i) throws JMSException
{
writeTypeDiscriminator(INT_TYPE);
writeIntImpl(i);
}
protected void writeIntImpl(int i)
{
_data.putInt(i);
}
protected void writeLong(long l) throws JMSException
{
writeTypeDiscriminator(LONG_TYPE);
_data.putLong(l);
}
protected void writeFloat(float v) throws JMSException
{
writeTypeDiscriminator(FLOAT_TYPE);
_data.putFloat(v);
}
protected void writeDouble(double v) throws JMSException
{
writeTypeDiscriminator(DOUBLE_TYPE);
_data.putDouble(v);
}
protected void writeString(String string) throws JMSException
{
if (string == null)
{
writeTypeDiscriminator(NULL_STRING_TYPE);
}
else
{
writeTypeDiscriminator(STRING_TYPE);
try
{
writeStringImpl(string);
}
catch (CharacterCodingException e)
{
JMSException jmse = new JMSException("Unable to encode string: " + e);
jmse.setLinkedException(e);
jmse.initCause(e);
throw jmse;
}
}
}
protected void writeStringImpl(String string)
throws CharacterCodingException
{
_data.putString(string, Charset.forName("UTF-8").newEncoder());
// we must write the null terminator ourselves
_data.put((byte) 0);
}
protected void writeBytes(byte[] bytes) throws JMSException
{
writeBytes(bytes, 0, bytes == null ? 0 : bytes.length);
}
protected void writeBytes(byte[] bytes, int offset, int length) throws JMSException
{
writeTypeDiscriminator(BYTEARRAY_TYPE);
if (bytes == null)
{
_data.putInt(-1);
}
else
{
_data.putInt(length);
_data.put(bytes, offset, length);
}
}
protected void writeObject(Object object) throws JMSException
{
checkWritable();
Class clazz;
if (object == null)
{
// string handles the output of null values
clazz = String.class;
}
else
{
clazz = object.getClass();
}
if (clazz == Byte.class)
{
writeByte((Byte) object);
}
else if (clazz == Boolean.class)
{
writeBoolean((Boolean) object);
}
else if (clazz == byte[].class)
{
writeBytes((byte[]) object);
}
else if (clazz == Short.class)
{
writeShort((Short) object);
}
else if (clazz == Character.class)
{
writeChar((Character) object);
}
else if (clazz == Integer.class)
{
writeInt((Integer) object);
}
else if (clazz == Long.class)
{
writeLong((Long) object);
}
else if (clazz == Float.class)
{
writeFloat((Float) object);
}
else if (clazz == Double.class)
{
writeDouble((Double) object);
}
else if (clazz == String.class)
{
writeString((String) object);
}
else
{
throw new MessageFormatException("Only primitives plus byte arrays and String are valid types");
}
}
}
| hastef88/andes | modules/andes-core/client/src/main/java/org/wso2/andes/client/message/AbstractBytesTypedMessage.java | Java | apache-2.0 | 23,169 |