repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
emundus/v6 | plugins/fabrik_element/captcha/layouts/fabrik-element-captcha-nocaptcha.php | 247 | <?php
defined('JPATH_BASE') or die;
$d = $displayData;
?>
<div class ="g-recaptcha" data-sitekey="<?php echo $d->site_key; ?>"></div>
<script src="https://www.google.com/recaptcha/api.js?hl=<?php echo $d->lang; ?>" async defer></script> | gpl-2.0 |
CERT-Polska/n6sdk | n6sdk/data_spec/__init__.py | 26527 | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2016 NASK. All rights reserved.
"""
.. note::
For basic information how to use the classes defined in this module
-- please consult the :ref:`data_spec_class` chapter of the tutorial.
"""
import collections
from pyramid.decorator import reify
from n6sdk.data_spec.fields import (
Field,
AnonymizedIPv4Field,
ASNField,
CCField,
DateTimeField,
DomainNameField,
DomainNameSubstringField,
EmailSimplifiedField,
ExtendedAddressField,
IBANSimplifiedField,
IntegerField,
IPv4Field,
IPv4NetField,
IPv6Field,
IPv6NetField,
ListOfDictsField,
MD5Field,
PortField,
SHA1Field,
SourceField,
UnicodeEnumField,
UnicodeLimitedField,
URLField,
URLSubstringField,
)
from n6sdk.exceptions import (
FieldValueError,
ParamKeyCleaningError,
ParamValueCleaningError,
ResultKeyCleaningError,
ResultValueCleaningError,
_KeyCleaningErrorMixin,
)
#
# Constants
#: A tuple of network incident data distribution restriction qualifiers
#: -- used in the :attr:`DataSpec.restriction` field specification.
RESTRICTION_ENUMS = (
'public', 'need-to-know', 'internal',
)
#: A tuple of network incident data confidence qualifiers
#: -- used in the :attr:`DataSpec.confidence` field specification.
CONFIDENCE_ENUMS = (
'low', 'medium', 'high',
)
#: A tuple of network incident category labels
#: -- used in the :attr:`DataSpec.category` field specification.
CATEGORY_ENUMS = (
'amplifier',
'bots',
'backdoor',
'cnc',
'dns-query',
'dos-attacker',
'dos-victim',
'flow',
'flow-anomaly',
'fraud',
'leak',
'malurl',
'malware-action',
'phish',
'proxy',
'sandbox-url',
'scanning',
'server-exploit',
'spam',
'spam-url',
'tor',
'vulnerable',
'webinject',
'other',
)
#: A tuple of network incident layer-#4-protocol labels
#: -- used in the :attr:`DataSpec.proto` field specification.
PROTO_ENUMS = (
'tcp', 'udp', 'icmp',
)
#: A tuple of network incident origin labels
#: -- used in the :attr:`DataSpec.origin` field specification.
ORIGIN_ENUMS = (
'c2',
'dropzone',
'proxy',
'p2p-crawler',
'p2p-drone',
'sinkhole',
'sandbox',
'honeypot',
'darknet',
'av',
'ids',
'waf',
)
#: A tuple of black list item status qualifiers
#: -- used in the :attr:`DataSpec.status` field specification.
STATUS_ENUMS = (
'active', 'delisted', 'expired', 'replaced',
)
#
# Auxiliary classes
class Ext(dict):
"""
An auxiliary class of a :class:`dict`-like container -- to be used
to extend field specifications in :class:`DataSpec` subclasses (for
usage examples, see the descriptions of :class:`DataSpec` and
:class:`AllSearchableDataSpec`).
"""
def __repr__(self):
return '{}({})'.format(self.__class__.__name__,
super(Ext, self).__repr__())
def copy(self):
return self.__class__(self)
def make_extended_field(self, field):
merged_init_kwargs = self.copy()
merged_init_kwargs.nondestructive_update(field._init_kwargs)
return field.__class__(**merged_init_kwargs)
def nondestructive_update(self, other):
if isinstance(other, collections.Mapping):
other = other.iteritems()
for key, value in other:
stored_value = self.setdefault(key, value)
if (stored_value is not value) and isinstance(stored_value, Ext):
if isinstance(value, Field):
self[key] = stored_value.make_extended_field(value)
elif isinstance(value, collections.Mapping):
merged_value = stored_value.copy()
merged_value.nondestructive_update(value)
self[key] = merged_value
#
# The abstract base class for any data specification classes
class BaseDataSpec(object):
"""
The base class for data specification classes.
Typically, you will not instantiate or subclass this class directly
-- instead, you may want to use :class:`DataSpec` or, more likely, a
subclass of it.
"""
def __init__(self, **kwargs):
self._all_param_fields = {}
self._required_param_fields = {}
self._single_param_fields = {}
self._all_result_fields = {}
self._required_result_fields = {}
self._set_fields()
super(BaseDataSpec, self).__init__(**kwargs)
#
# public properties
@reify
def all_keys(self):
"""
Instance property: a :class:`frozenset` of all keys.
(Includes all legal parameter names and result keys.)
"""
return self.all_param_keys | self.all_result_keys
@reify
def all_param_keys(self):
"""
Instance property: a :class:`frozenset` of all legal parameter names.
"""
return frozenset(self._all_param_fields)
@reify
def all_result_keys(self):
"""
Instance property: a :class:`frozenset` of all legal result keys.
"""
return frozenset(self._all_result_fields)
#
# public methods (possibly extendable)
#: .. note::
#: The method should **never** modify the given dictionary (or any
#: of its values). It should always return a new dictionary.
def clean_param_dict(self, params,
# optional keyword arguments:
ignored_keys=(),
forbidden_keys=(),
extra_required_keys=(),
discarded_keys=()):
keys = self._clean_keys(
params.viewkeys() - frozenset(ignored_keys),
self._all_param_fields.viewkeys() - frozenset(forbidden_keys),
self._required_param_fields.viewkeys() | frozenset(extra_required_keys),
frozenset(discarded_keys),
exc_class=ParamKeyCleaningError)
return dict(self._iter_clean_param_items(params, keys))
#: .. note::
#: The method should **never** modify the given dictionary (or any
#: of its values).
def clean_param_keys(self, params,
# optional keyword arguments:
ignored_keys=(),
forbidden_keys=(),
extra_required_keys=(),
discarded_keys=()):
return self._clean_keys(
params.viewkeys() - frozenset(ignored_keys),
self._all_param_fields.viewkeys() - frozenset(forbidden_keys),
self._required_param_fields.viewkeys() | frozenset(extra_required_keys),
frozenset(discarded_keys),
exc_class=ParamKeyCleaningError)
def param_field_specs(self, which='all', multi=True, single=True):
field_items = self._filter_by_which(which,
self._all_param_fields,
self._required_param_fields)
if not multi:
field_items &= self._single_param_fields.viewitems()
if not single:
field_items -= self._single_param_fields.viewitems()
return dict(field_items)
#: .. note::
#: The method should **never** modify the given dictionary (or any
#: of its values). It should always return a new dictionary.
def clean_result_dict(self, result,
# optional keyword arguments:
ignored_keys=(),
forbidden_keys=(),
extra_required_keys=(),
discarded_keys=()):
keys = self._clean_keys(
result.viewkeys() - frozenset(ignored_keys),
self._all_result_fields.viewkeys() - frozenset(forbidden_keys),
self._required_result_fields.viewkeys() | frozenset(extra_required_keys),
frozenset(discarded_keys),
exc_class=ResultKeyCleaningError)
return dict(self._iter_clean_result_items(result, keys))
#: .. note::
#: The method should **never** modify the given dictionary (or any
#: of its values).
def clean_result_keys(self, result,
# optional keyword arguments:
ignored_keys=(),
forbidden_keys=(),
extra_required_keys=(),
discarded_keys=()):
return self._clean_keys(
result.viewkeys() - frozenset(ignored_keys),
self._all_result_fields.viewkeys() - frozenset(forbidden_keys),
self._required_result_fields.viewkeys() | frozenset(extra_required_keys),
frozenset(discarded_keys),
exc_class=ResultKeyCleaningError)
def result_field_specs(self, which='all'):
return dict(self._filter_by_which(which,
self._all_result_fields,
self._required_result_fields))
#
# overridable/extendable methods
def get_adjusted_field(self, key, field, ext=None):
if ext is not None:
field = ext.make_extended_field(field)
return field
#
# non-public internals
def _set_fields(self):
key_to_field = {}
for key, field in self._iter_all_field_specs():
key = key.decode('ascii')
key_to_field[key] = field
if field.in_params is not None:
self._all_param_fields[key] = field
if field.in_params == 'required':
self._required_param_fields[key] = field
else:
assert field.in_params == 'optional'
if field.single_param:
self._single_param_fields[key] = field
if field.in_result is not None:
self._all_result_fields[key] = field
if field.in_result == 'required':
self._required_result_fields[key] = field
else:
assert field.in_result == 'optional'
# making all fields (including those Ext-updated)
# accessible also as instance attributes
vars(self).update(key_to_field)
def _iter_all_field_specs(self):
key_to_ext = collections.defaultdict(Ext)
seen_keys = set()
attr_containers = (self,) + self.__class__.__mro__
for ac in attr_containers:
for key, obj in vars(ac).iteritems():
if isinstance(obj, Ext):
key_to_ext[key].nondestructive_update(obj)
continue
if key in seen_keys:
continue
seen_keys.add(key)
if isinstance(obj, Field):
field_ext = key_to_ext.get(key)
field = self.get_adjusted_field(key, obj, field_ext)
yield key, field
for extra in self._iter_extra_param_specs(key, field):
yield extra
def _iter_extra_param_specs(self, key, parent_field):
for key_suffix, xfield in parent_field.extra_params.iteritems():
if xfield is None:
# field was masked ("removed") using Ext, e.g. in a subclass
continue
if not isinstance(xfield, Field):
raise TypeError('{!r} is not a {!r} instance'
.format(xfield, Field))
xkey = '{}.{}'.format(key, key_suffix)
xfield = self.get_adjusted_field(xkey, xfield)
yield xkey, xfield
# recursive yielding:
for extra in self._iter_extra_param_specs(xkey, xfield):
yield extra
@staticmethod
def _clean_keys(keys, legal_keys, required_keys, discarded_keys,
exc_class):
illegal_keys = keys - legal_keys
missing_keys = required_keys - keys
if illegal_keys or missing_keys:
assert issubclass(exc_class, _KeyCleaningErrorMixin)
raise exc_class(illegal_keys, missing_keys)
return {key.decode('ascii') for key in (keys - discarded_keys)}
def _iter_clean_param_items(self, params, keys):
error_info_seq = []
for key in keys:
assert key in self._all_param_fields
assert key in params
field = self._all_param_fields[key]
param_values = params[key]
assert param_values and type(param_values) is list
assert hasattr(field, 'single_param')
if field.single_param and len(param_values) > 1:
error_info_seq.append((
key,
param_values,
FieldValueError(public_message=(
u'Multiple values for a single-value-only field.'))
))
else:
cleaned_values = []
for value in param_values:
try:
cleaned_val = field.clean_param_value(value)
except Exception as exc:
error_info_seq.append((key, value, exc))
else:
cleaned_values.append(cleaned_val)
if cleaned_values:
yield key, cleaned_values
if error_info_seq:
raise ParamValueCleaningError(error_info_seq)
def _iter_clean_result_items(self, result, keys):
error_info_seq = []
for key in keys:
assert key in self._all_result_fields
assert key in result
field = self._all_result_fields[key]
value = result[key]
try:
yield key, field.clean_result_value(value)
except Exception as exc:
error_info_seq.append((key, value, exc))
if error_info_seq:
raise ResultValueCleaningError(error_info_seq)
@staticmethod
def _filter_by_which(which, all_fields, required_fields):
# select fields that match the `which` argument
if which == 'all':
return all_fields.viewitems()
elif which == 'required':
return required_fields.viewitems()
elif which == 'optional':
return all_fields.viewitems() - required_fields.viewitems()
else:
raise ValueError("{!r} is not one of: 'all', 'required', 'optional'"
.format(which))
#
# Concrete data specification base classes
class DataSpec(BaseDataSpec):
"""
The basic, ready-to-use, data specification class.
Typically, you will want to create a subclass of it (note that, by
default, all fields are *disabled as query parameters*, so you may
want to *enable* some of them). For example::
class MyDataSpec(DataSpec):
# enable `source` as a query parameter
source = Ext(in_params='optional')
# enable the `time.min` and `time.until` query parameters
# (leaving `time.max` still disabled)
time = Ext(
extra_params=Ext(
min=Ext(in_params='optional'),
until=Ext(in_params='optional'),
),
)
# enable `fqdn` and `fqdn.sub` as query parameters
# and add a new query parameter: `fqdn.prefix`
fqdn = Ext(
in_params='optional',
extra_params=Ext(
sub=Ext(in_params='optional'),
prefix=DomainNameSubstringField(in_params='optional'),
),
)
# completely disable the `modified` field
modified = None
# add a new field
weekday = UnicodeEnumField(
in_params='optional',
in_result='optional',
enum_values=(
'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday'),
),
)
.. seealso::
Compare this class with :class:`AllSearchableDataSpec`.
"""
#
# Fields that are always *required in results*
id = UnicodeLimitedField(
in_result='required',
max_length=64,
)
source = SourceField(
in_result='required',
)
restriction = UnicodeEnumField(
in_result='required',
enum_values=RESTRICTION_ENUMS,
)
confidence = UnicodeEnumField(
in_result='required',
enum_values=CONFIDENCE_ENUMS,
)
category = UnicodeEnumField(
in_result='required',
enum_values=CATEGORY_ENUMS,
)
time = DateTimeField(
in_params=None, # <- should be None even in subclasses
in_result='required',
extra_params=dict(
min=DateTimeField( # `time.min`
single_param=True,
),
max=DateTimeField( # `time.max`
single_param=True,
),
until=DateTimeField( # `time.until`
single_param=True,
),
),
)
#
# Fields related to `address`
# an `address` is a list of dicts -- each containing either
# `ip` or `ipv6` (but not both) and optionally some or all of:
# `asn`, `cc`, `dir`, `rdns`
address = ExtendedAddressField(
in_params=None, # <- should be None even in subclasses
in_result='optional',
)
# query params related to the components of `address` items
ip = IPv4Field(
in_result=None, # <- should be None even in subclasses
extra_params=dict(
net=IPv4NetField(), # `ip.net`
),
)
ipv6 = IPv6Field(
in_result=None, # <- should be None even in subclasses
extra_params=dict(
net=IPv6NetField(), # `ipv6.net`
),
)
asn = ASNField(
in_result=None, # <- should be None even in subclasses
)
cc = CCField(
in_result=None, # <- should be None even in subclasses
)
#
# Fields related only to black list events
active = Field(
in_params=None, # <- should be None even in subclasses
in_result=None, # <- typically will be None even in subclasses
extra_params=dict(
min=DateTimeField( # `active.min`
single_param=True,
),
max=DateTimeField( # `active.max`
single_param=True,
),
until=DateTimeField( # `active.until`
single_param=True,
),
),
)
expires = DateTimeField(
in_params=None, # <- should be None even in subclasses
in_result='optional',
)
replaces = UnicodeLimitedField(
in_result='optional',
max_length=64,
)
status = UnicodeEnumField(
in_result='optional',
enum_values=STATUS_ENUMS,
)
#
# Fields related only to aggregated (high frequency) events
count = IntegerField(
in_params=None, # <- should be None even in subclasses
in_result='optional',
min_value=0,
max_value=(2 ** 15 - 1),
)
until = DateTimeField(
in_params=None, # <- should be None even in subclasses
in_result='optional',
)
#
# Other fields
action = UnicodeLimitedField(
in_result='optional',
max_length=32,
)
adip = AnonymizedIPv4Field(
in_result='optional',
)
dip = IPv4Field(
in_result='optional',
)
dport = PortField(
in_result='optional',
)
email = EmailSimplifiedField(
in_result='optional',
)
fqdn = DomainNameField(
in_result='optional',
extra_params=dict(
sub=DomainNameSubstringField(), # `fqdn.sub`
),
)
iban = IBANSimplifiedField(
in_result='optional',
)
injects = ListOfDictsField(
in_params=None, # <- should be None even in subclasses
in_result='optional',
)
md5 = MD5Field(
in_result='optional',
)
modified = DateTimeField(
in_params=None, # <- should be None even in subclasses
in_result='optional',
extra_params=dict(
min=DateTimeField( # `modified.min`
single_param=True,
),
max=DateTimeField( # `modified.max`
single_param=True,
),
until=DateTimeField( # `modified.until`
single_param=True,
),
),
)
name = UnicodeLimitedField(
in_result='optional',
max_length=255,
)
origin = UnicodeEnumField(
in_result='optional',
enum_values=ORIGIN_ENUMS,
)
phone = UnicodeLimitedField(
in_result='optional',
max_length=20,
)
proto = UnicodeEnumField(
in_result='optional',
enum_values=PROTO_ENUMS,
)
registrar = UnicodeLimitedField(
in_result='optional',
max_length=100,
)
sha1 = SHA1Field(
in_result='optional',
)
sport = PortField(
in_result='optional',
)
target = UnicodeLimitedField(
in_result='optional',
max_length=100,
)
url = URLField(
in_result='optional',
extra_params=dict(
sub=URLSubstringField(), # `url.sub`
),
)
url_pattern = UnicodeLimitedField(
in_result='optional',
max_length=255,
disallow_empty=True,
)
username = UnicodeLimitedField(
in_result='optional',
max_length=64,
)
x509fp_sha1 = SHA1Field(
in_result='optional',
)
class AllSearchableDataSpec(DataSpec):
"""
A :class:`DataSpec` subclass with most of its fields marked as searchable.
You may want to use this class instead of :class:`DataSpec` if your
data backend makes it easy to search by various event attributes
(all relevant ones or most of them).
Typically, you will want to create your own subclass of
:class:`AllSearchableDataSpec` (especially to *disable* some
searchable parameters). For example::
class MyDataSpec(AllSearchableDataSpec):
# disable `source` as a query parameter
source = Ext(in_params=None)
# disable the `time.max` query parameter
# (leaving `time.min` and `time.until` still enabled)
time = Ext(
extra_params=Ext(
max=Ext(in_params=None),
),
)
# disable the `fqdn.sub` query parameter and, at the
# same time, add a new query parameter: `fqdn.prefix`
fqdn = Ext(
extra_params=Ext(
sub=Ext(in_params=None),
prefix=DomainNameSubstringField(in_params='optional'),
),
)
# completely disable the `modified` field (together with the
# related "extra params": `modified.min` etc.)
modified = None
# add a new field
weekday = UnicodeEnumField(
in_params='optional',
in_result='optional',
enum_values=(
'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday'),
),
)
.. seealso::
Compare this class with :class:`DataSpec`.
"""
#
# Fields that are always *required in results*
id = Ext(in_params='optional')
source = Ext(in_params='optional')
restriction = Ext(in_params='optional')
confidence = Ext(in_params='optional')
category = Ext(in_params='optional')
time = Ext(
extra_params=Ext(
min=Ext(in_params='optional'),
max=Ext(in_params='optional'),
until=Ext(in_params='optional'),
),
)
#
# Fields related to `address`
# (the `address` field from the superclass remains unchanged)
ip = Ext(
in_params='optional',
extra_params=Ext(
net=Ext(in_params='optional'),
),
)
ipv6 = Ext(
in_params='optional',
extra_params=Ext(
net=Ext(in_params='optional'),
),
)
asn = Ext(in_params='optional')
cc = Ext(in_params='optional')
#
# Fields related only to black list events
active = Ext(
extra_params=Ext(
min=Ext(in_params='optional'),
max=Ext(in_params='optional'),
until=Ext(in_params='optional'),
),
)
# (the `expires` field from the superclass remains unchanged)
replaces = Ext(in_params='optional')
status = Ext(in_params='optional')
#
# Fields related only to aggregated (high frequency) events
# (the `count` field from the superclass remains unchanged)
# (the `until` field from the superclass remains unchanged)
#
# Other fields
action = Ext(in_params='optional')
# (the `adip` field from the superclass remains unchanged)
dip = Ext(in_params='optional')
dport = Ext(in_params='optional')
email = Ext(in_params='optional')
fqdn = Ext(
in_params='optional',
extra_params=Ext(
sub=Ext(in_params='optional'),
),
)
iban = Ext(in_params='optional')
# (the `injects` field from the superclass remains unchanged)
md5 = Ext(in_params='optional')
modified = Ext(
extra_params=Ext(
min=Ext(in_params='optional'),
max=Ext(in_params='optional'),
until=Ext(in_params='optional'),
),
)
name = Ext(in_params='optional')
origin = Ext(in_params='optional')
phone = Ext(in_params='optional')
proto = Ext(in_params='optional')
registrar = Ext(in_params='optional')
sha1 = Ext(in_params='optional')
sport = Ext(in_params='optional')
target = Ext(in_params='optional')
url = Ext(
in_params='optional',
extra_params=Ext(
sub=Ext(in_params='optional'),
),
)
url_pattern = Ext(in_params='optional')
username = Ext(in_params='optional')
x509fp_sha1 = Ext(in_params='optional')
| gpl-2.0 |
zturtleman/mm3d | src/implui/animexportwin.cc | 9198 | /* Maverick Model 3D
*
* Copyright (c) 2004-2007 Kevin Worcester
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*
* See the COPYING file for full license text.
*/
#include "animexportwin.h"
#include "helpwin.h"
#include "viewpanel.h"
#include "model.h"
#include "mview.h"
#include "3dmprefs.h"
#include "misc.h"
#include "texture.h"
#include "texmgr.h"
#include "msg.h"
#include "mm3dport.h"
#include <unistd.h>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QLabel>
#include <QtWidgets/QShortcut>
#include <QtWidgets/QSpinBox>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QRadioButton>
#include <QtWidgets/QComboBox>
#include <QtGui/QImage>
#include <QtWidgets/QShortcut>
AnimExportWindow::AnimExportWindow( Model * model, ViewPanel * viewPanel, QWidget * parent )
: QDialog( parent ),
m_model( model ),
m_viewPanel( viewPanel )
{
setModal( true );
setupUi( this );
QString path = QString::fromUtf8( g_prefs( "ui_animexport_dir" ).stringValue().c_str() );
if ( g_prefs.exists( "ui_animexport_format" ) )
{
int f = g_prefs( "ui_animexport_format" ).intValue();
if ( f >= 0 && f < m_formatValue->count() )
{
m_formatValue->setCurrentIndex( f );
}
}
if ( g_prefs.exists( "ui_animexport_framerate" ) )
{
double fps = g_prefs( "ui_animexport_framerate" ).doubleValue();
if ( fps > 0.0001 )
{
char fpsStr[20] = "";
PORT_snprintf( fpsStr, sizeof(fpsStr), "%f", fps );
m_frameRateValue->setText( QString(fpsStr) );
}
}
if ( g_prefs.exists( "ui_animexport_seconds" ) )
{
int sec = g_prefs( "ui_animexport_seconds" ).intValue();
if ( sec > 0 )
{
char secStr[20] = "";
PORT_snprintf( secStr, sizeof(secStr), "%d", sec );
m_secondsValue->setText( QString(secStr) );
}
}
if ( g_prefs.exists( "ui_animexport_iterations" ) )
{
int iterations = g_prefs( "ui_animexport_iterations" ).intValue();
if ( iterations > 0 )
{
char itStr[20] = "";
PORT_snprintf( itStr, sizeof(itStr), "%d", iterations );
m_iterationsValue->setText( QString(itStr) );
}
}
if ( m_model )
{
bool labelAnims = false;
unsigned scount = m_model->getAnimCount( Model::ANIMMODE_SKELETAL );
unsigned fcount = m_model->getAnimCount( Model::ANIMMODE_FRAME );
if ( scount > 0 && fcount > 0 )
{
labelAnims = true;
}
unsigned a = 0;
for ( a = 0; a < scount; a++ )
{
QString name = labelAnims ? tr( "Skeletal - ", "Skeletal Animation prefix" ) : QString("");
name += m_model->getAnimName( Model::ANIMMODE_SKELETAL, a );
m_animValue->insertItem( a, name );
}
for ( a = 0; a < fcount; a++ )
{
QString name = labelAnims ? tr( "Frame - ", "Frame Animation prefix" ) : QString("");
name += m_model->getAnimName( Model::ANIMMODE_FRAME, a );
m_animValue->insertItem( scount + a, name );
}
const char * filename = m_model->getFilename();
if ( path.isNull() || path.isEmpty() )
{
std::string fullName = "";
std::string fullPath = "";
std::string baseName = "";
normalizePath( filename, fullName, fullPath, baseName );
if ( is_directory( fullPath.c_str() ) )
{
path = fullPath.c_str();
}
}
}
if ( path.isNull() || path.isEmpty() )
{
char * cwd = PORT_get_current_dir_name();
if ( cwd )
{
path = cwd;
free( cwd );
}
}
m_directoryLabel->setText( path );
if ( m_viewPanel )
{
int index = -1;
unsigned count = m_viewPanel->getModelViewCount();
for ( unsigned m = 0; m < count; m++ )
{
ModelView * v = m_viewPanel->getModelView( m );
QString name = tr( "[None]", "No viewport for animation image export" );
if ( v )
{
name = tr("Viewport %1 - ").arg(m+1);
name += v->getViewDirectionLabel();
if ( index == -1 && v->getViewDirection() == 0 )
{
index = m;
}
}
m_viewportValue->insertItem( m, name );
}
if ( index >= 0 )
{
m_viewportValue->setCurrentIndex( index );
}
}
QShortcut * help = new QShortcut( QKeySequence( tr("F1", "Help Shortcut")), this );
connect( help, SIGNAL(activated()), this, SLOT(helpNowEvent()) );
}
AnimExportWindow::~AnimExportWindow()
{
}
void AnimExportWindow::helpNowEvent()
{
HelpWin * win = new HelpWin( "olh_animexportwin.html", true );
win->show();
}
void AnimExportWindow::accept()
{
if ( m_viewPanel == NULL || m_model == NULL )
{
return;
}
ModelView * v = m_viewPanel->getModelView( m_viewportValue->currentIndex() );
if ( v == NULL )
{
return;
}
if ( !v->m_modelView->isValid() )
{
// invalid opengl context
return;
}
Model::AnimationModeE mode = Model::ANIMMODE_SKELETAL;
unsigned a = m_animValue->currentIndex();
if ( a >= m_model->getAnimCount( mode ) )
{
a -= m_model->getAnimCount( mode );
mode = Model::ANIMMODE_FRAME;
}
double fps = m_model->getAnimFPS( mode, a );
double spf = ( 1.0 / fps );
double duration = 0.0;
double tm = 0.0;
double outfps = m_frameRateValue->text().toDouble();
if ( outfps < 0.0001 )
{
msg_warning( (const char *) tr("Must have more than 0 frames per second").toUtf8() );
return;
}
double interval = (1.0 / outfps);
if ( m_timeButton->isChecked() )
{
duration = m_secondsValue->text().toDouble();
}
else
{
duration = spf
* m_iterationsValue->text().toInt()
* m_model->getAnimFrameCount( mode, a );
}
if ( duration <= 0.0 )
{
msg_warning( (const char *) tr("Must have more than 0 seconds of animation").toUtf8() );
return;
}
QString path = m_directoryLabel->text();
if ( is_directory( path.toUtf8() ) )
{
g_prefs( "ui_animexport_dir" ) = (const char *) path.toUtf8();
g_prefs( "ui_animexport_format" ) = m_formatValue->currentIndex();
g_prefs( "ui_animexport_framerate" ) = m_frameRateValue->text().toDouble();
g_prefs( "ui_animexport_seconds" ) = m_secondsValue->text().toInt();
g_prefs( "ui_animexport_iterations" ) = m_iterationsValue->text().toInt();
bool enable = m_model->setUndoEnabled( false );
m_model->setCurrentAnimation( mode, a );
int frameNum = 0;
char formatStr[20] = "";
QString saveFormat = QString( "JPEG" );
switch ( m_formatValue->currentIndex() )
{
case 0:
strcpy( formatStr, "%s/anim_%04d.jpg" );
break;
case 1:
strcpy( formatStr, "%s/anim_%d.jpg" );
break;
case 2:
strcpy( formatStr, "%s/anim_%04d.png" );
saveFormat = QString( "PNG" );
break;
case 3:
default:
strcpy( formatStr, "%s/anim_%d.png" );
saveFormat = QString( "PNG" );
break;
}
this->hide();
bool prompt = true;
bool keepGoing = true;
while ( keepGoing && tm <= duration )
{
m_model->setCurrentAnimationTime( tm );
v->updateCaptureGL();
frameNum++;
QString file = QString::asprintf( formatStr, (const char *) path.toUtf8(), frameNum );
QImage img = v->grabFramebuffer();
if ( !img.save( file, saveFormat.toUtf8(), 100 ) && prompt )
{
QString msg = tr( "Could not write file: " ) + QString("\n");
msg += file;
msg_error( (const char *) msg.toUtf8() );
keepGoing = false;
}
tm += interval;
}
m_model->setNoAnimation();
m_model->setUndoEnabled( enable );
v->updateView();
QDialog::accept();
}
else
{
msg_warning( (const char *) tr("Output directory does not exist.").toUtf8() );
}
}
void AnimExportWindow::reject()
{
QDialog::reject();
}
void AnimExportWindow::directoryButtonClicked()
{
QString dir = QFileDialog::getExistingDirectory( this, "Select an output directory", m_directoryLabel->text() );
if ( ! dir.isNull() && ! dir.isEmpty() )
{
m_directoryLabel->setText( dir );
}
}
| gpl-2.0 |
AlexKotikov/calcWithBrackets | src/org/kotikov/calc/PageBuilder.java | 8010 | package org.kotikov.calc;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.text.Position;
/*
*
Класс
преобразует: [4|1+2, 3|*3, 2|+4, 1|-5, 0|/6]
В структуру:
[4|1+2, 3|*3, 2|+4, 1|-5, 0|/6]
1|--------
4|1+2
2|--------
3|*3
3|--------
2|+4
4|--------
1|-5
5|--------
1|{4}
0|/6
-------------
Обработанный объект выглядит так, он больше не нужен
0|{5}
3|{2}
2|{3}
-1|
-1|
//кластер - это последовательность строчек из ArrayList по которым будует строиться часть дерева в соответсвии
//с правилами.
*/
public class PageBuilder implements Iterator {
private static final char LINKMARKER = '{';
private static final char MARKEREND = '}';
private static final char PAGESEPARATOR = '=';
private List<InstructionsLine> instructions;
private int position =0; //позиция элемента в коллекции для итератора
private int numberOfPage =0 ; //счетчик страниц
public PageBuilder(List<InstructionsLine> instructions) {
this.instructions = instructions;
}
public Iterator<InstructionsLine> createIterator(){
return this.buildPages().iterator();
}
public List<InstructionsLine> getPages()
{
return this.buildPages();
}
public Iterator<InstructionsLine> createIteratorForTesting(){
return this.instructions.iterator();
}
@Override
public boolean hasNext() {
if (position < this.instructions.size()) return true;
return false;
}
@Override
public Object next() {
InstructionsLine obj = this.instructions.get(position);
position++;
return obj;
}
@Override
public void remove() {
try {
throw new Exception ("Deleting is not allowed");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//[0|{5}, 4|{1}, 3|{2}, 2|{3}, -1|, -1|]
public boolean isInstructionCalculated (){
for (int i=0; i < this.instructions.size();i++){
if (this.instructions.get(i).treelevel !=-1)
if (this.instructions.get(i).expression.charAt(0) !=LINKMARKER)
return false;
}
return true;
}
private List<InstructionsLine> buildPages() {
List<InstructionsLine> result = new ArrayList<InstructionsLine>();
while (!this.isInstructionCalculated()) {
numberOfPage++;
result.add( //добавлять разделитель страницы
new InstructionsLine(numberOfPage, Character.toString(PAGESEPARATOR)+"==="));
result.addAll(this.buildPage());
}
return result;
}
private int getWeightOfFirstNode()
{
int max = 0;
for (int i=0; i < instructions.size() ; i++) {
if ((max < instructions.get(i).treelevel)
&& (instructions.get(i).expression.charAt(0)!=LINKMARKER))
max = instructions.get(i).treelevel;
}
//первый - это максимальный
return max;
}
private int getNumberOfLineOfFirstNodeInList()
{
int max = 0;
int index =0;
for (int i=0; i < instructions.size() ; i++) {
if ((max < instructions.get(i).treelevel)
&& (instructions.get(i).expression.charAt(0)!=LINKMARKER))
{
max = instructions.get(i).treelevel;
index = i; }
}
ExpressionCalculator calc = new ExpressionCalculator("");
if (index>0)
if ( calc.canBeCalculated(instructions.get(index).expression))
if ( ( instructions.get(index-1).treelevel == max-1 )
&& (( instructions.get(index-1).expression.charAt( instructions.get(index-1).expression.length()-1)=='-')
||
( instructions.get(index-1).expression.charAt( instructions.get(index-1).expression.length()-1)=='+')
||
( instructions.get(index-1).expression.charAt( instructions.get(index-1).expression.length()-1)=='/')
||
( instructions.get(index-1).expression.charAt( instructions.get(index-1).expression.length()-1)=='*')
)) {
instructions.get(index-1).treelevel = max;
index--;
}
//первый - это максимальный
return index;
}
private List<InstructionsLine> buildPage() {
List<InstructionsLine> kit = new ArrayList<InstructionsLine>();
int weight = getWeightOfFirstNode() ;
int firstLineIndex = getNumberOfLineOfFirstNodeInList();
//Просмотр списка от первого элемента с самым высоким индексом до конца списка
//Возможно что весь список состоит из таких элементов
for (int i=firstLineIndex; i < this.instructions.size();i++)
{
//Найти элемент-обломок если он стоит сразу до приоритетного элемента
//Изменить ему индекс на приоритетный и выйти из цикла чтобы в след. раз его забрать
String test = this.instructions.get(i).expression;
//Если нашли одиноко стоящий знак то надо его пометить иначе внешний while цикл никогда не закончится
if (this.instructions.get(i).treelevel == weight-1 )
if (this.instructions.get(i).expression.length()==1)
{
this.instructions.set(i,
new InstructionsLine(weight, LINKMARKER+ Integer.toString(numberOfPage)+MARKEREND+this.instructions.get(i).expression ) );
}
else if (weight>0) break;
//Если нашли ссылку {0} то пропускать, а не пытаться переписывать
if ((this.instructions.get(i).treelevel == 0)
&& (weight==0 )
&& (this.instructions.get(i).expression.charAt(0)==LINKMARKER))
continue;
//Добавить если нашли 1) элемент 2)маркер
if ( (this.instructions.get(i).treelevel==weight ) //это элемент
|| //это маркер
((this.instructions.get(i).treelevel==weight+1 )
&& ((this.instructions.get(i).expression.charAt(0)==LINKMARKER))))
{
kit.add(this.instructions.get(i)); //добавить в набор
this.instructions.set(i,new InstructionsLine(-1,"")); //и "удалить" из входящего набора
}
else
continue;
}
//добавляет метки чтобы потом составить\сшить по ним узлы дерева арифметического выражения
this.instructions.set(firstLineIndex,
new InstructionsLine(weight, LINKMARKER+ Integer.toString(numberOfPage)+MARKEREND ));
return kit;
}
public static void main(String[] args) throws Exception {
InstructionsBuilder instr = new InstructionsBuilder
("-1-(5-((22+22)*4-((2+1)+(-20-3)/3+(-21-2))-4*(22+22)))");
PageBuilder claster =new PageBuilder(instr.makeInstructionsFromExpression());
instr.show(instr.makeInstructionsFromExpression());
System.out.println();
Iterator<InstructionsLine> iter = claster.createIterator();
while (iter.hasNext())
{
System.out.println(iter.next());
}
}
}
| gpl-2.0 |
prosthetichead/Arcadia | Arcadia/TextChanger.cpp | 640 | #include "TextChanger.h"
TextChanger::TextChanger(assetHandle* ah_ref )
{
ah = ah_ref;
changeTimer = 0;
index = 0;
}
TextChanger::~TextChanger(void)
{
}
void TextChanger::setText(std::vector<std::string> textVector, int speed)
{
text = textVector;
changeSpeed = speed;
changeTimer = 0;
index = 0;
}
void TextChanger::update()
{
changeTimer++;
if (changeTimer >= changeSpeed) {
index++;
changeTimer = 0;
}
if (index > text.size()-1)
index = 0;
}
void TextChanger::draw(sf::RenderWindow &window, SkinHandle::Skin_Element &skin_item)
{
if (!text.empty()) {
ah->drawText(text.at(index), skin_item, window);
}
} | gpl-2.0 |
aaronr/Quantum-GIS | src/app/legend/qgsapplegendinterface.cpp | 3811 | /***************************************************************************
qgsapplegendinterface.cpp
--------------------------------------
Date : 19-Nov-2009
Copyright : (C) 2009 by Andres Manz
Email : manz dot andres at gmail dot com
****************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/* $Id$ */
#include "qgsapplegendinterface.h"
#include "qgslegend.h"
#include "qgslegendlayer.h"
#include "qgsmaplayer.h"
QgsAppLegendInterface::QgsAppLegendInterface( QgsLegend * legend )
: mLegend( legend )
{
connect( legend, SIGNAL( itemMoved( QModelIndex, QModelIndex ) ), this, SLOT( updateIndex( QModelIndex, QModelIndex ) ) );
}
QgsAppLegendInterface::~QgsAppLegendInterface()
{
}
int QgsAppLegendInterface::addGroup( QString name, bool expand, QTreeWidgetItem* parent )
{
return mLegend->addGroup( name, expand, parent );
}
int QgsAppLegendInterface::addGroup( QString name, bool expand, int parentIndex )
{
return mLegend->addGroup( name, expand, parentIndex );
}
void QgsAppLegendInterface::removeGroup( int groupIndex )
{
mLegend->removeGroup( groupIndex );
}
void QgsAppLegendInterface::moveLayer( QgsMapLayer * ml, int groupIndex )
{
mLegend->moveLayer( ml, groupIndex );
}
void QgsAppLegendInterface::updateIndex( QModelIndex oldIndex, QModelIndex newIndex )
{
if ( mLegend->isLegendGroup( newIndex ) )
{
emit groupIndexChanged( oldIndex.row(), newIndex.row() );
}
}
void QgsAppLegendInterface::setGroupExpanded( int groupIndex, bool expand )
{
mLegend->setExpanded( mLegend->model()->index( groupIndex, 0 ), expand );
}
void QgsAppLegendInterface::setGroupVisible( int groupIndex, bool visible )
{
if ( !groupExists( groupIndex ) )
{
return;
}
Qt::CheckState state = visible ? Qt::Checked : Qt::Unchecked;
mLegend->topLevelItem( groupIndex )->setCheckState( 0, state );
}
void QgsAppLegendInterface::setLayerVisible( QgsMapLayer * ml, bool visible )
{
mLegend->setLayerVisible( ml, visible );
}
QStringList QgsAppLegendInterface::groups()
{
return mLegend->groups();
}
QList< GroupLayerInfo > QgsAppLegendInterface::groupLayerRelationship()
{
if ( mLegend )
{
return mLegend->groupLayerRelationship();
}
return QList< GroupLayerInfo >();
}
bool QgsAppLegendInterface::groupExists( int groupIndex )
{
QModelIndex mi = mLegend->model()->index( groupIndex, 0 );
return ( mi.isValid() &&
mLegend->isLegendGroup( mi ) );
}
bool QgsAppLegendInterface::isGroupExpanded( int groupIndex )
{
return mLegend->isExpanded( mLegend->model()->index( groupIndex, 0 ) );
}
bool QgsAppLegendInterface::isGroupVisible( int groupIndex )
{
if ( !groupExists( groupIndex ) )
{
return false;
}
return ( Qt::Checked == mLegend->topLevelItem( groupIndex )->checkState( 0 ) );
}
bool QgsAppLegendInterface::isLayerVisible( QgsMapLayer * ml )
{
return ( Qt::Checked == mLegend->layerCheckState( ml ) );
}
QList< QgsMapLayer * > QgsAppLegendInterface::layers() const
{
return mLegend->layers();
}
void QgsAppLegendInterface::refreshLayerSymbology( QgsMapLayer *ml )
{
mLegend->refreshLayerSymbology( ml->id() );
}
| gpl-2.0 |
imfaber/imfaber_v2 | vendor/doctrine/collections/lib/Doctrine/Common/Collections/Collection.php | 8571 | <?php
/*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\Collections;
use Closure, Countable, IteratorAggregate, ArrayAccess;
/**
* The missing (SPL) Collection/Array/OrderedMap interface.
*
* A Collection resembles the nature of a regular PHP array. That is,
* it is essentially an <b>ordered map</b> that can also be used
* like a list.
*
* A Collection has an internal iterator just like a PHP array. In addition,
* a Collection can be iterated with external iterators, which is preferable.
* To use an external iterator simply use the foreach language construct to
* iterate over the collection (which calls {@link getIterator()} internally) or
* explicitly retrieve an iterator though {@link getIterator()} which can then be
* used to iterate over the collection.
* You can not rely on the internal iterator of the collection being at a certain
* position unless you explicitly positioned it before. Prefer iteration with
* external iterators.
*
* @since 2.0
* @author Guilherme Blanco <[email protected]>
* @author Jonathan Wage <[email protected]>
* @author Roman Borschel <[email protected]>
*/
interface Collection extends Countable, IteratorAggregate, ArrayAccess
{
/**
* Adds an element at the end of the collection.
*
* @param mixed $element The element to add.
*
* @return boolean Always TRUE.
*/
function add($element);
/**
* Clears the collection, removing all elements.
*
* @return void
*/
function clear();
/**
* Checks whether an element is contained in the collection.
* This is an O(n) operation, where n is the size of the collection.
*
* @param mixed $element The element to search for.
*
* @return boolean TRUE if the collection contains the element, FALSE otherwise.
*/
function contains($element);
/**
* Checks whether the collection is empty (contains no elements).
*
* @return boolean TRUE if the collection is empty, FALSE otherwise.
*/
function isEmpty();
/**
* Removes the element at the specified index from the collection.
*
* @param string|integer $key The kex/index of the element to remove.
*
* @return mixed The removed element or NULL, if the collection did not contain the element.
*/
function remove($key);
/**
* Removes the specified element from the collection, if it is found.
*
* @param mixed $element The element to remove.
*
* @return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
function removeElement($element);
/**
* Checks whether the collection contains an element with the specified key/index.
*
* @param string|integer $key The key/index to check for.
*
* @return boolean TRUE if the collection contains an element with the specified key/index,
* FALSE otherwise.
*/
function containsKey($key);
/**
* Gets the element at the specified key/index.
*
* @param string|integer $key The key/index of the element to retrieve.
*
* @return mixed
*/
function get($key);
/**
* Gets all keys/indices of the collection.
*
* @return array The keys/indices of the collection, in the order of the corresponding
* elements in the collection.
*/
function getKeys();
/**
* Gets all values of the collection.
*
* @return array The values of all elements in the collection, in the order they
* appear in the collection.
*/
function getValues();
/**
* Sets an element in the collection at the specified key/index.
*
* @param string|integer $key The key/index of the element to set.
* @param mixed $value The element to set.
*
* @return void
*/
function set($key, $value);
/**
* Gets a native PHP array representation of the collection.
*
* @return array
*/
function toArray();
/**
* Sets the internal iterator to the first element in the collection and returns this element.
*
* @return mixed
*/
function first();
/**
* Sets the internal iterator to the last element in the collection and returns this element.
*
* @return mixed
*/
function last();
/**
* Gets the key/index of the element at the current iterator position.
*
* @return int|string
*/
function key();
/**
* Gets the element of the collection at the current iterator position.
*
* @return mixed
*/
function current();
/**
* Moves the internal iterator position to the next element and returns this element.
*
* @return mixed
*/
function next();
/**
* Tests for the existence of an element that satisfies the given predicate.
*
* @param Closure $p The predicate.
*
* @return boolean TRUE if the predicate is TRUE for at least one element, FALSE otherwise.
*/
function exists(Closure $p);
/**
* Returns all the elements of this collection that satisfy the predicate p.
* The order of the elements is preserved.
*
* @param Closure $p The predicate used for filtering.
*
* @return Collection A collection with the results of the filter operation.
*/
function filter(Closure $p);
/**
* Tests whether the given predicate p holds for all elements of this collection.
*
* @param Closure $p The predicate.
*
* @return boolean TRUE, if the predicate yields TRUE for all elements, FALSE otherwise.
*/
function forAll(Closure $p);
/**
* Applies the given function to each element in the collection and returns
* a new collection with the elements returned by the function.
*
* @param Closure $func
*
* @return Collection
*/
function map(Closure $func);
/**
* Partitions this collection in two collections according to a predicate.
* Keys are preserved in the resulting collections.
*
* @param Closure $p The predicate on which to partition.
*
* @return array An array with two elements. The first element contains the collection
* of elements where the predicate returned TRUE, the second element
* contains the collection of elements where the predicate returned FALSE.
*/
function partition(Closure $p);
/**
* Gets the index/key of a given element. The comparison of two elements is strict,
* that means not only the value but also the type must match.
* For objects this means reference equality.
*
* @param mixed $element The element to search for.
*
* @return int|string|bool The key/index of the element or FALSE if the element was not found.
*/
function indexOf($element);
/**
* Extracts a slice of $length elements starting at position $offset from the Collection.
*
* If $length is null it returns all elements from $offset to the end of the Collection.
* Keys have to be preserved by this method. Calling this method will only return the
* selected slice and NOT change the elements contained in the collection slice is called on.
*
* @param int $offset The offset to start from.
* @param int|null $length The maximum number of elements to return, or null for no limit.
*
* @return array
*/
function slice($offset, $length = null);
}
| gpl-2.0 |
guod08/druid | server/src/test/java/io/druid/segment/realtime/plumber/MessageTimeRejectionPolicyFactoryTest.java | 1633 | /*
* Druid - a distributed column store.
* Copyright (C) 2012, 2013 Metamarkets Group Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 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.
*/
package io.druid.segment.realtime.plumber;
import junit.framework.Assert;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.junit.Test;
/**
*/
public class MessageTimeRejectionPolicyFactoryTest
{
@Test
public void testAccept() throws Exception
{
Period period = new Period("PT10M");
RejectionPolicy rejectionPolicy = new MessageTimeRejectionPolicyFactory().create(period);
DateTime now = new DateTime();
DateTime past = now.minus(period).minus(1);
DateTime future = now.plus(period).plus(1);
Assert.assertTrue(rejectionPolicy.accept(now.getMillis()));
Assert.assertFalse(rejectionPolicy.accept(past.getMillis()));
Assert.assertTrue(rejectionPolicy.accept(future.getMillis()));
Assert.assertFalse(rejectionPolicy.accept(now.getMillis()));
}
}
| gpl-2.0 |
ReagentX/heidnerComputerScienceProjects | Temp Sardegna Stuff/Constructions/BoatRunner.java | 248 |
/**
* Write a description of class BoarRunner here.
*
* Chris Sardegna
* 10/22/13
*/
public class BoatRunner
{
public BoatRunner(){
}
public static void main(String args []){
Boat boat1 = new Boat();
}
}
| gpl-2.0 |
alinelena/aten | src/command/measure.cpp | 4435 | /*
*** Measurement Commands
*** src/command/measure.cpp
Copyright T. Youngs 2007-2016
This file is part of Aten.
Aten 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.
Aten 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 Aten. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command/commands.h"
#include "parser/commandnode.h"
#include "model/bundle.h"
#include "model/model.h"
ATEN_USING_NAMESPACE
// Clear all measurements in current model
bool Commands::function_ClearMeasurements(CommandNode* c, Bundle& obj, ReturnValue& rv)
{
if (obj.notifyNull(Bundle::ModelPointer)) return false;
obj.rs()->beginUndoState("Remove all measurements");
obj.rs()->clearMeasurements();
obj.rs()->endUndoState();
rv.reset();
return true;
}
// Calculate a measurement within the current model, but don't display it
bool Commands::function_GeometryCalc(CommandNode* c, Bundle& obj, ReturnValue& rv)
{
if (obj.notifyNull(Bundle::ModelPointer)) return false;
Atom* atoms[4];
if (c->hasArg(3))
{
for (int n=0; n<4; ++n) atoms[n] = c->argType(n) == VTypes::IntegerData ? obj.rs()->atom(c->argi(n)-1) : (Atom*) c->argp(n, VTypes::AtomData);
rv.set(obj.rs()->torsion(atoms[0], atoms[1], atoms[2], atoms[3]));
}
else if (c->hasArg(2))
{
for (int n=0; n<3; ++n) atoms[n] = c->argType(n) == VTypes::IntegerData ? obj.rs()->atom(c->argi(n)-1) : (Atom*) c->argp(n, VTypes::AtomData);
rv.set(obj.rs()->angle(atoms[0], atoms[1], atoms[2]));
}
else
{
for (int n=0; n<2; ++n) atoms[n] = c->argType(n) == VTypes::IntegerData ? obj.rs()->atom(c->argi(n)-1) : (Atom*) c->argp(n, VTypes::AtomData);
rv.set(obj.rs()->distance(atoms[0], atoms[1]));
}
return true;
}
// List all measurements in current model
bool Commands::function_ListMeasurements(CommandNode* c, Bundle& obj, ReturnValue& rv)
{
if (obj.notifyNull(Bundle::ModelPointer)) return false;
obj.rs()->listMeasurements();
rv.reset();
return true;
}
// Make a measurement within the current model
bool Commands::function_Measure(CommandNode* c, Bundle& obj, ReturnValue& rv)
{
if (obj.notifyNull(Bundle::ModelPointer)) return false;
Atom* atoms[4];
if (c->hasArg(3))
{
obj.rs()->beginUndoState("Measure torsion");
for (int n=0; n<4; ++n) atoms[n] = c->argType(n) == VTypes::IntegerData ? obj.rs()->atom(c->argi(n)-1) : (Atom*) c->argp(n, VTypes::AtomData);
rv.set(obj.rs()->addTorsionMeasurement(atoms[0], atoms[1], atoms[2], atoms[3]));
}
else if (c->hasArg(2))
{
obj.rs()->beginUndoState("Measure angle");
for (int n=0; n<3; ++n) atoms[n] = c->argType(n) == VTypes::IntegerData ? obj.rs()->atom(c->argi(n)-1) : (Atom*) c->argp(n, VTypes::AtomData);
rv.set(obj.rs()->addAngleMeasurement(atoms[0], atoms[1], atoms[2]));
}
else
{
obj.rs()->beginUndoState("Measure distance");
for (int n=0; n<2; ++n) atoms[n] = c->argType(n) == VTypes::IntegerData ? obj.rs()->atom(c->argi(n)-1) : (Atom*) c->argp(n, VTypes::AtomData);
rv.set(obj.rs()->addDistanceMeasurement(atoms[0], atoms[1]));
}
obj.rs()->endUndoState();
return true;
}
// Make a series measurements of one type within the current atom selection
bool Commands::function_MeasureSelected(CommandNode* c, Bundle& obj, ReturnValue& rv)
{
if (obj.notifyNull(Bundle::ModelPointer)) return false;
switch (c->argi(0))
{
case (2):
obj.rs()->beginUndoState("Measure distances in selection");
obj.rs()->addMeasurementsInSelection(Measurement::DistanceMeasurement);
obj.rs()->endUndoState();
break;
case (3):
obj.rs()->beginUndoState("Measure angles in selection");
obj.rs()->addMeasurementsInSelection(Measurement::AngleMeasurement);
obj.rs()->endUndoState();
break;
case (4):
obj.rs()->beginUndoState("Measure torsions in selection");
obj.rs()->addMeasurementsInSelection(Measurement::TorsionMeasurement);
obj.rs()->endUndoState();
break;
default:
Messenger::print("%i does not represent a geometry type (number of atoms involved).", c->argi(0));
return false;
break;
}
return true;
}
| gpl-2.0 |
doodz/AppSshForm | ApptestSsh/ApptestSsh/View/Base/LocalOmvViewModel.cs | 3528 | using Doods.StdFramework.Interfaces;
using Doods.StdFramework.Views.PopupPages;
using Omv.Rpc.StdClient.Clients;
using Omv.Rpc.StdClient.Datas;
using Omv.Rpc.StdClient.Services;
using Rg.Plugins.Popup.Extensions;
using System.Threading.Tasks;
namespace ApptestSsh.Core.View.Base
{
public enum ProgressContentViewState
{
Closed,
Finished
}
public class LocalOmvViewModel : LocalViewModel
{
public LocalOmvViewModel(ILogger logger) : base(logger)
{
}
protected async Task ApplyChanges(ISshService ssh, bool showProgress)
{
if (showProgress)
{
var progressTask = ShowProgress();
}
var cmd = ConfigService.CreateApplyChangesBgCommand();
var res = await new OmvRpcQuery<string>(ssh, cmd).RunAsync(Token);
if (res != null)
{
await IsRunning(ssh, res);
}
if (_progressContentView != null)
{
_inputAlertDialogBase.PageClosedTaskCompletionSource
.SetResult(ProgressContentViewState.Finished);
}
}
private int _waitRunning = 1000;
private async Task IsRunning(ISshService ssh, string res)
{
var cmd = ExecService.CreateIsRunningCommand(res);
var data = await new OmvRpcQuery<IsRunningData>(ssh, cmd).RunAsync(Token);
if (data != null)
{
if (data.Running)
{
Task.Delay(_waitRunning).Wait();
await IsRunning(ssh, data.Filename);
_waitRunning += 1000;
if (_waitRunning > 5000)
_waitRunning = 1000;
}
else
{
_waitRunning = 1000;
}
}
}
private ProgressContentView _progressContentView;
private InputAlertDialogBase<ProgressContentViewState> _inputAlertDialogBase;
private async Task ShowProgress()
{
// create the TextInputView
_progressContentView = new ProgressContentView("Apply changes");
// create the Transparent Popup Page
// of type string since we need a string return
_inputAlertDialogBase = new InputAlertDialogBase<ProgressContentViewState>(_progressContentView);
// subscribe to the TextInputView's Button click event
_progressContentView.CloseButtonEventHandler +=
(sender, obj) =>
{
if (sender is ProgressContentView view)
{
// update the page completion source
_inputAlertDialogBase.PageClosedTaskCompletionSource
.SetResult(ProgressContentViewState.Closed);
}
};
// Push the page to Navigation Stack
await NavigationService.Navigation.PushPopupAsync(_inputAlertDialogBase);
// await for the user to enter the text input
var result = await _inputAlertDialogBase.PageClosedTask;
// Pop the page from Navigation Stack
await NavigationService.Navigation.PopPopupAsync();
_progressContentView = null;
_inputAlertDialogBase = null;
// return user inserted text value
//return result;
}
}
} | gpl-2.0 |
akashche/tzdbgen | src/main/java/build/tools/tzdb/support/com/redhat/openjdk/support7/LongUtils.java | 1446 | /*
* Copyright 2015 Red Hat, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 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 this program; see the file COPYING. If not see
* <http://www.gnu.org/licenses/>.
*/
package build.tools.tzdb.support.com.redhat.openjdk.support7;
/**
* Partial copy of Long from jdk7u
*/
public class LongUtils {
/**
* Compares two {@code long} values numerically.
* The value returned is identical to what would be returned by:
* <pre>
* Long.valueOf(x).compareTo(Long.valueOf(y))
* </pre>
*
* @param x the first {@code long} to compare
* @param y the second {@code long} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
*/
public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
}
| gpl-2.0 |
stalepig/deep-mucosal-imaging | CURRENT-dmi_0.2/Batch_stitch.py | 912 | import glob
import os
from ij import IJ
from ij.io import DirectoryChooser
dc = DirectoryChooser("Choose directory of LSM files...")
dirPath = dc.getDirectory()
if dirPath is not None:
fileList = glob.glob(dirPath+"*.lsm")
for path in fileList:
basename = os.path.splitext(os.path.basename(path))[0]
outputPath = dirPath + basename + "_stitched"
if not os.path.exists(outputPath):
os.mkdir(outputPath)
params = "type=[Positions from file] order=[Defined by image metadata] browse=[" + path + "] multi_series_file=[" + path + "] fusion_method=[Linear Blending] regression_threshold=0.30 max/avg_displacement_threshold=2.50 absolute_displacement_threshold=3.50 compute_overlap ignore_z_stage increase_overlap=10 subpixel_accuracy computation_parameters=[Save memory (but be slower)] image_output=[Write to disk] output_directory=[" + outputPath + "]";
IJ.run("Grid/Collection stitching", params)
| gpl-2.0 |
qkitgroup/qkit | qkit/drivers/Keithley_2000.py | 4848 | # filename: Keithley_2000.py
# version 0.1 written by JB,JNV, HR@KIT 2017-
# QKIT driver for a Keithley Multimeter 2000
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
import qkit
from qkit.core.instrument_base import Instrument
import logging
import numpy
import time,sys
import atexit
import serial
class Keithley_2000(Instrument):
'''
This is the driver for the Keithley 2000 Source Meter
Usage:
Initialize with
<name> = qkit.instruments.create('<name>', 'Keithley_2000', address='<GBIP address>', reset=<bool>)
'''
def __init__(self, name, address, reset=False):
'''
Initializes the Keithley, and communicates with the wrapper.
Input:
name (string) : name of the instrument
address (string) : GPIB address
reset (bool) : resets to default values, default=False
'''
# Start VISA communication
logging.info(__name__ + ': Initializing instrument Keithley 2000')
Instrument.__init__(self, name, tags=['physical'])
#self._address = address
self._rvol = 1
self.rvc_mode = False
self.four_wire = False
self.setup(address)
def setup(self, device="/dev/ttyUSB7"):
baudrate = 9600
timeout = 0.1
self.ser = self._std_open(device,baudrate,timeout)
atexit.register(self.ser.close)
def _std_open(self,device,baudrate,timeout):
# open serial port, 9600, 8,N,1, timeout 0.1
return serial.Serial(device, baudrate, timeout=timeout)
def remote_cmd(self, cmd):
cmd += "\r"
# clear queue first, old data,etc
rem_char = self.ser.inWaiting()
if rem_char:
self.ser.read(rem_char)
# send command
self.ser.write(str.encode(cmd))
# wait until data is processed
time.sleep(1)
# read back
rem_char = self.ser.inWaiting()
retval = self.ser.read(rem_char)
#print(retval)
return retval #str(retval)#.strip('\r')
def get_current_dc(self): #Return DC Current in auto-range
value = self.remote_cmd(":MEAS:CURR:DC?")
try:
return float(value)
except Exception as m:
print(m)
return
def get_resistance(self):
if self.rvc_mode:
return self._rvol/self.get_data()
else:
if self.four_wire:
return self.get_resistance_4W()
else:
return self.get_resistance_2W()
def get_data(self):
try:
ret = self.remote_cmd(":DATA?")
return float(ret)
except ValueError as e:
print(e)
print(ret)
return numpy.NaN
def get_resistance_2W(self):
try:
ret = self.remote_cmd(":MEAS:RES?")
return float(ret)
except ValueError as e:
print(e)
print(ret)
return numpy.NaN
def get_resistance_4W(self):
try:
ret = self.remote_cmd(":MEAS:FRES?")
return float(ret)
except ValueError as e:
print(e)
print(ret)
return numpy.NaN
def set_measure_4W(self,four_wire):
''' Sets 2 or 4 wire measurement mode '''
self.four_wire = four_wire
def set_resistance_via_current(self, status):
self.rvc_mode = status
self.ser.write(str.encode(":FUNC 'CURR:DC' \r"))
self.ser.write(str.encode(":CURR:DC:RANG:AUTO OFF \r"))
self.ser.write(str.encode(":CURR:DC:RANG 1e-3 \r"))
def set_reverence_voltage(self, voltage):
self._rvol = voltage
def set_current_range(self, range_value):
if 1e-3 <= range_value <= 1:
self.ser.write(str.encode(":CURR:DC:RANG %.04f \r"%(range_value)))
else:
print("Range must be decimal power of 10 between 1A and 10mA")
if __name__ == "__main__":
KEITH = Keithley_2000(name = "Keithley_2000", address="COM6")
print("DC current: {:.4g}A".format(KEITH.get_current_dc()))
| gpl-2.0 |
mgratch/metroinvestments | wp-content/plugins/pods/classes/fields/phone.php | 9142 | <?php
/**
* @package Pods\Fields
*/
class PodsField_Phone extends PodsField {
/**
* Field Type Group
*
* @var string
* @since 2.0
*/
public static $group = 'Text';
/**
* Field Type Identifier
*
* @var string
* @since 2.0
*/
public static $type = 'phone';
/**
* Field Type Label
*
* @var string
* @since 2.0
*/
public static $label = 'Phone';
/**
* Field Type Preparation
*
* @var string
* @since 2.0
*/
public static $prepare = '%s';
/**
* Do things like register/enqueue scripts and stylesheets
*
* @since 2.0
*/
public function __construct () {
self::$label = __( 'Phone', 'pods' );
}
/**
* Add options and set defaults to
*
* @param array $options
*
* @since 2.0
*/
public function options () {
$options = array(
self::$type . '_repeatable' => array(
'label' => __( 'Repeatable Field', 'pods' ),
'default' => 0,
'type' => 'boolean',
'help' => __( 'Making a field repeatable will add controls next to the field which allows users to Add/Remove/Reorder additional values. These values are saved in the database as an array, so searching and filtering by them may require further adjustments".', 'pods' ),
'boolean_yes_label' => '',
'dependency' => true,
'developer_mode' => true
),
self::$type . '_format' => array(
'label' => __( 'Format', 'pods' ),
'default' => '999-999-9999 x999',
'type' => 'pick',
'data' => array(
__( 'US', 'pods' ) => array(
'999-999-9999 x999' => '123-456-7890 x123',
'(999) 999-9999 x999' => '(123) 456-7890 x123',
'999.999.9999 x999' => '123.456.7890 x123'
),
__( 'International', 'pods' ) => array(
'international' => __( 'Any (no validation available)', 'pods' )
)
)
),
self::$type . '_options' => array(
'label' => __( 'Phone Options', 'pods' ),
'group' => array(
self::$type . '_enable_phone_extension' => array(
'label' => __( 'Enable Phone Extension?', 'pods' ),
'default' => 1,
'type' => 'boolean'
)
)
),
self::$type . '_max_length' => array(
'label' => __( 'Maximum Length', 'pods' ),
'default' => 25,
'type' => 'number',
'help' => __( 'Set to -1 for no limit', 'pods' )
),
self::$type . '_html5' => array(
'label' => __( 'Enable HTML5 Input Field?', 'pods' ),
'default' => apply_filters( 'pods_form_ui_field_html5', 0, self::$type ),
'type' => 'boolean'
)/*,
self::$type . '_size' => array(
'label' => __( 'Field Size', 'pods' ),
'default' => 'medium',
'type' => 'pick',
'data' => array(
'small' => __( 'Small', 'pods' ),
'medium' => __( 'Medium', 'pods' ),
'large' => __( 'Large', 'pods' )
)
)*/
);
return $options;
}
/**
* Define the current field's schema for DB table storage
*
* @param array $options
*
* @return array
* @since 2.0
*/
public function schema ( $options = null ) {
$length = (int) pods_var( self::$type . '_max_length', $options, 25, null, true );
$schema = 'VARCHAR(' . $length . ')';
if ( 255 < $length || $length < 1 )
$schema = 'LONGTEXT';
return $schema;
}
/**
* Customize output of the form field
*
* @param string $name
* @param mixed $value
* @param array $options
* @param array $pod
* @param int $id
*
* @since 2.0
*/
public function input ( $name, $value = null, $options = null, $pod = null, $id = null ) {
$options = (array) $options;
$form_field_type = PodsForm::$field_type;
if ( is_array( $value ) )
$value = implode( ' ', $value );
$field_type = 'phone';
if ( isset( $options[ 'name' ] ) && false === PodsForm::permission( self::$type, $options[ 'name' ], $options, null, $pod, $id ) ) {
if ( pods_var( 'read_only', $options, false ) ) {
$options[ 'readonly' ] = true;
$field_type = 'text';
}
else
return;
}
elseif ( !pods_has_permissions( $options ) && pods_var( 'read_only', $options, false ) ) {
$options[ 'readonly' ] = true;
$field_type = 'text';
}
pods_view( PODS_DIR . 'ui/fields/' . $field_type . '.php', compact( array_keys( get_defined_vars() ) ) );
}
/**
* Validate a value before it's saved
*
* @param mixed $value
* @param string $name
* @param array $options
* @param array $fields
* @param array $pod
* @param int $id
*
* @since 2.0
*/
public function validate ( $value, $name = null, $options = null, $fields = null, $pod = null, $id = null, $params = null ) {
$errors = array();
$label = strip_tags( pods_var_raw( 'label', $options, ucwords( str_replace( '_', ' ', $name ) ) ) );
$check = $this->pre_save( $value, $id, $name, $options, $fields, $pod, $params );
if ( is_array( $check ) )
$errors = $check;
else {
if ( 0 < strlen( $value ) && strlen( $check ) < 1 ) {
if ( 1 == pods_var( 'required', $options ) )
$errors[] = sprintf( __( 'The %s field is required.', 'pods' ), $label );
else
$errors[] = sprintf( __( 'Invalid phone number provided for the field %s.', 'pods' ), $label );
}
}
if ( !empty( $errors ) )
return $errors;
return true;
}
/**
* Change the value or perform actions after validation but before saving to the DB
*
* @param mixed $value
* @param int $id
* @param string $name
* @param array $options
* @param array $fields
* @param array $pod
* @param object $params
*
* @since 2.0
*/
public function pre_save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
$options = (array) $options;
if ( 'international' == pods_var( self::$type . '_format', $options ) ) {
// no validation/changes
}
else {
// Clean input
$number = preg_replace( '/([^0-9ext])/', '', $value );
$number = str_replace(
array( '-', '.', 'ext', 'x', 't', 'e', '(', ')' ),
array( '', '', '|', '|', '', '', '', '', ),
$number
);
// Get extension
$extension = explode( '|', $number );
if ( 1 < count( $extension ) ) {
$number = preg_replace( '/([^0-9])/', '', $extension[ 0 ] );
$extension = preg_replace( '/([^0-9])/', '', $extension[ 1 ] );
}
else
$extension = '';
// Build number array
$numbers = str_split( $number, 3 );
if ( isset( $numbers[ 3 ] ) ) {
$numbers[ 2 ] .= $numbers[ 3 ];
$numbers = array( $numbers[ 0 ], $numbers[ 1 ], $numbers[ 2 ] );
}
elseif ( isset( $numbers[ 1 ] ) )
$numbers = array( $numbers[ 0 ], $numbers[ 1 ] );
// Format number
if ( '(999) 999-9999 x999' == pods_var( self::$type . '_format', $options ) ) {
if ( 2 == count( $numbers ) )
$value = implode( '-', $numbers );
else
$value = '(' . $numbers[ 0 ] . ') ' . $numbers[ 1 ] . '-' . $numbers[ 2 ];
}
elseif ( '999.999.9999 x999' == pods_var( self::$type . '_format', $options ) )
$value = implode( '.', $numbers );
else //if ( '999-999-9999 x999' == pods_var( self::$type . '_format', $options ) )
$value = implode( '-', $numbers );
// Add extension
if ( 1 == pods_var( self::$type . '_enable_phone_extension', $options ) && 0 < strlen( $extension ) )
$value .= ' x' . $extension;
}
$length = (int) pods_var( self::$type . '_max_length', $options, 25 );
if ( 0 < $length && $length < pods_mb_strlen( $value ) ) {
$value = pods_mb_substr( $value, 0, $length );
}
return $value;
}
}
| gpl-2.0 |
shunghsiyu/OpenJML_XOR | OpenJML/tests/tests/deprecation.java | 2184 | package tests;
/** This tests that extensions are prohibited by -strict.
* (I suppose we should test that every non-extension is allowed by -strict, but we don't.) */
import org.junit.Test;
import com.sun.tools.javac.main.OptionName;
public class deprecation extends TCBase {
String opt = OptionName.DEPRECATION.name();
@Override
public void setUp() throws Exception {
// noCollectDiagnostics = true;
// jmldebug = true;
super.setUp();
expectedExit = 0;
}
@Test
public void testRepresents() {
main.addOptions("-deprecation");
helpTCF("A.java","public class A {\n" +
" //@ model int i;\n" +
" //@ represents i <- 0;\n }"
,"/A.java:3: warning: The left arrow is deprecated in represents clauses, use = instead",19
);
}
@Test
public void testRepresentsA() {
helpTCF("A.java","public class A {\n" +
" //@ model int i;\n" +
" //@ represents i <- 0;\n }"
);
}
@Test
public void testParsePlus() {
main.addOptions("-deprecation");
helpTCF("A.java","public class A {\n" +
" //+@ model int i;\n" +
" }"
,"/A.java:2: warning: The //+@ and //-@ annotation styles are deprecated - use keys instead",4
);
}
@Test
public void testParsePlusB() {
helpTCF("A.java","public class A {\n" +
" //+@ model int i;\n" +
" }"
);
}
@Test
public void testParseMinus() {
main.addOptions("-deprecation");
helpTCF("A.java","public class A {\n" +
" //-@ model int i;\n" +
" }"
,"/A.java:2: warning: The //+@ and //-@ annotation styles are deprecated - use keys instead",4
);
}
@Test
public void testParseMinusB() {
helpTCF("A.java","public class A {\n" +
" //-@ model int i;\n" +
" }"
);
}
}
| gpl-2.0 |
fritsch/xbmc | xbmc/interfaces/legacy/ModuleXbmc.cpp | 15818 | /*
* Copyright (C) 2005-2013 Team XBMC
* http://kodi.tv
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
//! @todo Need a uniform way of returning an error status
#include "network/Network.h"
#include "ModuleXbmc.h"
#include "Application.h"
#include "ServiceBroker.h"
#include "messaging/ApplicationMessenger.h"
#include "utils/URIUtils.h"
#include "aojsonrpc.h"
#ifndef TARGET_WINDOWS
#include "XTimeUtils.h"
#endif
#include "guilib/LocalizeStrings.h"
#include "GUIInfoManager.h"
#include "guilib/GUIAudioManager.h"
#include "guilib/GUIWindowManager.h"
#include "filesystem/File.h"
#include "filesystem/SpecialProtocol.h"
#include "utils/Crc32.h"
#include "FileItem.h"
#include "LangInfo.h"
#include "PlayListPlayer.h"
#include "settings/AdvancedSettings.h"
#include "settings/Settings.h"
#include "guilib/TextureManager.h"
#include "Util.h"
#include "cores/AudioEngine/Interfaces/AE.h"
#include "storage/MediaManager.h"
#include "utils/FileExtensionProvider.h"
#include "utils/LangCodeExpander.h"
#include "utils/StringUtils.h"
#include "utils/SystemInfo.h"
#include "AddonUtils.h"
#include "LanguageHook.h"
#include "threads/SystemClock.h"
#include <vector>
#include "utils/log.h"
using namespace KODI::MESSAGING;
#ifdef TARGET_POSIX
#include "platform/linux/XMemUtils.h"
#endif
namespace XBMCAddon
{
namespace xbmc
{
/*****************************************************************
* start of xbmc methods
*****************************************************************/
void log(const char* msg, int level)
{
// check for a valid loglevel
if (level < LOGDEBUG || level > LOGNONE)
level = LOGDEBUG;
CLog::Log(level, "%s", msg);
}
void shutdown()
{
XBMC_TRACE;
CApplicationMessenger::GetInstance().PostMsg(TMSG_SHUTDOWN);
}
void restart()
{
XBMC_TRACE;
CApplicationMessenger::GetInstance().PostMsg(TMSG_RESTART);
}
void executescript(const char* script)
{
XBMC_TRACE;
if (! script)
return;
CApplicationMessenger::GetInstance().PostMsg(TMSG_EXECUTE_SCRIPT, -1, -1, nullptr, script);
}
void executebuiltin(const char* function, bool wait /* = false*/)
{
XBMC_TRACE;
if (! function)
return;
if (wait)
CApplicationMessenger::GetInstance().SendMsg(TMSG_EXECUTE_BUILT_IN, -1, -1, nullptr, function);
else
CApplicationMessenger::GetInstance().PostMsg(TMSG_EXECUTE_BUILT_IN, -1, -1, nullptr, function);
}
String executeJSONRPC(const char* jsonrpccommand)
{
XBMC_TRACE;
DelayedCallGuard dg;
String ret;
if (! jsonrpccommand)
return ret;
// String method = jsonrpccommand;
CAddOnTransport transport;
CAddOnTransport::CAddOnClient client;
return JSONRPC::CJSONRPC::MethodCall(/*method*/ jsonrpccommand, &transport, &client);
}
void sleep(long timemillis)
{
XBMC_TRACE;
XbmcThreads::EndTime endTime(timemillis);
while (!endTime.IsTimePast())
{
LanguageHook* lh = NULL;
{
DelayedCallGuard dcguard;
lh = dcguard.getLanguageHook(); // borrow this
long nextSleep = endTime.MillisLeft();
if (nextSleep > 100)
nextSleep = 100; // only sleep for 100 millis
::Sleep(nextSleep);
}
if (lh != NULL)
lh->MakePendingCalls();
}
}
String getLocalizedString(int id)
{
XBMC_TRACE;
String label;
if (id >= 30000 && id <= 30999)
label = g_localizeStringsTemp.Get(id);
else if (id >= 32000 && id <= 32999)
label = g_localizeStringsTemp.Get(id);
else
label = g_localizeStrings.Get(id);
return label;
}
String getSkinDir()
{
XBMC_TRACE;
return CServiceBroker::GetSettings().GetString(CSettings::SETTING_LOOKANDFEEL_SKIN);
}
String getLanguage(int format /* = CLangCodeExpander::ENGLISH_NAME */, bool region /*= false*/)
{
XBMC_TRACE;
std::string lang = g_langInfo.GetEnglishLanguageName();
switch (format)
{
case CLangCodeExpander::ENGLISH_NAME:
{
if (region)
{
std::string region = "-" + g_langInfo.GetCurrentRegion();
return (lang += region);
}
return lang;
}
case CLangCodeExpander::ISO_639_1:
{
std::string langCode;
g_LangCodeExpander.ConvertToISO6391(lang, langCode);
if (region)
{
std::string region = g_langInfo.GetRegionLocale();
std::string region2Code;
g_LangCodeExpander.ConvertToISO6391(region, region2Code);
region2Code = "-" + region2Code;
return (langCode += region2Code);
}
return langCode;
}
case CLangCodeExpander::ISO_639_2:
{
std::string langCode;
g_LangCodeExpander.ConvertToISO6392B(lang, langCode);
if (region)
{
std::string region = g_langInfo.GetRegionLocale();
std::string region3Code;
g_LangCodeExpander.ConvertToISO6392B(region, region3Code);
region3Code = "-" + region3Code;
return (langCode += region3Code);
}
return langCode;
}
default:
return "";
}
}
String getIPAddress()
{
XBMC_TRACE;
char cTitleIP[32];
sprintf(cTitleIP, "127.0.0.1");
CNetworkInterface* iface = CServiceBroker::GetNetwork().GetFirstConnectedInterface();
if (iface)
return iface->GetCurrentIPAddress();
return cTitleIP;
}
long getDVDState()
{
XBMC_TRACE;
return g_mediaManager.GetDriveStatus();
}
long getFreeMem()
{
XBMC_TRACE;
MEMORYSTATUSEX stat;
stat.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&stat);
return (long)(stat.ullAvailPhys / ( 1024 * 1024 ));
}
// getCpuTemp() method
// ## Doesn't work right, use getInfoLabel('System.CPUTemperature') instead.
/*PyDoc_STRVAR(getCpuTemp__doc__,
"getCpuTemp() -- Returns the current cpu temperature as an integer."
""
"example:"
" - cputemp = xbmc.getCpuTemp()");
PyObject* XBMC_GetCpuTemp(PyObject *self, PyObject *args)
{
unsigned short cputemp;
unsigned short cpudec;
_outp(0xc004, (0x4c<<1)|0x01);
_outp(0xc008, 0x01);
_outpw(0xc000, _inpw(0xc000));
_outp(0xc002, (0) ? 0x0b : 0x0a);
while ((_inp(0xc000) & 8));
cputemp = _inpw(0xc006);
_outp(0xc004, (0x4c<<1)|0x01);
_outp(0xc008, 0x10);
_outpw(0xc000, _inpw(0xc000));
_outp(0xc002, (0) ? 0x0b : 0x0a);
while ((_inp(0xc000) & 8));
cpudec = _inpw(0xc006);
if (cpudec<10) cpudec = cpudec * 100;
if (cpudec<100) cpudec = cpudec *10;
return PyInt_FromLong((long)(cputemp + cpudec / 1000.0f));
}*/
String getInfoLabel(const char* cLine)
{
XBMC_TRACE;
if (!cLine)
{
String ret;
return ret;
}
int ret = g_infoManager.TranslateString(cLine);
//doesn't seem to be a single InfoTag?
//try full blown GuiInfoLabel then
if (ret == 0)
return CGUIInfoLabel::GetLabel(cLine);
else
return g_infoManager.GetLabel(ret);
}
String getInfoImage(const char * infotag)
{
XBMC_TRACE;
if (!infotag)
{
String ret;
return ret;
}
int ret = g_infoManager.TranslateString(infotag);
return g_infoManager.GetImage(ret, WINDOW_INVALID);
}
void playSFX(const char* filename, bool useCached)
{
XBMC_TRACE;
if (!filename)
return;
if (XFILE::CFile::Exists(filename))
{
g_audioManager.PlayPythonSound(filename,useCached);
}
}
void stopSFX()
{
XBMC_TRACE;
DelayedCallGuard dg;
g_audioManager.Stop();
}
void enableNavSounds(bool yesNo)
{
XBMC_TRACE;
g_audioManager.Enable(yesNo);
}
bool getCondVisibility(const char *condition)
{
XBMC_TRACE;
if (!condition)
return false;
bool ret;
{
XBMCAddonUtils::GuiLock lock(nullptr, false);
int id = CServiceBroker::GetGUI()->GetWindowManager().GetTopmostModalDialog();
if (id == WINDOW_INVALID) id = CServiceBroker::GetGUI()->GetWindowManager().GetActiveWindow();
ret = g_infoManager.EvaluateBool(condition,id);
}
return ret;
}
int getGlobalIdleTime()
{
XBMC_TRACE;
return g_application.GlobalIdleTime();
}
String getCacheThumbName(const String& path)
{
XBMC_TRACE;
auto crc = Crc32::ComputeFromLowerCase(path);
return StringUtils::Format("%08x.tbn", crc);
}
String makeLegalFilename(const String& filename, bool fatX)
{
XBMC_TRACE;
return CUtil::MakeLegalPath(filename);
}
String translatePath(const String& path)
{
XBMC_TRACE;
return CSpecialProtocol::TranslatePath(path);
}
Tuple<String,String> getCleanMovieTitle(const String& path, bool usefoldername)
{
XBMC_TRACE;
CFileItem item(path, false);
std::string strName = item.GetMovieName(usefoldername);
std::string strTitleAndYear;
std::string strTitle;
std::string strYear;
CUtil::CleanString(strName, strTitle, strTitleAndYear, strYear, usefoldername);
return Tuple<String,String>(strTitle,strYear);
}
String validatePath(const String& path)
{
XBMC_TRACE;
return CUtil::ValidatePath(path, true);
}
String getRegion(const char* id)
{
XBMC_TRACE;
std::string result;
if (strcmpi(id, "datelong") == 0)
{
result = g_langInfo.GetDateFormat(true);
StringUtils::Replace(result, "DDDD", "%A");
StringUtils::Replace(result, "MMMM", "%B");
StringUtils::Replace(result, "D", "%d");
StringUtils::Replace(result, "YYYY", "%Y");
}
else if (strcmpi(id, "dateshort") == 0)
{
result = g_langInfo.GetDateFormat(false);
StringUtils::Replace(result, "MM", "%m");
StringUtils::Replace(result, "DD", "%d");
#ifdef TARGET_WINDOWS
StringUtils::Replace(result, "M", "%#m");
StringUtils::Replace(result, "D", "%#d");
#else
StringUtils::Replace(result, "M", "%-m");
StringUtils::Replace(result, "D", "%-d");
#endif
StringUtils::Replace(result, "YYYY", "%Y");
}
else if (strcmpi(id, "tempunit") == 0)
result = g_langInfo.GetTemperatureUnitString();
else if (strcmpi(id, "speedunit") == 0)
result = g_langInfo.GetSpeedUnitString();
else if (strcmpi(id, "time") == 0)
{
result = g_langInfo.GetTimeFormat();
StringUtils::Replace(result, "H", "%H");
StringUtils::Replace(result, "h", "%I");
StringUtils::Replace(result, "mm", "%M");
StringUtils::Replace(result, "ss", "%S");
StringUtils::Replace(result, "xx", "%p");
}
else if (strcmpi(id, "meridiem") == 0)
result = StringUtils::Format("%s/%s",
g_langInfo.GetMeridiemSymbol(MeridiemSymbolAM).c_str(),
g_langInfo.GetMeridiemSymbol(MeridiemSymbolPM).c_str());
return result;
}
//! @todo Add a mediaType enum
String getSupportedMedia(const char* mediaType)
{
XBMC_TRACE;
String result;
if (strcmpi(mediaType, "video") == 0)
result = CServiceBroker::GetFileExtensionProvider().GetVideoExtensions();
else if (strcmpi(mediaType, "music") == 0)
result = CServiceBroker::GetFileExtensionProvider().GetMusicExtensions();
else if (strcmpi(mediaType, "picture") == 0)
result = CServiceBroker::GetFileExtensionProvider().GetPictureExtensions();
//! @todo implement
// else
// return an error
return result;
}
bool skinHasImage(const char* image)
{
XBMC_TRACE;
return g_TextureManager.HasTexture(image);
}
bool startServer(int iTyp, bool bStart, bool bWait)
{
XBMC_TRACE;
DelayedCallGuard dg;
return g_application.StartServer((CApplication::ESERVERS)iTyp, bStart != 0, bWait != 0);
}
void audioSuspend()
{
CServiceBroker::GetActiveAE().Suspend();
}
void audioResume()
{
CServiceBroker::GetActiveAE().Resume();
}
String convertLanguage(const char* language, int format)
{
std::string convertedLanguage;
switch (format)
{
case CLangCodeExpander::ENGLISH_NAME:
{
g_LangCodeExpander.Lookup(language, convertedLanguage);
// maybe it's a check whether the language exists or not
if (convertedLanguage.empty())
{
g_LangCodeExpander.ConvertToISO6392B(language, convertedLanguage);
g_LangCodeExpander.Lookup(convertedLanguage, convertedLanguage);
}
break;
}
case CLangCodeExpander::ISO_639_1:
g_LangCodeExpander.ConvertToISO6391(language, convertedLanguage);
break;
case CLangCodeExpander::ISO_639_2:
g_LangCodeExpander.ConvertToISO6392B(language, convertedLanguage);
break;
default:
return "";
}
return convertedLanguage;
}
String getUserAgent()
{
return CSysInfo::GetUserAgent();
}
int getSERVER_WEBSERVER() { return CApplication::ES_WEBSERVER; }
int getSERVER_AIRPLAYSERVER() { return CApplication::ES_AIRPLAYSERVER; }
int getSERVER_UPNPSERVER() { return CApplication::ES_UPNPSERVER; }
int getSERVER_UPNPRENDERER() { return CApplication::ES_UPNPRENDERER; }
int getSERVER_EVENTSERVER() { return CApplication::ES_EVENTSERVER; }
int getSERVER_JSONRPCSERVER() { return CApplication::ES_JSONRPCSERVER; }
int getSERVER_ZEROCONF() { return CApplication::ES_ZEROCONF; }
int getPLAYLIST_MUSIC() { return PLAYLIST_MUSIC; }
int getPLAYLIST_VIDEO() { return PLAYLIST_VIDEO; }
int getTRAY_OPEN() { return TRAY_OPEN; }
int getDRIVE_NOT_READY() { return DRIVE_NOT_READY; }
int getTRAY_CLOSED_NO_MEDIA() { return TRAY_CLOSED_NO_MEDIA; }
int getTRAY_CLOSED_MEDIA_PRESENT() { return TRAY_CLOSED_MEDIA_PRESENT; }
int getLOGDEBUG() { return LOGDEBUG; }
int getLOGINFO() { return LOGINFO; }
int getLOGNOTICE() { return LOGNOTICE; }
int getLOGWARNING() { return LOGWARNING; }
int getLOGERROR() { return LOGERROR; }
int getLOGSEVERE() { return LOGSEVERE; }
int getLOGFATAL() { return LOGFATAL; }
int getLOGNONE() { return LOGNONE; }
// language string formats
int getISO_639_1() { return CLangCodeExpander::ISO_639_1; }
int getISO_639_2(){ return CLangCodeExpander::ISO_639_2; }
int getENGLISH_NAME() { return CLangCodeExpander::ENGLISH_NAME; }
const int lLOGDEBUG = LOGDEBUG;
}
}
| gpl-2.0 |
edna-pws/soto | wp-content/plugins/tiny-compress-images/src/class-tiny-compress-fopen.php | 2803 | <?php
/*
* Tiny Compress Images - WordPress plugin.
* Copyright (C) 2015 Voormedia B.V.
*
* 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.
*/
class Tiny_Compress_Fopen extends Tiny_Compress {
protected function shrink_options($input) {
return array(
'http' => array(
'method' => 'POST',
'header' => array(
'Content-type: image/png',
'Authorization: Basic ' . base64_encode('api:' . $this->api_key),
'User-Agent: ' . Tiny_WP_Base::plugin_identification() . ' fopen',
),
'content' => $input
),
'ssl' => array(
'cafile' => self::get_ca_file(),
'verify_peer' => true
)
);
}
protected function shrink($input) {
$context = stream_context_create($this->shrink_options($input));
$request = @fopen($this->config['api']['url'], 'r', false, $context);
if (!$request) {
return array(array(
'error' => 'FopenError',
'message' => 'Could not compress, enable cURL for detailed error'
), null
);
}
$response = stream_get_contents($request);
$meta_data = stream_get_meta_data($request);
$output_url = self::parse_location_header($meta_data['wrapper_data']);
fclose($request);
return array(self::decode($response), $output_url);
}
protected function output_options() {
return array(
'http' => array(
'method' => 'GET',
),
'ssl' => array(
'cafile' => self::get_ca_file(),
'verify_peer' => true
)
);
}
protected function output($url) {
$context = stream_context_create($this->output_options());
$request = @fopen($url, 'rb', false, $context);
if ($request) {
$response = stream_get_contents($request);
fclose($request);
} else {
$response = '';
}
return $response;
}
}
| gpl-2.0 |
neilxdsouza/codehelper | src/global_variables.cpp | 267 | #include "global_variables.h"
#include "ui_navigation_order.h"
namespace global_variables {
int nGraphNodes;
std::vector<int> topologicalOrder;
std::string output_code_directory_prefix = "output/CppCodeGenerator/";
UiNavigationOrderType ui_navigation_order;
}
| gpl-2.0 |
yama/zencart1302-ja | zc_install/techsupp.php | 16631 | <?
//You must enter YOUR email address ($myemail on line below).
$myemail ="YOUR_EMAIL_ADDRESS_GOES_HERE";
// ****************************************************************
// * TECHSUPP.PHP
// * v1.2f June 22, 2005
// *
// * Tech Support tool to collect server and Zen Cart config info
// * Results can then be reported when requesting tech support on
// * the Zen Cart forums at www.zen-cart.com
// *
// * This file can be uploaded to /zencart and run directly
// * as http://myserver.com/zencart/techsupp.php
// * OR
// * This file can be uploaded to anywhere on your server, and it
// * will report system info, but will skip the Zen Cart specific items.
// *
// * Contributed by: DrByte
// *****************************************************************
// * v1.2f- added ability to list suggested paths for specific Zen Cart configure.php parameters
// * v1.2e- minor bugfixes
// * v1.2d- minor bugfixes and code to prevent ZC info if running from zc_install folder
// * v1.2c- added support for testing emails via PHP
// * v1.2b- added support for checking numerous additional system var's
// * v1.2 - added support for checking additional system var's
// * (these "may" give errors if safe_mode has ini_get disabled)
// * v1.1 - revised to work with or without Zen files available
// * - added some CSS for easier reading
// *****************************************************************
// If the email you send is properly received, then your mailserver (PHP) configuration settings are fine.
// If the emails you send from this tool are "not" received, then you should check with your
// webhosting provider to see whether there are special requirements for sending mail
// or perhaps you need to use an authentication method such as SMTPAUTH (which this tool cannot test).
// Further, you might check the mailserver logs to see what happens to your messages
// if they are not being received at the destination you entered in $myemail above.
// suppress errors
error_reporting(E_ALL & ~E_NOTICE);
if (!isset($PHP_SELF)) $PHP_SELF = $_SERVER['PHP_SELF'];
?>
<html><head>
<title>Technical Support -- System Specs</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
h1 {
color: #B56224;
}
h2 {
color: #D67732;
}
h3 {
color: #D67630;
}
.red {
color: #FF0000;
font-weight: bolder;
}
.green {color: #009900;
font-weight: bolder;
}
-->
</style>
</head>
<body>
<?php if ($myemail !='YOUR_EMAIL_ADDRESS_GOES_HERE' && $myemail !='') { ?>
<form method="POST" action="<?php echo basename(__FILE__); ?>">
<!-- DO NOT change ANY of the php sections -->
<?php
$ipi = getenv("REMOTE_ADDR");
$httprefi = getenv ("HTTP_REFERER");
$httpagenti = getenv ("HTTP_USER_AGENT");
?>
<input type=hidden name="ip" value="<?php echo $ipi ?>">
<input type=hidden name="httpref" value="<?php echo $httprefi ?>">
<input type=hidden name="httpagent" value="<?php echo $httpagenti ?>">
Your Name: <input type=text name="visitor" size="35">
<br>
Your Email: <input type=text name="visitormail" size="35">
<br><br>
Mail Message:
<br>
<textarea name=notes rows=4 cols=40>You may optionally enter a message here.</textarea>
<br>
<input type=submit name="submit" VALUE="Send Mail">
</form>
<?php
if (!isset($visitormail)) echo "Please fill in the fields and click Send.<br>(No content to process yet.) $ip";
$todayis = date("l, F j, Y, g:i a");
$subject = "EMAIL SYSTEM -- This is a TEST MESSAGE";
$message = " $todayis \n
Message: $notes \n
From: $visitor ($visitormail)\n
Additional Info : IP = $ip \n
Browser Info: $httpagent \n
Referral : $httpref \n
";
$from = "From: $myemail\r\n";
if ($myemail != "" && isset($_POST['submit']) ) {
mail($myemail, $subject, $message, $from);
}
?>
<p align=center><b>
Date: <?php echo $todayis ?>
<br>
Thank You : <?php echo $visitor ?> ( <?php echo $visitormail ?> )
<br>
<?php echo $ip ?></b>
<br><br>
<a href="<?php echo basename(__FILE__); ?>"> Send Another </a>
</p>
<?php
} else {
echo '<span class=green><em>{if you wish to enable email-testing support, please edit this file ('.basename(__FILE__).') and enter your email address at the top on the 3rd line}</span></em><br />';
}
?>
<h1>Server Configuration Details</h1>
<h2>Server Info</h2>
<ul>
<li><strong>Webserver: </strong><?=getenv("SERVER_SOFTWARE")?></li><br /><br />
<?php
$disk_freespaceGB=round(@diskfreespace(__FILE__)/1024/1024/1024,2);
$disk_freespaceMB=round(@diskfreespace(__FILE__)/1024/1024,2);
?>
<li><?php echo '<strong>Server Free Disk Space Reported</strong> = '.$disk_freespaceGB; ?> GB</li><br /><br />
<li><?php echo '<strong>MySQL Version Reported </strong>= '. @mysql_get_server_info(); ?></li>
<li><?php echo '<strong>PHP MySQL Support</strong> = '.(function_exists( 'mysql_connect' ) ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP PostGres SQL Support</strong> = '.(function_exists( 'pg_connect' ) ? ON : OFF); ?></li>
</ul>
<h2>PHP Info</h2><ul>
<li><strong>PHP version: </strong>
<? if (phpversion()=="4.1.2") {
echo "<span class='red'>".phpversion()." {You SHOULD upgrade this!}</span>";
} else {
echo phpversion();
} ?></li>
<li><?php echo '<strong>PHP API version</strong>= '.@php_sapi_name(); ?></li>
<li><strong>PHP Safe Mode</strong>=
<? if (ini_get("safe_mode")) {
echo "<span class='red'>ON</span>";
} else{
echo "OFF";
} ?></li>
<li><?php echo '<strong>PHP Register Globals</strong> = '.(ini_get('register_globals') ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP set_time_limit</strong> (max execution time) = '.ini_get("max_execution_time"); ?></li>
<li><?php echo '<strong>PHP Disabled Functions </strong>= '.ini_get("disable_functions"); ?></li>
<li><?php echo '<strong>PHP open_basedir </strong>= '.ini_get("open_basedir"); ?></li>
<li><?php echo '<strong>PHP Sessions Support </strong>= '.(@extension_loaded('session') ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP session.auto_start</strong> = '.(ini_get('session.auto_start') ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP session.use_trans_sid</strong> = '.(ini_get('session.use_trans_sid') ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP session.save_path = </strong>'.ini_get("session.save_path"); ?></li>
<li><?php echo '<strong>PHP Magic_Quotes_Runtime</strong> = '.(@get_magic_quotes_runtime() > 0 ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP GD Support</strong> = '.(@extension_loaded('gd')? ON : OFF); ?></li>
<li><?php echo '<strong>PHP ZLIB Support</strong> = '.(@extension_loaded('zlib')? ON : OFF); ?></li>
<li><?php echo '<strong>PHP OpenSSL Support</strong> = '.(@extension_loaded('openssl') ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP CURL Support</strong> = '.(@extension_loaded('curl') ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP File Uploads</strong> = '.(@ini_get('file_uploads') ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP File Upload Max Size</strong> = '.@ini_get('upload_max_filesize'); ?></li>
<li><?php echo '<strong>PHP Post Max Size</strong> = '.@ini_get('post_max_size'); ?></li>
<li><?php echo '<strong>PHP File Upload TMP Dir</strong> = '.ini_get("upload_tmp_dir"); ?></li>
<li><?php echo '<strong>PHP XML Support </strong>= '.(function_exists('xml_parser_create') ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP FTP Support</strong> = '.(@extension_loaded('ftp') ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP PFPRO Support</strong> = '.(@extension_loaded('pfpro') ? ON : OFF); ?></li>
<li><?php echo '<strong>PHP Sendmail_FROM</strong> = '.ini_get("sendmail_from"); ?></li>
<li><?php echo '<strong>PHP Sendmail_PATH</strong> = '.ini_get("sendmail_path"); ?></li>
<li><?php echo '<strong>PHP SMTP Settings</strong> = '.ini_get("SMTP"); ?></li>
<li><?php echo '<strong>PHP include_path = </strong>'.ini_get("include_path"); ?></li>
</ul>
<h2>Webserver/Page Info</h2>
<ul>
<li><?php echo '<strong>HTTP_HOST= </strong>"'.$_SERVER['HTTP_HOST'].'"'; ?></li>
<li><?php echo '<strong>HTTPS= </strong>"'.$_SERVER['HTTPS'].'"'; ?></li>
<li><?php echo '<strong>HTTP_USER_AGENT= </strong>"'.$_SERVER['HTTP_USER_AGENT'].'"'; ?></li>
<li><?php echo '<strong>HTTP_REFERRER= </strong>"'.$_SERVER['HTTP_REFERRER'].'"'; ?></li>
<li><?php echo '<strong>HTTP_ACCEPT= </strong>"'.$_SERVER['HTTP_ACCEPT'].'"'; ?></li>
<li><?php echo '<strong>HTTP_ACCEPT_LANGUAGE= </strong>"'.$_SERVER['HTTP_ACCEPT_LANGUAGE'].'"'; ?></li>
<li><?php echo '<strong>HTTP_ACCEPT_CHARSET= </strong>"'.$_SERVER['HTTP_ACCEPT_CHARSET'].'"'; ?></li>
<li><?php echo '<strong>HTTP_KEEP_ALIVE</strong>= "'.$_SERVER['HTTP_KEEP_ALIVE'].'"'; ?></li>
<li><?php echo '<strong>HTTP_CONNECTION</strong>= "'.$_SERVER['HTTP_CONNECTION'].'"'; ?></li>
<li><?php echo '<strong>PATH</strong>= "'.$_SERVER['PATH'].'"'; ?></li>
<li><?php echo '<strong>SERVER_ADMIN</strong>= "'.$_SERVER['SERVER_ADMIN'].'"'; ?></li>
<li><?php echo '<strong>SERVER_SOFTWARE</strong>= "'.$_SERVER['SERVER_SOFTWARE'].'"'; ?></li>
<li><?php echo '<strong>SERVER_NAME</strong>= "'.$_SERVER['SERVER_NAME'].'"'; ?></li>
<li><?php echo '<strong>DOCUMENT_ROOT</strong>= "'.$_SERVER['DOCUMENT_ROOT'].'"'; ?></li>
<li><?php echo '<span class=red>REQUEST_URI= "'.$_SERVER['REQUEST_URI'].'"</span>'; ?></li>
<li><?php echo '<span class=red>SCRIPT_NAME= "'.$_SERVER['SCRIPT_NAME'].'"</span>'; ?></li>
<li><?php echo '<span class=red>PHP_SELF= "'.$_SERVER['PHP_SELF'].'"</span>'; ?></li>
<li><?php echo '<span class=red>SCRIPT_FILENAME= "'.$_SERVER['SCRIPT_FILENAME'].'"</span>'; ?></li>
<li><?php echo '<span class=red>PATH_TRANSLATED= "'.$_SERVER['PATH_TRANSLATED'].'"</span>'; ?></li>
<li><?php echo '<span class=red>PHP __FILE__: "'.__FILE__.'"</span>'; ?></li>
<li><?php echo '<span class=red>PHP basename: "'.basename($PHP_SELF).'"</span>'; ?></li>
<li><?php echo '<span class=red>PHP dirname(self): "'.dirname($PHP_SELF).'"</span>'; ?></li>
<li><?php echo '<strong>SERVER_ADDR</strong>= "'.$_SERVER['SERVER_ADDR'].'"'; ?></li>
<li><?php echo '<strong>SERVER_PORT</strong>= "'.$_SERVER['SERVER_PORT'].'"'; ?></li>
<li><?php echo '<strong>REMOTE_HOST</strong>= "'.$_SERVER['REMOTE_HOST'].'"'; ?></li>
<li><?php echo '<strong>REMOTE_ADDR</strong>= "'.$_SERVER['REMOTE_ADDR'].'"'; ?></li>
<li><?php echo '<strong>REMOTE_PORT</strong>= "'.$_SERVER['REMOTE_PORT'].'"'; ?></li>
<li><?php echo '<strong>HTTP_X_FORWARDED_FOR</strong>= "'.$_SERVER['HTTP_X_FORWARDED_FOR'].'"'; ?></li>
<li><?php echo '<strong>HTTP_CLIENT_IP</strong>= "'.$_SERVER['HTTP_CLIENT_IP'].'"'; ?></li>
<li><?php echo '<strong>GATEWAY_INTERFACE</strong>= "'.$_SERVER['GATEWAY_INTERFACE'].'"'; ?></li>
<li><?php echo '<strong>SERVER_PROTOCOL</strong>= "'.$_SERVER['SERVER_PROTOCOL'].'"'; ?></li>
<li><?php echo '<strong>REQUEST_METHOD</strong>= "'.$_SERVER['REQUEST_METHOD'].'"'; ?></li>
<li><?php echo '<strong>QUERY_STRING</strong>= "'.$_SERVER['QUERY_STRING'].'"'; ?></li>
<li><?php echo '<strong>SERVER_SIGNATURE</strong>= "'.$_SERVER['SERVER_SIGNATURE'].'"'; ?></li>
</ul>
<h2>Zen Cart SUGGESTED path settings</h2>
<ul><h3>/includes/configure.php</h3>
<ul>
<li><strong>HTTP_SERVER: </strong> <?php echo 'http://'.$_SERVER['SERVER_NAME']; ?></li>
<li><strong>HTTPS_SERVER: </strong> <?php echo 'see Note...<span class=red>**</span>'; ?></li>
<li><strong>DIR_WS_CATALOG: </strong> <?php echo dirname($PHP_SELF); ?>/</li>
<li><strong>DIR_FS_CATALOG: </strong> <?php echo str_replace(basename($PHP_SELF),'',__FILE__); ?></li>
<li><strong>DIR_FS_SQL_CACHE: </strong> <?php echo str_replace(basename($PHP_SELF),'',__FILE__); ?>cache/</li>
</ul>
<h3>/admin/includes/configure.php</h3>
<ul>
<li><strong>HTTP_SERVER: </strong> <?php echo 'http://'.$_SERVER['SERVER_NAME']; ?></li>
<li><strong>HTTPS_SERVER: </strong> <?php echo 'see Note...<span class=red>**</span>'; ?></li>
<li><strong>HTTP_CATALOG_SERVER: </strong> <?php echo 'http://'.$_SERVER['SERVER_NAME']; ?></li>
<li><strong>HTTPS_CATALOG_SERVER: </strong> <?php echo 'see Note...<span class=red>**</span>'; ?></li>
<li><strong>DIR_WS_ADMIN: </strong> <?php echo dirname($PHP_SELF); ?>/admin/</li>
<li><strong>DIR_WS_CATALOG: </strong> <?php echo dirname($PHP_SELF); ?>/</li>
<li><strong>DIR_FS_ADMIN: </strong> <?php echo str_replace(basename($PHP_SELF),'',__FILE__); ?>admin/</li>
<li><strong>DIR_FS_CATALOG: </strong> <?php echo str_replace(basename($PHP_SELF),'',__FILE__); ?></li>
<li><strong>DIR_FS_SQL_CACHE: </strong> <?php echo str_replace(basename($PHP_SELF),'',__FILE__); ?>cache/</li>
</ul>
<span class="red">**</span> NOTE: This depends on your hosting arrangements. Talk to your hosting company for how to configure SSL on your server.
<br /></ul>
<br />
<?php
// Report the Zen Cart System info, if available.
if (file_exists('includes/application_top.php')) {
$path = (substr_count(__FILE__,'zc_install') || file_exists('mysql_zencart.sql')) ? '../' : '';
?>
<h2>Zen Cart System Info:</h2><ul>
<h3>System Folder Checkup</h3><ul>
<?php
//check folders status
foreach (array('cache'=>'777 read/write/execute',
'images'=>'777 read/write/execute (INCLUDE SUBDIRECTORIES TOO)',
'includes/languages/english/html_includes'=>'777 read/write (INCLUDE SUBDIRECTORIES TOO)',
'pub'=>'777 read/write/execute',
'admin/backups'=>'777 read/write',
'admin/images/graphs'=>'777 read/write/execute')
as $folder=>$chmod) {
$status = (@is_writable($path.$folder))? OK :(UNWRITABLE . ' ' . $chmod);
echo '<li><strong>Folder:</strong> '.$path.$folder . ' <strong>' . $status .'</strong></li>';
} ?>
</ul>
<?php if (substr_count(__FILE__,'zc_install') <1 && !file_exists('mysql_zencart.sql') ) {
if (headers_sent) echo 'YOU CAN SAFELY IGNORE THE FOLLOWING "Headers already sent" ERRORS:';
include('includes/application_top.php'); ?>
<h3>From APPLICATION_TOP.PHP</h3><ul>
<li><strong>Version: </strong><? echo PROJECT_VERSION_NAME; ?></li><br />
<li><strong>Version Major: </strong><? echo PROJECT_VERSION_MAJOR; ?></li><br />
<li><strong>Version Minor: </strong><? echo PROJECT_VERSION_MINOR; ?></li>
</ul>
<h3>Settings from Zen Cart Database:</h3><ul>
<li><strong>Installed Payment Modules: </strong><? echo MODULE_PAYMENT_INSTALLED; ?></li><br />
<li><strong>Installed Order Total Modules: </strong><? echo MODULE_ORDER_TOTAL_INSTALLED; ?></li><br />
<li><strong>Installed Shipping Modules: </strong><? echo MODULE_SHIPPING_INSTALLED; ?></li><br />
<li><strong>Default Currency: </strong><? echo DEFAULT_CURRENCY; ?></li><br />
<li><strong>Default Language: </strong><? echo DEFAULT_LANGUAGE; ?></li><br />
<li><strong>Enable Downloads: </strong><? echo DOWNLOAD_ENABLED; ?></li><br />
<li><strong>Enable GZip Compression: </strong><? echo GZIP_LEVEL; ?></li><br />
<li><strong>Admin Demo Status: </strong><? echo ADMIN_DEMO; ?></li>
</ul>
<?php
} //endif check if we're in zc_install
?>
</ul>
<?php
} //endif exists app_top
?>
<br /><strong><h2>PHP Modules:</h2></strong><ul>
<?
$le = get_loaded_extensions();
foreach($le as $module) {
print "<li>$module</li>";
}
?>
</ul>
<h2>PHP Info</h2><?php phpinfo(); ?>
<?php
echo "<br /><strong>SERVER variables:</strong><br />";
foreach($_SERVER as $key=>$value) {
echo "$key => $value<br />";
}
// now break it out into objects and arrays, if relevant
foreach($_SERVER as $key=>$value) {
if (is_object($value)) {
foreach($value as $subvalue) {
if (is_object($subvalue) || is_array($subvalue)) {
foreach($subvalue as $subvalue2) {
echo $key.'['.$value.']['.$subvalue.'] => '.$subvalue2.'<br />';
}
} else {
echo $key.'['.$value.'] => '.$subvalue.'<br />';
}
}
} else if (is_array($value)) {
foreach($value as $subvalue) {
if (is_array($subvalue)) {
foreach($subvalue as $subvalue2) {
echo $key.'['.$value.']['.$subvalue.'] => '.$subvalue2.'<br />';
}
} else {
echo $key.'['.$value.'] => '.$subvalue.'<br />';
}
}
} else {
// echo "$key => $value<br />";
}
}
?>
</body>
</html> | gpl-2.0 |
DNPA/OcfaArch | datainput/kaas/src/kaas.cpp | 8764 | // The Open Computer Forensics Architecture.
// Copyright (C) 2003..2006 KLPD <[email protected]>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include<iostream>
#include <facade/KickstartAccessor.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPCookie.h"
#include "Poco/Net/HTTPStream.h"
#include "Poco/InflatingStream.h"
#include <unistd.h>
#include <sstream>
#include <getopt.h>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;
class KaasHttpRequestHandler: public Poco::Net::HTTPRequestHandler
{
public:
KaasHttpRequestHandler(std::string inv,std::string name):mCase(inv),mModule(name) {}
void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
while (waitpid(-1,NULL,WNOHANG) > 0) {;}
std::string body;
request.stream() >> body;
std::stringstream ss;
ss << body;
boost::property_tree::ptree pt;
boost::property_tree::json_parser::read_json(ss,pt);
std::string givenCaseName = pt.get("case", "");
std::string sourceName = pt.get("source", "");
std::string itemName=pt.get("item", "");
std::string evidenceName="kaasitem";
std::string path=pt.get("uri", "");
if ( givenCaseName != mCase) {
response.setStatus(Poco::Net::HTTPServerResponse::HTTP_FORBIDDEN);
response.setReason("Incompativle investigation name");
response.setContentType("text/plain");
std::ostream &out=response.send();
//out << "Invalid case" << std::endl;
return;
}
if ((sourceName == "") || ( itemName == "") || (path == "")) {
response.setStatus(Poco::Net::HTTPServerResponse::HTTP_BAD_REQUEST);
response.setReason("Invalid or incomplete json command");
response.setContentType("text/plain");
std::ostream &out=response.send();
//out << "Problem processing json command" << std::endl;
return;
} else {
std::map<std::string,ocfa::misc::Scalar> attr;
response.setContentType("text/plain");
std::ostream &out=response.send();
out << "<H1>Starting kickstart into background process</H1>" << std::endl;
out << "Please watch the ocfa logging to see if kickstarting succeeded." << std::endl;
pid_t pid=fork();
if (pid == 0) {
try {
ocfa::facade::KickstartAccessor kickstart(mModule,"kaas");
if (mModule == "kickstart") {
kickstart.KickstartEvidence(mCase,sourceName,itemName,path,"LATIN1", evidenceName);
} else {
kickstart.TreeGraphKickstart(mCase,sourceName,itemName,evidenceName,mModule,&attr,path);
}
} catch (ocfa::misc::OcfaException &e) {
e.logWhat();
}
exit(0);
}
}
}
private:
std::string mCase;
std::string mModule;
};
class KaasHttpRequestHandlerFactory: public Poco::Net::HTTPRequestHandlerFactory
{
public:
KaasHttpRequestHandlerFactory(std::string inv,std::string name):mCase(inv),mModule(name) {}
Poco::Net::HTTPRequestHandler* createRequestHandler(const Poco::Net::HTTPServerRequest& request)
{
return new KaasHttpRequestHandler(mCase,mModule);
}
private:
std::string mCase;
std::string mModule;
};
class KaasService: public Poco::Util::ServerApplication
{
public:
KaasService(int port,std::string inv,std::string name):mServerPort(port),mCase(inv),mModule(name) {}
~KaasService() {}
protected:
void initialize(Application& self)
{
ServerApplication::initialize(self);
}
void uninitialize()
{
ServerApplication::uninitialize();
}
int main(const std::vector<std::string>& args)
{
Poco::Net::ServerSocket svs( mServerPort );
Poco::Net::HTTPServer srv(new KaasHttpRequestHandlerFactory(mCase,mModule), svs, new Poco::Net::HTTPServerParams);
srv.start();
waitForTerminationRequest();
srv.stop();
return Application::EXIT_OK;
}
private:
int mServerPort;
std::string mCase;
std::string mModule;
};
void usage(){
cout << "The kaas tool requires multiple options to be set, and has some aditional options: " << std::endl;
cout << " -M --module <modname> : Specify the treegraph module to load. (optional, default=kickstart) " << std::endl;
cout << " -P --port <port> : Specify the port to listen on. (optional, default=17488) " << std::endl;
cout << " -C --case <casename> : Specify the name of the active investigation. (optional, default=$OCFACASE) " << std::endl;
cout << " -a --attribute <k>=<v>: Specify a module specific attribute. You can specify multiple attributes" << std::endl;
cout << " this way by repeating the -a/--attribute multiple times. (optional)" << std::endl;
cout << std::endl;
cout << "Examples ::" << std::endl;
cout << " kaas -M sl -P 17489" << std::endl;
cout << " kaas" << std::endl;
exit(1);
}
int main(int argc, char *argv[]){
string caseName="";
int serverport = 17488;
string moduleName="kickstart";
char *ocfacaseenv=getenv("OCFACASE");
if (ocfacaseenv != 0) {
caseName=ocfacaseenv;
}
static struct option long_options[] = {
{"module",1,NULL,'M'},
{"case",1,NULL,'C'},
{"port",1,NULL,'P'},
{"help",1,NULL,'h'},
{"attribute",1,NULL,'a'},
{"daemon",1,NULL,'d'},
{0,0,0,0}
};
int c;
std::map<std::string,ocfa::misc::Scalar> attr;
while ((c=getopt_long(argc,argv,"M:C:P:a:h:",long_options,NULL)) != -1) {
switch(c) {
case ('M'): moduleName=optarg;
break;
case ('C'): caseName=optarg;
break;
case ('P'): serverport=boost::lexical_cast<int>(optarg);
if (serverport < 1024) {
std::cerr << "Invalid server port specified: " << serverport << "Reverting to default" << std::endl;
serverport = 17488;
}
break;
case ('a'): {
std::string keyVal=optarg;
int l = keyVal.length();
int i = keyVal.find_first_of("=");
if ((i > 0) && (i < l - 1)) {
std::string key = keyVal.substr(0, i);
std::string value = keyVal.substr(i + 1, keyVal.length() - 1);
attr[key]=value;
}
}
break;
case ('h'): usage();
exit(0);
break;
}
}
bool allok=true;
if (caseName=="") {
std::cerr << "casename name not specified" << std::endl;
allok=false;
}
if (allok == false) {
usage();
}
if (ocfacaseenv) {
if (strcmp(ocfacaseenv,caseName.c_str())) {
cerr << "ERROR: The OCFACASE enviroment variable is set to '" << ocfacaseenv << "' while the case specified is '" << caseName << "'!\n";
return 1;
}
}
cerr << "Starting Kaas service on port " << serverport << " casenmame=" << caseName << " modulename=" << moduleName << std::endl;
KaasService kaas(serverport,caseName,moduleName);
char* myargv[2];
myargv[0]=argv[0];
char daemon[40];
strcpy(daemon,"--daemon");
myargv[1]=daemon;
return kaas.run(2,myargv);
}
| gpl-2.0 |
Tjdowdell/Susan_Batchelor_Website | wp-content/plugins/appointment-booking/backend/modules/calendar/resources/js/ng-appointment_dialog.js | 30310 | ;(function() {
var module = angular.module('appointmentDialog', ['ui.date', 'customerDialog']);
/**
* DataSource service.
*/
module.factory('dataSource', function($q, $rootScope, $filter) {
var ds = {
loaded : false,
data : {
staff : [],
customers : [],
start_time : [],
end_time : [],
time_interval : 900,
status : {
items: [],
default: null
}
},
form : {
id : null,
staff : null,
service : null,
date : null,
start_time : null,
end_time : null,
customers : [],
notification : null
},
loadData : function() {
var deferred = $q.defer();
if (!ds.loaded) {
jQuery.get(
ajaxurl,
{ action : 'ab_get_data_for_appointment_form' },
function(data) {
ds.loaded = true;
ds.data = data;
// Add empty element to beginning of array for single-select customer form
ds.data.customers.unshift({name: ''});
if (data.staff.length) {
ds.form.staff = data.staff[0];
}
ds.form.start_time = data.start_time[0];
ds.form.end_time = data.end_time[1];
deferred.resolve();
},
'json'
);
} else {
deferred.resolve();
}
return deferred.promise;
},
findStaff : function(id) {
var result = null;
jQuery.each(ds.data.staff, function(key, item) {
if (item.id == id) {
result = item;
return false;
}
});
return result;
},
findService : function(staff_id, id) {
var result = null,
staff = ds.findStaff(staff_id);
if (staff !== null) {
jQuery.each(staff.services, function(key, item) {
if (item.id == id) {
result = item;
return false;
}
});
}
return result;
},
findTime : function(source, date) {
var result = null,
value_to_find = $filter('date')(date, 'HH:mm'),
time = source == 'start' ? ds.data.start_time : ds.data.end_time;
jQuery.each(time, function(key, item) {
if (item.value >= value_to_find) {
result = item;
return false;
}
});
return result;
},
findCustomer : function(id) {
var result = null;
jQuery.each(ds.data.customers, function(key, item) {
if (item.id == id) {
result = item;
return false;
}
});
return result;
},
resetCustomers : function() {
ds.data.customers.forEach(function(customer) {
customer.custom_fields = [];
customer.extras = [];
customer.status = ds.data.status.default;
customer.number_of_persons = 1;
customer.payment_gateway = null;
customer.payment_id = null;
customer.payment_title = null;
customer.compound_token = null;
});
},
getDataForEndTime : function() {
var result = [];
if (ds.form.start_time) {
var start_time = ds.form.start_time.value.split(':'),
end = (24 + parseInt(start_time[0])) + ':' + start_time[1];
jQuery.each(ds.data.end_time, function(key, item) {
if (item.value > end) {
return false;
}
if (item.value > ds.form.start_time.value) {
result.push(item);
}
});
}
return result;
},
setEndTimeBasedOnService : function() {
var i = jQuery.inArray(ds.form.start_time, ds.data.start_time),
d = ds.form.service ? ds.form.service.duration : ds.data.time_interval;
if (ds.form.service && ds.form.service.duration == 86400) {
ds.form.start_time = ds.data.start_time[0];
ds.form.end_time = ds.data.end_time[ 86400 / ds.data.time_interval ];
} else {
if (i !== -1) {
for (; i < ds.data.end_time.length; ++i) {
d -= ds.data.time_interval;
if (d < 0) {
break;
}
}
ds.form.end_time = ds.data.end_time[i];
}
}
},
getStartAndEndDates : function() {
var start_date = new Date(ds.form.date.getTime()),
start_time = ds.form.start_time.value.split(':'),
end_date = new Date(ds.form.date.getTime()),
end_time = ds.form.end_time.value.split(':');
start_date.setHours(start_time[0]);
start_date.setMinutes(start_time[1]);
end_date.setHours(end_time[0]);
end_date.setMinutes(end_time[1]);
return {
start_date : $filter('date')(start_date, 'yyyy-MM-dd HH:mm:00'),
end_date : $filter('date')(end_date, 'yyyy-MM-dd HH:mm:00')
};
},
getTotalNumberOfPersons : function () {
var result = 0;
ds.form.customers.forEach(function (item) {
result += parseInt(item.number_of_persons);
});
return result;
},
getTotalNotCancelledNumberOfPersons: function () {
var result = 0;
ds.form.customers.forEach(function (item) {
if (item.status != 'cancelled') {
result += parseInt(item.number_of_persons);
}
});
return result;
},
depositCompletePayment : function (payment_id, ca_id) {
jQuery.post(
ajaxurl,
{action: 'bookly_deposit_payments_complete_payment', payment_id: payment_id, ca_id: ca_id},
function (data) { },
'json'
);
}
};
return ds;
});
/**
* Controller for 'create/edit appointment' dialog form.
*/
module.controller('appointmentDialogCtrl', function($scope, $element, dataSource) {
// Set up initial data.
$scope.$calendar = null;
// Set up data source.
$scope.dataSource = dataSource;
$scope.form = dataSource.form; // shortcut
// Error messages.
$scope.errors = {};
// Callback to be called after editing appointment.
var callback = null;
/**
* Prepare the form for new event.
*
* @param int staff_id
* @param moment start_date
* @param function _callback
*/
$scope.configureNewForm = function(staff_id, start_date, _callback) {
jQuery.extend($scope.form, {
id : null,
staff : dataSource.findStaff(staff_id),
service : null,
date : start_date.clone().local().toDate(),
start_time : dataSource.findTime('start', start_date.format('HH:mm')),
end_time : null,
customers : [],
notification : 'no',
internal_note : null
});
$scope.errors = {};
dataSource.setEndTimeBasedOnService();
callback = _callback;
$scope.reInitChosen();
$scope.prepareExtras();
$scope.prepareCustomFields();
$scope.dataSource.resetCustomers();
};
/**
* Prepare the form for editing an event.
*/
$scope.configureEditForm = function(appointment_id, _callback) {
$scope.loading = true;
jQuery.post(
ajaxurl,
{action: 'ab_get_data_for_appointment', id: appointment_id},
function(response) {
$scope.$apply(function($scope) {
if (response.success) {
var start_date = moment(response.data.start_date),
end_date = moment(response.data.end_date);
jQuery.extend($scope.form, {
id : appointment_id,
staff : $scope.dataSource.findStaff(response.data.staff_id),
service : $scope.dataSource.findService(response.data.staff_id, response.data.service_id),
date : start_date.clone().local().toDate(),
start_time : $scope.dataSource.findTime('start', start_date.format('HH:mm')),
end_time : start_date.format('YYYY-MM-DD') == end_date.format('YYYY-MM-DD')
? $scope.dataSource.findTime('end', end_date.format('HH:mm'))
: $scope.dataSource.findTime('end', (24 + end_date.hour()) + end_date.format(':mm')),
customers : [],
notification : 'no',
internal_note : response.data.internal_note
});
$scope.reInitChosen();
$scope.prepareExtras();
$scope.prepareCustomFields();
$scope.dataSource.resetCustomers();
var customers_ids = [];
response.data.customers.forEach(function (item, i, arr) {
var customer = $scope.dataSource.findCustomer(item.id),
clone = {};
if (customers_ids.indexOf(item.id) === -1) {
customers_ids.push(item.id);
clone = customer;
} else {
// For Error: ngRepeat:dupes & chosen directive
angular.copy(customer, clone);
}
clone.ca_id = item.ca_id;
clone.extras = item.extras;
clone.status = item.status;
clone.payment_id = item.payment_id;
clone.custom_fields = item.custom_fields;
clone.number_of_persons = item.number_of_persons;
clone.payment_gateway = item.payment_gateway;
clone.payment_title = item.payment_title;
clone.compound_token = item.compound_token;
clone.compound_service = item.compound_service;
clone.deposit = item.deposit;
clone.deposit_due = item.deposit_due;
clone.deposit_payment_complete = item.deposit_payment_complete;
$scope.form.customers.push(clone);
});
}
$scope.loading = false;
});
},
'json'
);
$scope.errors = {};
callback = _callback;
};
var checkTimeInterval = function() {
var dates = $scope.dataSource.getStartAndEndDates();
jQuery.get(
ajaxurl,
{
action : 'ab_check_appointment_date_selection',
start_date : dates.start_date,
end_date : dates.end_date,
appointment_id : $scope.form.id,
staff_id : $scope.form.staff ? $scope.form.staff.id : null,
service_id : $scope.form.service ? $scope.form.service.id : null
},
function (response) {
$scope.$apply(function ($scope) {
$scope.errors = response;
});
},
'json'
);
};
$scope.onServiceChange = function() {
$scope.dataSource.setEndTimeBasedOnService();
$scope.reInitChosen();
$scope.prepareExtras();
$scope.prepareCustomFields();
checkTimeInterval();
};
$scope.onStaffChange = function() {
$scope.form.service = null;
};
$scope.onStartTimeChange = function() {
$scope.dataSource.setEndTimeBasedOnService();
checkTimeInterval();
};
$scope.onEndTimeChange = function() {
checkTimeInterval();
};
$scope.processForm = function() {
$scope.loading = true;
var dates = $scope.dataSource.getStartAndEndDates(),
customers = []
;
$scope.form.customers.forEach(function (item, i, arr) {
var customer_extras = {};
if ($scope.form.service) {
jQuery('#bookly-extras .service_' + $scope.form.service.id + ' input.extras-count').each(function () {
var extra_id = jQuery(this).data('id');
if (item.extras[extra_id] !== undefined) {
customer_extras[extra_id] = item.extras[extra_id];
}
});
}
customers.push({
id : item.id,
custom_fields : item.custom_fields,
extras : customer_extras,
status : item.status,
number_of_persons : item.number_of_persons,
ca_id : item.ca_id
});
});
jQuery.post(
ajaxurl,
{
action : 'ab_save_appointment_form',
id : $scope.form.id,
staff_id : $scope.form.staff ? $scope.form.staff.id : null,
service_id : $scope.form.service ? $scope.form.service.id : null,
start_date : dates.start_date,
end_date : dates.end_date,
customers : JSON.stringify(customers),
notification : $scope.form.notification,
internal_note : $scope.form.internal_note
},
function (response) {
$scope.$apply(function($scope) {
if (response.success) {
if (callback) {
// Call callback.
callback(response.data);
}
// Close the dialog.
$element.children().modal('hide');
} else {
$scope.errors = response.errors;
}
$scope.loading = false;
});
},
'json'
);
};
// On 'Cancel' button click.
$scope.closeDialog = function () {
// Close the dialog.
$element.children().modal('hide');
};
$scope.reInitChosen = function () {
jQuery('#chosen')
.chosen('destroy')
.chosen({
search_contains : true,
width : '100%',
max_selected_options: dataSource.form.service ? dataSource.form.service.capacity : 0
});
};
$scope.statusToString = function (status) {
return dataSource.data.status.items[status];
};
/**************************************************************************************************************
* New customer *
**************************************************************************************************************/
/**
* Create new customer.
* @param customer
*/
$scope.createCustomer = function(customer) {
// Add new customer to the list.
var new_customer = {
id : customer.id.toString(),
name : customer.name,
custom_fields : customer.custom_fields,
extras : customer.extras,
status : customer.status,
number_of_persons : 1
};
if (customer.email || customer.phone){
new_customer.name += ' (' + [customer.email, customer.phone].filter(Boolean).join(', ') + ')';
}
dataSource.data.customers.push(new_customer);
// Make it selected.
if (!dataSource.form.service || dataSource.form.customers.length < dataSource.form.service.capacity) {
dataSource.form.customers.push(new_customer);
}
setTimeout(function() { jQuery('#chosen').trigger('chosen:updated'); }, 0);
};
$scope.removeCustomer = function(customer) {
$scope.form.customers.splice($scope.form.customers.indexOf(customer), 1);
};
/**************************************************************************************************************
* Customer Details *
**************************************************************************************************************/
$scope.editCustomerDetails = function(customer) {
var $dialog = jQuery('#bookly-customer-details-dialog');
$dialog.find('input.ab-custom-field:text, textarea.ab-custom-field, select.ab-custom-field').val('');
$dialog.find('input.ab-custom-field:checkbox, input.ab-custom-field:radio').prop('checked', false);
$dialog.find('#bookly-extras :checkbox').prop('checked', false);
customer.custom_fields.forEach(function (field) {
var $custom_field = $dialog.find('#ab--custom-fields > *[data-id="' + field.id + '"]');
switch ($custom_field.data('type')) {
case 'checkboxes':
field.value.forEach(function (value) {
$custom_field.find('.ab-custom-field').filter(function () {
return this.value == value;
}).prop('checked', true);
});
break;
case 'radio-buttons':
$custom_field.find('.ab-custom-field').filter(function () {
return this.value == field.value;
}).prop('checked', true);
break;
default:
$custom_field.find('.ab-custom-field').val(field.value);
break;
}
});
angular.forEach(customer.extras, function (extra_count, extra_id) {
$dialog.find('#bookly-extras .extras-count[data-id="' + extra_id + '"]').val(extra_count);
});
// Prepare select for number of persons.
var $number_of_persons = $dialog.find('#ab-edit-number-of-persons');
var max = $scope.form.service
? parseInt($scope.form.service.capacity) - $scope.dataSource.getTotalNotCancelledNumberOfPersons() + ( customer.status != 'cancelled' ? parseInt(customer.number_of_persons) : 0 )
: 1;
$number_of_persons.empty();
for (var i = 1; i <= max; ++i) {
$number_of_persons.append('<option value="' + i + '">' + i + '</option>');
}
if (customer.number_of_persons > max) {
$number_of_persons.append('<option value="' + customer.number_of_persons + '">' + customer.number_of_persons + '</option>');
}
$number_of_persons.val(customer.number_of_persons);
$dialog.find('#ab-appointment-status').val(customer.status);
// Deposit
$dialog.find('#ab-deposit').val(customer.deposit);
$dialog.find('#ab-deposit-due').val(customer.deposit_due);
if (customer.deposit_payment_complete) {
$dialog.find('#ab-deposit-block').hide();
} else {
$dialog.find('#ab-deposit-block').show();
$dialog.find('#ab-deposit-complete-payment').on('click', function () {
$scope.dataSource.depositCompletePayment(customer.payment_id, customer.ca_id);
customer.deposit_payment_complete = true;
customer.deposit_due = 0;
$dialog.find('#ab-deposit-block').hide();
});
}
// this is used in SaveCustomFields()
$scope.edit_customer = customer;
$dialog.modal({show: true, backdrop: false})
.on('hidden.bs.modal', function () {
jQuery('body').addClass('modal-open');
});
};
$scope.prepareExtras = function () {
if ($scope.form.service) {
jQuery('#bookly-extras > *').hide();
var $service_extras = jQuery('#bookly-extras .service_' + $scope.form.service.id);
if ($service_extras.length) {
$service_extras.show();
jQuery('#bookly-extras').show();
} else {
jQuery('#bookly-extras').hide();
}
} else {
jQuery('#bookly-extras').hide();
}
};
// Hide or unhide custom fields for current service
$scope.prepareCustomFields = function () {
if (BooklyL10nAppDialog.cf_per_service == 1) {
var show = false;
jQuery('#ab--custom-fields div[data-services]').each(function() {
var $this = jQuery(this);
if (dataSource.form.service !== null) {
var services = $this.data('services');
if (services && jQuery.inArray(dataSource.form.service.id, services) > -1) {
$this.show();
show = true;
} else {
$this.hide();
}
} else {
$this.hide();
}
});
if (show) {
jQuery('#ab--custom-fields').show();
} else {
jQuery('#ab--custom-fields').hide();
}
}
};
$scope.saveCustomFields = function() {
var result = [],
extras = {},
$fields = jQuery('#ab--custom-fields > *'),
$number_of_persons = jQuery('#bookly-customer-details-dialog #ab-edit-number-of-persons')
;
$fields.each(function () {
var $this = jQuery(this),
value;
if ($this.is(':visible')) {
switch ($this.data('type')) {
case 'checkboxes':
value = [];
$this.find('.ab-custom-field:checked').each(function () {
value.push(this.value);
});
break;
case 'radio-buttons':
value = $this.find('.ab-custom-field:checked').val();
break;
default:
value = $this.find('.ab-custom-field').val();
break;
}
result.push({id: $this.data('id'), value: value});
}
});
if ($scope.form.service) {
jQuery('#bookly-extras .service_' + $scope.form.service.id + ' input.extras-count').each(function () {
if (this.value > 0) {
extras[jQuery(this).data('id')] = this.value;
}
});
}
$scope.edit_customer.custom_fields = result;
$scope.edit_customer.number_of_persons = $number_of_persons.val();
$scope.edit_customer.extras = extras;
$scope.edit_customer.status = jQuery('#bookly-customer-details-dialog #ab-appointment-status').val();
jQuery('#bookly-customer-details-dialog').modal('hide');
};
/**
* Datepicker options.
*/
$scope.dateOptions = {
dateFormat : BooklyL10nAppDialog.dpDateFormat,
dayNamesMin : BooklyL10nAppDialog.calendar.shortDays,
monthNames : BooklyL10nAppDialog.calendar.longMonths,
monthNamesShort : BooklyL10nAppDialog.calendar.shortMonths,
firstDay : BooklyL10nAppDialog.startOfWeek
};
});
/**
* Directive for slide up/down.
*/
module.directive('mySlideUp', function() {
return function(scope, element, attrs) {
element.hide();
// watch the expression, and update the UI on change.
scope.$watch(attrs.mySlideUp, function(value) {
if (value) {
element.delay(0).slideDown();
} else {
element.slideUp();
}
});
};
});
/**
* Directive for chosen.
*/
module.directive('chosen',function($timeout) {
var linker = function(scope,element,attrs) {
scope.$watch(attrs['chosen'], function() {
element.trigger('chosen:updated');
});
scope.$watchCollection(attrs['ngModel'], function() {
$timeout(function() {
element.trigger('chosen:updated');
});
});
scope.reInitChosen();
};
return {
restrict:'A',
link: linker
};
});
/**
* Directive for Popover jQuery plugin.
*/
module.directive('popover', function() {
return function(scope, element, attrs) {
element.popover({
trigger : 'hover',
content : attrs.popover,
html : true,
placement: 'top',
template: '<div class="popover bookly-font-xs" style="width: 220px" role="tooltip"><div class="popover-arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
});
};
});
})();
/**
* @param int appointment_id
* @param int staff_id
* @param moment start_date
* @param function callback
*/
var showAppointmentDialog = function (appointment_id, staff_id, start_date, callback) {
var $dialog = jQuery('#bookly-appointment-dialog');
var $scope = angular.element($dialog[0]).scope();
$scope.$apply(function ($scope) {
$scope.loading = true;
$dialog
.find('.modal-title')
.text(appointment_id ? BooklyL10nAppDialog.title.edit_appointment : BooklyL10nAppDialog.title.new_appointment);
// Populate data source.
$scope.dataSource.loadData().then(function() {
$scope.loading = false;
if (appointment_id) {
$scope.configureEditForm(appointment_id, callback);
} else {
$scope.configureNewForm(staff_id, start_date, callback);
}
});
});
// hide customer details dialog, if it remained opened.
if (jQuery('#bookly-customer-details-dialog').hasClass('in')) {
jQuery('#bookly-customer-details-dialog').modal('hide');
}
// hide new customer dialog, if it remained opened.
if (jQuery('#bookly-customer-dialog').hasClass('in')) {
jQuery('#bookly-customer-dialog').modal('hide');
}
$dialog.modal('show');
}; | gpl-2.0 |
hydrodog/lightwcsp | hydroprot/server.cc | 3858 | #include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <signal.h>
#include <cstring>
#include <string>
#include <csignal>
#include <fcntl.h>
using namespace std;
#define PORT "2000"
#define BACKLOG 10
#define BUFFSIZE 1024
int server_sock = -1;
// http://www.linuxhowtos.org/C_C++/socket.htm
// Using ipv4 or ipv6
// void inline *get_in_addr(struct sockaddr *sa)
// {
// if (sa->sa_family == AF_INET)
// return &(((struct sockaddr_in*) sa)->sin_addr);
// else
// return &(((struct sockaddr_in6*) sa)->sin6_addr);
// }
void signal_handler(int sig)
{
cout << "Caught signal " << sig << endl;
if(server_sock > 0)
close(server_sock);
exit(sig);
}
void error_die(const char *s)
{
perror(s);
exit(1);
}
int startup(uint16_t& port)
{
int sockfd;
struct addrinfo hints, *servinfo, *p;
int yes = 1;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // Make connection IP version agnostic
hints.ai_socktype = SOCK_STREAM; // Will use Stream sockets / TCP
hints.ai_flags = AI_PASSIVE; // use my IP
if(getaddrinfo(nullptr,PORT,&hints,&servinfo))
error_die("getaddrinfo");
// loop on linked list to bind
for(p = servinfo; p; p = p->ai_next)
{
if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0)
{
perror("server: socket");
continue;
}
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)))
perror("setsockopt");
// tries to bind
if (::bind(sockfd, p->ai_addr, p->ai_addrlen) < 0)
{
close(sockfd);
perror("server: bind");
continue;
}
break;
}
if(!p)
error_die("Server failed to bind");
// frees linked list's allocated memory
freeaddrinfo(servinfo);
if (listen(sockfd, BACKLOG) < 0)
error_die("listen");
port = atoi(PORT);
return sockfd;
}
int main(int argc, char *argv[])
{
if(argc < 2)
{
cout << "File is missing" << endl;
return 0;
}
struct stat fstats;
int fd = open(argv[1],O_RDONLY);
if(!fd)
{
cout << "Error opening the file" << endl;
return 0;
}
if(fstat(fd,&fstats))
{
cout << "Error getting file stats" << endl;
return 0;
}
signal(SIGINT, signal_handler);
uint16_t port = 0;
int client_sock = 0;
// int server_sock = -1;;
struct sockaddr_in client_name;
socklen_t client_name_len = sizeof(client_name);
server_sock = startup(port);
cout << "Hydroprot running on port " << port << endl;
cout << "Socket: " << server_sock << endl;
char buff[BUFFSIZE];
int opt;
for(;;)
{
client_sock = accept(server_sock, (struct sockaddr *) &client_name, &client_name_len);
// cout << "Accepted socket: " << client_sock << endl;
if (client_sock >= 0)
{
// memset(buff,0,BUFFSIZE);
// Read message (same as read())
// numchars is the message lentgh, or -1 if there's an error
int numchars = read(client_sock, &opt, sizeof(int));
if(numchars < 0)
perror("read");
if(!opt)
{
read(fd,buff,BUFFSIZE);
write(client_sock,buff,BUFFSIZE);
}
else
{
char *aux = buff;
aux[0] = 1;
*((int*)(aux+1)) = 325;
aux += 1 + sizeof(int);
aux[0] = 5;
*((unsigned long long*)(aux+1)) = 223314;
aux += 1 + sizeof(unsigned long long);
aux[0] = 6;
*((float*)(aux+1)) = 22.3314;
aux += 1 + sizeof(float);
aux[0] = 7;
*((double*)(aux+1)) = 2.23314;
aux += 1 + sizeof(double);
aux[0] = 3;
*((long*)(aux+1)) = -223314;
write(client_sock, buff, BUFFSIZE - 1);
}
// Send message back (same as write())
// write(client_sock, "4988.36,00.00,4988.36,00.00,5000.00,11.64,5000.00,00.00,4988.36", BUFFSIZE - 1);
close(client_sock);
}
else
perror("accept failed\n");
}
close(server_sock);
return 0;
} | gpl-2.0 |
FFMG/myoddweb.piger | monitor/api/python/Python-3.7.2/Lib/test/test_functools.py | 82757 | import abc
import builtins
import collections
import collections.abc
import copy
from itertools import permutations
import pickle
from random import choice
import sys
from test import support
import threading
import time
import typing
import unittest
import unittest.mock
from weakref import proxy
import contextlib
import functools
py_functools = support.import_fresh_module('functools', blocked=['_functools'])
c_functools = support.import_fresh_module('functools', fresh=['_functools'])
decimal = support.import_fresh_module('decimal', fresh=['_decimal'])
@contextlib.contextmanager
def replaced_module(name, replacement):
original_module = sys.modules[name]
sys.modules[name] = replacement
try:
yield
finally:
sys.modules[name] = original_module
def capture(*args, **kw):
"""capture all positional and keyword arguments"""
return args, kw
def signature(part):
""" return the signature of a partial object """
return (part.func, part.args, part.keywords, part.__dict__)
class MyTuple(tuple):
pass
class BadTuple(tuple):
def __add__(self, other):
return list(self) + list(other)
class MyDict(dict):
pass
class TestPartial:
def test_basic_examples(self):
p = self.partial(capture, 1, 2, a=10, b=20)
self.assertTrue(callable(p))
self.assertEqual(p(3, 4, b=30, c=40),
((1, 2, 3, 4), dict(a=10, b=30, c=40)))
p = self.partial(map, lambda x: x*10)
self.assertEqual(list(p([1,2,3,4])), [10, 20, 30, 40])
def test_attributes(self):
p = self.partial(capture, 1, 2, a=10, b=20)
# attributes should be readable
self.assertEqual(p.func, capture)
self.assertEqual(p.args, (1, 2))
self.assertEqual(p.keywords, dict(a=10, b=20))
def test_argument_checking(self):
self.assertRaises(TypeError, self.partial) # need at least a func arg
try:
self.partial(2)()
except TypeError:
pass
else:
self.fail('First arg not checked for callability')
def test_protection_of_callers_dict_argument(self):
# a caller's dictionary should not be altered by partial
def func(a=10, b=20):
return a
d = {'a':3}
p = self.partial(func, a=5)
self.assertEqual(p(**d), 3)
self.assertEqual(d, {'a':3})
p(b=7)
self.assertEqual(d, {'a':3})
def test_kwargs_copy(self):
# Issue #29532: Altering a kwarg dictionary passed to a constructor
# should not affect a partial object after creation
d = {'a': 3}
p = self.partial(capture, **d)
self.assertEqual(p(), ((), {'a': 3}))
d['a'] = 5
self.assertEqual(p(), ((), {'a': 3}))
def test_arg_combinations(self):
# exercise special code paths for zero args in either partial
# object or the caller
p = self.partial(capture)
self.assertEqual(p(), ((), {}))
self.assertEqual(p(1,2), ((1,2), {}))
p = self.partial(capture, 1, 2)
self.assertEqual(p(), ((1,2), {}))
self.assertEqual(p(3,4), ((1,2,3,4), {}))
def test_kw_combinations(self):
# exercise special code paths for no keyword args in
# either the partial object or the caller
p = self.partial(capture)
self.assertEqual(p.keywords, {})
self.assertEqual(p(), ((), {}))
self.assertEqual(p(a=1), ((), {'a':1}))
p = self.partial(capture, a=1)
self.assertEqual(p.keywords, {'a':1})
self.assertEqual(p(), ((), {'a':1}))
self.assertEqual(p(b=2), ((), {'a':1, 'b':2}))
# keyword args in the call override those in the partial object
self.assertEqual(p(a=3, b=2), ((), {'a':3, 'b':2}))
def test_positional(self):
# make sure positional arguments are captured correctly
for args in [(), (0,), (0,1), (0,1,2), (0,1,2,3)]:
p = self.partial(capture, *args)
expected = args + ('x',)
got, empty = p('x')
self.assertTrue(expected == got and empty == {})
def test_keyword(self):
# make sure keyword arguments are captured correctly
for a in ['a', 0, None, 3.5]:
p = self.partial(capture, a=a)
expected = {'a':a,'x':None}
empty, got = p(x=None)
self.assertTrue(expected == got and empty == ())
def test_no_side_effects(self):
# make sure there are no side effects that affect subsequent calls
p = self.partial(capture, 0, a=1)
args1, kw1 = p(1, b=2)
self.assertTrue(args1 == (0,1) and kw1 == {'a':1,'b':2})
args2, kw2 = p()
self.assertTrue(args2 == (0,) and kw2 == {'a':1})
def test_error_propagation(self):
def f(x, y):
x / y
self.assertRaises(ZeroDivisionError, self.partial(f, 1, 0))
self.assertRaises(ZeroDivisionError, self.partial(f, 1), 0)
self.assertRaises(ZeroDivisionError, self.partial(f), 1, 0)
self.assertRaises(ZeroDivisionError, self.partial(f, y=0), 1)
def test_weakref(self):
f = self.partial(int, base=16)
p = proxy(f)
self.assertEqual(f.func, p.func)
f = None
self.assertRaises(ReferenceError, getattr, p, 'func')
def test_with_bound_and_unbound_methods(self):
data = list(map(str, range(10)))
join = self.partial(str.join, '')
self.assertEqual(join(data), '0123456789')
join = self.partial(''.join)
self.assertEqual(join(data), '0123456789')
def test_nested_optimization(self):
partial = self.partial
inner = partial(signature, 'asdf')
nested = partial(inner, bar=True)
flat = partial(signature, 'asdf', bar=True)
self.assertEqual(signature(nested), signature(flat))
def test_nested_partial_with_attribute(self):
# see issue 25137
partial = self.partial
def foo(bar):
return bar
p = partial(foo, 'first')
p2 = partial(p, 'second')
p2.new_attr = 'spam'
self.assertEqual(p2.new_attr, 'spam')
def test_repr(self):
args = (object(), object())
args_repr = ', '.join(repr(a) for a in args)
kwargs = {'a': object(), 'b': object()}
kwargs_reprs = ['a={a!r}, b={b!r}'.format_map(kwargs),
'b={b!r}, a={a!r}'.format_map(kwargs)]
if self.partial in (c_functools.partial, py_functools.partial):
name = 'functools.partial'
else:
name = self.partial.__name__
f = self.partial(capture)
self.assertEqual(f'{name}({capture!r})', repr(f))
f = self.partial(capture, *args)
self.assertEqual(f'{name}({capture!r}, {args_repr})', repr(f))
f = self.partial(capture, **kwargs)
self.assertIn(repr(f),
[f'{name}({capture!r}, {kwargs_repr})'
for kwargs_repr in kwargs_reprs])
f = self.partial(capture, *args, **kwargs)
self.assertIn(repr(f),
[f'{name}({capture!r}, {args_repr}, {kwargs_repr})'
for kwargs_repr in kwargs_reprs])
def test_recursive_repr(self):
if self.partial in (c_functools.partial, py_functools.partial):
name = 'functools.partial'
else:
name = self.partial.__name__
f = self.partial(capture)
f.__setstate__((f, (), {}, {}))
try:
self.assertEqual(repr(f), '%s(...)' % (name,))
finally:
f.__setstate__((capture, (), {}, {}))
f = self.partial(capture)
f.__setstate__((capture, (f,), {}, {}))
try:
self.assertEqual(repr(f), '%s(%r, ...)' % (name, capture,))
finally:
f.__setstate__((capture, (), {}, {}))
f = self.partial(capture)
f.__setstate__((capture, (), {'a': f}, {}))
try:
self.assertEqual(repr(f), '%s(%r, a=...)' % (name, capture,))
finally:
f.__setstate__((capture, (), {}, {}))
def test_pickle(self):
with self.AllowPickle():
f = self.partial(signature, ['asdf'], bar=[True])
f.attr = []
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
f_copy = pickle.loads(pickle.dumps(f, proto))
self.assertEqual(signature(f_copy), signature(f))
def test_copy(self):
f = self.partial(signature, ['asdf'], bar=[True])
f.attr = []
f_copy = copy.copy(f)
self.assertEqual(signature(f_copy), signature(f))
self.assertIs(f_copy.attr, f.attr)
self.assertIs(f_copy.args, f.args)
self.assertIs(f_copy.keywords, f.keywords)
def test_deepcopy(self):
f = self.partial(signature, ['asdf'], bar=[True])
f.attr = []
f_copy = copy.deepcopy(f)
self.assertEqual(signature(f_copy), signature(f))
self.assertIsNot(f_copy.attr, f.attr)
self.assertIsNot(f_copy.args, f.args)
self.assertIsNot(f_copy.args[0], f.args[0])
self.assertIsNot(f_copy.keywords, f.keywords)
self.assertIsNot(f_copy.keywords['bar'], f.keywords['bar'])
def test_setstate(self):
f = self.partial(signature)
f.__setstate__((capture, (1,), dict(a=10), dict(attr=[])))
self.assertEqual(signature(f),
(capture, (1,), dict(a=10), dict(attr=[])))
self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20}))
f.__setstate__((capture, (1,), dict(a=10), None))
self.assertEqual(signature(f), (capture, (1,), dict(a=10), {}))
self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20}))
f.__setstate__((capture, (1,), None, None))
#self.assertEqual(signature(f), (capture, (1,), {}, {}))
self.assertEqual(f(2, b=20), ((1, 2), {'b': 20}))
self.assertEqual(f(2), ((1, 2), {}))
self.assertEqual(f(), ((1,), {}))
f.__setstate__((capture, (), {}, None))
self.assertEqual(signature(f), (capture, (), {}, {}))
self.assertEqual(f(2, b=20), ((2,), {'b': 20}))
self.assertEqual(f(2), ((2,), {}))
self.assertEqual(f(), ((), {}))
def test_setstate_errors(self):
f = self.partial(signature)
self.assertRaises(TypeError, f.__setstate__, (capture, (), {}))
self.assertRaises(TypeError, f.__setstate__, (capture, (), {}, {}, None))
self.assertRaises(TypeError, f.__setstate__, [capture, (), {}, None])
self.assertRaises(TypeError, f.__setstate__, (None, (), {}, None))
self.assertRaises(TypeError, f.__setstate__, (capture, None, {}, None))
self.assertRaises(TypeError, f.__setstate__, (capture, [], {}, None))
self.assertRaises(TypeError, f.__setstate__, (capture, (), [], None))
def test_setstate_subclasses(self):
f = self.partial(signature)
f.__setstate__((capture, MyTuple((1,)), MyDict(a=10), None))
s = signature(f)
self.assertEqual(s, (capture, (1,), dict(a=10), {}))
self.assertIs(type(s[1]), tuple)
self.assertIs(type(s[2]), dict)
r = f()
self.assertEqual(r, ((1,), {'a': 10}))
self.assertIs(type(r[0]), tuple)
self.assertIs(type(r[1]), dict)
f.__setstate__((capture, BadTuple((1,)), {}, None))
s = signature(f)
self.assertEqual(s, (capture, (1,), {}, {}))
self.assertIs(type(s[1]), tuple)
r = f(2)
self.assertEqual(r, ((1, 2), {}))
self.assertIs(type(r[0]), tuple)
def test_recursive_pickle(self):
with self.AllowPickle():
f = self.partial(capture)
f.__setstate__((f, (), {}, {}))
try:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.assertRaises(RecursionError):
pickle.dumps(f, proto)
finally:
f.__setstate__((capture, (), {}, {}))
f = self.partial(capture)
f.__setstate__((capture, (f,), {}, {}))
try:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
f_copy = pickle.loads(pickle.dumps(f, proto))
try:
self.assertIs(f_copy.args[0], f_copy)
finally:
f_copy.__setstate__((capture, (), {}, {}))
finally:
f.__setstate__((capture, (), {}, {}))
f = self.partial(capture)
f.__setstate__((capture, (), {'a': f}, {}))
try:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
f_copy = pickle.loads(pickle.dumps(f, proto))
try:
self.assertIs(f_copy.keywords['a'], f_copy)
finally:
f_copy.__setstate__((capture, (), {}, {}))
finally:
f.__setstate__((capture, (), {}, {}))
# Issue 6083: Reference counting bug
def test_setstate_refcount(self):
class BadSequence:
def __len__(self):
return 4
def __getitem__(self, key):
if key == 0:
return max
elif key == 1:
return tuple(range(1000000))
elif key in (2, 3):
return {}
raise IndexError
f = self.partial(object)
self.assertRaises(TypeError, f.__setstate__, BadSequence())
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestPartialC(TestPartial, unittest.TestCase):
if c_functools:
partial = c_functools.partial
class AllowPickle:
def __enter__(self):
return self
def __exit__(self, type, value, tb):
return False
def test_attributes_unwritable(self):
# attributes should not be writable
p = self.partial(capture, 1, 2, a=10, b=20)
self.assertRaises(AttributeError, setattr, p, 'func', map)
self.assertRaises(AttributeError, setattr, p, 'args', (1, 2))
self.assertRaises(AttributeError, setattr, p, 'keywords', dict(a=1, b=2))
p = self.partial(hex)
try:
del p.__dict__
except TypeError:
pass
else:
self.fail('partial object allowed __dict__ to be deleted')
def test_manually_adding_non_string_keyword(self):
p = self.partial(capture)
# Adding a non-string/unicode keyword to partial kwargs
p.keywords[1234] = 'value'
r = repr(p)
self.assertIn('1234', r)
self.assertIn("'value'", r)
with self.assertRaises(TypeError):
p()
def test_keystr_replaces_value(self):
p = self.partial(capture)
class MutatesYourDict(object):
def __str__(self):
p.keywords[self] = ['sth2']
return 'astr'
# Replacing the value during key formatting should keep the original
# value alive (at least long enough).
p.keywords[MutatesYourDict()] = ['sth']
r = repr(p)
self.assertIn('astr', r)
self.assertIn("['sth']", r)
class TestPartialPy(TestPartial, unittest.TestCase):
partial = py_functools.partial
class AllowPickle:
def __init__(self):
self._cm = replaced_module("functools", py_functools)
def __enter__(self):
return self._cm.__enter__()
def __exit__(self, type, value, tb):
return self._cm.__exit__(type, value, tb)
if c_functools:
class CPartialSubclass(c_functools.partial):
pass
class PyPartialSubclass(py_functools.partial):
pass
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestPartialCSubclass(TestPartialC):
if c_functools:
partial = CPartialSubclass
# partial subclasses are not optimized for nested calls
test_nested_optimization = None
class TestPartialPySubclass(TestPartialPy):
partial = PyPartialSubclass
class TestPartialMethod(unittest.TestCase):
class A(object):
nothing = functools.partialmethod(capture)
positional = functools.partialmethod(capture, 1)
keywords = functools.partialmethod(capture, a=2)
both = functools.partialmethod(capture, 3, b=4)
nested = functools.partialmethod(positional, 5)
over_partial = functools.partialmethod(functools.partial(capture, c=6), 7)
static = functools.partialmethod(staticmethod(capture), 8)
cls = functools.partialmethod(classmethod(capture), d=9)
a = A()
def test_arg_combinations(self):
self.assertEqual(self.a.nothing(), ((self.a,), {}))
self.assertEqual(self.a.nothing(5), ((self.a, 5), {}))
self.assertEqual(self.a.nothing(c=6), ((self.a,), {'c': 6}))
self.assertEqual(self.a.nothing(5, c=6), ((self.a, 5), {'c': 6}))
self.assertEqual(self.a.positional(), ((self.a, 1), {}))
self.assertEqual(self.a.positional(5), ((self.a, 1, 5), {}))
self.assertEqual(self.a.positional(c=6), ((self.a, 1), {'c': 6}))
self.assertEqual(self.a.positional(5, c=6), ((self.a, 1, 5), {'c': 6}))
self.assertEqual(self.a.keywords(), ((self.a,), {'a': 2}))
self.assertEqual(self.a.keywords(5), ((self.a, 5), {'a': 2}))
self.assertEqual(self.a.keywords(c=6), ((self.a,), {'a': 2, 'c': 6}))
self.assertEqual(self.a.keywords(5, c=6), ((self.a, 5), {'a': 2, 'c': 6}))
self.assertEqual(self.a.both(), ((self.a, 3), {'b': 4}))
self.assertEqual(self.a.both(5), ((self.a, 3, 5), {'b': 4}))
self.assertEqual(self.a.both(c=6), ((self.a, 3), {'b': 4, 'c': 6}))
self.assertEqual(self.a.both(5, c=6), ((self.a, 3, 5), {'b': 4, 'c': 6}))
self.assertEqual(self.A.both(self.a, 5, c=6), ((self.a, 3, 5), {'b': 4, 'c': 6}))
def test_nested(self):
self.assertEqual(self.a.nested(), ((self.a, 1, 5), {}))
self.assertEqual(self.a.nested(6), ((self.a, 1, 5, 6), {}))
self.assertEqual(self.a.nested(d=7), ((self.a, 1, 5), {'d': 7}))
self.assertEqual(self.a.nested(6, d=7), ((self.a, 1, 5, 6), {'d': 7}))
self.assertEqual(self.A.nested(self.a, 6, d=7), ((self.a, 1, 5, 6), {'d': 7}))
def test_over_partial(self):
self.assertEqual(self.a.over_partial(), ((self.a, 7), {'c': 6}))
self.assertEqual(self.a.over_partial(5), ((self.a, 7, 5), {'c': 6}))
self.assertEqual(self.a.over_partial(d=8), ((self.a, 7), {'c': 6, 'd': 8}))
self.assertEqual(self.a.over_partial(5, d=8), ((self.a, 7, 5), {'c': 6, 'd': 8}))
self.assertEqual(self.A.over_partial(self.a, 5, d=8), ((self.a, 7, 5), {'c': 6, 'd': 8}))
def test_bound_method_introspection(self):
obj = self.a
self.assertIs(obj.both.__self__, obj)
self.assertIs(obj.nested.__self__, obj)
self.assertIs(obj.over_partial.__self__, obj)
self.assertIs(obj.cls.__self__, self.A)
self.assertIs(self.A.cls.__self__, self.A)
def test_unbound_method_retrieval(self):
obj = self.A
self.assertFalse(hasattr(obj.both, "__self__"))
self.assertFalse(hasattr(obj.nested, "__self__"))
self.assertFalse(hasattr(obj.over_partial, "__self__"))
self.assertFalse(hasattr(obj.static, "__self__"))
self.assertFalse(hasattr(self.a.static, "__self__"))
def test_descriptors(self):
for obj in [self.A, self.a]:
with self.subTest(obj=obj):
self.assertEqual(obj.static(), ((8,), {}))
self.assertEqual(obj.static(5), ((8, 5), {}))
self.assertEqual(obj.static(d=8), ((8,), {'d': 8}))
self.assertEqual(obj.static(5, d=8), ((8, 5), {'d': 8}))
self.assertEqual(obj.cls(), ((self.A,), {'d': 9}))
self.assertEqual(obj.cls(5), ((self.A, 5), {'d': 9}))
self.assertEqual(obj.cls(c=8), ((self.A,), {'c': 8, 'd': 9}))
self.assertEqual(obj.cls(5, c=8), ((self.A, 5), {'c': 8, 'd': 9}))
def test_overriding_keywords(self):
self.assertEqual(self.a.keywords(a=3), ((self.a,), {'a': 3}))
self.assertEqual(self.A.keywords(self.a, a=3), ((self.a,), {'a': 3}))
def test_invalid_args(self):
with self.assertRaises(TypeError):
class B(object):
method = functools.partialmethod(None, 1)
def test_repr(self):
self.assertEqual(repr(vars(self.A)['both']),
'functools.partialmethod({}, 3, b=4)'.format(capture))
def test_abstract(self):
class Abstract(abc.ABCMeta):
@abc.abstractmethod
def add(self, x, y):
pass
add5 = functools.partialmethod(add, 5)
self.assertTrue(Abstract.add.__isabstractmethod__)
self.assertTrue(Abstract.add5.__isabstractmethod__)
for func in [self.A.static, self.A.cls, self.A.over_partial, self.A.nested, self.A.both]:
self.assertFalse(getattr(func, '__isabstractmethod__', False))
class TestUpdateWrapper(unittest.TestCase):
def check_wrapper(self, wrapper, wrapped,
assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
# Check attributes were assigned
for name in assigned:
self.assertIs(getattr(wrapper, name), getattr(wrapped, name))
# Check attributes were updated
for name in updated:
wrapper_attr = getattr(wrapper, name)
wrapped_attr = getattr(wrapped, name)
for key in wrapped_attr:
if name == "__dict__" and key == "__wrapped__":
# __wrapped__ is overwritten by the update code
continue
self.assertIs(wrapped_attr[key], wrapper_attr[key])
# Check __wrapped__
self.assertIs(wrapper.__wrapped__, wrapped)
def _default_update(self):
def f(a:'This is a new annotation'):
"""This is a test"""
pass
f.attr = 'This is also a test'
f.__wrapped__ = "This is a bald faced lie"
def wrapper(b:'This is the prior annotation'):
pass
functools.update_wrapper(wrapper, f)
return wrapper, f
def test_default_update(self):
wrapper, f = self._default_update()
self.check_wrapper(wrapper, f)
self.assertIs(wrapper.__wrapped__, f)
self.assertEqual(wrapper.__name__, 'f')
self.assertEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.attr, 'This is also a test')
self.assertEqual(wrapper.__annotations__['a'], 'This is a new annotation')
self.assertNotIn('b', wrapper.__annotations__)
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def test_default_update_doc(self):
wrapper, f = self._default_update()
self.assertEqual(wrapper.__doc__, 'This is a test')
def test_no_update(self):
def f():
"""This is a test"""
pass
f.attr = 'This is also a test'
def wrapper():
pass
functools.update_wrapper(wrapper, f, (), ())
self.check_wrapper(wrapper, f, (), ())
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.__doc__, None)
self.assertEqual(wrapper.__annotations__, {})
self.assertFalse(hasattr(wrapper, 'attr'))
def test_selective_update(self):
def f():
pass
f.attr = 'This is a different test'
f.dict_attr = dict(a=1, b=2, c=3)
def wrapper():
pass
wrapper.dict_attr = {}
assign = ('attr',)
update = ('dict_attr',)
functools.update_wrapper(wrapper, f, assign, update)
self.check_wrapper(wrapper, f, assign, update)
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.__doc__, None)
self.assertEqual(wrapper.attr, 'This is a different test')
self.assertEqual(wrapper.dict_attr, f.dict_attr)
def test_missing_attributes(self):
def f():
pass
def wrapper():
pass
wrapper.dict_attr = {}
assign = ('attr',)
update = ('dict_attr',)
# Missing attributes on wrapped object are ignored
functools.update_wrapper(wrapper, f, assign, update)
self.assertNotIn('attr', wrapper.__dict__)
self.assertEqual(wrapper.dict_attr, {})
# Wrapper must have expected attributes for updating
del wrapper.dict_attr
with self.assertRaises(AttributeError):
functools.update_wrapper(wrapper, f, assign, update)
wrapper.dict_attr = 1
with self.assertRaises(AttributeError):
functools.update_wrapper(wrapper, f, assign, update)
@support.requires_docstrings
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def test_builtin_update(self):
# Test for bug #1576241
def wrapper():
pass
functools.update_wrapper(wrapper, max)
self.assertEqual(wrapper.__name__, 'max')
self.assertTrue(wrapper.__doc__.startswith('max('))
self.assertEqual(wrapper.__annotations__, {})
class TestWraps(TestUpdateWrapper):
def _default_update(self):
def f():
"""This is a test"""
pass
f.attr = 'This is also a test'
f.__wrapped__ = "This is still a bald faced lie"
@functools.wraps(f)
def wrapper():
pass
return wrapper, f
def test_default_update(self):
wrapper, f = self._default_update()
self.check_wrapper(wrapper, f)
self.assertEqual(wrapper.__name__, 'f')
self.assertEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.attr, 'This is also a test')
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def test_default_update_doc(self):
wrapper, _ = self._default_update()
self.assertEqual(wrapper.__doc__, 'This is a test')
def test_no_update(self):
def f():
"""This is a test"""
pass
f.attr = 'This is also a test'
@functools.wraps(f, (), ())
def wrapper():
pass
self.check_wrapper(wrapper, f, (), ())
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.__doc__, None)
self.assertFalse(hasattr(wrapper, 'attr'))
def test_selective_update(self):
def f():
pass
f.attr = 'This is a different test'
f.dict_attr = dict(a=1, b=2, c=3)
def add_dict_attr(f):
f.dict_attr = {}
return f
assign = ('attr',)
update = ('dict_attr',)
@functools.wraps(f, assign, update)
@add_dict_attr
def wrapper():
pass
self.check_wrapper(wrapper, f, assign, update)
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.__doc__, None)
self.assertEqual(wrapper.attr, 'This is a different test')
self.assertEqual(wrapper.dict_attr, f.dict_attr)
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestReduce(unittest.TestCase):
if c_functools:
func = c_functools.reduce
def test_reduce(self):
class Squares:
def __init__(self, max):
self.max = max
self.sofar = []
def __len__(self):
return len(self.sofar)
def __getitem__(self, i):
if not 0 <= i < self.max: raise IndexError
n = len(self.sofar)
while n <= i:
self.sofar.append(n*n)
n += 1
return self.sofar[i]
def add(x, y):
return x + y
self.assertEqual(self.func(add, ['a', 'b', 'c'], ''), 'abc')
self.assertEqual(
self.func(add, [['a', 'c'], [], ['d', 'w']], []),
['a','c','d','w']
)
self.assertEqual(self.func(lambda x, y: x*y, range(2,8), 1), 5040)
self.assertEqual(
self.func(lambda x, y: x*y, range(2,21), 1),
2432902008176640000
)
self.assertEqual(self.func(add, Squares(10)), 285)
self.assertEqual(self.func(add, Squares(10), 0), 285)
self.assertEqual(self.func(add, Squares(0), 0), 0)
self.assertRaises(TypeError, self.func)
self.assertRaises(TypeError, self.func, 42, 42)
self.assertRaises(TypeError, self.func, 42, 42, 42)
self.assertEqual(self.func(42, "1"), "1") # func is never called with one item
self.assertEqual(self.func(42, "", "1"), "1") # func is never called with one item
self.assertRaises(TypeError, self.func, 42, (42, 42))
self.assertRaises(TypeError, self.func, add, []) # arg 2 must not be empty sequence with no initial value
self.assertRaises(TypeError, self.func, add, "")
self.assertRaises(TypeError, self.func, add, ())
self.assertRaises(TypeError, self.func, add, object())
class TestFailingIter:
def __iter__(self):
raise RuntimeError
self.assertRaises(RuntimeError, self.func, add, TestFailingIter())
self.assertEqual(self.func(add, [], None), None)
self.assertEqual(self.func(add, [], 42), 42)
class BadSeq:
def __getitem__(self, index):
raise ValueError
self.assertRaises(ValueError, self.func, 42, BadSeq())
# Test reduce()'s use of iterators.
def test_iterator_usage(self):
class SequenceClass:
def __init__(self, n):
self.n = n
def __getitem__(self, i):
if 0 <= i < self.n:
return i
else:
raise IndexError
from operator import add
self.assertEqual(self.func(add, SequenceClass(5)), 10)
self.assertEqual(self.func(add, SequenceClass(5), 42), 52)
self.assertRaises(TypeError, self.func, add, SequenceClass(0))
self.assertEqual(self.func(add, SequenceClass(0), 42), 42)
self.assertEqual(self.func(add, SequenceClass(1)), 0)
self.assertEqual(self.func(add, SequenceClass(1), 42), 42)
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(self.func(add, d), "".join(d.keys()))
class TestCmpToKey:
def test_cmp_to_key(self):
def cmp1(x, y):
return (x > y) - (x < y)
key = self.cmp_to_key(cmp1)
self.assertEqual(key(3), key(3))
self.assertGreater(key(3), key(1))
self.assertGreaterEqual(key(3), key(3))
def cmp2(x, y):
return int(x) - int(y)
key = self.cmp_to_key(cmp2)
self.assertEqual(key(4.0), key('4'))
self.assertLess(key(2), key('35'))
self.assertLessEqual(key(2), key('35'))
self.assertNotEqual(key(2), key('35'))
def test_cmp_to_key_arguments(self):
def cmp1(x, y):
return (x > y) - (x < y)
key = self.cmp_to_key(mycmp=cmp1)
self.assertEqual(key(obj=3), key(obj=3))
self.assertGreater(key(obj=3), key(obj=1))
with self.assertRaises((TypeError, AttributeError)):
key(3) > 1 # rhs is not a K object
with self.assertRaises((TypeError, AttributeError)):
1 < key(3) # lhs is not a K object
with self.assertRaises(TypeError):
key = self.cmp_to_key() # too few args
with self.assertRaises(TypeError):
key = self.cmp_to_key(cmp1, None) # too many args
key = self.cmp_to_key(cmp1)
with self.assertRaises(TypeError):
key() # too few args
with self.assertRaises(TypeError):
key(None, None) # too many args
def test_bad_cmp(self):
def cmp1(x, y):
raise ZeroDivisionError
key = self.cmp_to_key(cmp1)
with self.assertRaises(ZeroDivisionError):
key(3) > key(1)
class BadCmp:
def __lt__(self, other):
raise ZeroDivisionError
def cmp1(x, y):
return BadCmp()
with self.assertRaises(ZeroDivisionError):
key(3) > key(1)
def test_obj_field(self):
def cmp1(x, y):
return (x > y) - (x < y)
key = self.cmp_to_key(mycmp=cmp1)
self.assertEqual(key(50).obj, 50)
def test_sort_int(self):
def mycmp(x, y):
return y - x
self.assertEqual(sorted(range(5), key=self.cmp_to_key(mycmp)),
[4, 3, 2, 1, 0])
def test_sort_int_str(self):
def mycmp(x, y):
x, y = int(x), int(y)
return (x > y) - (x < y)
values = [5, '3', 7, 2, '0', '1', 4, '10', 1]
values = sorted(values, key=self.cmp_to_key(mycmp))
self.assertEqual([int(value) for value in values],
[0, 1, 1, 2, 3, 4, 5, 7, 10])
def test_hash(self):
def mycmp(x, y):
return y - x
key = self.cmp_to_key(mycmp)
k = key(10)
self.assertRaises(TypeError, hash, k)
self.assertNotIsInstance(k, collections.abc.Hashable)
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestCmpToKeyC(TestCmpToKey, unittest.TestCase):
if c_functools:
cmp_to_key = c_functools.cmp_to_key
class TestCmpToKeyPy(TestCmpToKey, unittest.TestCase):
cmp_to_key = staticmethod(py_functools.cmp_to_key)
class TestTotalOrdering(unittest.TestCase):
def test_total_ordering_lt(self):
@functools.total_ordering
class A:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __eq__(self, other):
return self.value == other.value
self.assertTrue(A(1) < A(2))
self.assertTrue(A(2) > A(1))
self.assertTrue(A(1) <= A(2))
self.assertTrue(A(2) >= A(1))
self.assertTrue(A(2) <= A(2))
self.assertTrue(A(2) >= A(2))
self.assertFalse(A(1) > A(2))
def test_total_ordering_le(self):
@functools.total_ordering
class A:
def __init__(self, value):
self.value = value
def __le__(self, other):
return self.value <= other.value
def __eq__(self, other):
return self.value == other.value
self.assertTrue(A(1) < A(2))
self.assertTrue(A(2) > A(1))
self.assertTrue(A(1) <= A(2))
self.assertTrue(A(2) >= A(1))
self.assertTrue(A(2) <= A(2))
self.assertTrue(A(2) >= A(2))
self.assertFalse(A(1) >= A(2))
def test_total_ordering_gt(self):
@functools.total_ordering
class A:
def __init__(self, value):
self.value = value
def __gt__(self, other):
return self.value > other.value
def __eq__(self, other):
return self.value == other.value
self.assertTrue(A(1) < A(2))
self.assertTrue(A(2) > A(1))
self.assertTrue(A(1) <= A(2))
self.assertTrue(A(2) >= A(1))
self.assertTrue(A(2) <= A(2))
self.assertTrue(A(2) >= A(2))
self.assertFalse(A(2) < A(1))
def test_total_ordering_ge(self):
@functools.total_ordering
class A:
def __init__(self, value):
self.value = value
def __ge__(self, other):
return self.value >= other.value
def __eq__(self, other):
return self.value == other.value
self.assertTrue(A(1) < A(2))
self.assertTrue(A(2) > A(1))
self.assertTrue(A(1) <= A(2))
self.assertTrue(A(2) >= A(1))
self.assertTrue(A(2) <= A(2))
self.assertTrue(A(2) >= A(2))
self.assertFalse(A(2) <= A(1))
def test_total_ordering_no_overwrite(self):
# new methods should not overwrite existing
@functools.total_ordering
class A(int):
pass
self.assertTrue(A(1) < A(2))
self.assertTrue(A(2) > A(1))
self.assertTrue(A(1) <= A(2))
self.assertTrue(A(2) >= A(1))
self.assertTrue(A(2) <= A(2))
self.assertTrue(A(2) >= A(2))
def test_no_operations_defined(self):
with self.assertRaises(ValueError):
@functools.total_ordering
class A:
pass
def test_type_error_when_not_implemented(self):
# bug 10042; ensure stack overflow does not occur
# when decorated types return NotImplemented
@functools.total_ordering
class ImplementsLessThan:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, ImplementsLessThan):
return self.value == other.value
return False
def __lt__(self, other):
if isinstance(other, ImplementsLessThan):
return self.value < other.value
return NotImplemented
@functools.total_ordering
class ImplementsGreaterThan:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, ImplementsGreaterThan):
return self.value == other.value
return False
def __gt__(self, other):
if isinstance(other, ImplementsGreaterThan):
return self.value > other.value
return NotImplemented
@functools.total_ordering
class ImplementsLessThanEqualTo:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, ImplementsLessThanEqualTo):
return self.value == other.value
return False
def __le__(self, other):
if isinstance(other, ImplementsLessThanEqualTo):
return self.value <= other.value
return NotImplemented
@functools.total_ordering
class ImplementsGreaterThanEqualTo:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, ImplementsGreaterThanEqualTo):
return self.value == other.value
return False
def __ge__(self, other):
if isinstance(other, ImplementsGreaterThanEqualTo):
return self.value >= other.value
return NotImplemented
@functools.total_ordering
class ComparatorNotImplemented:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, ComparatorNotImplemented):
return self.value == other.value
return False
def __lt__(self, other):
return NotImplemented
with self.subTest("LT < 1"), self.assertRaises(TypeError):
ImplementsLessThan(-1) < 1
with self.subTest("LT < LE"), self.assertRaises(TypeError):
ImplementsLessThan(0) < ImplementsLessThanEqualTo(0)
with self.subTest("LT < GT"), self.assertRaises(TypeError):
ImplementsLessThan(1) < ImplementsGreaterThan(1)
with self.subTest("LE <= LT"), self.assertRaises(TypeError):
ImplementsLessThanEqualTo(2) <= ImplementsLessThan(2)
with self.subTest("LE <= GE"), self.assertRaises(TypeError):
ImplementsLessThanEqualTo(3) <= ImplementsGreaterThanEqualTo(3)
with self.subTest("GT > GE"), self.assertRaises(TypeError):
ImplementsGreaterThan(4) > ImplementsGreaterThanEqualTo(4)
with self.subTest("GT > LT"), self.assertRaises(TypeError):
ImplementsGreaterThan(5) > ImplementsLessThan(5)
with self.subTest("GE >= GT"), self.assertRaises(TypeError):
ImplementsGreaterThanEqualTo(6) >= ImplementsGreaterThan(6)
with self.subTest("GE >= LE"), self.assertRaises(TypeError):
ImplementsGreaterThanEqualTo(7) >= ImplementsLessThanEqualTo(7)
with self.subTest("GE when equal"):
a = ComparatorNotImplemented(8)
b = ComparatorNotImplemented(8)
self.assertEqual(a, b)
with self.assertRaises(TypeError):
a >= b
with self.subTest("LE when equal"):
a = ComparatorNotImplemented(9)
b = ComparatorNotImplemented(9)
self.assertEqual(a, b)
with self.assertRaises(TypeError):
a <= b
def test_pickle(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
for name in '__lt__', '__gt__', '__le__', '__ge__':
with self.subTest(method=name, proto=proto):
method = getattr(Orderable_LT, name)
method_copy = pickle.loads(pickle.dumps(method, proto))
self.assertIs(method_copy, method)
@functools.total_ordering
class Orderable_LT:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __eq__(self, other):
return self.value == other.value
class TestLRU:
def test_lru(self):
def orig(x, y):
return 3 * x + y
f = self.module.lru_cache(maxsize=20)(orig)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(maxsize, 20)
self.assertEqual(currsize, 0)
self.assertEqual(hits, 0)
self.assertEqual(misses, 0)
domain = range(5)
for i in range(1000):
x, y = choice(domain), choice(domain)
actual = f(x, y)
expected = orig(x, y)
self.assertEqual(actual, expected)
hits, misses, maxsize, currsize = f.cache_info()
self.assertTrue(hits > misses)
self.assertEqual(hits + misses, 1000)
self.assertEqual(currsize, 20)
f.cache_clear() # test clearing
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 0)
self.assertEqual(misses, 0)
self.assertEqual(currsize, 0)
f(x, y)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 0)
self.assertEqual(misses, 1)
self.assertEqual(currsize, 1)
# Test bypassing the cache
self.assertIs(f.__wrapped__, orig)
f.__wrapped__(x, y)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 0)
self.assertEqual(misses, 1)
self.assertEqual(currsize, 1)
# test size zero (which means "never-cache")
@self.module.lru_cache(0)
def f():
nonlocal f_cnt
f_cnt += 1
return 20
self.assertEqual(f.cache_info().maxsize, 0)
f_cnt = 0
for i in range(5):
self.assertEqual(f(), 20)
self.assertEqual(f_cnt, 5)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 0)
self.assertEqual(misses, 5)
self.assertEqual(currsize, 0)
# test size one
@self.module.lru_cache(1)
def f():
nonlocal f_cnt
f_cnt += 1
return 20
self.assertEqual(f.cache_info().maxsize, 1)
f_cnt = 0
for i in range(5):
self.assertEqual(f(), 20)
self.assertEqual(f_cnt, 1)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 4)
self.assertEqual(misses, 1)
self.assertEqual(currsize, 1)
# test size two
@self.module.lru_cache(2)
def f(x):
nonlocal f_cnt
f_cnt += 1
return x*10
self.assertEqual(f.cache_info().maxsize, 2)
f_cnt = 0
for x in 7, 9, 7, 9, 7, 9, 8, 8, 8, 9, 9, 9, 8, 8, 8, 7:
# * * * *
self.assertEqual(f(x), x*10)
self.assertEqual(f_cnt, 4)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(hits, 12)
self.assertEqual(misses, 4)
self.assertEqual(currsize, 2)
def test_lru_hash_only_once(self):
# To protect against weird reentrancy bugs and to improve
# efficiency when faced with slow __hash__ methods, the
# LRU cache guarantees that it will only call __hash__
# only once per use as an argument to the cached function.
@self.module.lru_cache(maxsize=1)
def f(x, y):
return x * 3 + y
# Simulate the integer 5
mock_int = unittest.mock.Mock()
mock_int.__mul__ = unittest.mock.Mock(return_value=15)
mock_int.__hash__ = unittest.mock.Mock(return_value=999)
# Add to cache: One use as an argument gives one call
self.assertEqual(f(mock_int, 1), 16)
self.assertEqual(mock_int.__hash__.call_count, 1)
self.assertEqual(f.cache_info(), (0, 1, 1, 1))
# Cache hit: One use as an argument gives one additional call
self.assertEqual(f(mock_int, 1), 16)
self.assertEqual(mock_int.__hash__.call_count, 2)
self.assertEqual(f.cache_info(), (1, 1, 1, 1))
# Cache eviction: No use as an argument gives no additional call
self.assertEqual(f(6, 2), 20)
self.assertEqual(mock_int.__hash__.call_count, 2)
self.assertEqual(f.cache_info(), (1, 2, 1, 1))
# Cache miss: One use as an argument gives one additional call
self.assertEqual(f(mock_int, 1), 16)
self.assertEqual(mock_int.__hash__.call_count, 3)
self.assertEqual(f.cache_info(), (1, 3, 1, 1))
def test_lru_reentrancy_with_len(self):
# Test to make sure the LRU cache code isn't thrown-off by
# caching the built-in len() function. Since len() can be
# cached, we shouldn't use it inside the lru code itself.
old_len = builtins.len
try:
builtins.len = self.module.lru_cache(4)(len)
for i in [0, 0, 1, 2, 3, 3, 4, 5, 6, 1, 7, 2, 1]:
self.assertEqual(len('abcdefghijklmn'[:i]), i)
finally:
builtins.len = old_len
def test_lru_star_arg_handling(self):
# Test regression that arose in ea064ff3c10f
@functools.lru_cache()
def f(*args):
return args
self.assertEqual(f(1, 2), (1, 2))
self.assertEqual(f((1, 2)), ((1, 2),))
def test_lru_type_error(self):
# Regression test for issue #28653.
# lru_cache was leaking when one of the arguments
# wasn't cacheable.
@functools.lru_cache(maxsize=None)
def infinite_cache(o):
pass
@functools.lru_cache(maxsize=10)
def limited_cache(o):
pass
with self.assertRaises(TypeError):
infinite_cache([])
with self.assertRaises(TypeError):
limited_cache([])
def test_lru_with_maxsize_none(self):
@self.module.lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
self.assertEqual([fib(n) for n in range(16)],
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610])
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16))
fib.cache_clear()
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0))
def test_lru_with_maxsize_negative(self):
@self.module.lru_cache(maxsize=-10)
def eq(n):
return n
for i in (0, 1):
self.assertEqual([eq(n) for n in range(150)], list(range(150)))
self.assertEqual(eq.cache_info(),
self.module._CacheInfo(hits=0, misses=300, maxsize=-10, currsize=1))
def test_lru_with_exceptions(self):
# Verify that user_function exceptions get passed through without
# creating a hard-to-read chained exception.
# http://bugs.python.org/issue13177
for maxsize in (None, 128):
@self.module.lru_cache(maxsize)
def func(i):
return 'abc'[i]
self.assertEqual(func(0), 'a')
with self.assertRaises(IndexError) as cm:
func(15)
self.assertIsNone(cm.exception.__context__)
# Verify that the previous exception did not result in a cached entry
with self.assertRaises(IndexError):
func(15)
def test_lru_with_types(self):
for maxsize in (None, 128):
@self.module.lru_cache(maxsize=maxsize, typed=True)
def square(x):
return x * x
self.assertEqual(square(3), 9)
self.assertEqual(type(square(3)), type(9))
self.assertEqual(square(3.0), 9.0)
self.assertEqual(type(square(3.0)), type(9.0))
self.assertEqual(square(x=3), 9)
self.assertEqual(type(square(x=3)), type(9))
self.assertEqual(square(x=3.0), 9.0)
self.assertEqual(type(square(x=3.0)), type(9.0))
self.assertEqual(square.cache_info().hits, 4)
self.assertEqual(square.cache_info().misses, 4)
def test_lru_with_keyword_args(self):
@self.module.lru_cache()
def fib(n):
if n < 2:
return n
return fib(n=n-1) + fib(n=n-2)
self.assertEqual(
[fib(n=number) for number in range(16)],
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
)
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=28, misses=16, maxsize=128, currsize=16))
fib.cache_clear()
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=0, misses=0, maxsize=128, currsize=0))
def test_lru_with_keyword_args_maxsize_none(self):
@self.module.lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n=n-1) + fib(n=n-2)
self.assertEqual([fib(n=number) for number in range(16)],
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610])
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16))
fib.cache_clear()
self.assertEqual(fib.cache_info(),
self.module._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0))
def test_kwargs_order(self):
# PEP 468: Preserving Keyword Argument Order
@self.module.lru_cache(maxsize=10)
def f(**kwargs):
return list(kwargs.items())
self.assertEqual(f(a=1, b=2), [('a', 1), ('b', 2)])
self.assertEqual(f(b=2, a=1), [('b', 2), ('a', 1)])
self.assertEqual(f.cache_info(),
self.module._CacheInfo(hits=0, misses=2, maxsize=10, currsize=2))
def test_lru_cache_decoration(self):
def f(zomg: 'zomg_annotation'):
"""f doc string"""
return 42
g = self.module.lru_cache()(f)
for attr in self.module.WRAPPER_ASSIGNMENTS:
self.assertEqual(getattr(g, attr), getattr(f, attr))
def test_lru_cache_threaded(self):
n, m = 5, 11
def orig(x, y):
return 3 * x + y
f = self.module.lru_cache(maxsize=n*m)(orig)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(currsize, 0)
start = threading.Event()
def full(k):
start.wait(10)
for _ in range(m):
self.assertEqual(f(k, 0), orig(k, 0))
def clear():
start.wait(10)
for _ in range(2*m):
f.cache_clear()
orig_si = sys.getswitchinterval()
support.setswitchinterval(1e-6)
try:
# create n threads in order to fill cache
threads = [threading.Thread(target=full, args=[k])
for k in range(n)]
with support.start_threads(threads):
start.set()
hits, misses, maxsize, currsize = f.cache_info()
if self.module is py_functools:
# XXX: Why can be not equal?
self.assertLessEqual(misses, n)
self.assertLessEqual(hits, m*n - misses)
else:
self.assertEqual(misses, n)
self.assertEqual(hits, m*n - misses)
self.assertEqual(currsize, n)
# create n threads in order to fill cache and 1 to clear it
threads = [threading.Thread(target=clear)]
threads += [threading.Thread(target=full, args=[k])
for k in range(n)]
start.clear()
with support.start_threads(threads):
start.set()
finally:
sys.setswitchinterval(orig_si)
def test_lru_cache_threaded2(self):
# Simultaneous call with the same arguments
n, m = 5, 7
start = threading.Barrier(n+1)
pause = threading.Barrier(n+1)
stop = threading.Barrier(n+1)
@self.module.lru_cache(maxsize=m*n)
def f(x):
pause.wait(10)
return 3 * x
self.assertEqual(f.cache_info(), (0, 0, m*n, 0))
def test():
for i in range(m):
start.wait(10)
self.assertEqual(f(i), 3 * i)
stop.wait(10)
threads = [threading.Thread(target=test) for k in range(n)]
with support.start_threads(threads):
for i in range(m):
start.wait(10)
stop.reset()
pause.wait(10)
start.reset()
stop.wait(10)
pause.reset()
self.assertEqual(f.cache_info(), (0, (i+1)*n, m*n, i+1))
def test_lru_cache_threaded3(self):
@self.module.lru_cache(maxsize=2)
def f(x):
time.sleep(.01)
return 3 * x
def test(i, x):
with self.subTest(thread=i):
self.assertEqual(f(x), 3 * x, i)
threads = [threading.Thread(target=test, args=(i, v))
for i, v in enumerate([1, 2, 2, 3, 2])]
with support.start_threads(threads):
pass
def test_need_for_rlock(self):
# This will deadlock on an LRU cache that uses a regular lock
@self.module.lru_cache(maxsize=10)
def test_func(x):
'Used to demonstrate a reentrant lru_cache call within a single thread'
return x
class DoubleEq:
'Demonstrate a reentrant lru_cache call within a single thread'
def __init__(self, x):
self.x = x
def __hash__(self):
return self.x
def __eq__(self, other):
if self.x == 2:
test_func(DoubleEq(1))
return self.x == other.x
test_func(DoubleEq(1)) # Load the cache
test_func(DoubleEq(2)) # Load the cache
self.assertEqual(test_func(DoubleEq(2)), # Trigger a re-entrant __eq__ call
DoubleEq(2)) # Verify the correct return value
def test_early_detection_of_bad_call(self):
# Issue #22184
with self.assertRaises(TypeError):
@functools.lru_cache
def f():
pass
def test_lru_method(self):
class X(int):
f_cnt = 0
@self.module.lru_cache(2)
def f(self, x):
self.f_cnt += 1
return x*10+self
a = X(5)
b = X(5)
c = X(7)
self.assertEqual(X.f.cache_info(), (0, 0, 2, 0))
for x in 1, 2, 2, 3, 1, 1, 1, 2, 3, 3:
self.assertEqual(a.f(x), x*10 + 5)
self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 0, 0))
self.assertEqual(X.f.cache_info(), (4, 6, 2, 2))
for x in 1, 2, 1, 1, 1, 1, 3, 2, 2, 2:
self.assertEqual(b.f(x), x*10 + 5)
self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 4, 0))
self.assertEqual(X.f.cache_info(), (10, 10, 2, 2))
for x in 2, 1, 1, 1, 1, 2, 1, 3, 2, 1:
self.assertEqual(c.f(x), x*10 + 7)
self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 4, 5))
self.assertEqual(X.f.cache_info(), (15, 15, 2, 2))
self.assertEqual(a.f.cache_info(), X.f.cache_info())
self.assertEqual(b.f.cache_info(), X.f.cache_info())
self.assertEqual(c.f.cache_info(), X.f.cache_info())
def test_pickle(self):
cls = self.__class__
for f in cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(proto=proto, func=f):
f_copy = pickle.loads(pickle.dumps(f, proto))
self.assertIs(f_copy, f)
def test_copy(self):
cls = self.__class__
def orig(x, y):
return 3 * x + y
part = self.module.partial(orig, 2)
funcs = (cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth,
self.module.lru_cache(2)(part))
for f in funcs:
with self.subTest(func=f):
f_copy = copy.copy(f)
self.assertIs(f_copy, f)
def test_deepcopy(self):
cls = self.__class__
def orig(x, y):
return 3 * x + y
part = self.module.partial(orig, 2)
funcs = (cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth,
self.module.lru_cache(2)(part))
for f in funcs:
with self.subTest(func=f):
f_copy = copy.deepcopy(f)
self.assertIs(f_copy, f)
@py_functools.lru_cache()
def py_cached_func(x, y):
return 3 * x + y
@c_functools.lru_cache()
def c_cached_func(x, y):
return 3 * x + y
class TestLRUPy(TestLRU, unittest.TestCase):
module = py_functools
cached_func = py_cached_func,
@module.lru_cache()
def cached_meth(self, x, y):
return 3 * x + y
@staticmethod
@module.lru_cache()
def cached_staticmeth(x, y):
return 3 * x + y
class TestLRUC(TestLRU, unittest.TestCase):
module = c_functools
cached_func = c_cached_func,
@module.lru_cache()
def cached_meth(self, x, y):
return 3 * x + y
@staticmethod
@module.lru_cache()
def cached_staticmeth(x, y):
return 3 * x + y
class TestSingleDispatch(unittest.TestCase):
def test_simple_overloads(self):
@functools.singledispatch
def g(obj):
return "base"
def g_int(i):
return "integer"
g.register(int, g_int)
self.assertEqual(g("str"), "base")
self.assertEqual(g(1), "integer")
self.assertEqual(g([1,2,3]), "base")
def test_mro(self):
@functools.singledispatch
def g(obj):
return "base"
class A:
pass
class C(A):
pass
class B(A):
pass
class D(C, B):
pass
def g_A(a):
return "A"
def g_B(b):
return "B"
g.register(A, g_A)
g.register(B, g_B)
self.assertEqual(g(A()), "A")
self.assertEqual(g(B()), "B")
self.assertEqual(g(C()), "A")
self.assertEqual(g(D()), "B")
def test_register_decorator(self):
@functools.singledispatch
def g(obj):
return "base"
@g.register(int)
def g_int(i):
return "int %s" % (i,)
self.assertEqual(g(""), "base")
self.assertEqual(g(12), "int 12")
self.assertIs(g.dispatch(int), g_int)
self.assertIs(g.dispatch(object), g.dispatch(str))
# Note: in the assert above this is not g.
# @singledispatch returns the wrapper.
def test_wrapping_attributes(self):
@functools.singledispatch
def g(obj):
"Simple test"
return "Test"
self.assertEqual(g.__name__, "g")
if sys.flags.optimize < 2:
self.assertEqual(g.__doc__, "Simple test")
@unittest.skipUnless(decimal, 'requires _decimal')
@support.cpython_only
def test_c_classes(self):
@functools.singledispatch
def g(obj):
return "base"
@g.register(decimal.DecimalException)
def _(obj):
return obj.args
subn = decimal.Subnormal("Exponent < Emin")
rnd = decimal.Rounded("Number got rounded")
self.assertEqual(g(subn), ("Exponent < Emin",))
self.assertEqual(g(rnd), ("Number got rounded",))
@g.register(decimal.Subnormal)
def _(obj):
return "Too small to care."
self.assertEqual(g(subn), "Too small to care.")
self.assertEqual(g(rnd), ("Number got rounded",))
def test_compose_mro(self):
# None of the examples in this test depend on haystack ordering.
c = collections.abc
mro = functools._compose_mro
bases = [c.Sequence, c.MutableMapping, c.Mapping, c.Set]
for haystack in permutations(bases):
m = mro(dict, haystack)
self.assertEqual(m, [dict, c.MutableMapping, c.Mapping,
c.Collection, c.Sized, c.Iterable,
c.Container, object])
bases = [c.Container, c.Mapping, c.MutableMapping, collections.OrderedDict]
for haystack in permutations(bases):
m = mro(collections.ChainMap, haystack)
self.assertEqual(m, [collections.ChainMap, c.MutableMapping, c.Mapping,
c.Collection, c.Sized, c.Iterable,
c.Container, object])
# If there's a generic function with implementations registered for
# both Sized and Container, passing a defaultdict to it results in an
# ambiguous dispatch which will cause a RuntimeError (see
# test_mro_conflicts).
bases = [c.Container, c.Sized, str]
for haystack in permutations(bases):
m = mro(collections.defaultdict, [c.Sized, c.Container, str])
self.assertEqual(m, [collections.defaultdict, dict, c.Sized,
c.Container, object])
# MutableSequence below is registered directly on D. In other words, it
# precedes MutableMapping which means single dispatch will always
# choose MutableSequence here.
class D(collections.defaultdict):
pass
c.MutableSequence.register(D)
bases = [c.MutableSequence, c.MutableMapping]
for haystack in permutations(bases):
m = mro(D, bases)
self.assertEqual(m, [D, c.MutableSequence, c.Sequence, c.Reversible,
collections.defaultdict, dict, c.MutableMapping, c.Mapping,
c.Collection, c.Sized, c.Iterable, c.Container,
object])
# Container and Callable are registered on different base classes and
# a generic function supporting both should always pick the Callable
# implementation if a C instance is passed.
class C(collections.defaultdict):
def __call__(self):
pass
bases = [c.Sized, c.Callable, c.Container, c.Mapping]
for haystack in permutations(bases):
m = mro(C, haystack)
self.assertEqual(m, [C, c.Callable, collections.defaultdict, dict, c.Mapping,
c.Collection, c.Sized, c.Iterable,
c.Container, object])
def test_register_abc(self):
c = collections.abc
d = {"a": "b"}
l = [1, 2, 3]
s = {object(), None}
f = frozenset(s)
t = (1, 2, 3)
@functools.singledispatch
def g(obj):
return "base"
self.assertEqual(g(d), "base")
self.assertEqual(g(l), "base")
self.assertEqual(g(s), "base")
self.assertEqual(g(f), "base")
self.assertEqual(g(t), "base")
g.register(c.Sized, lambda obj: "sized")
self.assertEqual(g(d), "sized")
self.assertEqual(g(l), "sized")
self.assertEqual(g(s), "sized")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.MutableMapping, lambda obj: "mutablemapping")
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(g(l), "sized")
self.assertEqual(g(s), "sized")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(collections.ChainMap, lambda obj: "chainmap")
self.assertEqual(g(d), "mutablemapping") # irrelevant ABCs registered
self.assertEqual(g(l), "sized")
self.assertEqual(g(s), "sized")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.MutableSequence, lambda obj: "mutablesequence")
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "sized")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.MutableSet, lambda obj: "mutableset")
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.Mapping, lambda obj: "mapping")
self.assertEqual(g(d), "mutablemapping") # not specific enough
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sized")
g.register(c.Sequence, lambda obj: "sequence")
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "sized")
self.assertEqual(g(t), "sequence")
g.register(c.Set, lambda obj: "set")
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "set")
self.assertEqual(g(t), "sequence")
g.register(dict, lambda obj: "dict")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "mutablesequence")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "set")
self.assertEqual(g(t), "sequence")
g.register(list, lambda obj: "list")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "list")
self.assertEqual(g(s), "mutableset")
self.assertEqual(g(f), "set")
self.assertEqual(g(t), "sequence")
g.register(set, lambda obj: "concrete-set")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "list")
self.assertEqual(g(s), "concrete-set")
self.assertEqual(g(f), "set")
self.assertEqual(g(t), "sequence")
g.register(frozenset, lambda obj: "frozen-set")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "list")
self.assertEqual(g(s), "concrete-set")
self.assertEqual(g(f), "frozen-set")
self.assertEqual(g(t), "sequence")
g.register(tuple, lambda obj: "tuple")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "list")
self.assertEqual(g(s), "concrete-set")
self.assertEqual(g(f), "frozen-set")
self.assertEqual(g(t), "tuple")
def test_c3_abc(self):
c = collections.abc
mro = functools._c3_mro
class A(object):
pass
class B(A):
def __len__(self):
return 0 # implies Sized
@c.Container.register
class C(object):
pass
class D(object):
pass # unrelated
class X(D, C, B):
def __call__(self):
pass # implies Callable
expected = [X, c.Callable, D, C, c.Container, B, c.Sized, A, object]
for abcs in permutations([c.Sized, c.Callable, c.Container]):
self.assertEqual(mro(X, abcs=abcs), expected)
# unrelated ABCs don't appear in the resulting MRO
many_abcs = [c.Mapping, c.Sized, c.Callable, c.Container, c.Iterable]
self.assertEqual(mro(X, abcs=many_abcs), expected)
def test_false_meta(self):
# see issue23572
class MetaA(type):
def __len__(self):
return 0
class A(metaclass=MetaA):
pass
class AA(A):
pass
@functools.singledispatch
def fun(a):
return 'base A'
@fun.register(A)
def _(a):
return 'fun A'
aa = AA()
self.assertEqual(fun(aa), 'fun A')
def test_mro_conflicts(self):
c = collections.abc
@functools.singledispatch
def g(arg):
return "base"
class O(c.Sized):
def __len__(self):
return 0
o = O()
self.assertEqual(g(o), "base")
g.register(c.Iterable, lambda arg: "iterable")
g.register(c.Container, lambda arg: "container")
g.register(c.Sized, lambda arg: "sized")
g.register(c.Set, lambda arg: "set")
self.assertEqual(g(o), "sized")
c.Iterable.register(O)
self.assertEqual(g(o), "sized") # because it's explicitly in __mro__
c.Container.register(O)
self.assertEqual(g(o), "sized") # see above: Sized is in __mro__
c.Set.register(O)
self.assertEqual(g(o), "set") # because c.Set is a subclass of
# c.Sized and c.Container
class P:
pass
p = P()
self.assertEqual(g(p), "base")
c.Iterable.register(P)
self.assertEqual(g(p), "iterable")
c.Container.register(P)
with self.assertRaises(RuntimeError) as re_one:
g(p)
self.assertIn(
str(re_one.exception),
(("Ambiguous dispatch: <class 'collections.abc.Container'> "
"or <class 'collections.abc.Iterable'>"),
("Ambiguous dispatch: <class 'collections.abc.Iterable'> "
"or <class 'collections.abc.Container'>")),
)
class Q(c.Sized):
def __len__(self):
return 0
q = Q()
self.assertEqual(g(q), "sized")
c.Iterable.register(Q)
self.assertEqual(g(q), "sized") # because it's explicitly in __mro__
c.Set.register(Q)
self.assertEqual(g(q), "set") # because c.Set is a subclass of
# c.Sized and c.Iterable
@functools.singledispatch
def h(arg):
return "base"
@h.register(c.Sized)
def _(arg):
return "sized"
@h.register(c.Container)
def _(arg):
return "container"
# Even though Sized and Container are explicit bases of MutableMapping,
# this ABC is implicitly registered on defaultdict which makes all of
# MutableMapping's bases implicit as well from defaultdict's
# perspective.
with self.assertRaises(RuntimeError) as re_two:
h(collections.defaultdict(lambda: 0))
self.assertIn(
str(re_two.exception),
(("Ambiguous dispatch: <class 'collections.abc.Container'> "
"or <class 'collections.abc.Sized'>"),
("Ambiguous dispatch: <class 'collections.abc.Sized'> "
"or <class 'collections.abc.Container'>")),
)
class R(collections.defaultdict):
pass
c.MutableSequence.register(R)
@functools.singledispatch
def i(arg):
return "base"
@i.register(c.MutableMapping)
def _(arg):
return "mapping"
@i.register(c.MutableSequence)
def _(arg):
return "sequence"
r = R()
self.assertEqual(i(r), "sequence")
class S:
pass
class T(S, c.Sized):
def __len__(self):
return 0
t = T()
self.assertEqual(h(t), "sized")
c.Container.register(T)
self.assertEqual(h(t), "sized") # because it's explicitly in the MRO
class U:
def __len__(self):
return 0
u = U()
self.assertEqual(h(u), "sized") # implicit Sized subclass inferred
# from the existence of __len__()
c.Container.register(U)
# There is no preference for registered versus inferred ABCs.
with self.assertRaises(RuntimeError) as re_three:
h(u)
self.assertIn(
str(re_three.exception),
(("Ambiguous dispatch: <class 'collections.abc.Container'> "
"or <class 'collections.abc.Sized'>"),
("Ambiguous dispatch: <class 'collections.abc.Sized'> "
"or <class 'collections.abc.Container'>")),
)
class V(c.Sized, S):
def __len__(self):
return 0
@functools.singledispatch
def j(arg):
return "base"
@j.register(S)
def _(arg):
return "s"
@j.register(c.Container)
def _(arg):
return "container"
v = V()
self.assertEqual(j(v), "s")
c.Container.register(V)
self.assertEqual(j(v), "container") # because it ends up right after
# Sized in the MRO
def test_cache_invalidation(self):
from collections import UserDict
import weakref
class TracingDict(UserDict):
def __init__(self, *args, **kwargs):
super(TracingDict, self).__init__(*args, **kwargs)
self.set_ops = []
self.get_ops = []
def __getitem__(self, key):
result = self.data[key]
self.get_ops.append(key)
return result
def __setitem__(self, key, value):
self.set_ops.append(key)
self.data[key] = value
def clear(self):
self.data.clear()
td = TracingDict()
with support.swap_attr(weakref, "WeakKeyDictionary", lambda: td):
c = collections.abc
@functools.singledispatch
def g(arg):
return "base"
d = {}
l = []
self.assertEqual(len(td), 0)
self.assertEqual(g(d), "base")
self.assertEqual(len(td), 1)
self.assertEqual(td.get_ops, [])
self.assertEqual(td.set_ops, [dict])
self.assertEqual(td.data[dict], g.registry[object])
self.assertEqual(g(l), "base")
self.assertEqual(len(td), 2)
self.assertEqual(td.get_ops, [])
self.assertEqual(td.set_ops, [dict, list])
self.assertEqual(td.data[dict], g.registry[object])
self.assertEqual(td.data[list], g.registry[object])
self.assertEqual(td.data[dict], td.data[list])
self.assertEqual(g(l), "base")
self.assertEqual(g(d), "base")
self.assertEqual(td.get_ops, [list, dict])
self.assertEqual(td.set_ops, [dict, list])
g.register(list, lambda arg: "list")
self.assertEqual(td.get_ops, [list, dict])
self.assertEqual(len(td), 0)
self.assertEqual(g(d), "base")
self.assertEqual(len(td), 1)
self.assertEqual(td.get_ops, [list, dict])
self.assertEqual(td.set_ops, [dict, list, dict])
self.assertEqual(td.data[dict],
functools._find_impl(dict, g.registry))
self.assertEqual(g(l), "list")
self.assertEqual(len(td), 2)
self.assertEqual(td.get_ops, [list, dict])
self.assertEqual(td.set_ops, [dict, list, dict, list])
self.assertEqual(td.data[list],
functools._find_impl(list, g.registry))
class X:
pass
c.MutableMapping.register(X) # Will not invalidate the cache,
# not using ABCs yet.
self.assertEqual(g(d), "base")
self.assertEqual(g(l), "list")
self.assertEqual(td.get_ops, [list, dict, dict, list])
self.assertEqual(td.set_ops, [dict, list, dict, list])
g.register(c.Sized, lambda arg: "sized")
self.assertEqual(len(td), 0)
self.assertEqual(g(d), "sized")
self.assertEqual(len(td), 1)
self.assertEqual(td.get_ops, [list, dict, dict, list])
self.assertEqual(td.set_ops, [dict, list, dict, list, dict])
self.assertEqual(g(l), "list")
self.assertEqual(len(td), 2)
self.assertEqual(td.get_ops, [list, dict, dict, list])
self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list])
self.assertEqual(g(l), "list")
self.assertEqual(g(d), "sized")
self.assertEqual(td.get_ops, [list, dict, dict, list, list, dict])
self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list])
g.dispatch(list)
g.dispatch(dict)
self.assertEqual(td.get_ops, [list, dict, dict, list, list, dict,
list, dict])
self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list])
c.MutableSet.register(X) # Will invalidate the cache.
self.assertEqual(len(td), 2) # Stale cache.
self.assertEqual(g(l), "list")
self.assertEqual(len(td), 1)
g.register(c.MutableMapping, lambda arg: "mutablemapping")
self.assertEqual(len(td), 0)
self.assertEqual(g(d), "mutablemapping")
self.assertEqual(len(td), 1)
self.assertEqual(g(l), "list")
self.assertEqual(len(td), 2)
g.register(dict, lambda arg: "dict")
self.assertEqual(g(d), "dict")
self.assertEqual(g(l), "list")
g._clear_cache()
self.assertEqual(len(td), 0)
def test_annotations(self):
@functools.singledispatch
def i(arg):
return "base"
@i.register
def _(arg: collections.abc.Mapping):
return "mapping"
@i.register
def _(arg: "collections.abc.Sequence"):
return "sequence"
self.assertEqual(i(None), "base")
self.assertEqual(i({"a": 1}), "mapping")
self.assertEqual(i([1, 2, 3]), "sequence")
self.assertEqual(i((1, 2, 3)), "sequence")
self.assertEqual(i("str"), "sequence")
# Registering classes as callables doesn't work with annotations,
# you need to pass the type explicitly.
@i.register(str)
class _:
def __init__(self, arg):
self.arg = arg
def __eq__(self, other):
return self.arg == other
self.assertEqual(i("str"), "str")
def test_invalid_registrations(self):
msg_prefix = "Invalid first argument to `register()`: "
msg_suffix = (
". Use either `@register(some_class)` or plain `@register` on an "
"annotated function."
)
@functools.singledispatch
def i(arg):
return "base"
with self.assertRaises(TypeError) as exc:
@i.register(42)
def _(arg):
return "I annotated with a non-type"
self.assertTrue(str(exc.exception).startswith(msg_prefix + "42"))
self.assertTrue(str(exc.exception).endswith(msg_suffix))
with self.assertRaises(TypeError) as exc:
@i.register
def _(arg):
return "I forgot to annotate"
self.assertTrue(str(exc.exception).startswith(msg_prefix +
"<function TestSingleDispatch.test_invalid_registrations.<locals>._"
))
self.assertTrue(str(exc.exception).endswith(msg_suffix))
# FIXME: The following will only work after PEP 560 is implemented.
return
with self.assertRaises(TypeError) as exc:
@i.register
def _(arg: typing.Iterable[str]):
# At runtime, dispatching on generics is impossible.
# When registering implementations with singledispatch, avoid
# types from `typing`. Instead, annotate with regular types
# or ABCs.
return "I annotated with a generic collection"
self.assertTrue(str(exc.exception).startswith(msg_prefix +
"<function TestSingleDispatch.test_invalid_registrations.<locals>._"
))
self.assertTrue(str(exc.exception).endswith(msg_suffix))
def test_invalid_positional_argument(self):
@functools.singledispatch
def f(*args):
pass
msg = 'f requires at least 1 positional argument'
with self.assertRaisesRegex(TypeError, msg):
f()
if __name__ == '__main__':
unittest.main()
| gpl-2.0 |
nigelb/hbase-cluster-launch | hbase_cluster_launcher/launch.py | 1867 | #hbase_cluster-launcher is a tool for launching HBase clusters on
#Openstack clouds
#
#Copyright (C) 2013 NigelB
#
#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.
from argparse import ArgumentParser
import sys, os.path
from hbase_cluster_launcher.api import get_vm, get_registered_vms
def main():
argParse = ArgumentParser(description="HBase cluster launcher.")
subparsers = argParse.add_subparsers(description="Available VM APIs")
for vms in get_registered_vms():
p = get_vm(vms)()
parser_a = subparsers.add_parser(vms, help=p.description())
p.initialize_parser(parser_a)
args = argParse.parse_args()
launcher = args.vm
launcher.parse(args)
try:
args.config_dir = os.path.abspath(args.config_dir)
sys.path.append(args.config_dir)
from hbase_cluster_launcher.puppet.config import generate_puppet_enc_config, copy_lookup_to_puppet
machine_data = launcher.launch_vm(args)
puppet_lookup_file = generate_puppet_enc_config(args, machine_data)
copy_lookup_to_puppet(args, puppet_lookup_file)
except ImportError, io:
print "Sorry, could not find configuration directory."
if __name__ == "__main__":
main() | gpl-2.0 |
projectestac/wordpress-gce | third-party/nesbot/carbon/src/Carbon/Lang/sc.php | 374 | <?php
namespace SimpleCalendar\plugin_deps;
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/*
* Unknown default region, use the first alphabetically.
*/
return require __DIR__ . '/sc_IT.php';
| gpl-2.0 |
optimized4u/ProjectTrackingWebsite | ProjectTrackingServices/Areas/HelpPage/App_Start/HelpPageConfig.cs | 6517 | // Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace ProjectTrackingServices.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "ProjectTrackingServices.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | gpl-2.0 |
jescarri/mqtt-ruby-push_to_rest | bin/mttq-temp-display.rb | 6250 | #!/usr/bin/ruby
####################################################################################
# Author: Jesus Carrillo jesuscarrillo8 at gmail.com
####################################################################################
# License: GPL V2
####################################################################################
# Todo:
# Handle CTRL+C
# Add code to post to LCD Display Server -> Done
# Add Code to log data into a Database
####################################################################################
if ENV["RB_LIB_PATH"].nil?
$LOAD_PATH.unshift File.expand_path("#{ENV["PWD"]}/lib")
else
$LOAD_PATH.unshift File.expand_path("#{ENV["RB_LIB_PATH"]}")
end
require 'mosquitto'
require 'logger'
require 'display-rest'
require 'mysql_log'
require 'optparse'
require 'securerandom'
class Mqtt_display
#Globals
#Log object
@LOG = nil
def self.main(opts={})
#default options
options = {"mosquitto_host" => "192.168.1.254","topic"=>"/aeres-egipty/sensors","mosquitto_port"=> 1883 ,"keep_alive" => 5}
options=options.merge(opts)
#Setup global logging
setup_logging()
bmp_hash = nil
dht_hash = nil
#Create mosquitto object
#client_id needs to be random!
client_name = SecureRandom.uuid
mosquitto = Mosquitto::Client.new(client_name)
#Callbacks
#When connected
mosquitto.on_connect do |rc|
@LOG.info "Connected to mosquitto server #{options["mosquitto_host"]} with return code #{rc}"
mosquitto.subscribe(nil, options["topic"], Mosquitto::AT_MOST_ONCE)
end
#When subscribed
mosquitto.on_subscribe do |mid, granted_qos|
@LOG.info "Subscribed to topic #{options["topic"]}"
end
#When message Arrives
mosquitto.on_message do |message|
#Message Payload
#DHT,C=OK,T=26.000,H=37.300:BMP085,C=OK,T=26.900,P=1005.30
@LOG.info "Got Message: #{message.to_s}"
sensors = message.to_s.split(":")
dht = sensors[0]
bmp085 = sensors[1]
#DHT Payload DHT,C=OK,T=26.000,H=37.300
begin
dht_hash = {
"code" => dht.split(",")[1].split("=")[1],
"temp" => dht.split(",")[2].split("=")[1],
"humidity" => dht.split(",")[3].split("=")[1]
}
rescue
@LOG.error "CANNOT Parse DHT Sensor data"
dht_hash = nil
end
#BMP085,C=OK,T=26.900,P=1005.30
begin
bmp_hash = {
"code" => bmp085.split(",")[1].split("=")[1],
"temp" => bmp085.split(",")[2].split("=")[1],
"barometric_pressure" => bmp085.split(",")[3].split("=")[1]
}
rescue
@LOG.error "CANNOT Parse BMP Sensor data"
bmp_hash = nil
end
#Call post_data_to_display
post_data_to_display(options["api-endpoint"],dht_hash,bmp_hash)
end
mosquitto.on_disconnect do |rc|
@LOG.error "mosquitto client has been disconnected, trying to reconnect to host #{options["mosquitto_host"]}"
begin
@LOG.info "Reconnecting to #{options["mosquitto_host"]}"
mosquitto.connect(options["mosquitto_host"], options["mosquitto_port"],options["keep_alive"])
rescue
@LOG.error "Cannot reconnect, retrying in 60 seconds!"
sleep 60
retry
end
end
########################
#End of callbacks
########################
def self.post_data_to_display(endpoint,dht_hash,bmp_hash)
#code to make an API Call to the display server.
begin
puts "INSPECT #{dht_hash.inspect}"
lcd=LcdClient.new({ "endpoint"=> endpoint,"log_file" => "/var/tmp/mttq-temp-display.log" })
temp = (dht_hash["temp"].to_f + bmp_hash["temp"].to_f) / 2
hum = dht_hash["humidity"]
bar = bmp_hash["barometric_pressure"].to_f
lcd_text = "T:#{temp.round(2)} H:#{hum.to_f.round(2)}"
time = Time.new
lu = time.strftime("%Y-%m-%d %H:%M")
lcd_text2 = "LU:#{lu}"
#log data
###REPLACE db_opts with the correct credentials
db_opts = {"mysql_host" => "192.168.1.105","user"=>"dumper","passwd"=>"2Ddr6vjk", "database" => "sensor_data","log_file" => "/var/tmp/mttq-temp-display.log" }
db_log = Mysql_Logger.new(db_opts)
db_log.add_weather_data({"sensor_id"=>"ARDUINO-MQTT","temp"=>temp,"hum" => hum, "bar"=>bar})
db_log.close
rescue
#Add code to better Exception Handling
@LOG.error "ERROR PARSING OR CONNECTING TO DB"
end
begin
lcd.set_line({"line"=>1,"text"=>lcd_text})
lcd.set_line({"line"=>2,"text"=>lcd_text2})
rescue
#Add Retry Logic
@LOG.error "Cannot post to LCD Server"
end
end
#######################
#Main Code
#######################
#Connect to mosquitto Server
mosquitto.connect(options["mosquitto_host"], options["mosquitto_port"],options["keep_alive"])
#Start mosquitto loop
mosquitto.loop_forever(10, 1)
#
end
def self.setup_logging(opts={})
#default options
options = {"log_level" => Logger::INFO, "log_file" => "/var/tmp/mttq-temp-display.log" }
options.merge(opts)
#Initialize Logging
@LOG = Logger.new(options["log_file"])
@LOG.level = options["log_level"]
@LOG.progname = "mqtt-temp"
end
end
if __FILE__ == $0
options={}
begin
OptionParser.new do |opt|
opt.on('-a', '--api_endpoint API_ENDPOINT http|s://host:port') { |o| options["api-endpoint"] = o }
opt.on('-t', '--topic MQTT_TOPIC') { |o| options["topic"] = o }
opt.on('-h', '--host MQTT_HOST') { |o| options["mosquito-host"] = o }
opt.on('-p', '--port MQTT_PORT') { |o| options["mosquito-port"] = o }
end.parse!
rescue
puts "usage: #{$0} -a http|s://host:port -t topic -h mosquitto_host -p mosqito_port"
exit 255
end
unless options["api-endpoint"]
options["api-endpoint"] = "http://192.168.1.104:8000"
end
lcd=LcdClient.new({ "endpoint"=>options["api-endpoint"],"log_file" => "/var/tmp/mttq-temp-display.log" })
lcd.set_line({"line"=>1,"text"=>""})
lcd.set_line({"line"=>2,"text"=>""})
Mqtt_display.main(options)
#"/aeres-egipty/sensors"
end
| gpl-2.0 |
marktriggs/vufind | web/services/MyResearch/Account.php | 4757 | <?php
/**
* Account action for MyResearch module
*
* PHP version 5
*
* Copyright (C) Villanova University 2007.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @category VuFind
* @package Controller_MyResearch
* @author Andrew S. Nagy <[email protected]>
* @author Demian Katz <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/building_a_module Wiki
*/
require_once "Action.php";
require_once 'sys/User.php';
require_once 'Mail/RFC822.php';
/**
* Account action for MyResearch module
*
* @category VuFind
* @package Controller_MyResearch
* @author Andrew S. Nagy <[email protected]>
* @author Demian Katz <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/building_a_module Wiki
*/
class Account extends Action
{
/**
* Constructor
*
* @access public
*/
public function __construct()
{
}
/**
* Process parameters and display the page.
*
* @return void
* @access public
*/
public function launch()
{
global $interface;
global $configArray;
// Don't allow account creation if a non-DB authentication method
// is being used!!
if ($configArray['Authentication']['method'] !== 'DB') {
header('Location: Home');
die();
}
if (isset($_POST['submit'])) {
$result = $this->_processInput();
if (PEAR::isError($result)) {
$interface->assign('message', $result->getMessage());
$interface->assign('formVars', $_POST);
$interface->setTemplate('account.tpl');
$interface->display('layout.tpl');
} else {
// Now that the account is created, log the user in:
UserAccount::login();
header('Location: Home');
die();
}
} else {
$interface->setPageTitle('User Account');
$interface->setTemplate('account.tpl');
$interface->display('layout.tpl');
}
}
/**
* Process incoming parameters for account creation.
*
* @return mixed True on successful account creation, PEAR_Error otherwise.
* @access private
*/
private function _processInput()
{
// Validate Input
if (trim($_POST['username']) == '') {
return new PEAR_Error('Username cannot be blank');
}
if (trim($_POST['password']) == '') {
return new PEAR_Error('Password cannot be blank');
}
if ($_POST['password'] != $_POST['password2']) {
return new PEAR_Error('Passwords do not match');
}
if (!Mail_RFC822::isValidInetAddress($_POST['email'])) {
return new PEAR_Error('Email address is invalid');
}
// Create Account
$user = new User();
$user->username = $_POST['username'];
if (!$user->find()) {
// No username match found -- check for duplicate email:
$user = new User();
$user->email = $_POST['email'];
if (!$user->find()) {
// We need to reassign the username since we cleared it out when
// we did the search for duplicate email addresses:
$authN = AuthenticationFactory::initAuthentication('DB');
$user->username = $_POST['username'];
$authN->setPasswordForUser($user, $_POST['password']);
$user->firstname = $_POST['firstname'];
$user->lastname = $_POST['lastname'];
$user->created = date('Y-m-d h:i:s');
$user->insert();
} else {
return new PEAR_Error('That email address is already used');
}
} else {
return new PEAR_Error('That username is already taken');
}
return true;
}
}
?> | gpl-2.0 |
learnsqr/cursoZf2 | module/cinema/src/cinema/Module.php | 502 | <?php
namespace cinema;
use ZF\Apigility\Provider\ApigilityProviderInterface;
class Module implements ApigilityProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../../config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'ZF\Apigility\Autoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__,
),
),
);
}
}
| gpl-2.0 |
s3rvac/fit-projects | PDB/nbproject/src/zoo/ObjectData.java | 1638 | /**
* Project: PDB 2008
* Authors: Ondrej Lengal, [email protected]
* Libor Polcak, [email protected]
* Boris Prochazka, [email protected]
* Petr Zemek, [email protected]
*
* @brief Data of a drawable object from a db.
*
*/
package zoo;
import java.awt.Color;
import java.awt.image.BufferedImage;
/**
* @brief Data of a drawable object from a db.
*/
public class ObjectData implements Cloneable {
/// ID of an object which does not have any ID
public static final int NO_OBJECT_ID = -1;
/// Object type of an object which does not have any object type set
public static final int NO_OBJECT_TYPE = -1;
public static final int POINT_TYPE = 0;
public static final int POLYGON_TYPE = 1;
public static final int LINE_TYPE = 2;
public static final int RECTANGLE_TYPE = 3;
public static final int CIRCLE_TYPE = 4;
/// Object ID.
public int id = NO_OBJECT_ID;
/// Table name.
public String tableName = null;
/// Object name.
public String name = "";
/// Object description.
public String description = "";
/// Object type (point, rectangle, ...)
public int objectType = NO_OBJECT_TYPE;
/// Object 2D coordinates.
public int[] coordinates = null;
/// Object color.
public Color color = null;
/// Object photo.
BufferedImage photo = null;
/// Object deepClone.
public Object deepClone() {
try {
ObjectData copy = (ObjectData)super.clone();
copy.coordinates = (int[])coordinates.clone();
return copy;
} catch (CloneNotSupportedException ex) {
throw new Error("public Object deepClone()");
}
}
}
| gpl-2.0 |
newmind/uvnc_rds | uvnc_settings/uvnc_settings/inifile.cpp | 2641 | #include "stdafx.h"
#include "inifile.h"
IniFile::IniFile()
{
char WORKDIR[MAX_PATH];
if (GetModuleFileName(NULL, WORKDIR, MAX_PATH))
{
char* p = strrchr(WORKDIR, '\\');
if (p == NULL) return;
*p = '\0';
}
strcpy(myInifile,"");
strcat(myInifile,WORKDIR);//set the directory
strcat(myInifile,"\\");
strcat(myInifile,INIFILE_NAME);
}
void
IniFile::IniFileSetSecure()
{
char WORKDIR[MAX_PATH];
if (GetModuleFileName(NULL, WORKDIR, MAX_PATH))
{
char* p = strrchr(WORKDIR, '\\');
if (p == NULL) return;
*p = '\0';
}
strcpy(myInifile,"");
strcat(myInifile,WORKDIR);//set the directory
strcat(myInifile,"\\");
strcat(myInifile,INIFILE_NAME);
}
void
IniFile::IniFileSetTemp(char *lpCmdLine)
{
strcpy(myInifile,lpCmdLine);
}
IniFile::~IniFile()
{
}
bool
IniFile::WriteString(char *key1, char *key2,char *value)
{
//vnclog.Print(LL_INTERR, VNCLOG("%s \n"),myInifile);
return (FALSE != WritePrivateProfileString(key1,key2, value,myInifile));
}
bool
IniFile::WriteInt(char *key1, char *key2,int value)
{
char buf[32];
wsprintf(buf, "%d", value);
//vnclog.Print(LL_INTERR, VNCLOG("%s \n"),myInifile);
int result=WritePrivateProfileString(key1,key2, buf,myInifile);
if (result==0) return false;
return true;
}
int
IniFile::ReadInt(char *key1, char *key2,int Defaultvalue)
{
//vnclog.Print(LL_INTERR, VNCLOG("%s \n"),myInifile);
return GetPrivateProfileInt(key1, key2, Defaultvalue, myInifile);
}
void
IniFile::ReadString(char *key1, char *key2,char *value,int valuesize)
{
//vnclog.Print(LL_INTERR, VNCLOG("%s \n"),myInifile);
GetPrivateProfileString(key1,key2, "",value,valuesize,myInifile);
}
void
IniFile::ReadPassword(char *value,int valuesize)
{
//int size=ReadInt("ultravnc", "passwdsize",0);
//vnclog.Print(LL_INTERR, VNCLOG("%s \n"),myInifilePasswd);
GetPrivateProfileStruct("ultravnc","passwd",value,8,myInifile);
}
bool
IniFile::WritePassword(char *value)
{
//WriteInt("ultravnc", "passwdsize",sizeof(value));
//vnclog.Print(LL_INTERR, VNCLOG("%s \n"),myInifile);
return (FALSE != WritePrivateProfileStruct("ultravnc","passwd", value,8,myInifile));
}
void //PGM
IniFile::ReadPassword2(char *value,int valuesize) //PGM
{ //PGM
GetPrivateProfileStruct("ultravnc","passwd2",value,8,myInifile); //PGM
} //PGM
bool //PGM
IniFile::WritePassword2(char *value) //PGM
{ //PGM
return (FALSE != WritePrivateProfileStruct("ultravnc","passwd2", value,8,myInifile)); //PGM
} //PGM
bool IniFile::IsWritable()
{
bool writable = WriteInt("Permissions", "isWritable",1);
if (writable)
WritePrivateProfileSection("Permissions", "", myInifile);
return writable;
}
| gpl-2.0 |
mviitanen/marsmod | mcp/src/minecraft/net/minecraft/block/BlockLever.java | 14444 | package net.minecraft.block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockLever extends Block
{
private static final String __OBFID = "CL_00000264";
protected BlockLever()
{
super(Material.circuits);
this.setCreativeTab(CreativeTabs.tabRedstone);
}
/**
* Returns a bounding box from the pool of bounding boxes (this means this box can change after the pool has been
* cleared to be reused)
*/
public AxisAlignedBB getCollisionBoundingBoxFromPool(World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_)
{
return null;
}
public boolean isOpaqueCube()
{
return false;
}
public boolean renderAsNormalBlock()
{
return false;
}
/**
* The type of render function that is called for this block
*/
public int getRenderType()
{
return 12;
}
/**
* checks to see if you can place this block can be placed on that side of a block: BlockLever overrides
*/
public boolean canPlaceBlockOnSide(World p_149707_1_, int p_149707_2_, int p_149707_3_, int p_149707_4_, int p_149707_5_)
{
return p_149707_5_ == 0 && p_149707_1_.getBlock(p_149707_2_, p_149707_3_ + 1, p_149707_4_).isNormalCube() ? true : (p_149707_5_ == 1 && World.doesBlockHaveSolidTopSurface(p_149707_1_, p_149707_2_, p_149707_3_ - 1, p_149707_4_) ? true : (p_149707_5_ == 2 && p_149707_1_.getBlock(p_149707_2_, p_149707_3_, p_149707_4_ + 1).isNormalCube() ? true : (p_149707_5_ == 3 && p_149707_1_.getBlock(p_149707_2_, p_149707_3_, p_149707_4_ - 1).isNormalCube() ? true : (p_149707_5_ == 4 && p_149707_1_.getBlock(p_149707_2_ + 1, p_149707_3_, p_149707_4_).isNormalCube() ? true : p_149707_5_ == 5 && p_149707_1_.getBlock(p_149707_2_ - 1, p_149707_3_, p_149707_4_).isNormalCube()))));
}
public boolean canPlaceBlockAt(World p_149742_1_, int p_149742_2_, int p_149742_3_, int p_149742_4_)
{
return p_149742_1_.getBlock(p_149742_2_ - 1, p_149742_3_, p_149742_4_).isNormalCube() ? true : (p_149742_1_.getBlock(p_149742_2_ + 1, p_149742_3_, p_149742_4_).isNormalCube() ? true : (p_149742_1_.getBlock(p_149742_2_, p_149742_3_, p_149742_4_ - 1).isNormalCube() ? true : (p_149742_1_.getBlock(p_149742_2_, p_149742_3_, p_149742_4_ + 1).isNormalCube() ? true : (World.doesBlockHaveSolidTopSurface(p_149742_1_, p_149742_2_, p_149742_3_ - 1, p_149742_4_) ? true : p_149742_1_.getBlock(p_149742_2_, p_149742_3_ + 1, p_149742_4_).isNormalCube()))));
}
public int onBlockPlaced(World p_149660_1_, int p_149660_2_, int p_149660_3_, int p_149660_4_, int p_149660_5_, float p_149660_6_, float p_149660_7_, float p_149660_8_, int p_149660_9_)
{
int var11 = p_149660_9_ & 8;
int var10 = p_149660_9_ & 7;
byte var12 = -1;
if (p_149660_5_ == 0 && p_149660_1_.getBlock(p_149660_2_, p_149660_3_ + 1, p_149660_4_).isNormalCube())
{
var12 = 0;
}
if (p_149660_5_ == 1 && World.doesBlockHaveSolidTopSurface(p_149660_1_, p_149660_2_, p_149660_3_ - 1, p_149660_4_))
{
var12 = 5;
}
if (p_149660_5_ == 2 && p_149660_1_.getBlock(p_149660_2_, p_149660_3_, p_149660_4_ + 1).isNormalCube())
{
var12 = 4;
}
if (p_149660_5_ == 3 && p_149660_1_.getBlock(p_149660_2_, p_149660_3_, p_149660_4_ - 1).isNormalCube())
{
var12 = 3;
}
if (p_149660_5_ == 4 && p_149660_1_.getBlock(p_149660_2_ + 1, p_149660_3_, p_149660_4_).isNormalCube())
{
var12 = 2;
}
if (p_149660_5_ == 5 && p_149660_1_.getBlock(p_149660_2_ - 1, p_149660_3_, p_149660_4_).isNormalCube())
{
var12 = 1;
}
return var12 + var11;
}
/**
* Called when the block is placed in the world.
*/
public void onBlockPlacedBy(World p_149689_1_, int p_149689_2_, int p_149689_3_, int p_149689_4_, EntityLivingBase p_149689_5_, ItemStack p_149689_6_)
{
int var7 = p_149689_1_.getBlockMetadata(p_149689_2_, p_149689_3_, p_149689_4_);
int var8 = var7 & 7;
int var9 = var7 & 8;
if (var8 == func_149819_b(1))
{
if ((MathHelper.floor_double((double)(p_149689_5_.rotationYaw * 4.0F / 360.0F) + 0.5D) & 1) == 0)
{
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, 5 | var9, 2);
}
else
{
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, 6 | var9, 2);
}
}
else if (var8 == func_149819_b(0))
{
if ((MathHelper.floor_double((double)(p_149689_5_.rotationYaw * 4.0F / 360.0F) + 0.5D) & 1) == 0)
{
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, 7 | var9, 2);
}
else
{
p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, 0 | var9, 2);
}
}
}
public static int func_149819_b(int p_149819_0_)
{
switch (p_149819_0_)
{
case 0:
return 0;
case 1:
return 5;
case 2:
return 4;
case 3:
return 3;
case 4:
return 2;
case 5:
return 1;
default:
return -1;
}
}
public void onNeighborBlockChange(World p_149695_1_, int p_149695_2_, int p_149695_3_, int p_149695_4_, Block p_149695_5_)
{
if (this.func_149820_e(p_149695_1_, p_149695_2_, p_149695_3_, p_149695_4_))
{
int var6 = p_149695_1_.getBlockMetadata(p_149695_2_, p_149695_3_, p_149695_4_) & 7;
boolean var7 = false;
if (!p_149695_1_.getBlock(p_149695_2_ - 1, p_149695_3_, p_149695_4_).isNormalCube() && var6 == 1)
{
var7 = true;
}
if (!p_149695_1_.getBlock(p_149695_2_ + 1, p_149695_3_, p_149695_4_).isNormalCube() && var6 == 2)
{
var7 = true;
}
if (!p_149695_1_.getBlock(p_149695_2_, p_149695_3_, p_149695_4_ - 1).isNormalCube() && var6 == 3)
{
var7 = true;
}
if (!p_149695_1_.getBlock(p_149695_2_, p_149695_3_, p_149695_4_ + 1).isNormalCube() && var6 == 4)
{
var7 = true;
}
if (!World.doesBlockHaveSolidTopSurface(p_149695_1_, p_149695_2_, p_149695_3_ - 1, p_149695_4_) && var6 == 5)
{
var7 = true;
}
if (!World.doesBlockHaveSolidTopSurface(p_149695_1_, p_149695_2_, p_149695_3_ - 1, p_149695_4_) && var6 == 6)
{
var7 = true;
}
if (!p_149695_1_.getBlock(p_149695_2_, p_149695_3_ + 1, p_149695_4_).isNormalCube() && var6 == 0)
{
var7 = true;
}
if (!p_149695_1_.getBlock(p_149695_2_, p_149695_3_ + 1, p_149695_4_).isNormalCube() && var6 == 7)
{
var7 = true;
}
if (var7)
{
this.dropBlockAsItem(p_149695_1_, p_149695_2_, p_149695_3_, p_149695_4_, p_149695_1_.getBlockMetadata(p_149695_2_, p_149695_3_, p_149695_4_), 0);
p_149695_1_.setBlockToAir(p_149695_2_, p_149695_3_, p_149695_4_);
}
}
}
private boolean func_149820_e(World p_149820_1_, int p_149820_2_, int p_149820_3_, int p_149820_4_)
{
if (!this.canPlaceBlockAt(p_149820_1_, p_149820_2_, p_149820_3_, p_149820_4_))
{
this.dropBlockAsItem(p_149820_1_, p_149820_2_, p_149820_3_, p_149820_4_, p_149820_1_.getBlockMetadata(p_149820_2_, p_149820_3_, p_149820_4_), 0);
p_149820_1_.setBlockToAir(p_149820_2_, p_149820_3_, p_149820_4_);
return false;
}
else
{
return true;
}
}
public void setBlockBoundsBasedOnState(IBlockAccess p_149719_1_, int p_149719_2_, int p_149719_3_, int p_149719_4_)
{
int var5 = p_149719_1_.getBlockMetadata(p_149719_2_, p_149719_3_, p_149719_4_) & 7;
float var6 = 0.1875F;
if (var5 == 1)
{
this.setBlockBounds(0.0F, 0.2F, 0.5F - var6, var6 * 2.0F, 0.8F, 0.5F + var6);
}
else if (var5 == 2)
{
this.setBlockBounds(1.0F - var6 * 2.0F, 0.2F, 0.5F - var6, 1.0F, 0.8F, 0.5F + var6);
}
else if (var5 == 3)
{
this.setBlockBounds(0.5F - var6, 0.2F, 0.0F, 0.5F + var6, 0.8F, var6 * 2.0F);
}
else if (var5 == 4)
{
this.setBlockBounds(0.5F - var6, 0.2F, 1.0F - var6 * 2.0F, 0.5F + var6, 0.8F, 1.0F);
}
else if (var5 != 5 && var5 != 6)
{
if (var5 == 0 || var5 == 7)
{
var6 = 0.25F;
this.setBlockBounds(0.5F - var6, 0.4F, 0.5F - var6, 0.5F + var6, 1.0F, 0.5F + var6);
}
}
else
{
var6 = 0.25F;
this.setBlockBounds(0.5F - var6, 0.0F, 0.5F - var6, 0.5F + var6, 0.6F, 0.5F + var6);
}
}
/**
* Called upon block activation (right click on the block.)
*/
public boolean onBlockActivated(World p_149727_1_, int p_149727_2_, int p_149727_3_, int p_149727_4_, EntityPlayer p_149727_5_, int p_149727_6_, float p_149727_7_, float p_149727_8_, float p_149727_9_)
{
if (p_149727_1_.isClient)
{
return true;
}
else
{
int var10 = p_149727_1_.getBlockMetadata(p_149727_2_, p_149727_3_, p_149727_4_);
int var11 = var10 & 7;
int var12 = 8 - (var10 & 8);
p_149727_1_.setBlockMetadataWithNotify(p_149727_2_, p_149727_3_, p_149727_4_, var11 + var12, 3);
p_149727_1_.playSoundEffect((double)p_149727_2_ + 0.5D, (double)p_149727_3_ + 0.5D, (double)p_149727_4_ + 0.5D, "random.click", 0.3F, var12 > 0 ? 0.6F : 0.5F);
p_149727_1_.notifyBlocksOfNeighborChange(p_149727_2_, p_149727_3_, p_149727_4_, this);
if (var11 == 1)
{
p_149727_1_.notifyBlocksOfNeighborChange(p_149727_2_ - 1, p_149727_3_, p_149727_4_, this);
}
else if (var11 == 2)
{
p_149727_1_.notifyBlocksOfNeighborChange(p_149727_2_ + 1, p_149727_3_, p_149727_4_, this);
}
else if (var11 == 3)
{
p_149727_1_.notifyBlocksOfNeighborChange(p_149727_2_, p_149727_3_, p_149727_4_ - 1, this);
}
else if (var11 == 4)
{
p_149727_1_.notifyBlocksOfNeighborChange(p_149727_2_, p_149727_3_, p_149727_4_ + 1, this);
}
else if (var11 != 5 && var11 != 6)
{
if (var11 == 0 || var11 == 7)
{
p_149727_1_.notifyBlocksOfNeighborChange(p_149727_2_, p_149727_3_ + 1, p_149727_4_, this);
}
}
else
{
p_149727_1_.notifyBlocksOfNeighborChange(p_149727_2_, p_149727_3_ - 1, p_149727_4_, this);
}
return true;
}
}
public void breakBlock(World p_149749_1_, int p_149749_2_, int p_149749_3_, int p_149749_4_, Block p_149749_5_, int p_149749_6_)
{
if ((p_149749_6_ & 8) > 0)
{
p_149749_1_.notifyBlocksOfNeighborChange(p_149749_2_, p_149749_3_, p_149749_4_, this);
int var7 = p_149749_6_ & 7;
if (var7 == 1)
{
p_149749_1_.notifyBlocksOfNeighborChange(p_149749_2_ - 1, p_149749_3_, p_149749_4_, this);
}
else if (var7 == 2)
{
p_149749_1_.notifyBlocksOfNeighborChange(p_149749_2_ + 1, p_149749_3_, p_149749_4_, this);
}
else if (var7 == 3)
{
p_149749_1_.notifyBlocksOfNeighborChange(p_149749_2_, p_149749_3_, p_149749_4_ - 1, this);
}
else if (var7 == 4)
{
p_149749_1_.notifyBlocksOfNeighborChange(p_149749_2_, p_149749_3_, p_149749_4_ + 1, this);
}
else if (var7 != 5 && var7 != 6)
{
if (var7 == 0 || var7 == 7)
{
p_149749_1_.notifyBlocksOfNeighborChange(p_149749_2_, p_149749_3_ + 1, p_149749_4_, this);
}
}
else
{
p_149749_1_.notifyBlocksOfNeighborChange(p_149749_2_, p_149749_3_ - 1, p_149749_4_, this);
}
}
super.breakBlock(p_149749_1_, p_149749_2_, p_149749_3_, p_149749_4_, p_149749_5_, p_149749_6_);
}
public int isProvidingWeakPower(IBlockAccess p_149709_1_, int p_149709_2_, int p_149709_3_, int p_149709_4_, int p_149709_5_)
{
return (p_149709_1_.getBlockMetadata(p_149709_2_, p_149709_3_, p_149709_4_) & 8) > 0 ? 15 : 0;
}
public int isProvidingStrongPower(IBlockAccess p_149748_1_, int p_149748_2_, int p_149748_3_, int p_149748_4_, int p_149748_5_)
{
int var6 = p_149748_1_.getBlockMetadata(p_149748_2_, p_149748_3_, p_149748_4_);
if ((var6 & 8) == 0)
{
return 0;
}
else
{
int var7 = var6 & 7;
return var7 == 0 && p_149748_5_ == 0 ? 15 : (var7 == 7 && p_149748_5_ == 0 ? 15 : (var7 == 6 && p_149748_5_ == 1 ? 15 : (var7 == 5 && p_149748_5_ == 1 ? 15 : (var7 == 4 && p_149748_5_ == 2 ? 15 : (var7 == 3 && p_149748_5_ == 3 ? 15 : (var7 == 2 && p_149748_5_ == 4 ? 15 : (var7 == 1 && p_149748_5_ == 5 ? 15 : 0)))))));
}
}
/**
* Can this block provide power. Only wire currently seems to have this change based on its state.
*/
public boolean canProvidePower()
{
return true;
}
}
| gpl-2.0 |
BarloworldTransport/MAXSelenium | MAX_CreateNewUser.php | 2993 | <?php
// Set error reporting level for this script
error_reporting(E_ALL);
// : Includes
// : End
/**
* MAX_CreateNewUser.php
*
* @package MAX_CreateNewUser
* @author Clinton Wright <[email protected]>
* @copyright 2013 onwards Barloworld Transport (Pty) Ltd
* @license GNU GPL
* @link http://www.gnu.org/licenses/gpl.html
* * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class MAX_CreateNewUser
{
// : Constants
const DS = DIRECTORY_SEPARATOR;
// : End - Constants
// : Variables
public $_sessionObj;
public $_phpunitObj;
public $_waitObj;
protected $_tmp;
// : End
/**
* MAX_CreateNewUser::maxCreateNewUser
* Follows the process involved on MAX to create a new user
*/
public static function maxCreateNewUser()
{
try {
// Wait for page to load and for elements to be present on page
$e = $w->until(function ($session)
{
return $session->element('xpath', '//a[text()="' . self::$_tmp . '"]');
});
} catch (Exception $e) {
// Store error message into static array
self::$_errors[] = $e->getMessage();
return FALSE;
}
return TRUE;
// : End
}
// : End - Public Functions
// : Magic
/**
* MAX_CreateNewUser::__construct()
* Class constructor used to verify data given for the MAX create user process is correct and complete before running the process
* @param object: $_session
* @param object: $_w
* @param object: $_phpunit_fw_obj
*/
public function __construct(&$_session, &$_w, &$_phpunit_fw_obj, $_first_name, $_last_name, $_email, $_job_title, $_company, $_groups) {
try {
// : Save referenced objects into object
if ($_session && $_w && $_phpunit_fw_obj) {
var_dump($_session);
$this->_sessionObj = $_session;
$this->_waitObj = $_w;
$this->_phpunitObj = $_phpunit_fw_obj;
}
// : End
} catch (Exception $e) {
return FALSE;
}
// If reaches here then code passed
return TRUE;
}
// : End
// : Private Functions
// : End - Private Functions
}
| gpl-2.0 |
Chubaskin/buscarautos | components/com_expautospro/controllers/expimages.php | 4348 | <?php
/****************************************************************************************\
** @name EXP Autos 2.0 **
** @package Joomla 1.6 **
** @author EXP TEAM::Alexey Kurguz (Grusha) **
** @copyright Copyright (C) 2005 - 2011 EXP TEAM::Alexey Kurguz (Grusha) **
** @link http://www.feellove.eu **
** @license Commercial License **
\****************************************************************************************/
// No direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.controllerform');
require_once JPATH_COMPONENT . '/helpers/expfields.php';
class ExpAutosProControllerExpimages extends JControllerForm {
public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true)) {
return parent::getModel($name, $prefix, array('ignore_request' => false));
}
public function edit() {
$app = JFactory::getApplication();
$user = JFactory::getUser();
$addid = (int) JRequest::getInt('id', null, '', 'array');
$expisnew = (int) JRequest::getInt('expisnew', 0);
// Set the user id for the user to edit in the session.
$app->setUserState('com_expautospro.edit.expimages.id', $addid);
if (!(int) $user->get('id')) {
//JError::raiseError(403, $model->getError());
//return false;
}
$model = $this->getModel('Expimages', 'ExpAutosProModel');
if(!$model->expaddvalid($addid,$user->id)){
JError::raiseError(403, $model->getError());
return false;
}
if ($user->get('id')) {
$model->checkin($expuserId);
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=expimages&expisnew='.$expisnew.'&id='.(int)$addid, false));
}
public function save() {
JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$addid = (int) JRequest::getInt('id', null, '', 'array');
$expcatid = (int) JRequest::getInt('catid', null, '', 'array');
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('Expimages', 'ExpAutosProModel');
$user = JFactory::getUser();
$userId = (int) $user->get('id');
if(!$model->expaddvalid($expcatid,$user->id)){
JError::raiseError(403, $model->getError());
return false;
}
$data = JRequest::getVar('jform', array(), 'post', 'array');
$form = $model->getForm();
if (!$form) {
JError::raiseError(500, $model->getError());
return false;
}
$data = $model->validate($form, $data);
if ($data === false) {
$errors = $model->getErrors();
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if (JError::isError($errors[$i])) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
$app->setUserState('com_expautospro.edit.expimages.data', $data);
$userId = (int) $app->getUserState('com_expautospro.edit.expimages.id');
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=expimages&id=' . (int)$addid, false));
return false;
}
$return = $model->save($data);
$userId = (int) $app->getUserState('com_expautospro.edit.expimages.id');
if ($userId) {
$model->checkin($userId);
}
$app->setUserState('com_expautospro.edit.expimages.id', null);
$this->setMessage(JText::_('COM_EXPAUTOSPRO_CP_EXPADD_INFO_SAVE_SUCCESS_TEXT'));
$this->setRedirect(JRoute::_(($redirect = $app->getUserState('com_expautospro.edit.expimages.redirect')) ? $redirect : 'index.php?option=com_expautospro&view=explist&userid='.(int)$user->id.'&id=' . (int) $return, false));
$app->setUserState('com_expautospro.edit.expimages.data', null);
}
} | gpl-2.0 |
RicardoLans/KraakJeRot | ResourceFramework/obj/Debug/UserControls/NPCs/Arms/RightArm1.g.i.cs | 1985 | #pragma checksum "D:\GitHub\KraakJeRot\ResourceFramework\UserControls\NPCs\Arms\RightArm1.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "B1259B4B06362553C3A1C7C0A01E6CDD"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace ResourceFramework.UserControls.NPCs.Arms {
public partial class RightArm1 : System.Windows.Controls.UserControl {
internal System.Windows.Shapes.Path RightArm;
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/ResourceFramework;component/UserControls/NPCs/Arms/RightArm1.xaml", System.UriKind.Relative));
this.RightArm = ((System.Windows.Shapes.Path)(this.FindName("RightArm")));
}
}
}
| gpl-2.0 |
hmatuschek/intrinsic-noise-analyzer | app/models/variableruledelegate.cc | 2297 | #include "variableruledelegate.hh"
#include "../views/variableruleeditor.hh"
#include <QApplication>
#include <sstream>
using namespace iNA;
SpeciesRuleDelegate::SpeciesRuleDelegate(iNA::Ast::Model &model, QObject *parent)
: QItemDelegate(parent), _model(model)
{
// Pass...
}
QWidget *
SpeciesRuleDelegate::createEditor(
QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
VariableRuleEditor *editor = new VariableRuleEditor(parent);
Ast::Species *species = _model.getSpecies(index.row());
if (species->hasRule()) {
if (Ast::Node::isAssignmentRule(species->getRule())) {
editor->setRuleKind(VariableRuleData::ASSIGNMENT_RULE);
} else {
editor->setRuleKind(VariableRuleData::RATE_RULE);
}
// Serialize expression:
std::stringstream stream; stream << species->getRule()->getRule();
editor->setRuleExpression(stream.str().c_str());
} else {
editor->setRuleKind(VariableRuleData::NO_RULE);
}
return editor;
}
void
SpeciesRuleDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
VariableRuleEditor *rule_edit = static_cast<VariableRuleEditor *>(editor);
Ast::Species *species = _model.getSpecies(index.row());
if (species->hasRule()) {
if (Ast::Node::isAssignmentRule(species->getRule())) {
rule_edit->setRuleKind(VariableRuleData::ASSIGNMENT_RULE);
} else {
rule_edit->setRuleKind(VariableRuleData::RATE_RULE);
}
// Serialize expression:
std::stringstream stream; stream << species->getRule()->getRule();
rule_edit->setRuleExpression(stream.str().c_str());
} else {
rule_edit->setRuleKind(VariableRuleData::NO_RULE);
}
}
void
SpeciesRuleDelegate::setModelData(
QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
VariableRuleData *data = new VariableRuleData();
VariableRuleEditor *rule_edit = static_cast<VariableRuleEditor *>(editor);
data->setRuleKind(rule_edit->ruleKind());
data->setRuleExpression(rule_edit->ruleExpression());
model->setData(index, qVariantFromValue((void *)(data)), Qt::EditRole);
}
void
SpeciesRuleDelegate::updateEditorGeometry(
QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
| gpl-2.0 |
Ankama/harvey | src/com/ankamagames/dofus/harvey/numeric/longs/sets/interfaces/ICompositeContinuousLongSet.java | 642 | /**
*
*/
package com.ankamagames.dofus.harvey.numeric.longs.sets.interfaces;
import java.util.List;
import com.ankamagames.dofus.harvey.engine.common.sets.interfaces.ICompositeContinuousSet;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* @author sgros
*
*/
@NonNullByDefault
public interface ICompositeContinuousLongSet<ChildType extends IContinuousLongSet>
extends ICompositeContinuousSet<IContinuousLongBound, IContinuousLongSet, ISimpleContinuousLongSet, IElementaryContinuousLongSet, ICompositeContinuousLongSet<?>, ChildType>, IContinuousLongSet
{
public List<? extends IContinuousLongSet> splitInParts(int parts);
} | gpl-2.0 |
saltmktg/meetingtomorrow.com | wp-content/plugins/nelio-ab-testing/includes/admin/alternatives/post-alt-exp-edition-page-controller.php | 8328 | <?php
/**
* Copyright 2013 Nelio Software S.L.
* This script is distributed under the terms of the GNU General Public
* License.
*
* This script 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.
*
* This script 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/>.
*/
if ( !class_exists( 'NelioABPostAltExpEditionPageController' ) ) {
require_once( NELIOAB_MODELS_DIR . '/experiment.php' );
require_once( NELIOAB_MODELS_DIR . '/experiments-manager.php' );
require_once( NELIOAB_MODELS_DIR . '/alternatives/post-alternative-experiment.php' );
require_once( NELIOAB_MODELS_DIR . '/goals/alternative-experiment-goal.php' );
require_once( NELIOAB_ADMIN_DIR . '/views/alternatives/post-alt-exp-edition-page.php' );
require_once( NELIOAB_ADMIN_DIR . '/alternatives/alt-exp-super-controller.php' );
class NelioABPostAltExpEditionPageController extends NelioABAltExpSuperController {
public static function get_instance() {
return new NelioABPostAltExpEditionPageController();
}
public static function build() {
// Check settings
require_once( NELIOAB_ADMIN_DIR . '/error-controller.php' );
$error = NelioABErrorController::build_error_page_on_invalid_settings();
if ( $error ) return;
$aux = NelioABPostAltExpEditionPageController::get_instance();
$view = $aux->do_build();
$view->render();
}
public static function generate_html_content() {
$aux = NelioABPostAltExpEditionPageController::get_instance();
$view = $aux->do_build();
$view->render_content();
die();
}
protected function do_build() {
// Check settings
require_once( NELIOAB_ADMIN_DIR . '/error-controller.php' );
$error = NelioABErrorController::build_error_page_on_invalid_settings();
if ( $error ) return;
// Preparing labels for PAGE vs POST alternatives
// ----------------------------------------------
$alt_type = NelioABExperiment::PAGE_ALT_EXP;
$title = __( 'Edit Page Experiment', 'nelioab' );
if ( isset( $_GET['experiment-type'] ) &&
$_GET['experiment-type'] == NelioABExperiment::POST_ALT_EXP ) {
$alt_type = NelioABExperiment::POST_ALT_EXP;
$title = __( 'Edit Post Experiment', 'nelioab' );
}
// We recover the experiment (if any)
// ----------------------------------------------
global $nelioab_admin_controller;
$experiment = NULL;
$other_names = array();
if ( !empty( $nelioab_admin_controller->data ) ) {
$experiment = $nelioab_admin_controller->data;
$alt_type = $experiment->get_type();
}
else {
$experiment = new NelioABPostAlternativeExperiment( -time() );
$experiment->clear();
}
// ...and we also recover other experiment names (if any)
if ( isset( $_POST['other_names'] ) ) {
$other_names = json_decode( urldecode( $_POST['other_names'] ) );
}
else {
foreach( NelioABExperimentsManager::get_experiments() as $aux ) {
if ( $aux->get_id() != $experiment->get_id() )
array_push( $other_names, $aux->get_name() );
}
}
// Get id of Original page or post
// ----------------------------------------------
if ( isset( $_GET['post-id'] ) &&
$_GET['experiment-type'] == NelioABExperiment::POST_ALT_EXP )
$experiment->set_original( $_GET['post-id'] );
if ( isset( $_GET['page-id'] ) &&
$_GET['experiment-type'] == NelioABExperiment::PAGE_ALT_EXP )
$experiment->set_original( $_GET['page-id'] );
// Checking whether there are pages or posts available
// ---------------------------------------------------
// ...pages...
$list_of_pages = get_pages();
if ( $alt_type == NelioABExperiment::PAGE_ALT_EXP && count( $list_of_pages ) == 0 ) {
require_once( NELIOAB_ADMIN_DIR . '/views/errors/message-page.php' );
$view = new NelioABMessagePage(
sprintf(
__( 'There are no pages available.<br/><br/><a class="button button-primary" href="%s">Create one now.</a>', 'nelioab' ),
admin_url( '/post-new.php?post_type=page' )
)
);
return $view;
}
// ...posts...
$options_for_posts = array(
'posts_per_page' => 1 );
$list_of_posts = get_posts( $options_for_posts );
require_once( NELIOAB_UTILS_DIR . '/data-manager.php' );
NelioABArrays::sort_posts( $list_of_posts );
if ( $alt_type == NelioABExperiment::POST_ALT_EXP && count( $list_of_posts ) == 0 ) {
require_once( NELIOAB_ADMIN_DIR . '/views/errors/message-page.php' );
$view = new NelioABMessagePage(
sprintf(
__( 'There are no posts available.<br/><br/><a class="button button-primary" href="%s">Create one now</a>', 'nelioab' ),
admin_url( '/post-new.php' )
)
);
return $view;
}
// If everything is OK, we keep going!
// ---------------------------------------------------
// Creating the view
$view = $this->create_view( $alt_type );
foreach ( $other_names as $name )
$view->add_another_experiment_name( $name );
// Experiment information
$view->set_basic_info(
$experiment->get_id(),
$experiment->get_key_id(),
$experiment->get_name(),
$experiment->get_description(),
$experiment->get_finalization_mode(),
$experiment->get_finalization_value()
);
// Experiment specific variables and alternatives
$view->set_original_id( $experiment->get_originals_id() );
$view->set_alternatives( $experiment->get_json4js_alternatives() );
// Goals
$goals = $experiment->get_goals();
foreach ( $goals as $goal )
$view->add_goal( $goal->json4js() );
return $view;
}
public function create_view( $alt_type ) {
if ( $alt_type == NelioABExperiment::PAGE_ALT_EXP )
$title = __( 'Edit Page Experiment', 'nelioab' );
else
$title = __( 'Edit Post Experiment', 'nelioab' );
return new NelioABPostAltExpEditionPage( $title, $alt_type );
}
public function validate() {
$ok_parent = parent::validate();
// Check whatever is needed
$ok = true;
return $ok_parent && $ok;
}
public function edit_alternative_content() {
// 1. Save any local changes
global $nelioab_admin_controller;
$experiment = $nelioab_admin_controller->data;
// Before saving the experiment, we have to get the alternative we
// want to edit (after saving it, its IDs and/or its values may have
// change).
$alt_id = $_POST['content_to_edit'];
$alt_to_edit = false;
foreach ( $experiment->get_alternatives() as $alt ) {
if ( $alt->get_id() == $alt_id )
$alt_to_edit = $alt;
}
try {
$experiment->save();
}
catch ( Exception $e ) {
require_once( NELIOAB_ADMIN_DIR . '/error-controller.php' );
NelioABErrorController::build( $e );
}
// 2. Redirect to the edit page
update_post_meta( $alt_to_edit->get_value(), '_nelioab_original_id', $experiment->get_originals_id() );
echo '[NELIOAB_LINK]' . admin_url( 'post.php?action=edit&post=' . $alt_to_edit->get_value() ) . '[/NELIOAB_LINK]';
die();
}
public function build_experiment_from_post_data() {
$exp = new NelioABPostAlternativeExperiment( $_POST['exp_id'] );
$exp->set_original( $_POST['exp_original'] );
$exp = $this->compose_basic_alt_exp_using_post_data( $exp );
foreach ( $exp->get_alternatives() as $alt ) {
$alt->set_value( $alt->get_value() );
}
global $nelioab_admin_controller;
$nelioab_admin_controller->data = $exp;
}
public function manage_actions() {
if ( !isset( $_POST['action'] ) )
return;
parent::manage_actions();
if ( $_POST['action'] == 'edit_alt_content' )
if ( $this->validate() )
$this->edit_alternative_content();
}
}//NelioABPostAltExpEditionPageController
}
if ( isset( $_POST['nelioab_edit_ab_post_exp_form'] ) ) {
$controller = NelioABPostAltExpEditionPageController::get_instance();
$controller->manage_actions();
if ( !$controller->validate() )
$controller->print_ajax_errors();
}
| gpl-2.0 |
ctomiao2/ScrewTurnWiki | FSProviders/SqlCECommandBuilder.cs | 4013 |
using System;
using System.Collections.Generic;
using System.Text;
using ScrewTurn.Wiki.Plugins.SqlCommon;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
namespace ScrewTurn.Wiki.Plugins.FSProviders {
/// <summary>
/// Implements a command builder for SQL CE.
/// </summary>
public class SqlCECommandBuilder : ICommandBuilder {
private static SqlCeConnection connection = null;
/// <summary>
/// Gets the table and column name prefix.
/// </summary>
public string ObjectNamePrefix {
get { return "["; }
}
/// <summary>
/// Gets the table and column name suffix.
/// </summary>
public string ObjectNameSuffix {
get { return "]"; }
}
/// <summary>
/// Gets the parameter name prefix.
/// </summary>
public string ParameterNamePrefix {
get { return "@"; }
}
/// <summary>
/// Gets the parameter name suffix.
/// </summary>
public string ParameterNameSuffix {
get { return ""; }
}
/// <summary>
/// Gets the parameter name placeholder.
/// </summary>
public string ParameterPlaceholder {
get { throw new NotImplementedException(); }
}
/// <summary>
/// Gets a value indicating whether to use named parameters. If <c>false</c>,
/// parameter placeholders will be equal to <see cref="ParameterPlaceholder"/>.
/// </summary>
public bool UseNamedParameters {
get { return true; }
}
/// <summary>
/// Gets the string to use in order to separate queries in a batch.
/// </summary>
public string BatchQuerySeparator {
get { return "; "; }
}
/// <summary>
/// Gets a new database connection, open.
/// </summary>
/// <param name="connString">The connection string.</param>
/// <returns>The connection.</returns>
public DbConnection GetConnection(string connString) {
if(connection == null || connection.ConnectionString != connString) {
connection = new SqlCeConnection(connString);
}
if(connection.State != System.Data.ConnectionState.Open) {
connection.Open();
}
return connection;
}
/// <summary>
/// Gets a properly built database command, with the underlying connection already open.
/// </summary>
/// <param name="connString">The connection string.</param>
/// <param name="preparedQuery">The prepared query.</param>
/// <param name="parameters">The parameters, if any.</param>
/// <returns>The command.</returns>
public DbCommand GetCommand(string connString, string preparedQuery, List<Parameter> parameters) {
return GetCommand(GetConnection(connString), preparedQuery, parameters);
}
/// <summary>
/// Gets a properly built database command, re-using an open connection.
/// </summary>
/// <param name="connection">The open connection to use.</param>
/// <param name="preparedQuery">The prepared query.</param>
/// <param name="parameters">The parameters, if any.</param>
/// <returns>The command.</returns>
public DbCommand GetCommand(DbConnection connection, string preparedQuery, List<Parameter> parameters) {
DbCommand cmd = connection.CreateCommand();
cmd.CommandText = preparedQuery;
foreach(Parameter param in parameters) {
cmd.Parameters.Add(new SqlCeParameter("@" + param.Name, param.Value));
}
return cmd;
}
/// <summary>
/// Gets a properly built database command, re-using an open connection and a begun transaction.
/// </summary>
/// <param name="transaction">The transaction.</param>
/// <param name="preparedQuery">The prepared query.</param>
/// <param name="parameters">The parameters, if any.</param>
/// <returns>The command.</returns>
public DbCommand GetCommand(DbTransaction transaction, string preparedQuery, List<Parameter> parameters) {
DbCommand cmd = transaction.Connection.CreateCommand();
cmd.Transaction = transaction;
cmd.CommandText = preparedQuery;
foreach(Parameter param in parameters) {
cmd.Parameters.Add(new SqlCeParameter("@" + param.Name, param.Value));
}
return cmd;
}
}
}
| gpl-2.0 |
osreboot/Telekinetic-Reality | src/com/osreboot/tr/main/Help.java | 4231 | package com.osreboot.tr.main;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class Help {
public static ItemStack intro, scroll, levitation, node, node2, skp, basic, back, helpi, up, down, more, title;
public static Inventory help;
private static int length = 34;
public static void init(){
help = Bukkit.createInventory(null, 54, "Getting to know Telekinesis");
Main.holidayify(help);
intro = new ItemStack(Material.PAPER);
scroll = new ItemStack(Material.PAPER);
levitation = new ItemStack(Material.DIRT);
node = new ItemStack(Material.PAPER);
node2 = new ItemStack(Material.PAPER);
skp = new ItemStack(Material.PAPER);
basic = new ItemStack(Material.PAPER);
back = new ItemStack(Material.BOOK);
helpi = new ItemStack(Material.BOOK);
up = new ItemStack(Material.EMERALD);
down = new ItemStack(Material.EMERALD);
more = new ItemStack(Material.PAPER);
title = new ItemStack(Material.PAPER);
String[] d = Util.chop(ChatColor.YELLOW + "Welcome! This is your skill tree, get back here at any time with the command '/syntax'.", length, "");
addData(intro, d);
help.setItem(13, intro);
String[] d2 = Util.chop(ChatColor.YELLOW + "Use these buttons to scroll up and down your skill tree.", length, "");
addData(scroll, d2);
help.setItem(7, scroll);
String[] d3 = {ChatColor.GREEN + "Levitation [#/30]",
ChatColor.BLUE + "Want to make things fly? Basic",
ChatColor.BLUE + "levitation is nothing more than a",
ChatColor.BLUE + "little determination and a lot of",
ChatColor.BLUE + "free time." + ChatColor.LIGHT_PURPLE + " Vertical block",
ChatColor.LIGHT_PURPLE + "levitation.",
ChatColor.DARK_GRAY + "Hold right mouse and shift",
ChatColor.DARK_GRAY + "simultaneously while looking at a",
ChatColor.DARK_GRAY + "block. Hold shift and left click",
ChatColor.DARK_GRAY + "to drop levitated blocks."};
addData(levitation, d3);
help.setItem(49, levitation);
String[] d4 = Util.chop(ChatColor.YELLOW + "This is a node, left click when you have skill points to level it up and increase the efficacy of the ability!", length, "");
addData(node, d4);
help.setItem(48, node);
String[] d5 = Util.chop(ChatColor.YELLOW + "Getting your first skill point will be a hassle. Hold shift and right mouse simultaneously while looking at a block (not a tile entity!) that you want to levitate.", length, "");
addData(basic, d5);
help.setItem(22, basic);
String[] d6 = {ChatColor.GREEN + "Node name [your level/maximum level]",
ChatColor.BLUE + "Node description",
ChatColor.LIGHT_PURPLE + "Node functions",
ChatColor.DARK_GRAY + "Node controls"};
addData(node2, d6);
help.setItem(50, node2);
String[] d7 = Util.chop(ChatColor.YELLOW + "These are your skill points, they can be spent on upgrading nodes. You can earn more by practicing different telekinetic abilities.", length, "");
addData(skp, d7);
help.setItem(3, skp);
String[] d8 = {ChatColor.YELLOW + "Back"};
addData(back, d8);
help.setItem(45, back);
String[] d9 = {ChatColor.YELLOW + "Need help getting started?"};
addData(helpi, d9);
String[] d10 = {ChatColor.YELLOW + "Up"};
addData(up, d10);
help.setItem(8, up);
String[] d11 = {ChatColor.YELLOW + "Down"};
addData(down, d11);
help.setItem(53, down);
String[] d12 = Util.chop(ChatColor.YELLOW + "You can unlock more nodes by leveling up earlier ones in the tree.", length, "");
addData(more, d12);
help.setItem(40, more);
String[] d13 = Util.chop(ChatColor.YELLOW + "Your title and total skill level is displayed here.", length, "");
addData(title, d13);
help.setItem(0, title);
}
private static void addData(ItemStack i, String[] lore){
ItemMeta m = i.getItemMeta();
m.setDisplayName(lore[0]);
m.setLore(toArrayMinus(lore));
i.setItemMeta(m);
}
private static ArrayList<String> toArrayMinus(String[] s){
ArrayList<String> sa = new ArrayList<String>();
for(int i = 1; i < s.length; i++) sa.add(s[i]);
return sa;
}
}
| gpl-2.0 |
paperblag/karizia | wp-content/themes/twentythirteen/content.php | 2262 | <?php
/**
* The default template for displaying content
*
* Used for both single and index/archive/search.
*
* @package WordPress
* @subpackage Twenty_Thirteen
* @since Twenty Thirteen 1.0
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php if ( has_post_thumbnail() && ! post_password_required() && ! is_attachment() ) : ?>
<div class="entry-thumbnail">
<a href="<?php the_permalink(); ?>" rel="bookmark">
<?php the_post_thumbnail(); ?>
</a>
</div>
<?php endif; ?>
<?php if ( is_single() ) : ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php else : ?>
<h1 class="entry-title">
<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a>
</h1>
<?php endif; // is_single() ?>
<div class="entry-meta">
<?php twentythirteen_entry_meta(); ?>
<?php edit_post_link( __( 'Edit', 'twentythirteen' ), '<span class="edit-link">', '</span>' ); ?>
</div><!-- .entry-meta -->
</header><!-- .entry-header -->
<?php if ( is_search() ) : // Only display Excerpts for Search ?>
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
<?php else : ?>
<div class="entry-content">
<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentythirteen' ) ); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'twentythirteen' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>' ) ); ?>
</div><!-- .entry-content -->
<?php endif; ?>
<footer class="entry-meta">
<?php if ( comments_open() && ! is_single() ) : ?>
<div class="comments-link">
<?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a comment', 'twentythirteen' ) . '</span>', __( 'One comment so far', 'twentythirteen' ), __( 'View all % comments', 'twentythirteen' ) ); ?>
</div><!-- .comments-link -->
<?php endif; // comments_open() ?>
<?php if ( is_single() && get_the_author_meta( 'description' ) && is_multi_author() ) : ?>
<?php get_template_part( 'author-bio' ); ?>
<?php endif; ?>
</footer><!-- .entry-meta -->
</article><!-- #post -->
| gpl-2.0 |
cwrc/CWRC-Writer | src/js/modules/selection.js | 2019 | define(['jquery','jquery.snippet'], function($, snippet) {
/**
* @class Selection
* @param {Object} config
* @param {Writer} config.writer
* @param {String} config.parentId
*/
return function(config) {
var w = config.writer;
var lastUpdate = new Date().getTime();
$('#'+config.parentId).append('<div id="selection" style="margin-left: 10px;"></div>');
$(document.body).append('<div id="selectionContents" style="display: none;"></div>');
w.event('nodeChanged').subscribe(function() {
updateSelection(w.editor);
});
w.event('tagSelected').subscribe(function(tagId) {
updateSelection(w.editor);
});
/**
* @lends Selection.prototype
*/
var selection = {};
function updateSelection(ed) {
var timestamp = new Date().getTime();
var timeDiff = timestamp - lastUpdate; // track to avoid double update on nodeChanged/tagSelected combo
if ($('#selection').is(':visible') && timeDiff > 250) {
lastUpdate = new Date().getTime();
var range = ed.selection.getRng(true);
var contents = range.cloneContents();
$('#selectionContents').html(contents);
var xmlString = w.converter.buildXMLString($('#selectionContents'));
var escapedContents = w.utilities.escapeHTMLString(xmlString); //$('#selectionContents')[0].innerHTML
if (escapedContents.length < 100000 && escapedContents != '\uFEFF') {
$('#selection').html('<pre>'+escapedContents+'</pre>');
$('#selection > pre').snippet('html', {
style: 'typical',
transparent: true,
showNum: false,
menu: false
});
} else {
$('#selection').html('<pre>The selection is too large to display.</pre>');
}
}
}
// add to writer
w.selection = selection;
return selection;
};
}); | gpl-2.0 |
streamsupport/streamsupport | src/tests/java/org/openjdk/tests/tck/ThreadLocalRandom8Test.java | 8829 | /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package org.openjdk.tests.tck;
import java8.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java8.util.concurrent.atomic.LongAdder;
import junit.framework.Test;
import junit.framework.TestSuite;
@org.testng.annotations.Test
public class ThreadLocalRandom8Test extends JSR166TestCase {
// CVS rev. 1.12
// public static void main(String[] args) {
// main(suite(), args);
// }
public static Test suite() {
return new TestSuite(ThreadLocalRandom8Test.class);
}
// max sampled int bound
static final int MAX_INT_BOUND = (1 << 26);
// max sampled long bound
static final long MAX_LONG_BOUND = (1L << 42);
// Number of replications for other checks
static final int REPS =
Integer.getInteger("ThreadLocalRandom8Test.reps", 4);
/**
* Invoking sized ints, long, doubles, with negative sizes throws
* IllegalArgumentException
*/
public void testBadStreamSize() {
ThreadLocalRandom r = ThreadLocalRandom.current();
Runnable[] throwingActions = {
() -> r.ints(-1L),
() -> r.ints(-1L, 2, 3),
() -> r.longs(-1L),
() -> r.longs(-1L, -1L, 1L),
() -> r.doubles(-1L),
() -> r.doubles(-1L, .5, .6),
};
assertThrows(IllegalArgumentException.class, throwingActions);
}
/**
* Invoking bounded ints, long, doubles, with illegal bounds throws
* IllegalArgumentException
*/
public void testBadStreamBounds() {
ThreadLocalRandom r = ThreadLocalRandom.current();
Runnable[] throwingActions = {
() -> r.ints(2, 1),
() -> r.ints(10, 42, 42),
() -> r.longs(-1L, -1L),
() -> r.longs(10, 1L, -2L),
() -> r.doubles(0.0, 0.0),
() -> r.doubles(10, .5, .4),
};
assertThrows(IllegalArgumentException.class, throwingActions);
}
/**
* A parallel sized stream of ints generates the given number of values
*/
public void testIntsCount() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 0;
for (int reps = 0; reps < REPS; ++reps) {
counter.reset();
r.ints(size).parallel().forEach(x -> counter.increment());
assertEquals(size, counter.sum());
size += 524959;
}
}
/**
* A parallel sized stream of longs generates the given number of values
*/
public void testLongsCount() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 0;
for (int reps = 0; reps < REPS; ++reps) {
counter.reset();
r.longs(size).parallel().forEach(x -> counter.increment());
assertEquals(size, counter.sum());
size += 524959;
}
}
/**
* A parallel sized stream of doubles generates the given number of values
*/
public void testDoublesCount() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 0;
for (int reps = 0; reps < REPS; ++reps) {
counter.reset();
r.doubles(size).parallel().forEach(x -> counter.increment());
assertEquals(size, counter.sum());
size += 524959;
}
}
/**
* Each of a parallel sized stream of bounded ints is within bounds
*/
public void testBoundedInts() {
AtomicInteger fails = new AtomicInteger(0);
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 12345L;
for (int least = -15485867; least < MAX_INT_BOUND; least += 524959) {
for (int bound = least + 2; bound > least && bound < MAX_INT_BOUND; bound += 67867967) {
final int lo = least, hi = bound;
r.ints(size, lo, hi).parallel().forEach(
x -> {
if (x < lo || x >= hi)
fails.getAndIncrement(); });
}
}
assertEquals(0, fails.get());
}
/**
* Each of a parallel sized stream of bounded longs is within bounds
*/
public void testBoundedLongs() {
AtomicInteger fails = new AtomicInteger(0);
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 123L;
for (long least = -86028121; least < MAX_LONG_BOUND; least += 1982451653L) {
for (long bound = least + 2; bound > least && bound < MAX_LONG_BOUND; bound += Math.abs(bound * 7919)) {
final long lo = least, hi = bound;
r.longs(size, lo, hi).parallel().forEach(
x -> {
if (x < lo || x >= hi)
fails.getAndIncrement(); });
}
}
assertEquals(0, fails.get());
}
/**
* Each of a parallel sized stream of bounded doubles is within bounds
*/
public void testBoundedDoubles() {
AtomicInteger fails = new AtomicInteger(0);
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 456;
for (double least = 0.00011; least < 1.0e20; least *= 9) {
for (double bound = least * 1.0011; bound < 1.0e20; bound *= 17) {
final double lo = least, hi = bound;
r.doubles(size, lo, hi).parallel().forEach(
x -> {
if (x < lo || x >= hi)
fails.getAndIncrement(); });
}
}
assertEquals(0, fails.get());
}
/**
* A parallel unsized stream of ints generates at least 100 values
*/
public void testUnsizedIntsCount() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 100;
r.ints().limit(size).parallel().forEach(x -> counter.increment());
assertEquals(size, counter.sum());
}
/**
* A parallel unsized stream of longs generates at least 100 values
*/
public void testUnsizedLongsCount() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 100;
r.longs().limit(size).parallel().forEach(x -> counter.increment());
assertEquals(size, counter.sum());
}
/**
* A parallel unsized stream of doubles generates at least 100 values
*/
public void testUnsizedDoublesCount() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 100;
r.doubles().limit(size).parallel().forEach(x -> counter.increment());
assertEquals(size, counter.sum());
}
/**
* A sequential unsized stream of ints generates at least 100 values
*/
public void testUnsizedIntsCountSeq() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 100;
r.ints().limit(size).forEach(x -> counter.increment());
assertEquals(size, counter.sum());
}
/**
* A sequential unsized stream of longs generates at least 100 values
*/
public void testUnsizedLongsCountSeq() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 100;
r.longs().limit(size).forEach(x -> counter.increment());
assertEquals(size, counter.sum());
}
/**
* A sequential unsized stream of doubles generates at least 100 values
*/
public void testUnsizedDoublesCountSeq() {
LongAdder counter = new LongAdder();
ThreadLocalRandom r = ThreadLocalRandom.current();
long size = 100;
r.doubles().limit(size).forEach(x -> counter.increment());
assertEquals(size, counter.sum());
}
/**
* A deserialized/reserialized ThreadLocalRandom is always
* identical to ThreadLocalRandom.current()
*/
public void testSerialization() {
assertSame(
ThreadLocalRandom.current(),
serialClone(ThreadLocalRandom.current()));
// In the current implementation, there is exactly one shared instance
if (testImplementationDetails)
assertSame(
ThreadLocalRandom.current(),
java8.util.concurrent.CompletableFuture.supplyAsync(
() -> serialClone(ThreadLocalRandom.current())).join());
}
}
| gpl-2.0 |
stweil/TYPO3.CMS | typo3/sysext/workspaces/Configuration/RequestMiddlewares.php | 1374 | <?php
/**
* Definitions for middlewares provided by EXT:workspaces
*/
return [
'frontend' => [
'typo3/cms-workspaces/preview' => [
'target' => \TYPO3\CMS\Workspaces\Middleware\WorkspacePreview::class,
'after' => [
// A preview user will override an existing logged-in backend user
'typo3/cms-frontend/backend-user-authentication',
],
'before' => [
// Page Router should have not been called yet, in order to set up the Context's Workspace Aspect
'typo3/cms-frontend/page-resolver',
],
],
'typo3/cms-workspaces/preview-permissions' => [
'target' => \TYPO3\CMS\Workspaces\Middleware\WorkspacePreviewPermissions::class,
'after' => [
// The cookie/GET parameter information should have been evaluated
'typo3/cms-workspaces/preview',
// PageArguments are needed to find out the current Page ID
'typo3/cms-frontend/page-resolver',
'typo3/cms-frontend/page-argument-validator',
],
'before' => [
// TSFE should not yet have been called - determineId() is what relies on the information of this middleware
'typo3/cms-frontend/tsfe',
],
],
],
];
| gpl-2.0 |
WillDignazio/hotspot | src/share/vm/runtime/globals.hpp | 302505 | /*
* Copyright (c) 1997, 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.
*
* 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.
*
*/
#ifndef SHARE_VM_RUNTIME_GLOBALS_HPP
#define SHARE_VM_RUNTIME_GLOBALS_HPP
#include "utilities/debug.hpp"
// use this for flags that are true per default in the tiered build
// but false in non-tiered builds, and vice versa
#ifdef TIERED
#define trueInTiered true
#define falseInTiered false
#else
#define trueInTiered false
#define falseInTiered true
#endif
#ifdef TARGET_ARCH_x86
# include "globals_x86.hpp"
#endif
#ifdef TARGET_ARCH_sparc
# include "globals_sparc.hpp"
#endif
#ifdef TARGET_ARCH_zero
# include "globals_zero.hpp"
#endif
#ifdef TARGET_ARCH_arm
# include "globals_arm.hpp"
#endif
#ifdef TARGET_ARCH_ppc
# include "globals_ppc.hpp"
#endif
#ifdef TARGET_ARCH_aarch64
# include "globals_aarch64.hpp"
#endif
#ifdef TARGET_OS_FAMILY_linux
# include "globals_linux.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "globals_solaris.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "globals_windows.hpp"
#endif
#ifdef TARGET_OS_FAMILY_aix
# include "globals_aix.hpp"
#endif
#ifdef TARGET_OS_FAMILY_bsd
# include "globals_bsd.hpp"
#endif
#ifdef TARGET_OS_ARCH_linux_x86
# include "globals_linux_x86.hpp"
#endif
#ifdef TARGET_OS_ARCH_linux_sparc
# include "globals_linux_sparc.hpp"
#endif
#ifdef TARGET_OS_ARCH_linux_zero
# include "globals_linux_zero.hpp"
#endif
#ifdef TARGET_OS_ARCH_solaris_x86
# include "globals_solaris_x86.hpp"
#endif
#ifdef TARGET_OS_ARCH_solaris_sparc
# include "globals_solaris_sparc.hpp"
#endif
#ifdef TARGET_OS_ARCH_windows_x86
# include "globals_windows_x86.hpp"
#endif
#ifdef TARGET_OS_ARCH_linux_arm
# include "globals_linux_arm.hpp"
#endif
#ifdef TARGET_OS_ARCH_linux_ppc
# include "globals_linux_ppc.hpp"
#endif
#ifdef TARGET_OS_ARCH_linux_aarch64
# include "globals_linux_aarch64.hpp"
#endif
#ifdef TARGET_OS_ARCH_aix_ppc
# include "globals_aix_ppc.hpp"
#endif
#ifdef TARGET_OS_ARCH_bsd_x86
# include "globals_bsd_x86.hpp"
#endif
#ifdef TARGET_OS_ARCH_bsd_zero
# include "globals_bsd_zero.hpp"
#endif
#ifdef COMPILER1
#ifdef TARGET_ARCH_x86
# include "c1_globals_x86.hpp"
#endif
#ifdef TARGET_ARCH_sparc
# include "c1_globals_sparc.hpp"
#endif
#ifdef TARGET_ARCH_arm
# include "c1_globals_arm.hpp"
#endif
#ifdef TARGET_ARCH_aarch64
# include "c1_globals_aarch64.hpp"
#endif
#ifdef TARGET_OS_FAMILY_linux
# include "c1_globals_linux.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "c1_globals_solaris.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "c1_globals_windows.hpp"
#endif
#ifdef TARGET_OS_FAMILY_aix
# include "c1_globals_aix.hpp"
#endif
#ifdef TARGET_OS_FAMILY_bsd
# include "c1_globals_bsd.hpp"
#endif
#ifdef TARGET_ARCH_ppc
# include "c1_globals_ppc.hpp"
#endif
#endif
#ifdef COMPILER2
#ifdef TARGET_ARCH_x86
# include "c2_globals_x86.hpp"
#endif
#ifdef TARGET_ARCH_sparc
# include "c2_globals_sparc.hpp"
#endif
#ifdef TARGET_ARCH_arm
# include "c2_globals_arm.hpp"
#endif
#ifdef TARGET_ARCH_ppc
# include "c2_globals_ppc.hpp"
#endif
#ifdef TARGET_ARCH_aarch64
# include "c2_globals_aarch64.hpp"
#endif
#ifdef TARGET_OS_FAMILY_linux
# include "c2_globals_linux.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "c2_globals_solaris.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "c2_globals_windows.hpp"
#endif
#ifdef TARGET_OS_FAMILY_aix
# include "c2_globals_aix.hpp"
#endif
#ifdef TARGET_OS_FAMILY_bsd
# include "c2_globals_bsd.hpp"
#endif
#endif
#ifdef SHARK
#ifdef TARGET_ARCH_zero
# include "shark_globals_zero.hpp"
#endif
#endif
#if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)
define_pd_global(bool, BackgroundCompilation, false);
define_pd_global(bool, UseTLAB, false);
define_pd_global(bool, CICompileOSR, false);
define_pd_global(bool, UseTypeProfile, false);
define_pd_global(bool, UseOnStackReplacement, false);
define_pd_global(bool, InlineIntrinsics, false);
define_pd_global(bool, PreferInterpreterNativeStubs, true);
define_pd_global(bool, ProfileInterpreter, false);
define_pd_global(bool, ProfileTraps, false);
define_pd_global(bool, TieredCompilation, false);
define_pd_global(intx, CompileThreshold, 0);
define_pd_global(intx, OnStackReplacePercentage, 0);
define_pd_global(bool, ResizeTLAB, false);
define_pd_global(intx, FreqInlineSize, 0);
define_pd_global(size_t, NewSizeThreadIncrease, 4*K);
define_pd_global(intx, InlineClassNatives, true);
define_pd_global(intx, InlineUnsafeOps, true);
define_pd_global(intx, InitialCodeCacheSize, 160*K);
define_pd_global(intx, ReservedCodeCacheSize, 32*M);
define_pd_global(intx, NonProfiledCodeHeapSize, 0);
define_pd_global(intx, ProfiledCodeHeapSize, 0);
define_pd_global(intx, NonNMethodCodeHeapSize, 32*M);
define_pd_global(intx, CodeCacheExpansionSize, 32*K);
define_pd_global(intx, CodeCacheMinBlockLength, 1);
define_pd_global(intx, CodeCacheMinimumUseSpace, 200*K);
define_pd_global(size_t, MetaspaceSize, ScaleForWordSize(4*M));
define_pd_global(bool, NeverActAsServerClassMachine, true);
define_pd_global(uint64_t,MaxRAM, 1ULL*G);
#define CI_COMPILER_COUNT 0
#else
#ifdef COMPILER2
#define CI_COMPILER_COUNT 2
#else
#define CI_COMPILER_COUNT 1
#endif // COMPILER2
#endif // no compilers
// string type aliases used only in this file
typedef const char* ccstr;
typedef const char* ccstrlist; // represents string arguments which accumulate
struct Flag {
enum Flags {
// value origin
DEFAULT = 0,
COMMAND_LINE = 1,
ENVIRON_VAR = 2,
CONFIG_FILE = 3,
MANAGEMENT = 4,
ERGONOMIC = 5,
ATTACH_ON_DEMAND = 6,
INTERNAL = 7,
LAST_VALUE_ORIGIN = INTERNAL,
VALUE_ORIGIN_BITS = 4,
VALUE_ORIGIN_MASK = right_n_bits(VALUE_ORIGIN_BITS),
// flag kind
KIND_PRODUCT = 1 << 4,
KIND_MANAGEABLE = 1 << 5,
KIND_DIAGNOSTIC = 1 << 6,
KIND_EXPERIMENTAL = 1 << 7,
KIND_NOT_PRODUCT = 1 << 8,
KIND_DEVELOP = 1 << 9,
KIND_PLATFORM_DEPENDENT = 1 << 10,
KIND_READ_WRITE = 1 << 11,
KIND_C1 = 1 << 12,
KIND_C2 = 1 << 13,
KIND_ARCH = 1 << 14,
KIND_SHARK = 1 << 15,
KIND_LP64_PRODUCT = 1 << 16,
KIND_COMMERCIAL = 1 << 17,
KIND_MASK = ~VALUE_ORIGIN_MASK
};
enum Error {
// no error
SUCCESS = 0,
// flag name is missing
MISSING_NAME,
// flag value is missing
MISSING_VALUE,
// error parsing the textual form of the value
WRONG_FORMAT,
// flag is not writeable
NON_WRITABLE,
// flag value is outside of its bounds
OUT_OF_BOUNDS,
// flag value violates its constraint
VIOLATES_CONSTRAINT,
// there is no flag with the given name
INVALID_FLAG,
// other, unspecified error related to setting the flag
ERR_OTHER
};
const char* _type;
const char* _name;
void* _addr;
NOT_PRODUCT(const char* _doc;)
Flags _flags;
// points to all Flags static array
static Flag* flags;
// number of flags
static size_t numFlags;
static Flag* find_flag(const char* name) { return find_flag(name, strlen(name), true, true); };
static Flag* find_flag(const char* name, size_t length, bool allow_locked = false, bool return_flag = false);
static Flag* fuzzy_match(const char* name, size_t length, bool allow_locked = false);
void check_writable();
bool is_bool() const;
bool get_bool() const;
void set_bool(bool value);
bool is_int() const;
int get_int() const;
void set_int(int value);
bool is_uint() const;
uint get_uint() const;
void set_uint(uint value);
bool is_intx() const;
intx get_intx() const;
void set_intx(intx value);
bool is_uintx() const;
uintx get_uintx() const;
void set_uintx(uintx value);
bool is_uint64_t() const;
uint64_t get_uint64_t() const;
void set_uint64_t(uint64_t value);
bool is_size_t() const;
size_t get_size_t() const;
void set_size_t(size_t value);
bool is_double() const;
double get_double() const;
void set_double(double value);
bool is_ccstr() const;
bool ccstr_accumulates() const;
ccstr get_ccstr() const;
void set_ccstr(ccstr value);
Flags get_origin();
void set_origin(Flags origin);
bool is_default();
bool is_ergonomic();
bool is_command_line();
bool is_product() const;
bool is_manageable() const;
bool is_diagnostic() const;
bool is_experimental() const;
bool is_notproduct() const;
bool is_develop() const;
bool is_read_write() const;
bool is_commercial() const;
bool is_constant_in_binary() const;
bool is_unlocker() const;
bool is_unlocked() const;
bool is_writeable() const;
bool is_external() const;
bool is_unlocker_ext() const;
bool is_unlocked_ext() const;
bool is_writeable_ext() const;
bool is_external_ext() const;
void unlock_diagnostic();
void get_locked_message(char*, int) const;
void get_locked_message_ext(char*, int) const;
// printRanges will print out flags type, name and range values as expected by -XX:+PrintFlagsRanges
void print_on(outputStream* st, bool withComments = false, bool printRanges = false);
void print_kind(outputStream* st);
void print_as_flag(outputStream* st);
static const char* flag_error_str(Flag::Error error) {
switch (error) {
case Flag::MISSING_NAME: return "MISSING_NAME";
case Flag::MISSING_VALUE: return "MISSING_VALUE";
case Flag::NON_WRITABLE: return "NON_WRITABLE";
case Flag::OUT_OF_BOUNDS: return "OUT_OF_BOUNDS";
case Flag::VIOLATES_CONSTRAINT: return "VIOLATES_CONSTRAINT";
case Flag::INVALID_FLAG: return "INVALID_FLAG";
case Flag::ERR_OTHER: return "ERR_OTHER";
case Flag::SUCCESS: return "SUCCESS";
default: return "NULL";
}
}
};
// debug flags control various aspects of the VM and are global accessible
// use FlagSetting to temporarily change some debug flag
// e.g. FlagSetting fs(DebugThisAndThat, true);
// restored to previous value upon leaving scope
class FlagSetting {
bool val;
bool* flag;
public:
FlagSetting(bool& fl, bool newValue) { flag = &fl; val = fl; fl = newValue; }
~FlagSetting() { *flag = val; }
};
class CounterSetting {
intx* counter;
public:
CounterSetting(intx* cnt) { counter = cnt; (*counter)++; }
~CounterSetting() { (*counter)--; }
};
class IntFlagSetting {
int val;
int* flag;
public:
IntFlagSetting(int& fl, int newValue) { flag = &fl; val = fl; fl = newValue; }
~IntFlagSetting() { *flag = val; }
};
class UIntFlagSetting {
uint val;
uint* flag;
public:
UIntFlagSetting(uint& fl, uint newValue) { flag = &fl; val = fl; fl = newValue; }
~UIntFlagSetting() { *flag = val; }
};
class UIntXFlagSetting {
uintx val;
uintx* flag;
public:
UIntXFlagSetting(uintx& fl, uintx newValue) { flag = &fl; val = fl; fl = newValue; }
~UIntXFlagSetting() { *flag = val; }
};
class DoubleFlagSetting {
double val;
double* flag;
public:
DoubleFlagSetting(double& fl, double newValue) { flag = &fl; val = fl; fl = newValue; }
~DoubleFlagSetting() { *flag = val; }
};
class SizeTFlagSetting {
size_t val;
size_t* flag;
public:
SizeTFlagSetting(size_t& fl, size_t newValue) { flag = &fl; val = fl; fl = newValue; }
~SizeTFlagSetting() { *flag = val; }
};
class CommandLineFlags {
public:
static Flag::Error boolAt(const char* name, size_t len, bool* value, bool allow_locked = false, bool return_flag = false);
static Flag::Error boolAt(const char* name, bool* value, bool allow_locked = false, bool return_flag = false) { return boolAt(name, strlen(name), value, allow_locked, return_flag); }
static Flag::Error boolAtPut(const char* name, size_t len, bool* value, Flag::Flags origin);
static Flag::Error boolAtPut(const char* name, bool* value, Flag::Flags origin) { return boolAtPut(name, strlen(name), value, origin); }
static Flag::Error intAt(const char* name, size_t len, int* value, bool allow_locked = false, bool return_flag = false);
static Flag::Error intAt(const char* name, int* value, bool allow_locked = false, bool return_flag = false) { return intAt(name, strlen(name), value, allow_locked, return_flag); }
static Flag::Error intAtPut(const char* name, size_t len, int* value, Flag::Flags origin);
static Flag::Error intAtPut(const char* name, int* value, Flag::Flags origin) { return intAtPut(name, strlen(name), value, origin); }
static Flag::Error uintAt(const char* name, size_t len, uint* value, bool allow_locked = false, bool return_flag = false);
static Flag::Error uintAt(const char* name, uint* value, bool allow_locked = false, bool return_flag = false) { return uintAt(name, strlen(name), value, allow_locked, return_flag); }
static Flag::Error uintAtPut(const char* name, size_t len, uint* value, Flag::Flags origin);
static Flag::Error uintAtPut(const char* name, uint* value, Flag::Flags origin) { return uintAtPut(name, strlen(name), value, origin); }
static Flag::Error intxAt(const char* name, size_t len, intx* value, bool allow_locked = false, bool return_flag = false);
static Flag::Error intxAt(const char* name, intx* value, bool allow_locked = false, bool return_flag = false) { return intxAt(name, strlen(name), value, allow_locked, return_flag); }
static Flag::Error intxAtPut(const char* name, size_t len, intx* value, Flag::Flags origin);
static Flag::Error intxAtPut(const char* name, intx* value, Flag::Flags origin) { return intxAtPut(name, strlen(name), value, origin); }
static Flag::Error uintxAt(const char* name, size_t len, uintx* value, bool allow_locked = false, bool return_flag = false);
static Flag::Error uintxAt(const char* name, uintx* value, bool allow_locked = false, bool return_flag = false) { return uintxAt(name, strlen(name), value, allow_locked, return_flag); }
static Flag::Error uintxAtPut(const char* name, size_t len, uintx* value, Flag::Flags origin);
static Flag::Error uintxAtPut(const char* name, uintx* value, Flag::Flags origin) { return uintxAtPut(name, strlen(name), value, origin); }
static Flag::Error size_tAt(const char* name, size_t len, size_t* value, bool allow_locked = false, bool return_flag = false);
static Flag::Error size_tAt(const char* name, size_t* value, bool allow_locked = false, bool return_flag = false) { return size_tAt(name, strlen(name), value, allow_locked, return_flag); }
static Flag::Error size_tAtPut(const char* name, size_t len, size_t* value, Flag::Flags origin);
static Flag::Error size_tAtPut(const char* name, size_t* value, Flag::Flags origin) { return size_tAtPut(name, strlen(name), value, origin); }
static Flag::Error uint64_tAt(const char* name, size_t len, uint64_t* value, bool allow_locked = false, bool return_flag = false);
static Flag::Error uint64_tAt(const char* name, uint64_t* value, bool allow_locked = false, bool return_flag = false) { return uint64_tAt(name, strlen(name), value, allow_locked, return_flag); }
static Flag::Error uint64_tAtPut(const char* name, size_t len, uint64_t* value, Flag::Flags origin);
static Flag::Error uint64_tAtPut(const char* name, uint64_t* value, Flag::Flags origin) { return uint64_tAtPut(name, strlen(name), value, origin); }
static Flag::Error doubleAt(const char* name, size_t len, double* value, bool allow_locked = false, bool return_flag = false);
static Flag::Error doubleAt(const char* name, double* value, bool allow_locked = false, bool return_flag = false) { return doubleAt(name, strlen(name), value, allow_locked, return_flag); }
static Flag::Error doubleAtPut(const char* name, size_t len, double* value, Flag::Flags origin);
static Flag::Error doubleAtPut(const char* name, double* value, Flag::Flags origin) { return doubleAtPut(name, strlen(name), value, origin); }
static Flag::Error ccstrAt(const char* name, size_t len, ccstr* value, bool allow_locked = false, bool return_flag = false);
static Flag::Error ccstrAt(const char* name, ccstr* value, bool allow_locked = false, bool return_flag = false) { return ccstrAt(name, strlen(name), value, allow_locked, return_flag); }
// Contract: Flag will make private copy of the incoming value.
// Outgoing value is always malloc-ed, and caller MUST call free.
static Flag::Error ccstrAtPut(const char* name, size_t len, ccstr* value, Flag::Flags origin);
static Flag::Error ccstrAtPut(const char* name, ccstr* value, Flag::Flags origin) { return ccstrAtPut(name, strlen(name), value, origin); }
// Returns false if name is not a command line flag.
static bool wasSetOnCmdline(const char* name, bool* value);
static void printSetFlags(outputStream* out);
// printRanges will print out flags type, name and range values as expected by -XX:+PrintFlagsRanges
static void printFlags(outputStream* out, bool withComments, bool printRanges = false);
static void verify() PRODUCT_RETURN;
};
// use this for flags that are true by default in the debug version but
// false in the optimized version, and vice versa
#ifdef ASSERT
#define trueInDebug true
#define falseInDebug false
#else
#define trueInDebug false
#define falseInDebug true
#endif
// use this for flags that are true per default in the product build
// but false in development builds, and vice versa
#ifdef PRODUCT
#define trueInProduct true
#define falseInProduct false
#else
#define trueInProduct false
#define falseInProduct true
#endif
#ifdef JAVASE_EMBEDDED
#define falseInEmbedded false
#else
#define falseInEmbedded true
#endif
// develop flags are settable / visible only during development and are constant in the PRODUCT version
// product flags are always settable / visible
// notproduct flags are settable / visible only during development and are not declared in the PRODUCT version
// A flag must be declared with one of the following types:
// bool, intx, uintx, size_t, ccstr, double, or uint64_t.
// The type "ccstr" is an alias for "const char*" and is used
// only in this file, because the macrology requires single-token type names.
// Note: Diagnostic options not meant for VM tuning or for product modes.
// They are to be used for VM quality assurance or field diagnosis
// of VM bugs. They are hidden so that users will not be encouraged to
// try them as if they were VM ordinary execution options. However, they
// are available in the product version of the VM. Under instruction
// from support engineers, VM customers can turn them on to collect
// diagnostic information about VM problems. To use a VM diagnostic
// option, you must first specify +UnlockDiagnosticVMOptions.
// (This master switch also affects the behavior of -Xprintflags.)
//
// experimental flags are in support of features that are not
// part of the officially supported product, but are available
// for experimenting with. They could, for example, be performance
// features that may not have undergone full or rigorous QA, but which may
// help performance in some cases and released for experimentation
// by the community of users and developers. This flag also allows one to
// be able to build a fully supported product that nonetheless also
// ships with some unsupported, lightly tested, experimental features.
// Like the UnlockDiagnosticVMOptions flag above, there is a corresponding
// UnlockExperimentalVMOptions flag, which allows the control and
// modification of the experimental flags.
//
// Nota bene: neither diagnostic nor experimental options should be used casually,
// and they are not supported on production loads, except under explicit
// direction from support engineers.
//
// manageable flags are writeable external product flags.
// They are dynamically writeable through the JDK management interface
// (com.sun.management.HotSpotDiagnosticMXBean API) and also through JConsole.
// These flags are external exported interface (see CCC). The list of
// manageable flags can be queried programmatically through the management
// interface.
//
// A flag can be made as "manageable" only if
// - the flag is defined in a CCC as an external exported interface.
// - the VM implementation supports dynamic setting of the flag.
// This implies that the VM must *always* query the flag variable
// and not reuse state related to the flag state at any given time.
// - you want the flag to be queried programmatically by the customers.
//
// product_rw flags are writeable internal product flags.
// They are like "manageable" flags but for internal/private use.
// The list of product_rw flags are internal/private flags which
// may be changed/removed in a future release. It can be set
// through the management interface to get/set value
// when the name of flag is supplied.
//
// A flag can be made as "product_rw" only if
// - the VM implementation supports dynamic setting of the flag.
// This implies that the VM must *always* query the flag variable
// and not reuse state related to the flag state at any given time.
//
// Note that when there is a need to support develop flags to be writeable,
// it can be done in the same way as product_rw.
//
// range is a macro that will expand to min and max arguments for range
// checking code if provided - see commandLineFlagRangeList.hpp
//
// constraint is a macro that will expand to custom function call
// for constraint checking if provided - see commandLineFlagConstraintList.hpp
//
#define RUNTIME_FLAGS(develop, develop_pd, product, product_pd, diagnostic, experimental, notproduct, manageable, product_rw, lp64_product, range, constraint) \
\
lp64_product(bool, UseCompressedOops, false, \
"Use 32-bit object references in 64-bit VM. " \
"lp64_product means flag is always constant in 32 bit VM") \
\
lp64_product(bool, UseCompressedClassPointers, false, \
"Use 32-bit class pointers in 64-bit VM. " \
"lp64_product means flag is always constant in 32 bit VM") \
\
notproduct(bool, CheckCompressedOops, true, \
"Generate checks in encoding/decoding code in debug VM") \
\
product_pd(size_t, HeapBaseMinAddress, \
"OS specific low limit for heap base address") \
\
product(uintx, HeapSearchSteps, 3 PPC64_ONLY(+17), \
"Heap allocation steps through preferred address regions to find" \
" where it can allocate the heap. Number of steps to take per " \
"region.") \
range(1, max_uintx) \
\
diagnostic(bool, PrintCompressedOopsMode, false, \
"Print compressed oops base address and encoding mode") \
\
lp64_product(intx, ObjectAlignmentInBytes, 8, \
"Default object alignment in bytes, 8 is minimum") \
range(8, 256) \
constraint(ObjectAlignmentInBytesConstraintFunc,AtParse) \
\
product(bool, AssumeMP, false, \
"Instruct the VM to assume multiple processors are available") \
\
/* UseMembar is theoretically a temp flag used for memory barrier */ \
/* removal testing. It was supposed to be removed before FCS but has */ \
/* been re-added (see 6401008) */ \
product_pd(bool, UseMembar, \
"(Unstable) Issues membars on thread state transitions") \
\
develop(bool, CleanChunkPoolAsync, falseInEmbedded, \
"Clean the chunk pool asynchronously") \
\
experimental(bool, AlwaysSafeConstructors, false, \
"Force safe construction, as if all fields are final.") \
\
/* Temporary: See 6948537 */ \
experimental(bool, UseMemSetInBOT, true, \
"(Unstable) uses memset in BOT updates in GC code") \
\
diagnostic(bool, UnlockDiagnosticVMOptions, trueInDebug, \
"Enable normal processing of flags relating to field diagnostics")\
\
experimental(bool, UnlockExperimentalVMOptions, false, \
"Enable normal processing of flags relating to experimental " \
"features") \
\
product(bool, JavaMonitorsInStackTrace, true, \
"Print information about Java monitor locks when the stacks are" \
"dumped") \
\
product_pd(bool, UseLargePages, \
"Use large page memory") \
\
product_pd(bool, UseLargePagesIndividualAllocation, \
"Allocate large pages individually for better affinity") \
\
develop(bool, LargePagesIndividualAllocationInjectError, false, \
"Fail large pages individual allocation") \
\
product(bool, UseLargePagesInMetaspace, false, \
"Use large page memory in metaspace. " \
"Only used if UseLargePages is enabled.") \
\
develop(bool, TracePageSizes, false, \
"Trace page size selection and usage") \
\
product(bool, UseNUMA, false, \
"Use NUMA if available") \
\
product(bool, UseNUMAInterleaving, false, \
"Interleave memory across NUMA nodes if available") \
\
product(size_t, NUMAInterleaveGranularity, 2*M, \
"Granularity to use for NUMA interleaving on Windows OS") \
\
product(bool, ForceNUMA, false, \
"Force NUMA optimizations on single-node/UMA systems") \
\
product(uintx, NUMAChunkResizeWeight, 20, \
"Percentage (0-100) used to weight the current sample when " \
"computing exponentially decaying average for " \
"AdaptiveNUMAChunkSizing") \
range(0, 100) \
\
product(size_t, NUMASpaceResizeRate, 1*G, \
"Do not reallocate more than this amount per collection") \
\
product(bool, UseAdaptiveNUMAChunkSizing, true, \
"Enable adaptive chunk sizing for NUMA") \
\
product(bool, NUMAStats, false, \
"Print NUMA stats in detailed heap information") \
\
product(uintx, NUMAPageScanRate, 256, \
"Maximum number of pages to include in the page scan procedure") \
\
product_pd(bool, NeedsDeoptSuspend, \
"True for register window machines (sparc/ia64)") \
\
product(intx, UseSSE, 99, \
"Highest supported SSE instructions set on x86/x64") \
\
product(bool, UseAES, false, \
"Control whether AES instructions can be used on x86/x64") \
\
product(bool, UseSHA, false, \
"Control whether SHA instructions can be used " \
"on SPARC and on ARM") \
\
product(bool, UseGHASHIntrinsics, false, \
"Use intrinsics for GHASH versions of crypto") \
\
product(size_t, LargePageSizeInBytes, 0, \
"Large page size (0 to let VM choose the page size)") \
\
product(size_t, LargePageHeapSizeThreshold, 128*M, \
"Use large pages if maximum heap is at least this big") \
\
product(bool, ForceTimeHighResolution, false, \
"Using high time resolution (for Win32 only)") \
\
develop(bool, TraceItables, false, \
"Trace initialization and use of itables") \
\
develop(bool, TracePcPatching, false, \
"Trace usage of frame::patch_pc") \
\
develop(bool, TraceJumps, false, \
"Trace assembly jumps in thread ring buffer") \
\
develop(bool, TraceRelocator, false, \
"Trace the bytecode relocator") \
\
develop(bool, TraceLongCompiles, false, \
"Print out every time compilation is longer than " \
"a given threshold") \
\
develop(bool, SafepointALot, false, \
"Generate a lot of safepoints. This works with " \
"GuaranteedSafepointInterval") \
\
product_pd(bool, BackgroundCompilation, \
"A thread requesting compilation is not blocked during " \
"compilation") \
\
product(bool, PrintVMQWaitTime, false, \
"Print out the waiting time in VM operation queue") \
\
develop(bool, TraceOopMapGeneration, false, \
"Show OopMapGeneration") \
\
product(bool, MethodFlushing, true, \
"Reclamation of zombie and not-entrant methods") \
\
develop(bool, VerifyStack, false, \
"Verify stack of each thread when it is entering a runtime call") \
\
diagnostic(bool, ForceUnreachable, false, \
"Make all non code cache addresses to be unreachable by " \
"forcing use of 64bit literal fixups") \
\
notproduct(bool, StressDerivedPointers, false, \
"Force scavenge when a derived pointer is detected on stack " \
"after rtm call") \
\
develop(bool, TraceDerivedPointers, false, \
"Trace traversal of derived pointers on stack") \
\
notproduct(bool, TraceCodeBlobStacks, false, \
"Trace stack-walk of codeblobs") \
\
product(bool, PrintJNIResolving, false, \
"Used to implement -v:jni") \
\
notproduct(bool, PrintRewrites, false, \
"Print methods that are being rewritten") \
\
product(bool, UseInlineCaches, true, \
"Use Inline Caches for virtual calls ") \
\
develop(bool, InlineArrayCopy, true, \
"Inline arraycopy native that is known to be part of " \
"base library DLL") \
\
develop(bool, InlineObjectHash, true, \
"Inline Object::hashCode() native that is known to be part " \
"of base library DLL") \
\
develop(bool, InlineNatives, true, \
"Inline natives that are known to be part of base library DLL") \
\
develop(bool, InlineMathNatives, true, \
"Inline SinD, CosD, etc.") \
\
develop(bool, InlineClassNatives, true, \
"Inline Class.isInstance, etc") \
\
develop(bool, InlineThreadNatives, true, \
"Inline Thread.currentThread, etc") \
\
develop(bool, InlineUnsafeOps, true, \
"Inline memory ops (native methods) from sun.misc.Unsafe") \
\
product(bool, CriticalJNINatives, true, \
"Check for critical JNI entry points") \
\
notproduct(bool, StressCriticalJNINatives, false, \
"Exercise register saving code in critical natives") \
\
product(bool, UseSSE42Intrinsics, false, \
"SSE4.2 versions of intrinsics") \
\
product(bool, UseAESIntrinsics, false, \
"Use intrinsics for AES versions of crypto") \
\
product(bool, UseSHA1Intrinsics, false, \
"Use intrinsics for SHA-1 crypto hash function. " \
"Requires that UseSHA is enabled.") \
\
product(bool, UseSHA256Intrinsics, false, \
"Use intrinsics for SHA-224 and SHA-256 crypto hash functions. " \
"Requires that UseSHA is enabled.") \
\
product(bool, UseSHA512Intrinsics, false, \
"Use intrinsics for SHA-384 and SHA-512 crypto hash functions. " \
"Requires that UseSHA is enabled.") \
\
product(bool, UseCRC32Intrinsics, false, \
"use intrinsics for java.util.zip.CRC32") \
\
product(bool, UseCRC32CIntrinsics, false, \
"use intrinsics for java.util.zip.CRC32C") \
\
diagnostic(ccstrlist, DisableIntrinsic, "", \
"do not expand intrinsics whose (internal) names appear here") \
\
develop(bool, TraceCallFixup, false, \
"Trace all call fixups") \
\
develop(bool, DeoptimizeALot, false, \
"Deoptimize at every exit from the runtime system") \
\
notproduct(ccstrlist, DeoptimizeOnlyAt, "", \
"A comma separated list of bcis to deoptimize at") \
\
product(bool, DeoptimizeRandom, false, \
"Deoptimize random frames on random exit from the runtime system")\
\
notproduct(bool, ZombieALot, false, \
"Create zombies (non-entrant) at exit from the runtime system") \
\
product(bool, UnlinkSymbolsALot, false, \
"Unlink unreferenced symbols from the symbol table at safepoints")\
\
notproduct(bool, WalkStackALot, false, \
"Trace stack (no print) at every exit from the runtime system") \
\
product(bool, Debugging, false, \
"Set when executing debug methods in debug.cpp " \
"(to prevent triggering assertions)") \
\
notproduct(bool, StrictSafepointChecks, trueInDebug, \
"Enable strict checks that safepoints cannot happen for threads " \
"that use No_Safepoint_Verifier") \
\
notproduct(bool, VerifyLastFrame, false, \
"Verify oops on last frame on entry to VM") \
\
develop(bool, TraceHandleAllocation, false, \
"Print out warnings when suspiciously many handles are allocated")\
\
product(bool, FailOverToOldVerifier, true, \
"Fail over to old verifier when split verifier fails") \
\
develop(bool, ShowSafepointMsgs, false, \
"Show message about safepoint synchronization") \
\
product(bool, SafepointTimeout, false, \
"Time out and warn or fail after SafepointTimeoutDelay " \
"milliseconds if failed to reach safepoint") \
\
develop(bool, DieOnSafepointTimeout, false, \
"Die upon failure to reach safepoint (see SafepointTimeout)") \
\
/* 50 retries * (5 * current_retry_count) millis = ~6.375 seconds */ \
/* typically, at most a few retries are needed */ \
product(intx, SuspendRetryCount, 50, \
"Maximum retry count for an external suspend request") \
\
product(intx, SuspendRetryDelay, 5, \
"Milliseconds to delay per retry (* current_retry_count)") \
\
product(bool, AssertOnSuspendWaitFailure, false, \
"Assert/Guarantee on external suspend wait failure") \
\
product(bool, TraceSuspendWaitFailures, false, \
"Trace external suspend wait failures") \
\
product(bool, MaxFDLimit, true, \
"Bump the number of file descriptors to maximum in Solaris") \
\
diagnostic(bool, LogEvents, true, \
"Enable the various ring buffer event logs") \
\
diagnostic(uintx, LogEventsBufferEntries, 10, \
"Number of ring buffer event logs") \
range(1, NOT_LP64(1*K) LP64_ONLY(1*M)) \
\
product(bool, BytecodeVerificationRemote, true, \
"Enable the Java bytecode verifier for remote classes") \
\
product(bool, BytecodeVerificationLocal, false, \
"Enable the Java bytecode verifier for local classes") \
\
develop(bool, ForceFloatExceptions, trueInDebug, \
"Force exceptions on FP stack under/overflow") \
\
develop(bool, VerifyStackAtCalls, false, \
"Verify that the stack pointer is unchanged after calls") \
\
develop(bool, TraceJavaAssertions, false, \
"Trace java language assertions") \
\
notproduct(bool, CheckAssertionStatusDirectives, false, \
"Temporary - see javaClasses.cpp") \
\
notproduct(bool, PrintMallocFree, false, \
"Trace calls to C heap malloc/free allocation") \
\
product(bool, PrintOopAddress, false, \
"Always print the location of the oop") \
\
notproduct(bool, VerifyCodeCache, false, \
"Verify code cache on memory allocation/deallocation") \
\
develop(bool, ZapDeadCompiledLocals, false, \
"Zap dead locals in compiler frames") \
\
notproduct(bool, ZapDeadLocalsOld, false, \
"Zap dead locals (old version, zaps all frames when " \
"entering the VM") \
\
notproduct(bool, CheckOopishValues, false, \
"Warn if value contains oop (requires ZapDeadLocals)") \
\
develop(bool, UseMallocOnly, false, \
"Use only malloc/free for allocation (no resource area/arena)") \
\
develop(bool, PrintMalloc, false, \
"Print all malloc/free calls") \
\
develop(bool, PrintMallocStatistics, false, \
"Print malloc/free statistics") \
\
develop(bool, ZapResourceArea, trueInDebug, \
"Zap freed resource/arena space with 0xABABABAB") \
\
notproduct(bool, ZapVMHandleArea, trueInDebug, \
"Zap freed VM handle space with 0xBCBCBCBC") \
\
develop(bool, ZapJNIHandleArea, trueInDebug, \
"Zap freed JNI handle space with 0xFEFEFEFE") \
\
notproduct(bool, ZapStackSegments, trueInDebug, \
"Zap allocated/freed stack segments with 0xFADFADED") \
\
develop(bool, ZapUnusedHeapArea, trueInDebug, \
"Zap unused heap space with 0xBAADBABE") \
\
develop(bool, TraceZapUnusedHeapArea, false, \
"Trace zapping of unused heap space") \
\
develop(bool, CheckZapUnusedHeapArea, false, \
"Check zapping of unused heap space") \
\
develop(bool, ZapFillerObjects, trueInDebug, \
"Zap filler objects with 0xDEAFBABE") \
\
develop(bool, PrintVMMessages, true, \
"Print VM messages on console") \
\
product(bool, PrintGCApplicationConcurrentTime, false, \
"Print the time the application has been running") \
\
product(bool, PrintGCApplicationStoppedTime, false, \
"Print the time the application has been stopped") \
\
diagnostic(bool, VerboseVerification, false, \
"Display detailed verification details") \
\
notproduct(uintx, ErrorHandlerTest, 0, \
"If > 0, provokes an error after VM initialization; the value " \
"determines which error to provoke. See test_error_handler() " \
"in debug.cpp.") \
\
notproduct(uintx, TestCrashInErrorHandler, 0, \
"If > 0, provokes an error inside VM error handler (a secondary " \
"crash). see test_error_handler() in debug.cpp.") \
\
notproduct(bool, TestSafeFetchInErrorHandler, false, \
"If true, tests SafeFetch inside error handler.") \
\
develop(bool, Verbose, false, \
"Print additional debugging information from other modes") \
\
develop(bool, PrintMiscellaneous, false, \
"Print uncategorized debugging information (requires +Verbose)") \
\
develop(bool, WizardMode, false, \
"Print much more debugging information") \
\
product(bool, ShowMessageBoxOnError, false, \
"Keep process alive on VM fatal error") \
\
product(bool, CreateCoredumpOnCrash, true, \
"Create core/mini dump on VM fatal error") \
\
product(uintx, ErrorLogTimeout, 2 * 60, \
"Timeout, in seconds, to limit the time spent on writing an " \
"error log in case of a crash.") \
\
product_pd(bool, UseOSErrorReporting, \
"Let VM fatal error propagate to the OS (ie. WER on Windows)") \
\
product(bool, SuppressFatalErrorMessage, false, \
"Report NO fatal error message (avoid deadlock)") \
\
product(ccstrlist, OnError, "", \
"Run user-defined commands on fatal error; see VMError.cpp " \
"for examples") \
\
product(ccstrlist, OnOutOfMemoryError, "", \
"Run user-defined commands on first java.lang.OutOfMemoryError") \
\
manageable(bool, HeapDumpBeforeFullGC, false, \
"Dump heap to file before any major stop-the-world GC") \
\
manageable(bool, HeapDumpAfterFullGC, false, \
"Dump heap to file after any major stop-the-world GC") \
\
manageable(bool, HeapDumpOnOutOfMemoryError, false, \
"Dump heap to file when java.lang.OutOfMemoryError is thrown") \
\
manageable(ccstr, HeapDumpPath, NULL, \
"When HeapDumpOnOutOfMemoryError is on, the path (filename or " \
"directory) of the dump file (defaults to java_pid<pid>.hprof " \
"in the working directory)") \
\
develop(size_t, SegmentedHeapDumpThreshold, 2*G, \
"Generate a segmented heap dump (JAVA PROFILE 1.0.2 format) " \
"when the heap usage is larger than this") \
\
develop(size_t, HeapDumpSegmentSize, 1*G, \
"Approximate segment size when generating a segmented heap dump") \
\
develop(bool, BreakAtWarning, false, \
"Execute breakpoint upon encountering VM warning") \
\
develop(bool, TraceVMOperation, false, \
"Trace VM operations") \
\
develop(bool, UseFakeTimers, false, \
"Tell whether the VM should use system time or a fake timer") \
\
product(ccstr, NativeMemoryTracking, "off", \
"Native memory tracking options") \
\
diagnostic(bool, PrintNMTStatistics, false, \
"Print native memory tracking summary data if it is on") \
\
diagnostic(bool, LogCompilation, false, \
"Log compilation activity in detail to LogFile") \
\
product(bool, PrintCompilation, false, \
"Print compilations") \
\
diagnostic(bool, TraceNMethodInstalls, false, \
"Trace nmethod installation") \
\
diagnostic(intx, ScavengeRootsInCode, 2, \
"0: do not allow scavengable oops in the code cache; " \
"1: allow scavenging from the code cache; " \
"2: emit as many constants as the compiler can see") \
range(0, 2) \
\
product(bool, AlwaysRestoreFPU, false, \
"Restore the FPU control word after every JNI call (expensive)") \
\
product(bool, MemoryMapImage, false, \
"Memory map entire runtime image") \
\
diagnostic(bool, PrintCompilation2, false, \
"Print additional statistics per compilation") \
\
diagnostic(bool, PrintAdapterHandlers, false, \
"Print code generated for i2c/c2i adapters") \
\
diagnostic(bool, VerifyAdapterCalls, trueInDebug, \
"Verify that i2c/c2i adapters are called properly") \
\
develop(bool, VerifyAdapterSharing, false, \
"Verify that the code for shared adapters is the equivalent") \
\
diagnostic(bool, PrintAssembly, false, \
"Print assembly code (using external disassembler.so)") \
\
diagnostic(ccstr, PrintAssemblyOptions, NULL, \
"Print options string passed to disassembler.so") \
\
diagnostic(bool, PrintNMethods, false, \
"Print assembly code for nmethods when generated") \
\
diagnostic(bool, PrintNativeNMethods, false, \
"Print assembly code for native nmethods when generated") \
\
develop(bool, PrintDebugInfo, false, \
"Print debug information for all nmethods when generated") \
\
develop(bool, PrintRelocations, false, \
"Print relocation information for all nmethods when generated") \
\
develop(bool, PrintDependencies, false, \
"Print dependency information for all nmethods when generated") \
\
develop(bool, PrintExceptionHandlers, false, \
"Print exception handler tables for all nmethods when generated") \
\
develop(bool, StressCompiledExceptionHandlers, false, \
"Exercise compiled exception handlers") \
\
develop(bool, InterceptOSException, false, \
"Start debugger when an implicit OS (e.g. NULL) " \
"exception happens") \
\
product(bool, PrintCodeCache, false, \
"Print the code cache memory usage when exiting") \
\
develop(bool, PrintCodeCache2, false, \
"Print detailed usage information on the code cache when exiting")\
\
product(bool, PrintCodeCacheOnCompilation, false, \
"Print the code cache memory usage each time a method is " \
"compiled") \
\
diagnostic(bool, PrintStubCode, false, \
"Print generated stub code") \
\
product(bool, StackTraceInThrowable, true, \
"Collect backtrace in throwable when exception happens") \
\
product(bool, OmitStackTraceInFastThrow, true, \
"Omit backtraces for some 'hot' exceptions in optimized code") \
\
product(bool, ProfilerPrintByteCodeStatistics, false, \
"Print bytecode statistics when dumping profiler output") \
\
product(bool, ProfilerRecordPC, false, \
"Collect ticks for each 16 byte interval of compiled code") \
\
product(bool, ProfileVM, false, \
"Profile ticks that fall within VM (either in the VM Thread " \
"or VM code called through stubs)") \
\
product(bool, ProfileIntervals, false, \
"Print profiles for each interval (see ProfileIntervalsTicks)") \
\
notproduct(bool, ProfilerCheckIntervals, false, \
"Collect and print information on spacing of profiler ticks") \
\
product(bool, PrintWarnings, true, \
"Print JVM warnings to output stream") \
\
notproduct(uintx, WarnOnStalledSpinLock, 0, \
"Print warnings for stalled SpinLocks") \
\
product(bool, RegisterFinalizersAtInit, true, \
"Register finalizable objects at end of Object.<init> or " \
"after allocation") \
\
develop(bool, RegisterReferences, true, \
"Tell whether the VM should register soft/weak/final/phantom " \
"references") \
\
develop(bool, IgnoreRewrites, false, \
"Suppress rewrites of bytecodes in the oopmap generator. " \
"This is unsafe!") \
\
develop(bool, PrintCodeCacheExtension, false, \
"Print extension of code cache") \
\
develop(bool, UsePrivilegedStack, true, \
"Enable the security JVM functions") \
\
develop(bool, ProtectionDomainVerification, true, \
"Verify protection domain before resolution in system dictionary")\
\
product(bool, ClassUnloading, true, \
"Do unloading of classes") \
\
product(bool, ClassUnloadingWithConcurrentMark, true, \
"Do unloading of classes with a concurrent marking cycle") \
\
develop(bool, DisableStartThread, false, \
"Disable starting of additional Java threads " \
"(for debugging only)") \
\
develop(bool, MemProfiling, false, \
"Write memory usage profiling to log file") \
\
notproduct(bool, PrintSystemDictionaryAtExit, false, \
"Print the system dictionary at exit") \
\
experimental(intx, PredictedLoadedClassCount, 0, \
"Experimental: Tune loaded class cache starting size") \
\
diagnostic(bool, UnsyncloadClass, false, \
"Unstable: VM calls loadClass unsynchronized. Custom " \
"class loader must call VM synchronized for findClass " \
"and defineClass.") \
\
product(bool, AlwaysLockClassLoader, false, \
"Require the VM to acquire the class loader lock before calling " \
"loadClass() even for class loaders registering " \
"as parallel capable") \
\
product(bool, AllowParallelDefineClass, false, \
"Allow parallel defineClass requests for class loaders " \
"registering as parallel capable") \
\
product(bool, MustCallLoadClassInternal, false, \
"Call loadClassInternal() rather than loadClass()") \
\
product_pd(bool, DontYieldALot, \
"Throw away obvious excess yield calls") \
\
product_pd(bool, ConvertSleepToYield, \
"Convert sleep(0) to thread yield " \
"(may be off for Solaris to improve GUI)") \
\
product(bool, ConvertYieldToSleep, false, \
"Convert yield to a sleep of MinSleepInterval to simulate Win32 " \
"behavior") \
\
develop(bool, UseDetachedThreads, true, \
"Use detached threads that are recycled upon termination " \
"(for Solaris only)") \
\
product(bool, UseLWPSynchronization, true, \
"Use LWP-based instead of libthread-based synchronization " \
"(SPARC only)") \
\
experimental(ccstr, SyncKnobs, NULL, \
"(Unstable) Various monitor synchronization tunables") \
\
experimental(intx, EmitSync, 0, \
"(Unsafe, Unstable) " \
"Control emission of inline sync fast-path code") \
\
product(intx, MonitorBound, 0, "Bound Monitor population") \
\
product(bool, MonitorInUseLists, false, "Track Monitors for Deflation") \
\
experimental(intx, SyncFlags, 0, "(Unsafe, Unstable) " \
"Experimental Sync flags") \
\
experimental(intx, SyncVerbose, 0, "(Unstable)") \
\
diagnostic(bool, InlineNotify, true, "intrinsify subset of notify") \
\
experimental(intx, ClearFPUAtPark, 0, "(Unsafe, Unstable)") \
\
experimental(intx, hashCode, 5, \
"(Unstable) select hashCode generation algorithm") \
\
experimental(intx, WorkAroundNPTLTimedWaitHang, 0, \
"(Unstable, Linux-specific) " \
"avoid NPTL-FUTEX hang pthread_cond_timedwait") \
\
product(bool, FilterSpuriousWakeups, true, \
"When true prevents OS-level spurious, or premature, wakeups " \
"from Object.wait (Ignored for Windows)") \
\
experimental(intx, NativeMonitorTimeout, -1, "(Unstable)") \
\
experimental(intx, NativeMonitorFlags, 0, "(Unstable)") \
\
experimental(intx, NativeMonitorSpinLimit, 20, "(Unstable)") \
\
develop(bool, UsePthreads, false, \
"Use pthread-based instead of libthread-based synchronization " \
"(SPARC only)") \
\
product(bool, ReduceSignalUsage, false, \
"Reduce the use of OS signals in Java and/or the VM") \
\
develop_pd(bool, ShareVtableStubs, \
"Share vtable stubs (smaller code but worse branch prediction") \
\
develop(bool, LoadLineNumberTables, true, \
"Tell whether the class file parser loads line number tables") \
\
develop(bool, LoadLocalVariableTables, true, \
"Tell whether the class file parser loads local variable tables") \
\
develop(bool, LoadLocalVariableTypeTables, true, \
"Tell whether the class file parser loads local variable type" \
"tables") \
\
product(bool, AllowUserSignalHandlers, false, \
"Do not complain if the application installs signal handlers " \
"(Solaris & Linux only)") \
\
product(bool, UseSignalChaining, true, \
"Use signal-chaining to invoke signal handlers installed " \
"by the application (Solaris & Linux only)") \
\
product(bool, UseAltSigs, false, \
"Use alternate signals instead of SIGUSR1 & SIGUSR2 for VM " \
"internal signals (Solaris only)") \
\
product(bool, AllowJNIEnvProxy, false, \
"Allow JNIEnv proxies for jdbx") \
\
product(bool, JNIDetachReleasesMonitors, true, \
"JNI DetachCurrentThread releases monitors owned by thread") \
\
product(bool, RestoreMXCSROnJNICalls, false, \
"Restore MXCSR when returning from JNI calls") \
\
product(bool, CheckJNICalls, false, \
"Verify all arguments to JNI calls") \
\
product(bool, CheckEndorsedAndExtDirs, false, \
"Verify the endorsed and extension directories are not used") \
\
product(bool, UseFastJNIAccessors, true, \
"Use optimized versions of Get<Primitive>Field") \
\
product(intx, MaxJNILocalCapacity, 65536, \
"Maximum allowable local JNI handle capacity to " \
"EnsureLocalCapacity() and PushLocalFrame(), " \
"where <= 0 is unlimited, default: 65536") \
\
product(bool, EagerXrunInit, false, \
"Eagerly initialize -Xrun libraries; allows startup profiling, " \
"but not all -Xrun libraries may support the state of the VM " \
"at this time") \
\
product(bool, PreserveAllAnnotations, false, \
"Preserve RuntimeInvisibleAnnotations as well " \
"as RuntimeVisibleAnnotations") \
\
develop(uintx, PreallocatedOutOfMemoryErrorCount, 4, \
"Number of OutOfMemoryErrors preallocated with backtrace") \
\
product(bool, UseXMMForArrayCopy, false, \
"Use SSE2 MOVQ instruction for Arraycopy") \
\
product(intx, FieldsAllocationStyle, 1, \
"0 - type based with oops first, " \
"1 - with oops last, " \
"2 - oops in super and sub classes are together") \
range(0, 2) \
\
product(bool, CompactFields, true, \
"Allocate nonstatic fields in gaps between previous fields") \
\
notproduct(bool, PrintFieldLayout, false, \
"Print field layout for each class") \
\
/* Need to limit the extent of the padding to reasonable size. */\
/* 8K is well beyond the reasonable HW cache line size, even with */\
/* aggressive prefetching, while still leaving the room for segregating */\
/* among the distinct pages. */\
product(intx, ContendedPaddingWidth, 128, \
"How many bytes to pad the fields/classes marked @Contended with")\
range(0, 8192) \
constraint(ContendedPaddingWidthConstraintFunc,AtParse) \
\
product(bool, EnableContended, true, \
"Enable @Contended annotation support") \
\
product(bool, RestrictContended, true, \
"Restrict @Contended to trusted classes") \
\
product(bool, UseBiasedLocking, true, \
"Enable biased locking in JVM") \
\
product(intx, BiasedLockingStartupDelay, 4000, \
"Number of milliseconds to wait before enabling biased locking") \
\
diagnostic(bool, PrintBiasedLockingStatistics, false, \
"Print statistics of biased locking in JVM") \
\
product(intx, BiasedLockingBulkRebiasThreshold, 20, \
"Threshold of number of revocations per type to try to " \
"rebias all objects in the heap of that type") \
\
product(intx, BiasedLockingBulkRevokeThreshold, 40, \
"Threshold of number of revocations per type to permanently " \
"revoke biases of all objects in the heap of that type") \
\
product(intx, BiasedLockingDecayTime, 25000, \
"Decay time (in milliseconds) to re-enable bulk rebiasing of a " \
"type after previous bulk rebias") \
\
/* tracing */ \
\
notproduct(bool, TraceRuntimeCalls, false, \
"Trace run-time calls") \
\
develop(bool, TraceJNICalls, false, \
"Trace JNI calls") \
\
develop(bool, StressRewriter, false, \
"Stress linktime bytecode rewriting") \
\
notproduct(bool, TraceJVMCalls, false, \
"Trace JVM calls") \
\
product(ccstr, TraceJVMTI, NULL, \
"Trace flags for JVMTI functions and events") \
\
/* This option can change an EMCP method into an obsolete method. */ \
/* This can affect tests that except specific methods to be EMCP. */ \
/* This option should be used with caution. */ \
product(bool, StressLdcRewrite, false, \
"Force ldc -> ldc_w rewrite during RedefineClasses") \
\
product(intx, TraceRedefineClasses, 0, \
"Trace level for JVMTI RedefineClasses") \
\
/* change to false by default sometime after Mustang */ \
product(bool, VerifyMergedCPBytecodes, true, \
"Verify bytecodes after RedefineClasses constant pool merging") \
\
develop(bool, TraceJNIHandleAllocation, false, \
"Trace allocation/deallocation of JNI handle blocks") \
\
develop(bool, TraceBytecodes, false, \
"Trace bytecode execution") \
\
develop(bool, TraceClassInitialization, false, \
"Trace class initialization") \
\
product(bool, TraceExceptions, false, \
"Trace exceptions") \
\
develop(bool, TraceICs, false, \
"Trace inline cache changes") \
\
notproduct(bool, TraceInvocationCounterOverflow, false, \
"Trace method invocation counter overflow") \
\
develop(bool, TraceInlineCacheClearing, false, \
"Trace clearing of inline caches in nmethods") \
\
develop(bool, TraceDependencies, false, \
"Trace dependencies") \
\
develop(bool, VerifyDependencies, trueInDebug, \
"Exercise and verify the compilation dependency mechanism") \
\
develop(bool, TraceNewOopMapGeneration, false, \
"Trace OopMapGeneration") \
\
develop(bool, TraceNewOopMapGenerationDetailed, false, \
"Trace OopMapGeneration: print detailed cell states") \
\
develop(bool, TimeOopMap, false, \
"Time calls to GenerateOopMap::compute_map() in sum") \
\
develop(bool, TimeOopMap2, false, \
"Time calls to GenerateOopMap::compute_map() individually") \
\
develop(bool, TraceMonitorMismatch, false, \
"Trace monitor matching failures during OopMapGeneration") \
\
develop(bool, TraceOopMapRewrites, false, \
"Trace rewriting of method oops during oop map generation") \
\
develop(bool, TraceSafepoint, false, \
"Trace safepoint operations") \
\
develop(bool, TraceICBuffer, false, \
"Trace usage of IC buffer") \
\
develop(bool, TraceCompiledIC, false, \
"Trace changes of compiled IC") \
\
notproduct(bool, TraceZapDeadLocals, false, \
"Trace zapping dead locals") \
\
develop(bool, TraceStartupTime, false, \
"Trace setup time") \
\
develop(bool, TraceProtectionDomainVerification, false, \
"Trace protection domain verification") \
\
develop(bool, TraceClearedExceptions, false, \
"Print when an exception is forcibly cleared") \
\
product(bool, TraceClassResolution, false, \
"Trace all constant pool resolutions (for debugging)") \
\
product(bool, TraceBiasedLocking, false, \
"Trace biased locking in JVM") \
\
product(bool, TraceMonitorInflation, false, \
"Trace monitor inflation in JVM") \
\
/* gc */ \
\
product(bool, UseSerialGC, false, \
"Use the Serial garbage collector") \
\
product(bool, UseG1GC, false, \
"Use the Garbage-First garbage collector") \
\
product(bool, UseParallelGC, false, \
"Use the Parallel Scavenge garbage collector") \
\
product(bool, UseParallelOldGC, false, \
"Use the Parallel Old garbage collector") \
\
product(uintx, HeapMaximumCompactionInterval, 20, \
"How often should we maximally compact the heap (not allowing " \
"any dead space)") \
\
product(uintx, HeapFirstMaximumCompactionCount, 3, \
"The collection count for the first maximum compaction") \
\
product(bool, UseMaximumCompactionOnSystemGC, true, \
"Use maximum compaction in the Parallel Old garbage collector " \
"for a system GC") \
\
product(uintx, ParallelOldDeadWoodLimiterMean, 50, \
"The mean used by the parallel compact dead wood " \
"limiter (a number between 0-100)") \
range(0, 100) \
\
product(uintx, ParallelOldDeadWoodLimiterStdDev, 80, \
"The standard deviation used by the parallel compact dead wood " \
"limiter (a number between 0-100)") \
range(0, 100) \
\
product(uint, ParallelGCThreads, 0, \
"Number of parallel threads parallel gc will use") \
\
product(bool, UseDynamicNumberOfGCThreads, false, \
"Dynamically choose the number of parallel threads " \
"parallel gc will use") \
\
diagnostic(bool, ForceDynamicNumberOfGCThreads, false, \
"Force dynamic selection of the number of " \
"parallel threads parallel gc will use to aid debugging") \
\
product(size_t, HeapSizePerGCThread, ScaleForWordSize(64*M), \
"Size of heap (bytes) per GC thread used in calculating the " \
"number of GC threads") \
range((uintx)os::vm_page_size(), max_uintx) \
\
product(bool, TraceDynamicGCThreads, false, \
"Trace the dynamic GC thread usage") \
\
develop(bool, ParallelOldGCSplitALot, false, \
"Provoke splitting (copying data from a young gen space to " \
"multiple destination spaces)") \
\
develop(uintx, ParallelOldGCSplitInterval, 3, \
"How often to provoke splitting a young gen space") \
range(0, max_uintx) \
\
product(uint, ConcGCThreads, 0, \
"Number of threads concurrent gc will use") \
\
product(size_t, YoungPLABSize, 4096, \
"Size of young gen promotion LAB's (in HeapWords)") \
constraint(YoungPLABSizeConstraintFunc,AfterMemoryInit) \
\
product(size_t, OldPLABSize, 1024, \
"Size of old gen promotion LAB's (in HeapWords), or Number \
of blocks to attempt to claim when refilling CMS LAB's") \
\
product(uintx, GCTaskTimeStampEntries, 200, \
"Number of time stamp entries per gc worker thread") \
range(1, max_uintx) \
\
product(bool, AlwaysTenure, false, \
"Always tenure objects in eden (ParallelGC only)") \
\
product(bool, NeverTenure, false, \
"Never tenure objects in eden, may tenure on overflow " \
"(ParallelGC only)") \
\
product(bool, ScavengeBeforeFullGC, true, \
"Scavenge youngest generation before each full GC.") \
\
develop(bool, ScavengeWithObjectsInToSpace, false, \
"Allow scavenges to occur when to-space contains objects") \
\
product(bool, UseConcMarkSweepGC, false, \
"Use Concurrent Mark-Sweep GC in the old generation") \
\
product(bool, ExplicitGCInvokesConcurrent, false, \
"A System.gc() request invokes a concurrent collection; " \
"(effective only when using concurrent collectors)") \
\
product(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false, \
"A System.gc() request invokes a concurrent collection and " \
"also unloads classes during such a concurrent gc cycle " \
"(effective only when UseConcMarkSweepGC)") \
\
product(bool, GCLockerInvokesConcurrent, false, \
"The exit of a JNI critical section necessitating a scavenge, " \
"also kicks off a background concurrent collection") \
\
product(uintx, GCLockerEdenExpansionPercent, 5, \
"How much the GC can expand the eden by while the GC locker " \
"is active (as a percentage)") \
range(0, 100) \
\
diagnostic(uintx, GCLockerRetryAllocationCount, 2, \
"Number of times to retry allocations when " \
"blocked by the GC locker") \
\
develop(bool, UseCMSAdaptiveFreeLists, true, \
"Use adaptive free lists in the CMS generation") \
\
develop(bool, UseAsyncConcMarkSweepGC, true, \
"Use Asynchronous Concurrent Mark-Sweep GC in the old generation")\
\
product(bool, UseCMSBestFit, true, \
"Use CMS best fit allocation strategy") \
\
product(bool, UseParNewGC, false, \
"Use parallel threads in the new generation") \
\
product(bool, PrintTaskqueue, false, \
"Print taskqueue statistics for parallel collectors") \
\
product(bool, PrintTerminationStats, false, \
"Print termination statistics for parallel collectors") \
\
product(uintx, ParallelGCBufferWastePct, 10, \
"Wasted fraction of parallel allocation buffer") \
range(0, 100) \
\
product(uintx, TargetPLABWastePct, 10, \
"Target wasted space in last buffer as percent of overall " \
"allocation") \
range(1, 100) \
\
product(uintx, PLABWeight, 75, \
"Percentage (0-100) used to weight the current sample when " \
"computing exponentially decaying average for ResizePLAB") \
range(0, 100) \
\
product(bool, ResizePLAB, true, \
"Dynamically resize (survivor space) promotion LAB's") \
\
product(bool, PrintPLAB, false, \
"Print (survivor space) promotion LAB's sizing decisions") \
\
product(intx, ParGCArrayScanChunk, 50, \
"Scan a subset of object array and push remainder, if array is " \
"bigger than this") \
range(1, max_intx) \
\
product(bool, ParGCUseLocalOverflow, false, \
"Instead of a global overflow list, use local overflow stacks") \
\
product(bool, ParGCTrimOverflow, true, \
"Eagerly trim the local overflow lists " \
"(when ParGCUseLocalOverflow)") \
\
notproduct(bool, ParGCWorkQueueOverflowALot, false, \
"Simulate work queue overflow in ParNew") \
\
notproduct(uintx, ParGCWorkQueueOverflowInterval, 1000, \
"An `interval' counter that determines how frequently " \
"we simulate overflow; a smaller number increases frequency") \
\
product(uintx, ParGCDesiredObjsFromOverflowList, 20, \
"The desired number of objects to claim from the overflow list") \
\
diagnostic(uintx, ParGCStridesPerThread, 2, \
"The number of strides per worker thread that we divide up the " \
"card table scanning work into") \
range(1, max_uintx) \
\
diagnostic(intx, ParGCCardsPerStrideChunk, 256, \
"The number of cards in each chunk of the parallel chunks used " \
"during card table scanning") \
range(1, max_intx) \
\
product(uintx, OldPLABWeight, 50, \
"Percentage (0-100) used to weight the current sample when " \
"computing exponentially decaying average for resizing " \
"OldPLABSize") \
range(0, 100) \
\
product(bool, ResizeOldPLAB, true, \
"Dynamically resize (old gen) promotion LAB's") \
\
product(bool, PrintOldPLAB, false, \
"Print (old gen) promotion LAB's sizing decisions") \
\
product(size_t, CMSOldPLABMax, 1024, \
"Maximum size of CMS gen promotion LAB caches per worker " \
"per block size") \
range(1, max_uintx) \
\
product(size_t, CMSOldPLABMin, 16, \
"Minimum size of CMS gen promotion LAB caches per worker " \
"per block size") \
range(1, max_uintx) \
constraint(CMSOldPLABMinConstraintFunc,AfterErgo) \
\
product(uintx, CMSOldPLABNumRefills, 4, \
"Nominal number of refills of CMS gen promotion LAB cache " \
"per worker per block size") \
range(1, max_uintx) \
\
product(bool, CMSOldPLABResizeQuicker, false, \
"React on-the-fly during a scavenge to a sudden " \
"change in block demand rate") \
\
product(uintx, CMSOldPLABToleranceFactor, 4, \
"The tolerance of the phase-change detector for on-the-fly " \
"PLAB resizing during a scavenge") \
range(1, max_uintx) \
\
product(uintx, CMSOldPLABReactivityFactor, 2, \
"The gain in the feedback loop for on-the-fly PLAB resizing " \
"during a scavenge") \
\
product(bool, AlwaysPreTouch, false, \
"Force all freshly committed pages to be pre-touched") \
\
product_pd(size_t, CMSYoungGenPerWorker, \
"The maximum size of young gen chosen by default per GC worker " \
"thread available") \
range(1, max_uintx) \
\
product(uintx, CMSIncrementalSafetyFactor, 10, \
"Percentage (0-100) used to add conservatism when computing the " \
"duty cycle") \
range(0, 100) \
\
product(uintx, CMSExpAvgFactor, 50, \
"Percentage (0-100) used to weight the current sample when " \
"computing exponential averages for CMS statistics") \
range(0, 100) \
\
product(uintx, CMS_FLSWeight, 75, \
"Percentage (0-100) used to weight the current sample when " \
"computing exponentially decaying averages for CMS FLS " \
"statistics") \
range(0, 100) \
\
product(uintx, CMS_FLSPadding, 1, \
"The multiple of deviation from mean to use for buffering " \
"against volatility in free list demand") \
\
product(uintx, FLSCoalescePolicy, 2, \
"CMS: aggressiveness level for coalescing, increasing " \
"from 0 to 4") \
range(0, 4) \
\
product(bool, FLSAlwaysCoalesceLarge, false, \
"CMS: larger free blocks are always available for coalescing") \
\
product(double, FLSLargestBlockCoalesceProximity, 0.99, \
"CMS: the smaller the percentage the greater the coalescing " \
"force") \
\
product(double, CMSSmallCoalSurplusPercent, 1.05, \
"CMS: the factor by which to inflate estimated demand of small " \
"block sizes to prevent coalescing with an adjoining block") \
\
product(double, CMSLargeCoalSurplusPercent, 0.95, \
"CMS: the factor by which to inflate estimated demand of large " \
"block sizes to prevent coalescing with an adjoining block") \
\
product(double, CMSSmallSplitSurplusPercent, 1.10, \
"CMS: the factor by which to inflate estimated demand of small " \
"block sizes to prevent splitting to supply demand for smaller " \
"blocks") \
\
product(double, CMSLargeSplitSurplusPercent, 1.00, \
"CMS: the factor by which to inflate estimated demand of large " \
"block sizes to prevent splitting to supply demand for smaller " \
"blocks") \
\
product(bool, CMSExtrapolateSweep, false, \
"CMS: cushion for block demand during sweep") \
\
product(uintx, CMS_SweepWeight, 75, \
"Percentage (0-100) used to weight the current sample when " \
"computing exponentially decaying average for inter-sweep " \
"duration") \
range(0, 100) \
\
product(uintx, CMS_SweepPadding, 1, \
"The multiple of deviation from mean to use for buffering " \
"against volatility in inter-sweep duration") \
\
product(uintx, CMS_SweepTimerThresholdMillis, 10, \
"Skip block flux-rate sampling for an epoch unless inter-sweep " \
"duration exceeds this threshold in milliseconds") \
\
product(bool, CMSClassUnloadingEnabled, true, \
"Whether class unloading enabled when using CMS GC") \
\
product(uintx, CMSClassUnloadingMaxInterval, 0, \
"When CMS class unloading is enabled, the maximum CMS cycle " \
"count for which classes may not be unloaded") \
\
develop(intx, CMSDictionaryChoice, 0, \
"Use BinaryTreeDictionary as default in the CMS generation") \
\
product(uintx, CMSIndexedFreeListReplenish, 4, \
"Replenish an indexed free list with this number of chunks") \
\
product(bool, CMSReplenishIntermediate, true, \
"Replenish all intermediate free-list caches") \
\
product(bool, CMSSplitIndexedFreeListBlocks, true, \
"When satisfying batched demand, split blocks from the " \
"IndexedFreeList whose size is a multiple of requested size") \
\
product(bool, CMSLoopWarn, false, \
"Warn in case of excessive CMS looping") \
\
develop(bool, CMSOverflowEarlyRestoration, false, \
"Restore preserved marks early") \
\
product(size_t, MarkStackSize, NOT_LP64(32*K) LP64_ONLY(4*M), \
"Size of marking stack") \
\
product(size_t, MarkStackSizeMax, NOT_LP64(4*M) LP64_ONLY(512*M), \
"Maximum size of marking stack") \
range(1, (max_jint - 1)) \
\
notproduct(bool, CMSMarkStackOverflowALot, false, \
"Simulate frequent marking stack / work queue overflow") \
\
notproduct(uintx, CMSMarkStackOverflowInterval, 1000, \
"An \"interval\" counter that determines how frequently " \
"to simulate overflow; a smaller number increases frequency") \
\
product(uintx, CMSMaxAbortablePrecleanLoops, 0, \
"Maximum number of abortable preclean iterations, if > 0") \
\
product(intx, CMSMaxAbortablePrecleanTime, 5000, \
"Maximum time in abortable preclean (in milliseconds)") \
\
product(uintx, CMSAbortablePrecleanMinWorkPerIteration, 100, \
"Nominal minimum work per abortable preclean iteration") \
\
manageable(intx, CMSAbortablePrecleanWaitMillis, 100, \
"Time that we sleep between iterations when not given " \
"enough work per iteration") \
\
product(size_t, CMSRescanMultiple, 32, \
"Size (in cards) of CMS parallel rescan task") \
range(1, max_uintx) \
\
product(size_t, CMSConcMarkMultiple, 32, \
"Size (in cards) of CMS concurrent MT marking task") \
range(1, max_uintx) \
\
product(bool, CMSAbortSemantics, false, \
"Whether abort-on-overflow semantics is implemented") \
\
product(bool, CMSParallelInitialMarkEnabled, true, \
"Use the parallel initial mark.") \
\
product(bool, CMSParallelRemarkEnabled, true, \
"Whether parallel remark enabled (only if ParNewGC)") \
\
product(bool, CMSParallelSurvivorRemarkEnabled, true, \
"Whether parallel remark of survivor space " \
"enabled (effective only if CMSParallelRemarkEnabled)") \
\
product(bool, CMSPLABRecordAlways, true, \
"Always record survivor space PLAB boundaries (effective only " \
"if CMSParallelSurvivorRemarkEnabled)") \
\
product(bool, CMSEdenChunksRecordAlways, true, \
"Always record eden chunks used for the parallel initial mark " \
"or remark of eden") \
\
product(bool, CMSPrintEdenSurvivorChunks, false, \
"Print the eden and the survivor chunks used for the parallel " \
"initial mark or remark of the eden/survivor spaces") \
\
product(bool, CMSConcurrentMTEnabled, true, \
"Whether multi-threaded concurrent work enabled " \
"(effective only if ParNewGC)") \
\
product(bool, CMSPrecleaningEnabled, true, \
"Whether concurrent precleaning enabled") \
\
product(uintx, CMSPrecleanIter, 3, \
"Maximum number of precleaning iteration passes") \
range(0, 9) \
\
product(uintx, CMSPrecleanDenominator, 3, \
"CMSPrecleanNumerator:CMSPrecleanDenominator yields convergence " \
"ratio") \
range(1, max_uintx) \
constraint(CMSPrecleanDenominatorConstraintFunc,AfterErgo) \
\
product(uintx, CMSPrecleanNumerator, 2, \
"CMSPrecleanNumerator:CMSPrecleanDenominator yields convergence " \
"ratio") \
range(0, max_uintx-1) \
constraint(CMSPrecleanNumeratorConstraintFunc,AfterErgo) \
\
product(bool, CMSPrecleanRefLists1, true, \
"Preclean ref lists during (initial) preclean phase") \
\
product(bool, CMSPrecleanRefLists2, false, \
"Preclean ref lists during abortable preclean phase") \
\
product(bool, CMSPrecleanSurvivors1, false, \
"Preclean survivors during (initial) preclean phase") \
\
product(bool, CMSPrecleanSurvivors2, true, \
"Preclean survivors during abortable preclean phase") \
\
product(uintx, CMSPrecleanThreshold, 1000, \
"Do not iterate again if number of dirty cards is less than this")\
range(100, max_uintx) \
\
product(bool, CMSCleanOnEnter, true, \
"Clean-on-enter optimization for reducing number of dirty cards") \
\
product(uintx, CMSRemarkVerifyVariant, 1, \
"Choose variant (1,2) of verification following remark") \
range(1, 2) \
\
product(size_t, CMSScheduleRemarkEdenSizeThreshold, 2*M, \
"If Eden size is below this, do not try to schedule remark") \
\
product(uintx, CMSScheduleRemarkEdenPenetration, 50, \
"The Eden occupancy percentage (0-100) at which " \
"to try and schedule remark pause") \
range(0, 100) \
\
product(uintx, CMSScheduleRemarkSamplingRatio, 5, \
"Start sampling eden top at least before young gen " \
"occupancy reaches 1/<ratio> of the size at which " \
"we plan to schedule remark") \
range(1, max_uintx) \
\
product(uintx, CMSSamplingGrain, 16*K, \
"The minimum distance between eden samples for CMS (see above)") \
range(1, max_uintx) \
\
product(bool, CMSScavengeBeforeRemark, false, \
"Attempt scavenge before the CMS remark step") \
\
develop(bool, CMSTraceSweeper, false, \
"Trace some actions of the CMS sweeper") \
\
product(uintx, CMSWorkQueueDrainThreshold, 10, \
"Don't drain below this size per parallel worker/thief") \
\
manageable(intx, CMSWaitDuration, 2000, \
"Time in milliseconds that CMS thread waits for young GC") \
\
develop(uintx, CMSCheckInterval, 1000, \
"Interval in milliseconds that CMS thread checks if it " \
"should start a collection cycle") \
\
product(bool, CMSYield, true, \
"Yield between steps of CMS") \
\
product(size_t, CMSBitMapYieldQuantum, 10*M, \
"Bitmap operations should process at most this many bits " \
"between yields") \
range(1, max_uintx) \
\
product(bool, CMSDumpAtPromotionFailure, false, \
"Dump useful information about the state of the CMS old " \
"generation upon a promotion failure") \
\
product(bool, CMSPrintChunksInDump, false, \
"In a dump enabled by CMSDumpAtPromotionFailure, include " \
"more detailed information about the free chunks") \
\
product(bool, CMSPrintObjectsInDump, false, \
"In a dump enabled by CMSDumpAtPromotionFailure, include " \
"more detailed information about the allocated objects") \
\
diagnostic(bool, FLSVerifyAllHeapReferences, false, \
"Verify that all references across the FLS boundary " \
"are to valid objects") \
\
diagnostic(bool, FLSVerifyLists, false, \
"Do lots of (expensive) FreeListSpace verification") \
\
diagnostic(bool, FLSVerifyIndexTable, false, \
"Do lots of (expensive) FLS index table verification") \
\
develop(bool, FLSVerifyDictionary, false, \
"Do lots of (expensive) FLS dictionary verification") \
\
develop(bool, VerifyBlockOffsetArray, false, \
"Do (expensive) block offset array verification") \
\
diagnostic(bool, BlockOffsetArrayUseUnallocatedBlock, false, \
"Maintain _unallocated_block in BlockOffsetArray " \
"(currently applicable only to CMS collector)") \
\
develop(bool, TraceCMSState, false, \
"Trace the state of the CMS collection") \
\
product(intx, RefDiscoveryPolicy, 0, \
"Select type of reference discovery policy: " \
"reference-based(0) or referent-based(1)") \
range(ReferenceProcessor::DiscoveryPolicyMin, \
ReferenceProcessor::DiscoveryPolicyMax) \
\
product(bool, ParallelRefProcEnabled, false, \
"Enable parallel reference processing whenever possible") \
\
product(bool, ParallelRefProcBalancingEnabled, true, \
"Enable balancing of reference processing queues") \
\
product(uintx, CMSTriggerRatio, 80, \
"Percentage of MinHeapFreeRatio in CMS generation that is " \
"allocated before a CMS collection cycle commences") \
range(0, 100) \
\
product(uintx, CMSBootstrapOccupancy, 50, \
"Percentage CMS generation occupancy at which to " \
"initiate CMS collection for bootstrapping collection stats") \
range(0, 100) \
\
product(intx, CMSInitiatingOccupancyFraction, -1, \
"Percentage CMS generation occupancy to start a CMS collection " \
"cycle. A negative value means that CMSTriggerRatio is used") \
range(min_intx, 100) \
\
product(uintx, InitiatingHeapOccupancyPercent, 45, \
"Percentage of the (entire) heap occupancy to start a " \
"concurrent GC cycle. It is used by GCs that trigger a " \
"concurrent GC cycle based on the occupancy of the entire heap, " \
"not just one of the generations (e.g., G1). A value of 0 " \
"denotes 'do constant GC cycles'.") \
range(0, 100) \
\
manageable(intx, CMSTriggerInterval, -1, \
"Commence a CMS collection cycle (at least) every so many " \
"milliseconds (0 permanently, -1 disabled)") \
range(-1, max_intx) \
\
product(bool, UseCMSInitiatingOccupancyOnly, false, \
"Only use occupancy as a criterion for starting a CMS collection")\
\
product(uintx, CMSIsTooFullPercentage, 98, \
"An absolute ceiling above which CMS will always consider the " \
"unloading of classes when class unloading is enabled") \
range(0, 100) \
\
develop(bool, CMSTestInFreeList, false, \
"Check if the coalesced range is already in the " \
"free lists as claimed") \
\
notproduct(bool, CMSVerifyReturnedBytes, false, \
"Check that all the garbage collected was returned to the " \
"free lists") \
\
notproduct(bool, ScavengeALot, false, \
"Force scavenge at every Nth exit from the runtime system " \
"(N=ScavengeALotInterval)") \
\
develop(bool, FullGCALot, false, \
"Force full gc at every Nth exit from the runtime system " \
"(N=FullGCALotInterval)") \
\
notproduct(bool, GCALotAtAllSafepoints, false, \
"Enforce ScavengeALot/GCALot at all potential safepoints") \
\
product(bool, PrintPromotionFailure, false, \
"Print additional diagnostic information following " \
"promotion failure") \
\
notproduct(bool, PromotionFailureALot, false, \
"Use promotion failure handling on every youngest generation " \
"collection") \
\
develop(uintx, PromotionFailureALotCount, 1000, \
"Number of promotion failures occurring at PLAB " \
"refill attempts (ParNew) or promotion attempts " \
"(other young collectors)") \
\
develop(uintx, PromotionFailureALotInterval, 5, \
"Total collections between promotion failures a lot") \
\
experimental(uintx, WorkStealingSleepMillis, 1, \
"Sleep time when sleep is used for yields") \
\
experimental(uintx, WorkStealingYieldsBeforeSleep, 5000, \
"Number of yields before a sleep is done during work stealing") \
\
experimental(uintx, WorkStealingHardSpins, 4096, \
"Number of iterations in a spin loop between checks on " \
"time out of hard spin") \
\
experimental(uintx, WorkStealingSpinToYieldRatio, 10, \
"Ratio of hard spins to calls to yield") \
\
develop(uintx, ObjArrayMarkingStride, 512, \
"Number of object array elements to push onto the marking stack " \
"before pushing a continuation entry") \
\
develop(bool, MetadataAllocationFailALot, false, \
"Fail metadata allocations at intervals controlled by " \
"MetadataAllocationFailALotInterval") \
\
develop(uintx, MetadataAllocationFailALotInterval, 1000, \
"Metadata allocation failure a lot interval") \
\
develop(bool, TraceMetadataChunkAllocation, false, \
"Trace chunk metadata allocations") \
\
product(bool, TraceMetadataHumongousAllocation, false, \
"Trace humongous metadata allocations") \
\
develop(bool, TraceMetavirtualspaceAllocation, false, \
"Trace virtual space metadata allocations") \
\
notproduct(bool, ExecuteInternalVMTests, false, \
"Enable execution of internal VM tests") \
\
notproduct(bool, VerboseInternalVMTests, false, \
"Turn on logging for internal VM tests.") \
\
product_pd(bool, UseTLAB, "Use thread-local object allocation") \
\
product_pd(bool, ResizeTLAB, \
"Dynamically resize TLAB size for threads") \
\
product(bool, ZeroTLAB, false, \
"Zero out the newly created TLAB") \
\
product(bool, FastTLABRefill, true, \
"Use fast TLAB refill code") \
\
product(bool, PrintTLAB, false, \
"Print various TLAB related information") \
\
product(bool, TLABStats, true, \
"Provide more detailed and expensive TLAB statistics " \
"(with PrintTLAB)") \
\
product_pd(bool, NeverActAsServerClassMachine, \
"Never act like a server-class machine") \
\
product(bool, AlwaysActAsServerClassMachine, false, \
"Always act like a server-class machine") \
\
product_pd(uint64_t, MaxRAM, \
"Real memory size (in bytes) used to set maximum heap size") \
\
product(size_t, ErgoHeapSizeLimit, 0, \
"Maximum ergonomically set heap size (in bytes); zero means use " \
"MaxRAM / MaxRAMFraction") \
\
product(uintx, MaxRAMFraction, 4, \
"Maximum fraction (1/n) of real memory used for maximum heap " \
"size") \
range(1, max_uintx) \
\
product(uintx, DefaultMaxRAMFraction, 4, \
"Maximum fraction (1/n) of real memory used for maximum heap " \
"size; deprecated: to be renamed to MaxRAMFraction") \
range(1, max_uintx) \
\
product(uintx, MinRAMFraction, 2, \
"Minimum fraction (1/n) of real memory used for maximum heap " \
"size on systems with small physical memory size") \
range(1, max_uintx) \
\
product(uintx, InitialRAMFraction, 64, \
"Fraction (1/n) of real memory used for initial heap size") \
range(1, max_uintx) \
\
develop(uintx, MaxVirtMemFraction, 2, \
"Maximum fraction (1/n) of virtual memory used for ergonomically "\
"determining maximum heap size") \
\
product(bool, UseAutoGCSelectPolicy, false, \
"Use automatic collection selection policy") \
\
product(uintx, AutoGCSelectPauseMillis, 5000, \
"Automatic GC selection pause threshold in milliseconds") \
\
product(bool, UseAdaptiveSizePolicy, true, \
"Use adaptive generation sizing policies") \
\
product(bool, UsePSAdaptiveSurvivorSizePolicy, true, \
"Use adaptive survivor sizing policies") \
\
product(bool, UseAdaptiveGenerationSizePolicyAtMinorCollection, true, \
"Use adaptive young-old sizing policies at minor collections") \
\
product(bool, UseAdaptiveGenerationSizePolicyAtMajorCollection, true, \
"Use adaptive young-old sizing policies at major collections") \
\
product(bool, UseAdaptiveSizePolicyWithSystemGC, false, \
"Include statistics from System.gc() for adaptive size policy") \
\
product(bool, UseAdaptiveGCBoundary, false, \
"Allow young-old boundary to move") \
\
develop(bool, TraceAdaptiveGCBoundary, false, \
"Trace young-old boundary moves") \
\
develop(intx, PSAdaptiveSizePolicyResizeVirtualSpaceAlot, -1, \
"Resize the virtual spaces of the young or old generations") \
\
product(uintx, AdaptiveSizeThroughPutPolicy, 0, \
"Policy for changing generation size for throughput goals") \
\
develop(bool, PSAdjustTenuredGenForMinorPause, false, \
"Adjust tenured generation to achieve a minor pause goal") \
\
develop(bool, PSAdjustYoungGenForMajorPause, false, \
"Adjust young generation to achieve a major pause goal") \
\
product(uintx, AdaptiveSizePolicyInitializingSteps, 20, \
"Number of steps where heuristics is used before data is used") \
\
develop(uintx, AdaptiveSizePolicyReadyThreshold, 5, \
"Number of collections before the adaptive sizing is started") \
\
product(uintx, AdaptiveSizePolicyOutputInterval, 0, \
"Collection interval for printing information; zero means never") \
\
product(bool, UseAdaptiveSizePolicyFootprintGoal, true, \
"Use adaptive minimum footprint as a goal") \
\
product(uintx, AdaptiveSizePolicyWeight, 10, \
"Weight given to exponential resizing, between 0 and 100") \
range(0, 100) \
\
product(uintx, AdaptiveTimeWeight, 25, \
"Weight given to time in adaptive policy, between 0 and 100") \
range(0, 100) \
\
product(uintx, PausePadding, 1, \
"How much buffer to keep for pause time") \
\
product(uintx, PromotedPadding, 3, \
"How much buffer to keep for promotion failure") \
\
product(uintx, SurvivorPadding, 3, \
"How much buffer to keep for survivor overflow") \
\
product(uintx, ThresholdTolerance, 10, \
"Allowed collection cost difference between generations") \
range(0, 100) \
\
product(uintx, AdaptiveSizePolicyCollectionCostMargin, 50, \
"If collection costs are within margin, reduce both by full " \
"delta") \
\
product(uintx, YoungGenerationSizeIncrement, 20, \
"Adaptive size percentage change in young generation") \
range(0, 100) \
\
product(uintx, YoungGenerationSizeSupplement, 80, \
"Supplement to YoungedGenerationSizeIncrement used at startup") \
range(0, 100) \
\
product(uintx, YoungGenerationSizeSupplementDecay, 8, \
"Decay factor to YoungedGenerationSizeSupplement") \
range(1, max_uintx) \
\
product(uintx, TenuredGenerationSizeIncrement, 20, \
"Adaptive size percentage change in tenured generation") \
range(0, 100) \
\
product(uintx, TenuredGenerationSizeSupplement, 80, \
"Supplement to TenuredGenerationSizeIncrement used at startup") \
range(0, 100) \
\
product(uintx, TenuredGenerationSizeSupplementDecay, 2, \
"Decay factor to TenuredGenerationSizeIncrement") \
range(1, max_uintx) \
\
product(uintx, MaxGCPauseMillis, max_uintx, \
"Adaptive size policy maximum GC pause time goal in millisecond, "\
"or (G1 Only) the maximum GC time per MMU time slice") \
\
product(uintx, GCPauseIntervalMillis, 0, \
"Time slice for MMU specification") \
\
product(uintx, MaxGCMinorPauseMillis, max_uintx, \
"Adaptive size policy maximum GC minor pause time goal " \
"in millisecond") \
\
product(uintx, GCTimeRatio, 99, \
"Adaptive size policy application time to GC time ratio") \
\
product(uintx, AdaptiveSizeDecrementScaleFactor, 4, \
"Adaptive size scale down factor for shrinking") \
range(1, max_uintx) \
\
product(bool, UseAdaptiveSizeDecayMajorGCCost, true, \
"Adaptive size decays the major cost for long major intervals") \
\
product(uintx, AdaptiveSizeMajorGCDecayTimeScale, 10, \
"Time scale over which major costs decay") \
\
product(uintx, MinSurvivorRatio, 3, \
"Minimum ratio of young generation/survivor space size") \
\
product(uintx, InitialSurvivorRatio, 8, \
"Initial ratio of young generation/survivor space size") \
\
product(size_t, BaseFootPrintEstimate, 256*M, \
"Estimate of footprint other than Java Heap") \
\
product(bool, UseGCOverheadLimit, true, \
"Use policy to limit of proportion of time spent in GC " \
"before an OutOfMemory error is thrown") \
\
product(uintx, GCTimeLimit, 98, \
"Limit of the proportion of time spent in GC before " \
"an OutOfMemoryError is thrown (used with GCHeapFreeLimit)") \
range(0, 100) \
\
product(uintx, GCHeapFreeLimit, 2, \
"Minimum percentage of free space after a full GC before an " \
"OutOfMemoryError is thrown (used with GCTimeLimit)") \
range(0, 100) \
\
develop(uintx, AdaptiveSizePolicyGCTimeLimitThreshold, 5, \
"Number of consecutive collections before gc time limit fires") \
\
product(bool, PrintAdaptiveSizePolicy, false, \
"Print information about AdaptiveSizePolicy") \
\
product(intx, PrefetchCopyIntervalInBytes, -1, \
"How far ahead to prefetch destination area (<= 0 means off)") \
\
product(intx, PrefetchScanIntervalInBytes, -1, \
"How far ahead to prefetch scan area (<= 0 means off)") \
\
product(intx, PrefetchFieldsAhead, -1, \
"How many fields ahead to prefetch in oop scan (<= 0 means off)") \
\
diagnostic(bool, VerifySilently, false, \
"Do not print the verification progress") \
\
diagnostic(bool, VerifyDuringStartup, false, \
"Verify memory system before executing any Java code " \
"during VM initialization") \
\
diagnostic(bool, VerifyBeforeExit, trueInDebug, \
"Verify system before exiting") \
\
diagnostic(bool, VerifyBeforeGC, false, \
"Verify memory system before GC") \
\
diagnostic(bool, VerifyAfterGC, false, \
"Verify memory system after GC") \
\
diagnostic(bool, VerifyDuringGC, false, \
"Verify memory system during GC (between phases)") \
\
diagnostic(bool, GCParallelVerificationEnabled, true, \
"Enable parallel memory system verification") \
\
diagnostic(bool, DeferInitialCardMark, false, \
"When +ReduceInitialCardMarks, explicitly defer any that " \
"may arise from new_pre_store_barrier") \
\
product(bool, UseCondCardMark, false, \
"Check for already marked card before updating card table") \
\
diagnostic(bool, VerifyRememberedSets, false, \
"Verify GC remembered sets") \
\
diagnostic(bool, VerifyObjectStartArray, true, \
"Verify GC object start array if verify before/after") \
\
product(bool, DisableExplicitGC, false, \
"Ignore calls to System.gc()") \
\
notproduct(bool, CheckMemoryInitialization, false, \
"Check memory initialization") \
\
diagnostic(bool, BindCMSThreadToCPU, false, \
"Bind CMS Thread to CPU if possible") \
\
diagnostic(uintx, CPUForCMSThread, 0, \
"When BindCMSThreadToCPU is true, the CPU to bind CMS thread to") \
\
product(bool, BindGCTaskThreadsToCPUs, false, \
"Bind GCTaskThreads to CPUs if possible") \
\
product(bool, UseGCTaskAffinity, false, \
"Use worker affinity when asking for GCTasks") \
\
product(uintx, ProcessDistributionStride, 4, \
"Stride through processors when distributing processes") \
\
product(uintx, CMSCoordinatorYieldSleepCount, 10, \
"Number of times the coordinator GC thread will sleep while " \
"yielding before giving up and resuming GC") \
\
product(uintx, CMSYieldSleepCount, 0, \
"Number of times a GC thread (minus the coordinator) " \
"will sleep while yielding before giving up and resuming GC") \
\
/* gc tracing */ \
manageable(bool, PrintGC, false, \
"Print message at garbage collection") \
\
manageable(bool, PrintGCDetails, false, \
"Print more details at garbage collection") \
\
manageable(bool, PrintGCDateStamps, false, \
"Print date stamps at garbage collection") \
\
manageable(bool, PrintGCTimeStamps, false, \
"Print timestamps at garbage collection") \
\
manageable(bool, PrintGCID, true, \
"Print an identifier for each garbage collection") \
\
product(bool, PrintGCTaskTimeStamps, false, \
"Print timestamps for individual gc worker thread tasks") \
\
develop(intx, ConcGCYieldTimeout, 0, \
"If non-zero, assert that GC threads yield within this " \
"number of milliseconds") \
\
product(bool, PrintReferenceGC, false, \
"Print times spent handling reference objects during GC " \
"(enabled only when PrintGCDetails)") \
\
develop(bool, TraceReferenceGC, false, \
"Trace handling of soft/weak/final/phantom references") \
\
develop(bool, TraceFinalizerRegistration, false, \
"Trace registration of final references") \
\
notproduct(bool, TraceScavenge, false, \
"Trace scavenge") \
\
product(bool, IgnoreEmptyClassPaths, false, \
"Ignore empty path elements in -classpath") \
\
product(bool, TraceClassPaths, false, \
"Trace processing of class paths") \
\
product_rw(bool, TraceClassLoading, false, \
"Trace all classes loaded") \
\
product(bool, TraceClassLoadingPreorder, false, \
"Trace all classes loaded in order referenced (not loaded)") \
\
product_rw(bool, TraceClassUnloading, false, \
"Trace unloading of classes") \
\
product_rw(bool, TraceLoaderConstraints, false, \
"Trace loader constraints") \
\
develop(bool, TraceClassLoaderData, false, \
"Trace class loader loader_data lifetime") \
\
product(size_t, InitialBootClassLoaderMetaspaceSize, \
NOT_LP64(2200*K) LP64_ONLY(4*M), \
"Initial size of the boot class loader data metaspace") \
\
product(bool, TraceYoungGenTime, false, \
"Trace accumulated time for young collection") \
\
product(bool, TraceOldGenTime, false, \
"Trace accumulated time for old collection") \
\
product(bool, PrintTenuringDistribution, false, \
"Print tenuring age information") \
\
product_rw(bool, PrintHeapAtGC, false, \
"Print heap layout before and after each GC") \
\
product_rw(bool, PrintHeapAtGCExtended, false, \
"Print extended information about the layout of the heap " \
"when -XX:+PrintHeapAtGC is set") \
\
product(bool, PrintHeapAtSIGBREAK, true, \
"Print heap layout in response to SIGBREAK") \
\
manageable(bool, PrintClassHistogramBeforeFullGC, false, \
"Print a class histogram before any major stop-world GC") \
\
manageable(bool, PrintClassHistogramAfterFullGC, false, \
"Print a class histogram after any major stop-world GC") \
\
manageable(bool, PrintClassHistogram, false, \
"Print a histogram of class instances") \
\
develop(bool, TraceWorkGang, false, \
"Trace activities of work gangs") \
\
product(bool, TraceParallelOldGCTasks, false, \
"Trace multithreaded GC activity") \
\
develop(bool, TraceBlockOffsetTable, false, \
"Print BlockOffsetTable maps") \
\
develop(bool, TraceCardTableModRefBS, false, \
"Print CardTableModRefBS maps") \
\
develop(bool, TraceGCTaskManager, false, \
"Trace actions of the GC task manager") \
\
develop(bool, TraceGCTaskQueue, false, \
"Trace actions of the GC task queues") \
\
diagnostic(bool, TraceGCTaskThread, false, \
"Trace actions of the GC task threads") \
\
product(bool, PrintParallelOldGCPhaseTimes, false, \
"Print the time taken by each phase in ParallelOldGC " \
"(PrintGCDetails must also be enabled)") \
\
develop(bool, TraceParallelOldGCMarkingPhase, false, \
"Trace marking phase in ParallelOldGC") \
\
develop(bool, TraceParallelOldGCSummaryPhase, false, \
"Trace summary phase in ParallelOldGC") \
\
develop(bool, TraceParallelOldGCCompactionPhase, false, \
"Trace compaction phase in ParallelOldGC") \
\
develop(bool, TraceParallelOldGCDensePrefix, false, \
"Trace dense prefix computation for ParallelOldGC") \
\
develop(bool, IgnoreLibthreadGPFault, false, \
"Suppress workaround for libthread GP fault") \
\
product(bool, PrintJNIGCStalls, false, \
"Print diagnostic message when GC is stalled " \
"by JNI critical section") \
\
experimental(double, ObjectCountCutOffPercent, 0.5, \
"The percentage of the used heap that the instances of a class " \
"must occupy for the class to generate a trace event") \
\
/* GC log rotation setting */ \
\
product(bool, UseGCLogFileRotation, false, \
"Rotate gclog files (for long running applications). It requires "\
"-Xloggc:<filename>") \
\
product(uintx, NumberOfGCLogFiles, 0, \
"Number of gclog files in rotation " \
"(default: 0, no rotation)") \
\
product(size_t, GCLogFileSize, 8*K, \
"GC log file size, requires UseGCLogFileRotation. " \
"Set to 0 to only trigger rotation via jcmd") \
\
/* JVMTI heap profiling */ \
\
diagnostic(bool, TraceJVMTIObjectTagging, false, \
"Trace JVMTI object tagging calls") \
\
diagnostic(bool, VerifyBeforeIteration, false, \
"Verify memory system before JVMTI iteration") \
\
/* compiler interface */ \
\
develop(bool, CIPrintCompilerName, false, \
"when CIPrint is active, print the name of the active compiler") \
\
diagnostic(bool, CIPrintCompileQueue, false, \
"display the contents of the compile queue whenever a " \
"compilation is enqueued") \
\
develop(bool, CIPrintRequests, false, \
"display every request for compilation") \
\
product(bool, CITime, false, \
"collect timing information for compilation") \
\
develop(bool, CITimeVerbose, false, \
"be more verbose in compilation timings") \
\
develop(bool, CITimeEach, false, \
"display timing information after each successful compilation") \
\
develop(bool, CICountOSR, false, \
"use a separate counter when assigning ids to osr compilations") \
\
develop(bool, CICompileNatives, true, \
"compile native methods if supported by the compiler") \
\
develop_pd(bool, CICompileOSR, \
"compile on stack replacement methods if supported by the " \
"compiler") \
\
develop(bool, CIPrintMethodCodes, false, \
"print method bytecodes of the compiled code") \
\
develop(bool, CIPrintTypeFlow, false, \
"print the results of ciTypeFlow analysis") \
\
develop(bool, CITraceTypeFlow, false, \
"detailed per-bytecode tracing of ciTypeFlow analysis") \
\
develop(intx, OSROnlyBCI, -1, \
"OSR only at this bci. Negative values mean exclude that bci") \
\
/* compiler */ \
\
/* notice: the max range value here is max_jint, not max_intx */ \
/* because of overflow issue */ \
product(intx, CICompilerCount, CI_COMPILER_COUNT, \
"Number of compiler threads to run") \
range(0, max_jint) \
constraint(CICompilerCountConstraintFunc, AtParse) \
\
product(intx, CompilationPolicyChoice, 0, \
"which compilation policy (0-3)") \
range(0, 3) \
\
develop(bool, UseStackBanging, true, \
"use stack banging for stack overflow checks (required for " \
"proper StackOverflow handling; disable only to measure cost " \
"of stackbanging)") \
\
develop(bool, UseStrictFP, true, \
"use strict fp if modifier strictfp is set") \
\
develop(bool, GenerateSynchronizationCode, true, \
"generate locking/unlocking code for synchronized methods and " \
"monitors") \
\
develop(bool, GenerateCompilerNullChecks, true, \
"Generate explicit null checks for loads/stores/calls") \
\
develop(bool, GenerateRangeChecks, true, \
"Generate range checks for array accesses") \
\
develop_pd(bool, ImplicitNullChecks, \
"Generate code for implicit null checks") \
\
product_pd(bool, TrapBasedNullChecks, \
"Generate code for null checks that uses a cmp and trap " \
"instruction raising SIGTRAP. This is only used if an access to" \
"null (+offset) will not raise a SIGSEGV, i.e.," \
"ImplicitNullChecks don't work (PPC64).") \
\
product(bool, PrintSafepointStatistics, false, \
"Print statistics about safepoint synchronization") \
\
product(intx, PrintSafepointStatisticsCount, 300, \
"Total number of safepoint statistics collected " \
"before printing them out") \
\
product(intx, PrintSafepointStatisticsTimeout, -1, \
"Print safepoint statistics only when safepoint takes " \
"more than PrintSafepointSatisticsTimeout in millis") \
\
product(bool, TraceSafepointCleanupTime, false, \
"Print the break down of clean up tasks performed during " \
"safepoint") \
\
product(bool, Inline, true, \
"Enable inlining") \
\
product(bool, ClipInlining, true, \
"Clip inlining if aggregate method exceeds DesiredMethodLimit") \
\
develop(bool, UseCHA, true, \
"Enable CHA") \
\
product(bool, UseTypeProfile, true, \
"Check interpreter profile for historically monomorphic calls") \
\
diagnostic(bool, PrintInlining, false, \
"Print inlining optimizations") \
\
product(bool, UsePopCountInstruction, false, \
"Use population count instruction") \
\
develop(bool, EagerInitialization, false, \
"Eagerly initialize classes if possible") \
\
diagnostic(bool, LogTouchedMethods, false, \
"Log methods which have been ever touched in runtime") \
\
diagnostic(bool, PrintTouchedMethodsAtExit, false, \
"Print all methods that have been ever touched in runtime") \
\
develop(bool, TraceMethodReplacement, false, \
"Print when methods are replaced do to recompilation") \
\
develop(bool, PrintMethodFlushing, false, \
"Print the nmethods being flushed") \
\
diagnostic(bool, PrintMethodFlushingStatistics, false, \
"print statistics about method flushing") \
\
diagnostic(intx, HotMethodDetectionLimit, 100000, \
"Number of compiled code invocations after which " \
"the method is considered as hot by the flusher") \
\
diagnostic(intx, MinPassesBeforeFlush, 10, \
"Minimum number of sweeper passes before an nmethod " \
"can be flushed") \
\
product(bool, UseCodeAging, true, \
"Insert counter to detect warm methods") \
\
diagnostic(bool, StressCodeAging, false, \
"Start with counters compiled in") \
\
develop(bool, UseRelocIndex, false, \
"Use an index to speed random access to relocations") \
\
develop(bool, StressCodeBuffers, false, \
"Exercise code buffer expansion and other rare state changes") \
\
diagnostic(bool, DebugNonSafepoints, trueInDebug, \
"Generate extra debugging information for non-safepoints in " \
"nmethods") \
\
product(bool, PrintVMOptions, false, \
"Print flags that appeared on the command line") \
\
product(bool, IgnoreUnrecognizedVMOptions, false, \
"Ignore unrecognized VM options") \
\
product(bool, PrintCommandLineFlags, false, \
"Print flags specified on command line or set by ergonomics") \
\
product(bool, PrintFlagsInitial, false, \
"Print all VM flags before argument processing and exit VM") \
\
product(bool, PrintFlagsFinal, false, \
"Print all VM flags after argument and ergonomic processing") \
\
notproduct(bool, PrintFlagsWithComments, false, \
"Print all VM flags with default values and descriptions and " \
"exit") \
\
product(bool, PrintFlagsRanges, false, \
"Print VM flags and their ranges and exit VM") \
\
diagnostic(bool, SerializeVMOutput, true, \
"Use a mutex to serialize output to tty and LogFile") \
\
diagnostic(bool, DisplayVMOutput, true, \
"Display all VM output on the tty, independently of LogVMOutput") \
\
diagnostic(bool, LogVMOutput, false, \
"Save VM output to LogFile") \
\
diagnostic(ccstr, LogFile, NULL, \
"If LogVMOutput or LogCompilation is on, save VM output to " \
"this file [default: ./hotspot_pid%p.log] (%p replaced with pid)")\
\
product(ccstr, ErrorFile, NULL, \
"If an error occurs, save the error data to this file " \
"[default: ./hs_err_pid%p.log] (%p replaced with pid)") \
\
product(bool, DisplayVMOutputToStderr, false, \
"If DisplayVMOutput is true, display all VM output to stderr") \
\
product(bool, DisplayVMOutputToStdout, false, \
"If DisplayVMOutput is true, display all VM output to stdout") \
\
product(bool, UseHeavyMonitors, false, \
"use heavyweight instead of lightweight Java monitors") \
\
product(bool, PrintStringTableStatistics, false, \
"print statistics about the StringTable and SymbolTable") \
\
diagnostic(bool, VerifyStringTableAtExit, false, \
"verify StringTable contents at exit") \
\
notproduct(bool, PrintSymbolTableSizeHistogram, false, \
"print histogram of the symbol table") \
\
notproduct(bool, ExitVMOnVerifyError, false, \
"standard exit from VM if bytecode verify error " \
"(only in debug mode)") \
\
notproduct(ccstr, AbortVMOnException, NULL, \
"Call fatal if this exception is thrown. Example: " \
"java -XX:AbortVMOnException=java.lang.NullPointerException Foo") \
\
notproduct(ccstr, AbortVMOnExceptionMessage, NULL, \
"Call fatal if the exception pointed by AbortVMOnException " \
"has this message") \
\
develop(bool, DebugVtables, false, \
"add debugging code to vtable dispatch") \
\
develop(bool, PrintVtables, false, \
"print vtables when printing klass") \
\
notproduct(bool, PrintVtableStats, false, \
"print vtables stats at end of run") \
\
develop(bool, TraceCreateZombies, false, \
"trace creation of zombie nmethods") \
\
notproduct(bool, IgnoreLockingAssertions, false, \
"disable locking assertions (for speed)") \
\
product(bool, RangeCheckElimination, true, \
"Eliminate range checks") \
\
develop_pd(bool, UncommonNullCast, \
"track occurrences of null in casts; adjust compiler tactics") \
\
develop(bool, TypeProfileCasts, true, \
"treat casts like calls for purposes of type profiling") \
\
develop(bool, DelayCompilationDuringStartup, true, \
"Delay invoking the compiler until main application class is " \
"loaded") \
\
develop(bool, CompileTheWorld, false, \
"Compile all methods in all classes in bootstrap class path " \
"(stress test)") \
\
develop(bool, CompileTheWorldPreloadClasses, true, \
"Preload all classes used by a class before start loading") \
\
notproduct(intx, CompileTheWorldSafepointInterval, 100, \
"Force a safepoint every n compiles so sweeper can keep up") \
\
develop(bool, FillDelaySlots, true, \
"Fill delay slots (on SPARC only)") \
\
develop(bool, TimeLivenessAnalysis, false, \
"Time computation of bytecode liveness analysis") \
\
develop(bool, TraceLivenessGen, false, \
"Trace the generation of liveness analysis information") \
\
notproduct(bool, TraceLivenessQuery, false, \
"Trace queries of liveness analysis information") \
\
notproduct(bool, CollectIndexSetStatistics, false, \
"Collect information about IndexSets") \
\
develop(bool, UseLoopSafepoints, true, \
"Generate Safepoint nodes in every loop") \
\
develop(intx, FastAllocateSizeLimit, 128*K, \
/* Note: This value is zero mod 1<<13 for a cheap sparc set. */ \
"Inline allocations larger than this in doublewords must go slow")\
\
product(bool, AggressiveOpts, false, \
"Enable aggressive optimizations - see arguments.cpp") \
\
product_pd(uintx, TypeProfileLevel, \
"=XYZ, with Z: Type profiling of arguments at call; " \
"Y: Type profiling of return value at call; " \
"X: Type profiling of parameters to methods; " \
"X, Y and Z in 0=off ; 1=jsr292 only; 2=all methods") \
\
product(intx, TypeProfileArgsLimit, 2, \
"max number of call arguments to consider for type profiling") \
\
product(intx, TypeProfileParmsLimit, 2, \
"max number of incoming parameters to consider for type profiling"\
", -1 for all") \
\
/* statistics */ \
develop(bool, CountCompiledCalls, false, \
"Count method invocations") \
\
notproduct(bool, CountRuntimeCalls, false, \
"Count VM runtime calls") \
\
develop(bool, CountJNICalls, false, \
"Count jni method invocations") \
\
notproduct(bool, CountJVMCalls, false, \
"Count jvm method invocations") \
\
notproduct(bool, CountRemovableExceptions, false, \
"Count exceptions that could be replaced by branches due to " \
"inlining") \
\
notproduct(bool, ICMissHistogram, false, \
"Produce histogram of IC misses") \
\
notproduct(bool, PrintClassStatistics, false, \
"Print class statistics at end of run") \
\
notproduct(bool, PrintMethodStatistics, false, \
"Print method statistics at end of run") \
\
/* interpreter */ \
develop(bool, ClearInterpreterLocals, false, \
"Always clear local variables of interpreter activations upon " \
"entry") \
\
product_pd(bool, RewriteBytecodes, \
"Allow rewriting of bytecodes (bytecodes are not immutable)") \
\
product_pd(bool, RewriteFrequentPairs, \
"Rewrite frequently used bytecode pairs into a single bytecode") \
\
diagnostic(bool, PrintInterpreter, false, \
"Print the generated interpreter code") \
\
product(bool, UseInterpreter, true, \
"Use interpreter for non-compiled methods") \
\
develop(bool, UseFastSignatureHandlers, true, \
"Use fast signature handlers for native calls") \
\
product(bool, UseLoopCounter, true, \
"Increment invocation counter on backward branch") \
\
product_pd(bool, UseOnStackReplacement, \
"Use on stack replacement, calls runtime if invoc. counter " \
"overflows in loop") \
\
notproduct(bool, TraceOnStackReplacement, false, \
"Trace on stack replacement") \
\
product_pd(bool, PreferInterpreterNativeStubs, \
"Use always interpreter stubs for native methods invoked via " \
"interpreter") \
\
develop(bool, CountBytecodes, false, \
"Count number of bytecodes executed") \
\
develop(bool, PrintBytecodeHistogram, false, \
"Print histogram of the executed bytecodes") \
\
develop(bool, PrintBytecodePairHistogram, false, \
"Print histogram of the executed bytecode pairs") \
\
diagnostic(bool, PrintSignatureHandlers, false, \
"Print code generated for native method signature handlers") \
\
develop(bool, VerifyOops, false, \
"Do plausibility checks for oops") \
\
develop(bool, CheckUnhandledOops, false, \
"Check for unhandled oops in VM code") \
\
develop(bool, VerifyJNIFields, trueInDebug, \
"Verify jfieldIDs for instance fields") \
\
notproduct(bool, VerifyJNIEnvThread, false, \
"Verify JNIEnv.thread == Thread::current() when entering VM " \
"from JNI") \
\
develop(bool, VerifyFPU, false, \
"Verify FPU state (check for NaN's, etc.)") \
\
develop(bool, VerifyThread, false, \
"Watch the thread register for corruption (SPARC only)") \
\
develop(bool, VerifyActivationFrameSize, false, \
"Verify that activation frame didn't become smaller than its " \
"minimal size") \
\
develop(bool, TraceFrequencyInlining, false, \
"Trace frequency based inlining") \
\
develop_pd(bool, InlineIntrinsics, \
"Inline intrinsics that can be statically resolved") \
\
product_pd(bool, ProfileInterpreter, \
"Profile at the bytecode level during interpretation") \
\
develop(bool, TraceProfileInterpreter, false, \
"Trace profiling at the bytecode level during interpretation. " \
"This outputs the profiling information collected to improve " \
"jit compilation.") \
\
develop_pd(bool, ProfileTraps, \
"Profile deoptimization traps at the bytecode level") \
\
product(intx, ProfileMaturityPercentage, 20, \
"number of method invocations/branches (expressed as % of " \
"CompileThreshold) before using the method's profile") \
range(0, 100) \
\
diagnostic(bool, PrintMethodData, false, \
"Print the results of +ProfileInterpreter at end of run") \
\
develop(bool, VerifyDataPointer, trueInDebug, \
"Verify the method data pointer during interpreter profiling") \
\
develop(bool, VerifyCompiledCode, false, \
"Include miscellaneous runtime verifications in nmethod code; " \
"default off because it disturbs nmethod size heuristics") \
\
notproduct(bool, CrashGCForDumpingJavaThread, false, \
"Manually make GC thread crash then dump java stack trace; " \
"Test only") \
\
/* compilation */ \
product(bool, UseCompiler, true, \
"Use Just-In-Time compilation") \
\
develop(bool, TraceCompilationPolicy, false, \
"Trace compilation policy") \
\
develop(bool, TimeCompilationPolicy, false, \
"Time the compilation policy") \
\
product(bool, UseCounterDecay, true, \
"Adjust recompilation counters") \
\
develop(intx, CounterHalfLifeTime, 30, \
"Half-life time of invocation counters (in seconds)") \
\
develop(intx, CounterDecayMinIntervalLength, 500, \
"The minimum interval (in milliseconds) between invocation of " \
"CounterDecay") \
\
product(bool, AlwaysCompileLoopMethods, false, \
"When using recompilation, never interpret methods " \
"containing loops") \
\
product(bool, DontCompileHugeMethods, true, \
"Do not compile methods > HugeMethodLimit") \
\
/* Bytecode escape analysis estimation. */ \
product(bool, EstimateArgEscape, true, \
"Analyze bytecodes to estimate escape state of arguments") \
\
product(intx, BCEATraceLevel, 0, \
"How much tracing to do of bytecode escape analysis estimates") \
\
product(intx, MaxBCEAEstimateLevel, 5, \
"Maximum number of nested calls that are analyzed by BC EA") \
\
product(intx, MaxBCEAEstimateSize, 150, \
"Maximum bytecode size of a method to be analyzed by BC EA") \
\
product(intx, AllocatePrefetchStyle, 1, \
"0 = no prefetch, " \
"1 = prefetch instructions for each allocation, " \
"2 = use TLAB watermark to gate allocation prefetch, " \
"3 = use BIS instruction on Sparc for allocation prefetch") \
range(0, 3) \
\
product(intx, AllocatePrefetchDistance, -1, \
"Distance to prefetch ahead of allocation pointer") \
\
product(intx, AllocatePrefetchLines, 3, \
"Number of lines to prefetch ahead of array allocation pointer") \
\
product(intx, AllocateInstancePrefetchLines, 1, \
"Number of lines to prefetch ahead of instance allocation " \
"pointer") \
\
product(intx, AllocatePrefetchStepSize, 16, \
"Step size in bytes of sequential prefetch instructions") \
\
product(intx, AllocatePrefetchInstr, 0, \
"Prefetch instruction to prefetch ahead of allocation pointer") \
\
/* deoptimization */ \
develop(bool, TraceDeoptimization, false, \
"Trace deoptimization") \
\
develop(bool, DebugDeoptimization, false, \
"Tracing various information while debugging deoptimization") \
\
product(intx, SelfDestructTimer, 0, \
"Will cause VM to terminate after a given time (in minutes) " \
"(0 means off)") \
\
product(intx, MaxJavaStackTraceDepth, 1024, \
"The maximum number of lines in the stack trace for Java " \
"exceptions (0 means all)") \
\
NOT_EMBEDDED(diagnostic(intx, GuaranteedSafepointInterval, 1000, \
"Guarantee a safepoint (at least) every so many milliseconds " \
"(0 means none)")) \
\
EMBEDDED_ONLY(product(intx, GuaranteedSafepointInterval, 0, \
"Guarantee a safepoint (at least) every so many milliseconds " \
"(0 means none)")) \
\
product(intx, SafepointTimeoutDelay, 10000, \
"Delay in milliseconds for option SafepointTimeout") \
\
product(intx, NmethodSweepActivity, 10, \
"Removes cold nmethods from code cache if > 0. Higher values " \
"result in more aggressive sweeping") \
range(0, 2000) \
\
notproduct(bool, LogSweeper, false, \
"Keep a ring buffer of sweeper activity") \
\
notproduct(intx, SweeperLogEntries, 1024, \
"Number of records in the ring buffer of sweeper activity") \
\
notproduct(intx, MemProfilingInterval, 500, \
"Time between each invocation of the MemProfiler") \
\
develop(intx, MallocCatchPtr, -1, \
"Hit breakpoint when mallocing/freeing this pointer") \
\
notproduct(ccstrlist, SuppressErrorAt, "", \
"List of assertions (file:line) to muzzle") \
\
notproduct(size_t, HandleAllocationLimit, 1024, \
"Threshold for HandleMark allocation when +TraceHandleAllocation "\
"is used") \
\
develop(size_t, TotalHandleAllocationLimit, 1024, \
"Threshold for total handle allocation when " \
"+TraceHandleAllocation is used") \
\
develop(intx, StackPrintLimit, 100, \
"number of stack frames to print in VM-level stack dump") \
\
notproduct(intx, MaxElementPrintSize, 256, \
"maximum number of elements to print") \
\
notproduct(intx, MaxSubklassPrintSize, 4, \
"maximum number of subklasses to print when printing klass") \
\
product(intx, MaxInlineLevel, 9, \
"maximum number of nested calls that are inlined") \
\
product(intx, MaxRecursiveInlineLevel, 1, \
"maximum number of nested recursive calls that are inlined") \
\
develop(intx, MaxForceInlineLevel, 100, \
"maximum number of nested calls that are forced for inlining " \
"(using CompilerOracle or marked w/ @ForceInline)") \
\
product_pd(intx, InlineSmallCode, \
"Only inline already compiled methods if their code size is " \
"less than this") \
\
product(intx, MaxInlineSize, 35, \
"The maximum bytecode size of a method to be inlined") \
\
product_pd(intx, FreqInlineSize, \
"The maximum bytecode size of a frequent method to be inlined") \
\
product(intx, MaxTrivialSize, 6, \
"The maximum bytecode size of a trivial method to be inlined") \
\
product(intx, MinInliningThreshold, 250, \
"The minimum invocation count a method needs to have to be " \
"inlined") \
\
develop(intx, MethodHistogramCutoff, 100, \
"The cutoff value for method invocation histogram (+CountCalls)") \
\
develop(intx, ProfilerNumberOfInterpretedMethods, 25, \
"Number of interpreted methods to show in profile") \
\
develop(intx, ProfilerNumberOfCompiledMethods, 25, \
"Number of compiled methods to show in profile") \
\
develop(intx, ProfilerNumberOfStubMethods, 25, \
"Number of stub methods to show in profile") \
\
develop(intx, ProfilerNumberOfRuntimeStubNodes, 25, \
"Number of runtime stub nodes to show in profile") \
\
product(intx, ProfileIntervalsTicks, 100, \
"Number of ticks between printing of interval profile " \
"(+ProfileIntervals)") \
\
notproduct(intx, ScavengeALotInterval, 1, \
"Interval between which scavenge will occur with +ScavengeALot") \
\
notproduct(intx, FullGCALotInterval, 1, \
"Interval between which full gc will occur with +FullGCALot") \
\
notproduct(intx, FullGCALotStart, 0, \
"For which invocation to start FullGCAlot") \
\
notproduct(intx, FullGCALotDummies, 32*K, \
"Dummy object allocated with +FullGCALot, forcing all objects " \
"to move") \
\
develop(intx, DontYieldALotInterval, 10, \
"Interval between which yields will be dropped (milliseconds)") \
\
develop(intx, MinSleepInterval, 1, \
"Minimum sleep() interval (milliseconds) when " \
"ConvertSleepToYield is off (used for Solaris)") \
\
develop(intx, ProfilerPCTickThreshold, 15, \
"Number of ticks in a PC buckets to be a hotspot") \
\
notproduct(intx, DeoptimizeALotInterval, 5, \
"Number of exits until DeoptimizeALot kicks in") \
\
notproduct(intx, ZombieALotInterval, 5, \
"Number of exits until ZombieALot kicks in") \
\
diagnostic(intx, MallocVerifyInterval, 0, \
"If non-zero, verify C heap after every N calls to " \
"malloc/realloc/free") \
\
diagnostic(intx, MallocVerifyStart, 0, \
"If non-zero, start verifying C heap after Nth call to " \
"malloc/realloc/free") \
\
diagnostic(uintx, MallocMaxTestWords, 0, \
"If non-zero, maximum number of words that malloc/realloc can " \
"allocate (for testing only)") \
\
product(intx, TypeProfileWidth, 2, \
"Number of receiver types to record in call/cast profile") \
\
develop(intx, BciProfileWidth, 2, \
"Number of return bci's to record in ret profile") \
\
product(intx, PerMethodRecompilationCutoff, 400, \
"After recompiling N times, stay in the interpreter (-1=>'Inf')") \
range(-1, max_intx) \
\
product(intx, PerBytecodeRecompilationCutoff, 200, \
"Per-BCI limit on repeated recompilation (-1=>'Inf')") \
range(-1, max_intx) \
\
product(intx, PerMethodTrapLimit, 100, \
"Limit on traps (of one kind) in a method (includes inlines)") \
\
experimental(intx, PerMethodSpecTrapLimit, 5000, \
"Limit on speculative traps (of one kind) in a method " \
"(includes inlines)") \
\
product(intx, PerBytecodeTrapLimit, 4, \
"Limit on traps (of one kind) at a particular BCI") \
\
experimental(intx, SpecTrapLimitExtraEntries, 3, \
"Extra method data trap entries for speculation") \
\
develop(intx, InlineFrequencyRatio, 20, \
"Ratio of call site execution to caller method invocation") \
\
develop_pd(intx, InlineFrequencyCount, \
"Count of call site execution necessary to trigger frequent " \
"inlining") \
\
develop(intx, InlineThrowCount, 50, \
"Force inlining of interpreted methods that throw this often") \
\
develop(intx, InlineThrowMaxSize, 200, \
"Force inlining of throwing methods smaller than this") \
\
develop(intx, ProfilerNodeSize, 1024, \
"Size in K to allocate for the Profile Nodes of each thread") \
\
/* gc parameters */ \
product(size_t, InitialHeapSize, 0, \
"Initial heap size (in bytes); zero means use ergonomics") \
\
product(size_t, MaxHeapSize, ScaleForWordSize(96*M), \
"Maximum heap size (in bytes)") \
\
product(size_t, OldSize, ScaleForWordSize(4*M), \
"Initial tenured generation size (in bytes)") \
\
product(size_t, NewSize, ScaleForWordSize(1*M), \
"Initial new generation size (in bytes)") \
\
product(size_t, MaxNewSize, max_uintx, \
"Maximum new generation size (in bytes), max_uintx means set " \
"ergonomically") \
\
product(size_t, PretenureSizeThreshold, 0, \
"Maximum size in bytes of objects allocated in DefNew " \
"generation; zero means no maximum") \
\
product(size_t, TLABSize, 0, \
"Starting TLAB size (in bytes); zero means set ergonomically") \
\
product(size_t, MinTLABSize, 2*K, \
"Minimum allowed TLAB size (in bytes)") \
range(1, max_uintx) \
\
product(uintx, TLABAllocationWeight, 35, \
"Allocation averaging weight") \
range(0, 100) \
\
/* Limit the lower bound of this flag to 1 as it is used */ \
/* in a division expression. */ \
product(uintx, TLABWasteTargetPercent, 1, \
"Percentage of Eden that can be wasted") \
range(1, 100) \
\
product(uintx, TLABRefillWasteFraction, 64, \
"Maximum TLAB waste at a refill (internal fragmentation)") \
range(1, max_uintx) \
\
product(uintx, TLABWasteIncrement, 4, \
"Increment allowed waste at slow allocation") \
\
product(uintx, SurvivorRatio, 8, \
"Ratio of eden/survivor space size") \
\
product(uintx, NewRatio, 2, \
"Ratio of old/new generation sizes") \
\
product_pd(size_t, NewSizeThreadIncrease, \
"Additional size added to desired new generation size per " \
"non-daemon thread (in bytes)") \
\
product_pd(size_t, MetaspaceSize, \
"Initial size of Metaspaces (in bytes)") \
\
product(size_t, MaxMetaspaceSize, max_uintx, \
"Maximum size of Metaspaces (in bytes)") \
\
product(size_t, CompressedClassSpaceSize, 1*G, \
"Maximum size of class area in Metaspace when compressed " \
"class pointers are used") \
range(1*M, 3*G) \
\
manageable(uintx, MinHeapFreeRatio, 40, \
"The minimum percentage of heap free after GC to avoid expansion."\
" For most GCs this applies to the old generation. In G1 and" \
" ParallelGC it applies to the whole heap.") \
range(0, 100) \
constraint(MinHeapFreeRatioConstraintFunc,AfterErgo) \
\
manageable(uintx, MaxHeapFreeRatio, 70, \
"The maximum percentage of heap free after GC to avoid shrinking."\
" For most GCs this applies to the old generation. In G1 and" \
" ParallelGC it applies to the whole heap.") \
range(0, 100) \
constraint(MaxHeapFreeRatioConstraintFunc,AfterErgo) \
\
product(intx, SoftRefLRUPolicyMSPerMB, 1000, \
"Number of milliseconds per MB of free space in the heap") \
\
product(size_t, MinHeapDeltaBytes, ScaleForWordSize(128*K), \
"The minimum change in heap space due to GC (in bytes)") \
\
product(size_t, MinMetaspaceExpansion, ScaleForWordSize(256*K), \
"The minimum expansion of Metaspace (in bytes)") \
\
product(uintx, MaxMetaspaceFreeRatio, 70, \
"The maximum percentage of Metaspace free after GC to avoid " \
"shrinking") \
range(0, 100) \
constraint(MaxMetaspaceFreeRatioConstraintFunc,AfterErgo) \
\
product(uintx, MinMetaspaceFreeRatio, 40, \
"The minimum percentage of Metaspace free after GC to avoid " \
"expansion") \
range(0, 99) \
constraint(MinMetaspaceFreeRatioConstraintFunc,AfterErgo) \
\
product(size_t, MaxMetaspaceExpansion, ScaleForWordSize(4*M), \
"The maximum expansion of Metaspace without full GC (in bytes)") \
\
product(uintx, QueuedAllocationWarningCount, 0, \
"Number of times an allocation that queues behind a GC " \
"will retry before printing a warning") \
\
diagnostic(uintx, VerifyGCStartAt, 0, \
"GC invoke count where +VerifyBefore/AfterGC kicks in") \
\
diagnostic(intx, VerifyGCLevel, 0, \
"Generation level at which to start +VerifyBefore/AfterGC") \
\
product(uintx, MaxTenuringThreshold, 15, \
"Maximum value for tenuring threshold") \
range(0, markOopDesc::max_age + 1) \
constraint(MaxTenuringThresholdConstraintFunc,AfterErgo) \
\
product(uintx, InitialTenuringThreshold, 7, \
"Initial value for tenuring threshold") \
range(0, markOopDesc::max_age + 1) \
constraint(InitialTenuringThresholdConstraintFunc,AfterErgo) \
\
product(uintx, TargetSurvivorRatio, 50, \
"Desired percentage of survivor space used after scavenge") \
range(0, 100) \
\
product(uintx, MarkSweepDeadRatio, 5, \
"Percentage (0-100) of the old gen allowed as dead wood. " \
"Serial mark sweep treats this as both the minimum and maximum " \
"value. " \
"CMS uses this value only if it falls back to mark sweep. " \
"Par compact uses a variable scale based on the density of the " \
"generation and treats this as the maximum value when the heap " \
"is either completely full or completely empty. Par compact " \
"also has a smaller default value; see arguments.cpp.") \
range(0, 100) \
\
product(uintx, MarkSweepAlwaysCompactCount, 4, \
"How often should we fully compact the heap (ignoring the dead " \
"space parameters)") \
range(1, max_uintx) \
\
product(intx, PrintCMSStatistics, 0, \
"Statistics for CMS") \
\
product(bool, PrintCMSInitiationStatistics, false, \
"Statistics for initiating a CMS collection") \
\
product(intx, PrintFLSStatistics, 0, \
"Statistics for CMS' FreeListSpace") \
\
product(intx, PrintFLSCensus, 0, \
"Census for CMS' FreeListSpace") \
\
develop(uintx, GCExpandToAllocateDelayMillis, 0, \
"Delay between expansion and allocation (in milliseconds)") \
\
develop(uintx, GCWorkerDelayMillis, 0, \
"Delay in scheduling GC workers (in milliseconds)") \
\
product(intx, DeferThrSuspendLoopCount, 4000, \
"(Unstable) Number of times to iterate in safepoint loop " \
"before blocking VM threads ") \
\
product(intx, DeferPollingPageLoopCount, -1, \
"(Unsafe,Unstable) Number of iterations in safepoint loop " \
"before changing safepoint polling page to RO ") \
\
product(intx, SafepointSpinBeforeYield, 2000, "(Unstable)") \
\
product(bool, PSChunkLargeArrays, true, \
"Process large arrays in chunks") \
\
product(uintx, GCDrainStackTargetSize, 64, \
"Number of entries we will try to leave on the stack " \
"during parallel gc") \
\
/* stack parameters */ \
product_pd(intx, StackYellowPages, \
"Number of yellow zone (recoverable overflows) pages") \
range(1, max_intx) \
\
product_pd(intx, StackRedPages, \
"Number of red zone (unrecoverable overflows) pages") \
range(1, max_intx) \
\
/* greater stack shadow pages can't generate instruction to bang stack */ \
product_pd(intx, StackShadowPages, \
"Number of shadow zone (for overflow checking) pages " \
"this should exceed the depth of the VM and native call stack") \
range(1, 50) \
\
product_pd(intx, ThreadStackSize, \
"Thread Stack Size (in Kbytes)") \
\
product_pd(intx, VMThreadStackSize, \
"Non-Java Thread Stack Size (in Kbytes)") \
\
product_pd(intx, CompilerThreadStackSize, \
"Compiler Thread Stack Size (in Kbytes)") \
\
develop_pd(size_t, JVMInvokeMethodSlack, \
"Stack space (bytes) required for JVM_InvokeMethod to complete") \
\
/* code cache parameters */ \
/* ppc64/tiered compilation has large code-entry alignment. */ \
develop(uintx, CodeCacheSegmentSize, 64 PPC64_ONLY(+64) NOT_PPC64(TIERED_ONLY(+64)),\
"Code cache segment size (in bytes) - smallest unit of " \
"allocation") \
range(1, 1024) \
\
develop_pd(intx, CodeEntryAlignment, \
"Code entry alignment for generated code (in bytes)") \
\
product_pd(intx, OptoLoopAlignment, \
"Align inner loops to zero relative to this modulus") \
\
product_pd(uintx, InitialCodeCacheSize, \
"Initial code cache size (in bytes)") \
\
develop_pd(uintx, CodeCacheMinimumUseSpace, \
"Minimum code cache size (in bytes) required to start VM.") \
\
product(bool, SegmentedCodeCache, false, \
"Use a segmented code cache") \
\
product_pd(uintx, ReservedCodeCacheSize, \
"Reserved code cache size (in bytes) - maximum code cache size") \
\
product_pd(uintx, NonProfiledCodeHeapSize, \
"Size of code heap with non-profiled methods (in bytes)") \
\
product_pd(uintx, ProfiledCodeHeapSize, \
"Size of code heap with profiled methods (in bytes)") \
\
product_pd(uintx, NonNMethodCodeHeapSize, \
"Size of code heap with non-nmethods (in bytes)") \
\
product_pd(uintx, CodeCacheExpansionSize, \
"Code cache expansion size (in bytes)") \
\
develop_pd(uintx, CodeCacheMinBlockLength, \
"Minimum number of segments in a code cache block") \
range(1, 100) \
\
notproduct(bool, ExitOnFullCodeCache, false, \
"Exit the VM if we fill the code cache") \
\
product(bool, UseCodeCacheFlushing, true, \
"Remove cold/old nmethods from the code cache") \
\
product(uintx, StartAggressiveSweepingAt, 10, \
"Start aggressive sweeping if X[%] of the code cache is free." \
"Segmented code cache: X[%] of the non-profiled heap." \
"Non-segmented code cache: X[%] of the total code cache") \
range(0, 100) \
\
/* interpreter debugging */ \
develop(intx, BinarySwitchThreshold, 5, \
"Minimal number of lookupswitch entries for rewriting to binary " \
"switch") \
\
develop(intx, StopInterpreterAt, 0, \
"Stop interpreter execution at specified bytecode number") \
\
develop(intx, TraceBytecodesAt, 0, \
"Trace bytecodes starting with specified bytecode number") \
\
/* compiler interface */ \
develop(intx, CIStart, 0, \
"The id of the first compilation to permit") \
\
develop(intx, CIStop, max_jint, \
"The id of the last compilation to permit") \
\
develop(intx, CIStartOSR, 0, \
"The id of the first osr compilation to permit " \
"(CICountOSR must be on)") \
\
develop(intx, CIStopOSR, max_jint, \
"The id of the last osr compilation to permit " \
"(CICountOSR must be on)") \
\
develop(intx, CIBreakAtOSR, -1, \
"The id of osr compilation to break at") \
\
develop(intx, CIBreakAt, -1, \
"The id of compilation to break at") \
\
product(ccstrlist, CompileOnly, "", \
"List of methods (pkg/class.name) to restrict compilation to") \
\
product(ccstr, CompileCommandFile, NULL, \
"Read compiler commands from this file [.hotspot_compiler]") \
\
product(ccstrlist, CompileCommand, "", \
"Prepend to .hotspot_compiler; e.g. log,java/lang/String.<init>") \
\
develop(bool, ReplayCompiles, false, \
"Enable replay of compilations from ReplayDataFile") \
\
product(ccstr, ReplayDataFile, NULL, \
"File containing compilation replay information" \
"[default: ./replay_pid%p.log] (%p replaced with pid)") \
\
product(ccstr, InlineDataFile, NULL, \
"File containing inlining replay information" \
"[default: ./inline_pid%p.log] (%p replaced with pid)") \
\
develop(intx, ReplaySuppressInitializers, 2, \
"Control handling of class initialization during replay: " \
"0 - don't do anything special; " \
"1 - treat all class initializers as empty; " \
"2 - treat class initializers for application classes as empty; " \
"3 - allow all class initializers to run during bootstrap but " \
" pretend they are empty after starting replay") \
range(0, 3) \
\
develop(bool, ReplayIgnoreInitErrors, false, \
"Ignore exceptions thrown during initialization for replay") \
\
product(bool, DumpReplayDataOnError, true, \
"Record replay data for crashing compiler threads") \
\
product(bool, CICompilerCountPerCPU, false, \
"1 compiler thread for log(N CPUs)") \
\
develop(intx, CIFireOOMAt, -1, \
"Fire OutOfMemoryErrors throughout CI for testing the compiler " \
"(non-negative value throws OOM after this many CI accesses " \
"in each compile)") \
notproduct(intx, CICrashAt, -1, \
"id of compilation to trigger assert in compiler thread for " \
"the purpose of testing, e.g. generation of replay data") \
notproduct(bool, CIObjectFactoryVerify, false, \
"enable potentially expensive verification in ciObjectFactory") \
\
/* Priorities */ \
product_pd(bool, UseThreadPriorities, "Use native thread priorities") \
\
product(intx, ThreadPriorityPolicy, 0, \
"0 : Normal. "\
" VM chooses priorities that are appropriate for normal "\
" applications. On Solaris NORM_PRIORITY and above are mapped "\
" to normal native priority. Java priorities below " \
" NORM_PRIORITY map to lower native priority values. On "\
" Windows applications are allowed to use higher native "\
" priorities. However, with ThreadPriorityPolicy=0, VM will "\
" not use the highest possible native priority, "\
" THREAD_PRIORITY_TIME_CRITICAL, as it may interfere with "\
" system threads. On Linux thread priorities are ignored "\
" because the OS does not support static priority in "\
" SCHED_OTHER scheduling class which is the only choice for "\
" non-root, non-realtime applications. "\
"1 : Aggressive. "\
" Java thread priorities map over to the entire range of "\
" native thread priorities. Higher Java thread priorities map "\
" to higher native thread priorities. This policy should be "\
" used with care, as sometimes it can cause performance "\
" degradation in the application and/or the entire system. On "\
" Linux this policy requires root privilege.") \
range(0, 1) \
\
product(bool, ThreadPriorityVerbose, false, \
"Print priority changes") \
\
product(intx, CompilerThreadPriority, -1, \
"The native priority at which compiler threads should run " \
"(-1 means no change)") \
\
product(intx, VMThreadPriority, -1, \
"The native priority at which the VM thread should run " \
"(-1 means no change)") \
\
product(bool, CompilerThreadHintNoPreempt, true, \
"(Solaris only) Give compiler threads an extra quanta") \
\
product(bool, VMThreadHintNoPreempt, false, \
"(Solaris only) Give VM thread an extra quanta") \
\
product(intx, JavaPriority1_To_OSPriority, -1, \
"Map Java priorities to OS priorities") \
\
product(intx, JavaPriority2_To_OSPriority, -1, \
"Map Java priorities to OS priorities") \
\
product(intx, JavaPriority3_To_OSPriority, -1, \
"Map Java priorities to OS priorities") \
\
product(intx, JavaPriority4_To_OSPriority, -1, \
"Map Java priorities to OS priorities") \
\
product(intx, JavaPriority5_To_OSPriority, -1, \
"Map Java priorities to OS priorities") \
\
product(intx, JavaPriority6_To_OSPriority, -1, \
"Map Java priorities to OS priorities") \
\
product(intx, JavaPriority7_To_OSPriority, -1, \
"Map Java priorities to OS priorities") \
\
product(intx, JavaPriority8_To_OSPriority, -1, \
"Map Java priorities to OS priorities") \
\
product(intx, JavaPriority9_To_OSPriority, -1, \
"Map Java priorities to OS priorities") \
\
product(intx, JavaPriority10_To_OSPriority,-1, \
"Map Java priorities to OS priorities") \
\
experimental(bool, UseCriticalJavaThreadPriority, false, \
"Java thread priority 10 maps to critical scheduling priority") \
\
experimental(bool, UseCriticalCompilerThreadPriority, false, \
"Compiler thread(s) run at critical scheduling priority") \
\
experimental(bool, UseCriticalCMSThreadPriority, false, \
"ConcurrentMarkSweep thread runs at critical scheduling priority")\
\
/* compiler debugging */ \
notproduct(intx, CompileTheWorldStartAt, 1, \
"First class to consider when using +CompileTheWorld") \
\
notproduct(intx, CompileTheWorldStopAt, max_jint, \
"Last class to consider when using +CompileTheWorld") \
\
develop(intx, NewCodeParameter, 0, \
"Testing Only: Create a dedicated integer parameter before " \
"putback") \
\
/* new oopmap storage allocation */ \
develop(intx, MinOopMapAllocation, 8, \
"Minimum number of OopMap entries in an OopMapSet") \
\
/* Background Compilation */ \
develop(intx, LongCompileThreshold, 50, \
"Used with +TraceLongCompiles") \
\
/* recompilation */ \
product_pd(intx, CompileThreshold, \
"number of interpreted method invocations before (re-)compiling") \
\
product(double, CompileThresholdScaling, 1.0, \
"Factor to control when first compilation happens " \
"(both with and without tiered compilation): " \
"values greater than 1.0 delay counter overflow, " \
"values between 0 and 1.0 rush counter overflow, " \
"value of 1.0 leaves compilation thresholds unchanged " \
"value of 0.0 is equivalent to -Xint. " \
"" \
"Flag can be set as per-method option. " \
"If a value is specified for a method, compilation thresholds " \
"for that method are scaled by both the value of the global flag "\
"and the value of the per-method flag.") \
\
product(intx, Tier0InvokeNotifyFreqLog, 7, \
"Interpreter (tier 0) invocation notification frequency") \
\
product(intx, Tier2InvokeNotifyFreqLog, 11, \
"C1 without MDO (tier 2) invocation notification frequency") \
\
product(intx, Tier3InvokeNotifyFreqLog, 10, \
"C1 with MDO profiling (tier 3) invocation notification " \
"frequency") \
\
product(intx, Tier23InlineeNotifyFreqLog, 20, \
"Inlinee invocation (tiers 2 and 3) notification frequency") \
\
product(intx, Tier0BackedgeNotifyFreqLog, 10, \
"Interpreter (tier 0) invocation notification frequency") \
\
product(intx, Tier2BackedgeNotifyFreqLog, 14, \
"C1 without MDO (tier 2) invocation notification frequency") \
\
product(intx, Tier3BackedgeNotifyFreqLog, 13, \
"C1 with MDO profiling (tier 3) invocation notification " \
"frequency") \
\
product(intx, Tier2CompileThreshold, 0, \
"threshold at which tier 2 compilation is invoked") \
\
product(intx, Tier2BackEdgeThreshold, 0, \
"Back edge threshold at which tier 2 compilation is invoked") \
\
product(intx, Tier3InvocationThreshold, 200, \
"Compile if number of method invocations crosses this " \
"threshold") \
\
product(intx, Tier3MinInvocationThreshold, 100, \
"Minimum invocation to compile at tier 3") \
\
product(intx, Tier3CompileThreshold, 2000, \
"Threshold at which tier 3 compilation is invoked (invocation " \
"minimum must be satisfied") \
\
product(intx, Tier3BackEdgeThreshold, 60000, \
"Back edge threshold at which tier 3 OSR compilation is invoked") \
\
product(intx, Tier4InvocationThreshold, 5000, \
"Compile if number of method invocations crosses this " \
"threshold") \
\
product(intx, Tier4MinInvocationThreshold, 600, \
"Minimum invocation to compile at tier 4") \
\
product(intx, Tier4CompileThreshold, 15000, \
"Threshold at which tier 4 compilation is invoked (invocation " \
"minimum must be satisfied") \
\
product(intx, Tier4BackEdgeThreshold, 40000, \
"Back edge threshold at which tier 4 OSR compilation is invoked") \
\
product(intx, Tier3DelayOn, 5, \
"If C2 queue size grows over this amount per compiler thread " \
"stop compiling at tier 3 and start compiling at tier 2") \
\
product(intx, Tier3DelayOff, 2, \
"If C2 queue size is less than this amount per compiler thread " \
"allow methods compiled at tier 2 transition to tier 3") \
\
product(intx, Tier3LoadFeedback, 5, \
"Tier 3 thresholds will increase twofold when C1 queue size " \
"reaches this amount per compiler thread") \
\
product(intx, Tier4LoadFeedback, 3, \
"Tier 4 thresholds will increase twofold when C2 queue size " \
"reaches this amount per compiler thread") \
\
product(intx, TieredCompileTaskTimeout, 50, \
"Kill compile task if method was not used within " \
"given timeout in milliseconds") \
\
product(intx, TieredStopAtLevel, 4, \
"Stop at given compilation level") \
\
product(intx, Tier0ProfilingStartPercentage, 200, \
"Start profiling in interpreter if the counters exceed tier 3 " \
"thresholds by the specified percentage") \
\
product(uintx, IncreaseFirstTierCompileThresholdAt, 50, \
"Increase the compile threshold for C1 compilation if the code " \
"cache is filled by the specified percentage") \
range(0, 99) \
\
product(intx, TieredRateUpdateMinTime, 1, \
"Minimum rate sampling interval (in milliseconds)") \
\
product(intx, TieredRateUpdateMaxTime, 25, \
"Maximum rate sampling interval (in milliseconds)") \
\
product_pd(bool, TieredCompilation, \
"Enable tiered compilation") \
\
product(bool, PrintTieredEvents, false, \
"Print tiered events notifications") \
\
product_pd(intx, OnStackReplacePercentage, \
"NON_TIERED number of method invocations/branches (expressed as " \
"% of CompileThreshold) before (re-)compiling OSR code") \
\
product(intx, InterpreterProfilePercentage, 33, \
"NON_TIERED number of method invocations/branches (expressed as " \
"% of CompileThreshold) before profiling in the interpreter") \
range(0, 100) \
\
develop(intx, MaxRecompilationSearchLength, 10, \
"The maximum number of frames to inspect when searching for " \
"recompilee") \
\
develop(intx, MaxInterpretedSearchLength, 3, \
"The maximum number of interpreted frames to skip when searching "\
"for recompilee") \
\
develop(intx, DesiredMethodLimit, 8000, \
"The desired maximum method size (in bytecodes) after inlining") \
\
develop(intx, HugeMethodLimit, 8000, \
"Don't compile methods larger than this if " \
"+DontCompileHugeMethods") \
\
/* New JDK 1.4 reflection implementation */ \
\
develop(intx, FastSuperclassLimit, 8, \
"Depth of hardwired instanceof accelerator array") \
\
/* Properties for Java libraries */ \
\
product(size_t, MaxDirectMemorySize, 0, \
"Maximum total size of NIO direct-buffer allocations") \
\
/* Flags used for temporary code during development */ \
\
diagnostic(bool, UseNewCode, false, \
"Testing Only: Use the new version while testing") \
\
diagnostic(bool, UseNewCode2, false, \
"Testing Only: Use the new version while testing") \
\
diagnostic(bool, UseNewCode3, false, \
"Testing Only: Use the new version while testing") \
\
/* flags for performance data collection */ \
\
product(bool, UsePerfData, falseInEmbedded, \
"Flag to disable jvmstat instrumentation for performance testing "\
"and problem isolation purposes") \
\
product(bool, PerfDataSaveToFile, false, \
"Save PerfData memory to hsperfdata_<pid> file on exit") \
\
product(ccstr, PerfDataSaveFile, NULL, \
"Save PerfData memory to the specified absolute pathname. " \
"The string %p in the file name (if present) " \
"will be replaced by pid") \
\
product(intx, PerfDataSamplingInterval, 50, \
"Data sampling interval (in milliseconds)") \
\
develop(bool, PerfTraceDataCreation, false, \
"Trace creation of Performance Data Entries") \
\
develop(bool, PerfTraceMemOps, false, \
"Trace PerfMemory create/attach/detach calls") \
\
product(bool, PerfDisableSharedMem, false, \
"Store performance data in standard memory") \
\
product(intx, PerfDataMemorySize, 64*K, \
"Size of performance data memory region. Will be rounded " \
"up to a multiple of the native os page size.") \
\
product(intx, PerfMaxStringConstLength, 1024, \
"Maximum PerfStringConstant string length before truncation") \
\
product(bool, PerfAllowAtExitRegistration, false, \
"Allow registration of atexit() methods") \
\
product(bool, PerfBypassFileSystemCheck, false, \
"Bypass Win32 file system criteria checks (Windows Only)") \
\
product(intx, UnguardOnExecutionViolation, 0, \
"Unguard page and retry on no-execute fault (Win32 only) " \
"0=off, 1=conservative, 2=aggressive") \
range(0, 2) \
\
/* Serviceability Support */ \
\
product(bool, ManagementServer, false, \
"Create JMX Management Server") \
\
product(bool, DisableAttachMechanism, false, \
"Disable mechanism that allows tools to attach to this VM") \
\
product(bool, StartAttachListener, false, \
"Always start Attach Listener at VM startup") \
\
manageable(bool, PrintConcurrentLocks, false, \
"Print java.util.concurrent locks in thread dump") \
\
product(bool, TransmitErrorReport, false, \
"Enable error report transmission on erroneous termination") \
\
product(ccstr, ErrorReportServer, NULL, \
"Override built-in error report server address") \
\
/* Shared spaces */ \
\
product(bool, UseSharedSpaces, true, \
"Use shared spaces for metadata") \
\
product(bool, VerifySharedSpaces, false, \
"Verify shared spaces (false for default archive, true for " \
"archive specified by -XX:SharedArchiveFile)") \
\
product(bool, RequireSharedSpaces, false, \
"Require shared spaces for metadata") \
\
product(bool, DumpSharedSpaces, false, \
"Special mode: JVM reads a class list, loads classes, builds " \
"shared spaces, and dumps the shared spaces to a file to be " \
"used in future JVM runs") \
\
product(bool, PrintSharedSpaces, false, \
"Print usage of shared spaces") \
\
product(bool, PrintSharedArchiveAndExit, false, \
"Print shared archive file contents") \
\
product(bool, PrintSharedDictionary, false, \
"If PrintSharedArchiveAndExit is true, also print the shared " \
"dictionary") \
\
product(size_t, SharedReadWriteSize, NOT_LP64(12*M) LP64_ONLY(16*M), \
"Size of read-write space for metadata (in bytes)") \
\
product(size_t, SharedReadOnlySize, NOT_LP64(12*M) LP64_ONLY(16*M), \
"Size of read-only space for metadata (in bytes)") \
\
product(uintx, SharedMiscDataSize, NOT_LP64(2*M) LP64_ONLY(4*M), \
"Size of the shared miscellaneous data area (in bytes)") \
\
product(uintx, SharedMiscCodeSize, 120*K, \
"Size of the shared miscellaneous code area (in bytes)") \
\
product(uintx, SharedBaseAddress, LP64_ONLY(32*G) \
NOT_LP64(LINUX_ONLY(2*G) NOT_LINUX(0)), \
"Address to allocate shared memory region for class data") \
\
product(uintx, SharedSymbolTableBucketSize, 4, \
"Average number of symbols per bucket in shared table") \
\
diagnostic(bool, IgnoreUnverifiableClassesDuringDump, false, \
"Do not quit -Xshare:dump even if we encounter unverifiable " \
"classes. Just exclude them from the shared dictionary.") \
\
diagnostic(bool, PrintMethodHandleStubs, false, \
"Print generated stub code for method handles") \
\
develop(bool, TraceMethodHandles, false, \
"trace internal method handle operations") \
\
diagnostic(bool, VerifyMethodHandles, trueInDebug, \
"perform extra checks when constructing method handles") \
\
diagnostic(bool, ShowHiddenFrames, false, \
"show method handle implementation frames (usually hidden)") \
\
experimental(bool, TrustFinalNonStaticFields, false, \
"trust final non-static declarations for constant folding") \
\
diagnostic(bool, FoldStableValues, true, \
"Optimize loads from stable fields (marked w/ @Stable)") \
\
develop(bool, TraceInvokeDynamic, false, \
"trace internal invoke dynamic operations") \
\
diagnostic(bool, PauseAtStartup, false, \
"Causes the VM to pause at startup time and wait for the pause " \
"file to be removed (default: ./vm.paused.<pid>)") \
\
diagnostic(ccstr, PauseAtStartupFile, NULL, \
"The file to create and for whose removal to await when pausing " \
"at startup. (default: ./vm.paused.<pid>)") \
\
diagnostic(bool, PauseAtExit, false, \
"Pause and wait for keypress on exit if a debugger is attached") \
\
product(bool, ExtendedDTraceProbes, false, \
"Enable performance-impacting dtrace probes") \
\
product(bool, DTraceMethodProbes, false, \
"Enable dtrace probes for method-entry and method-exit") \
\
product(bool, DTraceAllocProbes, false, \
"Enable dtrace probes for object allocation") \
\
product(bool, DTraceMonitorProbes, false, \
"Enable dtrace probes for monitor events") \
\
product(bool, RelaxAccessControlCheck, false, \
"Relax the access control checks in the verifier") \
\
product(uintx, StringTableSize, defaultStringTableSize, \
"Number of buckets in the interned String table") \
range(minimumStringTableSize, 111*defaultStringTableSize) \
\
experimental(uintx, SymbolTableSize, defaultSymbolTableSize, \
"Number of buckets in the JVM internal Symbol table") \
range(minimumSymbolTableSize, 111*defaultSymbolTableSize) \
\
product(bool, UseStringDeduplication, false, \
"Use string deduplication") \
\
product(bool, PrintStringDeduplicationStatistics, false, \
"Print string deduplication statistics") \
\
product(uintx, StringDeduplicationAgeThreshold, 3, \
"A string must reach this age (or be promoted to an old region) " \
"to be considered for deduplication") \
range(1, markOopDesc::max_age) \
\
diagnostic(bool, StringDeduplicationResizeALot, false, \
"Force table resize every time the table is scanned") \
\
diagnostic(bool, StringDeduplicationRehashALot, false, \
"Force table rehash every time the table is scanned") \
\
develop(bool, TraceDefaultMethods, false, \
"Trace the default method processing steps") \
\
diagnostic(bool, WhiteBoxAPI, false, \
"Enable internal testing APIs") \
\
product(bool, PrintGCCause, true, \
"Include GC cause in GC logging") \
\
experimental(intx, SurvivorAlignmentInBytes, 0, \
"Default survivor space alignment in bytes") \
constraint(SurvivorAlignmentInBytesConstraintFunc,AfterErgo) \
\
product(bool , AllowNonVirtualCalls, false, \
"Obey the ACC_SUPER flag and allow invokenonvirtual calls") \
\
product(ccstr, DumpLoadedClassList, NULL, \
"Dump the names all loaded classes, that could be stored into " \
"the CDS archive, in the specified file") \
\
product(ccstr, SharedClassListFile, NULL, \
"Override the default CDS class list") \
\
diagnostic(ccstr, SharedArchiveFile, NULL, \
"Override the default location of the CDS archive file") \
\
product(ccstr, ExtraSharedClassListFile, NULL, \
"Extra classlist for building the CDS archive file") \
\
experimental(size_t, ArrayAllocatorMallocLimit, \
SOLARIS_ONLY(64*K) NOT_SOLARIS((size_t)-1), \
"Allocation less than this value will be allocated " \
"using malloc. Larger allocations will use mmap.") \
\
experimental(bool, AlwaysAtomicAccesses, false, \
"Accesses to all variables should always be atomic") \
\
product(bool, EnableTracing, false, \
"Enable event-based tracing") \
\
product(bool, UseLockedTracing, false, \
"Use locked-tracing when doing event-based tracing") \
\
diagnostic(bool, UseUnalignedAccesses, false, \
"Use unaligned memory accesses in sun.misc.Unsafe") \
\
product_pd(bool, PreserveFramePointer, \
"Use the FP register for holding the frame pointer " \
"and not as a general purpose register.") \
\
diagnostic(bool, CheckIntrinsics, true, \
"When a class C is loaded, check that " \
"(1) all intrinsics defined by the VM for class C are present "\
"in the loaded class file and are marked with the " \
"@HotSpotIntrinsicCandidate annotation, that " \
"(2) there is an intrinsic registered for all loaded methods " \
"that are annotated with the @HotSpotIntrinsicCandidate " \
"annotation, and that " \
"(3) no orphan methods exist for class C (i.e., methods for " \
"which the VM declares an intrinsic but that are not declared "\
"in the loaded class C. " \
"Check (3) is available only in debug builds.")
/*
* Macros for factoring of globals
*/
// Interface macros
#define DECLARE_PRODUCT_FLAG(type, name, value, doc) extern "C" type name;
#define DECLARE_PD_PRODUCT_FLAG(type, name, doc) extern "C" type name;
#define DECLARE_DIAGNOSTIC_FLAG(type, name, value, doc) extern "C" type name;
#define DECLARE_EXPERIMENTAL_FLAG(type, name, value, doc) extern "C" type name;
#define DECLARE_MANAGEABLE_FLAG(type, name, value, doc) extern "C" type name;
#define DECLARE_PRODUCT_RW_FLAG(type, name, value, doc) extern "C" type name;
#ifdef PRODUCT
#define DECLARE_DEVELOPER_FLAG(type, name, value, doc) extern "C" type CONST_##name; const type name = value;
#define DECLARE_PD_DEVELOPER_FLAG(type, name, doc) extern "C" type CONST_##name; const type name = pd_##name;
#define DECLARE_NOTPRODUCT_FLAG(type, name, value, doc) extern "C" type CONST_##name;
#else
#define DECLARE_DEVELOPER_FLAG(type, name, value, doc) extern "C" type name;
#define DECLARE_PD_DEVELOPER_FLAG(type, name, doc) extern "C" type name;
#define DECLARE_NOTPRODUCT_FLAG(type, name, value, doc) extern "C" type name;
#endif // PRODUCT
// Special LP64 flags, product only needed for now.
#ifdef _LP64
#define DECLARE_LP64_PRODUCT_FLAG(type, name, value, doc) extern "C" type name;
#else
#define DECLARE_LP64_PRODUCT_FLAG(type, name, value, doc) const type name = value;
#endif // _LP64
// Implementation macros
#define MATERIALIZE_PRODUCT_FLAG(type, name, value, doc) type name = value;
#define MATERIALIZE_PD_PRODUCT_FLAG(type, name, doc) type name = pd_##name;
#define MATERIALIZE_DIAGNOSTIC_FLAG(type, name, value, doc) type name = value;
#define MATERIALIZE_EXPERIMENTAL_FLAG(type, name, value, doc) type name = value;
#define MATERIALIZE_MANAGEABLE_FLAG(type, name, value, doc) type name = value;
#define MATERIALIZE_PRODUCT_RW_FLAG(type, name, value, doc) type name = value;
#ifdef PRODUCT
#define MATERIALIZE_DEVELOPER_FLAG(type, name, value, doc) type CONST_##name = value;
#define MATERIALIZE_PD_DEVELOPER_FLAG(type, name, doc) type CONST_##name = pd_##name;
#define MATERIALIZE_NOTPRODUCT_FLAG(type, name, value, doc) type CONST_##name = value;
#else
#define MATERIALIZE_DEVELOPER_FLAG(type, name, value, doc) type name = value;
#define MATERIALIZE_PD_DEVELOPER_FLAG(type, name, doc) type name = pd_##name;
#define MATERIALIZE_NOTPRODUCT_FLAG(type, name, value, doc) type name = value;
#endif // PRODUCT
#ifdef _LP64
#define MATERIALIZE_LP64_PRODUCT_FLAG(type, name, value, doc) type name = value;
#else
#define MATERIALIZE_LP64_PRODUCT_FLAG(type, name, value, doc) /* flag is constant */
#endif // _LP64
// Only materialize src code for range checking when required, ignore otherwise
#define IGNORE_RANGE(a, b)
// Only materialize src code for contraint checking when required, ignore otherwise
#define IGNORE_CONSTRAINT(func,type)
RUNTIME_FLAGS(DECLARE_DEVELOPER_FLAG, \
DECLARE_PD_DEVELOPER_FLAG, \
DECLARE_PRODUCT_FLAG, \
DECLARE_PD_PRODUCT_FLAG, \
DECLARE_DIAGNOSTIC_FLAG, \
DECLARE_EXPERIMENTAL_FLAG, \
DECLARE_NOTPRODUCT_FLAG, \
DECLARE_MANAGEABLE_FLAG, \
DECLARE_PRODUCT_RW_FLAG, \
DECLARE_LP64_PRODUCT_FLAG, \
IGNORE_RANGE, \
IGNORE_CONSTRAINT)
RUNTIME_OS_FLAGS(DECLARE_DEVELOPER_FLAG, \
DECLARE_PD_DEVELOPER_FLAG, \
DECLARE_PRODUCT_FLAG, \
DECLARE_PD_PRODUCT_FLAG, \
DECLARE_DIAGNOSTIC_FLAG, \
DECLARE_NOTPRODUCT_FLAG, \
IGNORE_RANGE, \
IGNORE_CONSTRAINT)
ARCH_FLAGS(DECLARE_DEVELOPER_FLAG, \
DECLARE_PRODUCT_FLAG, \
DECLARE_DIAGNOSTIC_FLAG, \
DECLARE_EXPERIMENTAL_FLAG, \
DECLARE_NOTPRODUCT_FLAG, \
IGNORE_RANGE, \
IGNORE_CONSTRAINT)
// Extensions
#include "runtime/globals_ext.hpp"
#endif // SHARE_VM_RUNTIME_GLOBALS_HPP
| gpl-2.0 |
collective/ECSpooler | lib/soapwrapper.py | 7578 | # -*- coding: utf-8 -*-
# $Id$
#
import os
#import sys
#import time
import logging
#import threading
#from threading import Thread
#from urllib2 import URLError
#from copy import deepcopy
#from types import StringTypes
# Python build-in xmlrpclib
import xmlrpclib
# spyne
from spyne.decorator import srpc, rpc
from spyne.service import ServiceBase
from spyne.model.complex import Array
#from spyne.model.primitive import Integer
from spyne.model.primitive import Unicode
#from spyne.model.primitive import String
#from spyne.model.primitive import AnyDict
#from spyne.model.primitive import Mandatory
from spyne.util.simple import wsgi_soap11_application
try:
from wsgiref.simple_server import make_server
except ImportError:
print("Error: example server code requires Python >= 2.5")
raise
# local imports
from lib.data.dto import TARGET_NAMESPACE
from lib.data.dto import SpoolerState, State
#from lib.data.dto import BackendStatus
from lib.data.dto import Backend
from lib.data.dto import BackendInputField
from lib.data.dto import BackendTestField
from lib.data.dto import DictElem
from lib.data.dto import Answer
def set_spooler_host(host):
"""
"""
global __host
__host = host
def set_spooler_port(port):
"""
"""
global __port
__port = port
def _get_spooler_proxy():
"""
"""
return xmlrpclib.ServerProxy("http://%s:%s" % (__host, __port))
def _get_user_auth_dict(username, password):
"""
"""
return {"username":username, "password":password}
class SoapWrapper(ServiceBase):
"""
"""
@rpc(Unicode, Unicode, _returns=State)
def getPID(self, username, password):
"""
Returns the process ID
@param authdata: username and password for authentication
@return: current process ID
"""
#sp = _get_spooler_proxy()
#state = sp.getStatus(_get_user_auth_dict(username, password))
result = State()
result.pid = os.getpid()
return result
@srpc(Unicode, Unicode, _returns=SpoolerState)
def getState(username, password): #@NoSelf
"""
Returns status information such aus PID, number of tests and
result in the queue as well as a list with IDs of all registered
backends.
@param username:
@param password:
@throws Exception:
"""
sp = _get_spooler_proxy()
state = sp.getStatus(_get_user_auth_dict(username, password))
result = SpoolerState()
result.backends = state.get('backends', [])
result.queueCount = state.get('queue', 0)
result.resultCount = state.get('results', 0)
return result
@srpc(Unicode, Unicode, _returns=Array(Backend))
#@srpc(Unicode, Unicode, _returns=AnyDict)
def getBackends(username, password): #@NoSelf
sp = _get_spooler_proxy()
backends = sp.getBackends(_get_user_auth_dict(username, password))
result = []
for key, values in backends.iteritems():
#print name
#print values
backend = Backend()
backend.name = values['name']
#backend.url = values['url']
#backend.isBusy = values['isBusy']
backend.version = values['version']
backend.id = values['id']
result.append(backend)
return result
@srpc(Unicode, Unicode, Unicode, _returns=Array(BackendInputField))
def getBackendInputFields(username, password, backendId): #@NoSelf
sp = _get_spooler_proxy()
fields = sp.getBackendInputFields(_get_user_auth_dict(username, password), backendId)
result = []
for key, values in fields.iteritems():
inputField = BackendInputField()
inputField.name = key
inputField.description = values['description']
inputField.format = values['format']
inputField.required = values['required']
inputField.label = values['label']
inputField.languageIndependent = values['languageIndependent']
inputField.i18n_domain = values['i18n_domain']
inputField.type = values['type']
if values.has_key('accessor'):
inputField.accessor = values['accessor']
else:
inputField.accessor = ''
result.append(inputField)
return result
@srpc(Unicode, Unicode, Unicode, _returns=Array(BackendTestField))
def getBackendTestFields(username, password, backendId): #@NoSelf
sp = _get_spooler_proxy()
fields = sp.getBackendTestFields(_get_user_auth_dict(username, password), backendId)
result = []
for key, value in fields.iteritems():
testField = BackendTestField()
testField.id = key
testField.name = value
result.append(testField)
return result
@srpc(Unicode, Unicode, _returns=Array(Answer))
def pullJobs(username, password): #@NoSelf
sp = _get_spooler_proxy()
results = sp.getResults(_get_user_auth_dict(username, password))
answers = []
for key, value in results.iteritems():
answer = Answer()
answer.id = value['id']
answer.message = value['message']
answer.value = value['value']
answers.append(answer)
return answers
@srpc(Unicode, Unicode, Unicode, _returns=Answer)
def pull(username, password, jobId): #@NoSelf
sp = _get_spooler_proxy()
result = sp.pull(_get_user_auth_dict(username, password), jobId)
answer = Answer()
for key, value in result.iteritems():
answer.id = value['id']
answer.message = value['message']
answer.value = value['value']
return answer
@srpc(Unicode, Unicode, Unicode, Unicode, Array(Unicode), Array(DictElem), _returns=Unicode)
def push(username, password, submission, backend, tests, options): #@NoSelf
sp = _get_spooler_proxy()
# create job data dict with mandatory keys
jobdata = {'backend' : backend,
'submission' : submission,
'tests' : tests
}
# add options
for x in options:
jobdata.update({x.key : x.value})
append = sp.push(_get_user_auth_dict(username, password), jobdata)
return append
# ==============================================================================
if __name__ == '__main__':
"""
"""
#logging.basicConfig(level=logging.INFO)
#logging.getLogger('spyne.protocol.xml').setLevel(logging.INFO)
host = '0.0.0.0'
port = 3050
set_spooler_host("0.0.0.0")
set_spooler_port(5050)
logging.info("listening to http://%s:%d" % (host, port))
logging.info("wsdl is at: http://localhost:%d/?wsdl" % (port))
wsgi_app = wsgi_soap11_application([SoapWrapper], TARGET_NAMESPACE)
server = make_server(host, port, wsgi_app)
logging.info("pid = %s" % os.getpid())
server.serve_forever()
| gpl-2.0 |
xharbour/core | contrib/hbzlib/zipcomp.cpp | 15094 | /*
* $Id: zipcomp.cpp 9685 2012-09-16 05:42:35Z andijahja $
*/
/*
* Harbour Project source code:
* Zlib low level interface for Harbour
*
* Copyright 2000-2001 Luiz Rafael Culik <[email protected]>
* www - http://www.harbour-project.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 this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA ( or visit the web site http://www.gnu.org/ ).
*
* As a special exception, the Harbour Project gives permission for
* additional uses of the text contained in its release of Harbour.
*
* The exception is that, if you link the Harbour libraries with other
* files to produce an executable, this does not by itself cause the
* resulting executable to be covered by the GNU General Public License.
* Your use of that executable is in no way restricted on account of
* linking the Harbour library code into it.
*
* This exception does not however invalidate any other reasons why
* the executable file might be covered by the GNU General Public License.
*
* This exception applies only to the code released by the Harbour
* Project under the name Harbour. If you copy code from other
* Harbour Project or Free Software Foundation releases into a copy of
* Harbour, as the General Public License permits, the exception does
* not apply to the code that you add in this way. To avoid misleading
* anyone as to the status of such modified files, you must delete
* this exception notice from them.
*
* If you write modifications of your own for Harbour, it is your choice
* whether to permit this exception to apply to your modifications.
* If you do not wish that, delete this exception notice.
*
*/
#define HB_OS_WIN_32_USED
#include "hbzip2.h"
//extern PHB_ITEM ZipArray;
PHB_ITEM pDiskStatus = NULL;
PHB_ITEM pProgressInfo = NULL;
extern PHB_ITEM ChangeDiskBlock;
#ifdef __cplusplus
extern "C" {
#endif
extern HB_ZIP_INTERNAL pZipI;
//bool hb_SetProgressofTdSpan( DWORD, int iSoFar, void* pData );
class SpanCallbackc : public CZipSpanCallback
{
bool Callback( int iProgress )
{
PHB_ITEM Disk = hb_itemPutNL( NULL, m_uDiskNeeded );
( void ) iProgress;
hb_vmEvalBlockV( ChangeDiskBlock, 1, Disk );
hb_itemRelease( Disk );
return TRUE;
}
};
class SpanActionCallbackc : public CZipActionCallback
{
bool Callback( int iProgress )
{
PHB_ITEM Disk = hb_itemPutNL( NULL, m_uTotalSoFar ), Total = hb_itemPutNL( NULL, m_uTotalToDo );
( void ) iProgress;
hb_vmEvalBlockV( pProgressInfo, 2, Disk, Total );
hb_itemRelease( Disk );
hb_itemRelease( Total );
return TRUE;
}
};
int hb_CompressFile( const char * szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBlock, BOOL bOverWrite, const char * szPassWord, BOOL bPath, BOOL bDrive, PHB_ITEM pProgress )
{
ULONG ulCount = 0;
const char * szDummy;
char * szDummyLower = NULL;
char * szFileLower = hb_strdup( ( char * ) szFile );
BOOL bFileExist = hb_fsFile( szFile );
BOOL bAdded = FALSE;
BOOL bReturn = TRUE;
DWORD dwSize;
CZipArchive szZip;
SpanCallbackc span;
SpanActionCallbackc spanac;
szZip.SetSpanCallback( &span );
#ifdef HB_OS_WIN_32
hb_strLower( szFileLower, strlen( szFileLower ) );
#endif
try
{
if( ( bFileExist && bOverWrite ) || ! bFileExist )
{
szZip.Open( szFile, CZipArchive::zipCreate, 0 );
}
else
{
szZip.Open( szFile, CZipArchive::zipOpen, 0 );
}
}
catch( CZipException )
{
bReturn = FALSE;
}
catch( ... )
{
}
if( bReturn )
{
if( szPassWord != NULL )
{
szZip.SetPassword( szPassWord );
}
if( pZipI.szComment != NULL )
{
szZip.SetGlobalComment( pZipI.szComment );
hb_xfree( pZipI.szComment );
}
if( HB_IS_BLOCK( pProgress ) )
{
pProgressInfo = pProgress;
szZip.SetCallback( &spanac );
}
for( ulCount = 1; ( ulCount <= hb_arrayLen( pArray ) ); ulCount++ )
{
szDummy = ( char * ) hb_arrayGetCPtr( pArray, ulCount );
dwSize = GetCurrentFileSize( szDummy );
bAdded = FALSE;
szDummyLower = hb_strdup( ( char * ) szDummy );
#ifdef HB_OS_WIN_32
hb_strLower( szDummyLower, strlen( szDummyLower ) );
#endif
// Prevent adding current archive file !
if( strstr( szFileLower, szDummyLower ) == NULL && strstr( szDummyLower, szFileLower ) == NULL )
{
if( dwSize != ( DWORD ) -1 )
{
if( pBlock != NULL )
{
PHB_ITEM FileName = hb_itemPutC( NULL, hb_arrayGetCPtr( pArray, ulCount ) ), FilePos = hb_itemPutNI( NULL, ulCount );
hb_vmEvalBlockV( pBlock, 2, FileName, FilePos );
hb_itemRelease( FileName );
hb_itemRelease( FilePos );
}
try
{
if( bPath && ! bAdded )
{
szZip.AddNewFile( szDummy, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 );
bAdded = TRUE;
}
else if( ! bDrive && ! bPath && ! bAdded )
{
szZip.AddNewFile( szDummy, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 );
}
}
catch( ... )
{
}
}
}
hb_xfree( szDummyLower );
}
}
hb_xfree( szFileLower );
try
{
szZip.Close();
}
catch( CZipException )
{
bReturn = FALSE;
}
catch( ... )
{
}
return ( int ) bReturn;
}
int hb_CmpTdSpan( const char * szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBlock, BOOL bOverWrite, const char * szPassWord, int iSpanSize, BOOL bPath, BOOL bDrive, PHB_ITEM pProgress )
{
ULONG ulCount = 0;
const char * szDummy;
DWORD dwSize;
BOOL bAdded = FALSE;
BOOL bReturn = TRUE;
BOOL bFileExist = hb_fsFile( szFile );
CZipArchive szZip;
SpanCallbackc span;
SpanActionCallbackc spanac;
szZip.SetSpanCallback( &span );
if( iSpanSize == 0 )
{
iSpanSize = 1457664;
}
try
{
if( ( bFileExist && bOverWrite ) || ! bFileExist )
{
szZip.Open( szFile, CZipArchive::zipCreateSpan, iSpanSize );
}
else
{
bReturn = FALSE;
return ( int ) bReturn;
}
}
catch( CZipException )
{
bReturn = FALSE;
}
catch( ... )
{
}
//if (! bReturn )
//{
if( szPassWord != NULL )
{
szZip.SetPassword( szPassWord );
}
if( pZipI.szComment != NULL )
{
szZip.SetGlobalComment( pZipI.szComment );
hb_xfree( pZipI.szComment );
}
if( HB_IS_BLOCK( pProgress ) )
{
pProgressInfo = pProgress;
szZip.SetCallback( &spanac );
}
for( ulCount = 1; ( ulCount <= hb_arrayLen( pArray ) ); ulCount++ )
{
szDummy = ( char * ) hb_arrayGetCPtr( pArray, ulCount );
dwSize = GetCurrentFileSize( szDummy );
bAdded = FALSE;
if( dwSize != ( DWORD ) -1 )
{
if( pBlock != NULL )
{
PHB_ITEM FileName = hb_itemPutC( NULL, hb_arrayGetCPtr( pArray, ulCount ) ), FilePos = hb_itemPutNI( NULL, ulCount );
hb_vmEvalBlockV( pBlock, 2, FileName, FilePos );
hb_itemRelease( FileName );
hb_itemRelease( FilePos );
}
try
{
if( bPath && ! bAdded )
{
szZip.AddNewFile( szDummy, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 );
bAdded = TRUE;
}
else if( ! bDrive && ! bPath && ! bAdded )
{
szZip.AddNewFile( szDummy, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 );
}
}
catch( ... )
{
}
}
}
//}
try
{
szZip.Close();
}
catch( CZipException )
{
bReturn = FALSE;
}
catch( ... )
{
}
return ( int ) bReturn;
}
bool hb_SetProgressofTdSpan( DWORD a, int iSoFar, void * pData )
{
PHB_ITEM Disk = hb_itemPutNL( NULL, iSoFar ), Total = hb_itemPutNL( NULL, a );
HB_SYMBOL_UNUSED( pData );
hb_vmEvalBlockV( pProgressInfo, 2, Disk, Total );
hb_itemRelease( Disk );
hb_itemRelease( Total );
return TRUE;
}
int hb_CompressFileStd( char * szFile, char * szFiletoCompress, int iCompLevel, PHB_ITEM pBlock, BOOL bOverWrite, char * szPassWord, BOOL bPath, BOOL bDrive, PHB_ITEM pProgress )
{
DWORD dwSize;
BOOL bFileExist = hb_fsFile( szFile );
BOOL bReturn = TRUE;
BOOL bAdded = FALSE;
CZipArchive szZip;
SpanCallbackc span;
SpanActionCallbackc spanac;
szZip.SetSpanCallback( &span );
try
{
if( ( bFileExist && bOverWrite ) || ! bFileExist )
{
szZip.Open( szFile, CZipArchive::zipCreate, 0 );
}
else
{
szZip.Open( szFile, CZipArchive::zipOpen, 0 );
}
}
catch( CZipException )
{
bReturn = FALSE;
}
if( bReturn )
{
if( szPassWord != NULL )
{
szZip.SetPassword( szPassWord );
}
if( pZipI.szComment != NULL )
{
szZip.SetGlobalComment( pZipI.szComment );
hb_xfree( pZipI.szComment );
}
if( HB_IS_BLOCK( pProgress ) )
{
pProgressInfo = pProgress;
szZip.SetCallback( &spanac );
}
try
{
dwSize = GetCurrentFileSize( szFiletoCompress );
if( dwSize != ( DWORD ) -1 )
{
if( pBlock != NULL )
{
PHB_ITEM FileName = hb_itemPutC( NULL, szFiletoCompress );
hb_vmEvalBlockV( pBlock, 1, FileName );
hb_itemRelease( FileName );
}
#if ( defined( __WIN32__ ) || defined( __MINGW32__ ) ) && defined( HB_USE_DRIVE_ADD )
if( bDrive && ! bAdded )
{
if( ! szZip.AddNewFileDrv( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) )
{
bReturn = FALSE;
}
else
{
bAdded = TRUE;
}
}
#endif
if( bPath && ! bAdded )
{
if( ! szZip.AddNewFile( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) )
{
bReturn = FALSE;
}
else
{
bAdded = TRUE;
}
}
else if( ! bDrive && ! bPath && ! bAdded )
{
if( ! szZip.AddNewFile( szFiletoCompress, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 ) )
{
bReturn = FALSE;
}
}
}
}
catch( ... )
{
}
}
try
{
szZip.Close();
}
catch( CZipException )
{
bReturn = FALSE;
}
catch( ... )
{
}
return ( int ) bReturn;
}
int hb_CmpTdSpanStd( char * szFile, char * szFiletoCompress, int iCompLevel, PHB_ITEM pBlock, BOOL bOverWrite, char * szPassWord, int iSpanSize, BOOL bPath, BOOL bDrive, PHB_ITEM pProgress )
{
DWORD dwSize;
BOOL bAdded = FALSE;
BOOL bReturn = TRUE;
BOOL bFileExist = hb_fsFile( szFile );
CZipArchive szZip;
SpanCallbackc span;
SpanActionCallbackc spanac;
szZip.SetSpanCallback( &span );
if( iSpanSize == 0 )
{
iSpanSize = 1457664;
}
try
{
if( ( bFileExist && bOverWrite ) || ! bFileExist )
{
szZip.Open( szFile, CZipArchive::zipCreateSpan, iSpanSize );
}
else
{
return ( int ) false;
}
}
catch( CZipException )
{
bReturn = FALSE;
}
catch( ... )
{
}
if( szPassWord != NULL )
{
szZip.SetPassword( szPassWord );
}
if( pZipI.szComment != NULL )
{
szZip.SetGlobalComment( pZipI.szComment );
hb_xfree( pZipI.szComment );
}
if( HB_IS_BLOCK( pProgress ) )
{
pProgressInfo = pProgress;
szZip.SetCallback( &spanac );
}
if( bReturn )
{
try
{
if( szPassWord != NULL )
{
szZip.SetPassword( szPassWord );
}
dwSize = GetCurrentFileSize( szFiletoCompress );
if( pBlock != NULL )
{
PHB_ITEM FileName = hb_itemPutC( NULL, szFiletoCompress );
hb_vmEvalBlockV( pBlock, 1, FileName );
hb_itemRelease( FileName );
}
#if defined( __WIN32__ ) || defined( __MINGW32__ )
if( bDrive && ! bAdded )
{
if( ! szZip.AddNewFileDrv( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) )
{
bReturn = FALSE;
}
else
{
bAdded = TRUE;
}
}
#endif
if( bPath && ! bAdded )
{
if( ! szZip.AddNewFile( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) )
{
bReturn = FALSE;
}
else
{
bAdded = TRUE;
}
}
else if( ! bDrive && ! bPath && ! bAdded )
{
if( ! szZip.AddNewFile( szFiletoCompress, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 ) )
{
bReturn = FALSE;
}
}
}
catch( ... )
{
}
}
try
{
szZip.Close();
}
catch( CZipException )
{
bReturn = FALSE;
}
catch( ... )
{
}
if( pProgressInfo )
{
hb_itemRelease( pProgressInfo );
}
return ( int ) bReturn;
}
#ifdef __cplusplus
}
#endif
| gpl-2.0 |
Automattic/wp-calypso | client/my-sites/backup/rewind-flow/rewind-config-editor.tsx | 2625 | import { useTranslate } from 'i18n-calypso';
import { FunctionComponent, ChangeEvent } from 'react';
import FormCheckbox from 'calypso/components/forms/form-checkbox';
import FormLabel from 'calypso/components/forms/form-label';
import type { RewindConfig } from './types';
import './style.scss';
interface Props {
currentConfig: RewindConfig;
onConfigChange: ( config: RewindConfig ) => void;
}
const BackupRewindConfigEditor: FunctionComponent< Props > = ( {
currentConfig,
onConfigChange,
} ) => {
const translate = useTranslate();
const onChange = ( { target: { name, checked } }: ChangeEvent< HTMLInputElement > ) =>
onConfigChange( {
...currentConfig,
[ name ]: checked,
} );
const checkboxes = [
{
name: 'themes',
label: translate( '{{strong}}WordPress themes{{/strong}}', {
components: {
strong: <strong />,
},
} ),
},
{
name: 'plugins',
label: translate( '{{strong}}WordPress plugins{{/strong}}', {
components: {
strong: <strong />,
},
} ),
},
{
name: 'roots',
label: translate(
'{{strong}}WordPress root{{/strong}} (includes wp-config php and any non WordPress files)',
{
components: {
strong: <strong />,
},
}
),
},
{
name: 'contents',
label: translate(
'{{strong}}WP-content directory{{/strong}} (excludes themes, plugins, and uploads)',
{
components: {
strong: <strong />,
},
}
),
},
{
name: 'sqls',
label: translate( '{{strong}}Site database{{/strong}} (includes pages, and posts)', {
components: {
strong: <strong />,
},
} ),
},
{
name: 'uploads',
label: translate(
'{{strong}}Media uploads{{/strong}} (you must also select {{em}}Site database{{/em}} for restored media uploads to appear)',
{
components: {
strong: <strong />,
em: <em />,
},
comment:
'"Site database" is another item of the list, at the same level as "Media Uploads"',
}
),
},
];
return (
<div className="rewind-flow__rewind-config-editor">
{ checkboxes.map( ( { name, label } ) => (
<FormLabel
className="rewind-flow__rewind-config-editor-label"
key={ name }
optional={ false }
required={ false }
>
<FormCheckbox
checked={ currentConfig[ name as keyof RewindConfig ] }
className="rewind-flow__rewind-config-editor-checkbox"
name={ name }
onChange={ onChange }
/>
<span className="rewind-flow__rewind-config-editor-label-text">{ label }</span>
</FormLabel>
) ) }
</div>
);
};
export default BackupRewindConfigEditor;
| gpl-2.0 |
vdm-io/Joomla-Component-Builder | admin/views/components_mysql_tweaks/tmpl/default_head.php | 1841 | <?php
/**
* @package Joomla.Component.Builder
*
* @created 30th April, 2015
* @author Llewellyn van der Merwe <http://www.joomlacomponentbuilder.com>
* @gitea Joomla Component Builder <https://git.vdm.dev/joomla/Component-Builder>
* @github Joomla Component Builder <https://github.com/vdm-io/Joomla-Component-Builder>
* @copyright Copyright (C) 2015 Vast Development Method. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>
<tr>
<?php if ($this->canEdit&& $this->canState): ?>
<th width="1%" class="nowrap center hidden-phone">
<?php echo JHtml::_('searchtools.sort', '', 'a.ordering', $this->listDirn, $this->listOrder, null, 'asc', 'JGRID_HEADING_ORDERING', 'icon-menu-2'); ?>
</th>
<th width="20" class="nowrap center">
<?php echo JHtml::_('grid.checkall'); ?>
</th>
<?php else: ?>
<th width="20" class="nowrap center hidden-phone">
▾
</th>
<th width="20" class="nowrap center">
■
</th>
<?php endif; ?>
<th class="nowrap" >
<?php echo JText::_('COM_COMPONENTBUILDER_COMPONENT_MYSQL_TWEAKS_JOOMLA_COMPONENT_LABEL'); ?>
</th>
<?php if ($this->canState): ?>
<th width="10" class="nowrap center" >
<?php echo JHtml::_('searchtools.sort', 'COM_COMPONENTBUILDER_COMPONENT_MYSQL_TWEAKS_STATUS', 'a.published', $this->listDirn, $this->listOrder); ?>
</th>
<?php else: ?>
<th width="10" class="nowrap center" >
<?php echo JText::_('COM_COMPONENTBUILDER_COMPONENT_MYSQL_TWEAKS_STATUS'); ?>
</th>
<?php endif; ?>
<th width="5" class="nowrap center hidden-phone" >
<?php echo JHtml::_('searchtools.sort', 'COM_COMPONENTBUILDER_COMPONENT_MYSQL_TWEAKS_ID', 'a.id', $this->listDirn, $this->listOrder); ?>
</th>
</tr> | gpl-2.0 |
rolandoislas/PeripheralsPlusPlus | src/api/java/forestry/api/recipes/ICarpenterManager.java | 2557 | /*******************************************************************************
* Copyright 2011-2014 SirSengir
*
* This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details.
******************************************************************************/
package forestry.api.recipes;
import javax.annotation.Nullable;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.ShapedRecipes;
import net.minecraftforge.fluids.FluidStack;
/**
* Provides an interface to the recipe manager of the carpenter.
* <p>
* The manager is initialized at the beginning of Forestry's BaseMod.load() cycle. Begin adding recipes in BaseMod.ModsLoaded() and this shouldn't be null even
* if your mod loads before Forestry.
* <p>
* Accessible via {@link RecipeManagers}
* <p>
* Only shaped recipes can be added currently.
*
* @author SirSengir
*/
public interface ICarpenterManager extends ICraftingProvider<ICarpenterRecipe> {
/**
* Add a shaped recipe to the carpenter.
*
* @param box ItemStack of one item representing the required box (carton, crate) for this recipe. May be null.
* @param product Crafting result.
* @param materials Materials needed in the crafting matrix. This gets passed directly to {@link ShapedRecipes}. Notation is the same.
*/
void addRecipe(ItemStack box, ItemStack product, Object... materials);
/**
* Add a shaped recipe to the carpenter.
*
* @param packagingTime Number of work cycles required to craft the recipe once.
* @param box ItemStack of one item representing the required box (carton, crate) for this recipe. May be empty.
* @param product Crafting result.
* @param materials Materials needed in the crafting matrix. This gets passed directly to {@link ShapedRecipes}. Notation is the same.
*/
void addRecipe(int packagingTime, ItemStack box, ItemStack product, Object... materials);
/**
* Add a shaped recipe to the carpenter.
*
* @param packagingTime Number of work cycles required to craft the recipe once.
* @param liquid Liquid required in carpenter's tank.
* @param box ItemStack of one item representing the required box (carton, crate) for this recipe. May be empty.
* @param product Crafting result.
* @param materials Materials needed in the crafting matrix. This gets passed directly to {@link ShapedRecipes}. Notation is the same.
*/
void addRecipe(int packagingTime, @Nullable FluidStack liquid, ItemStack box, ItemStack product, Object... materials);
}
| gpl-2.0 |
middle8media/IFE | wp-content/plugins/restrict-content-pro/includes/admin/members-page.php | 10818 | <?php
function rcp_members_page()
{
global $rcp_options, $rcp_db_name, $wpdb;
$current_page = admin_url( '/admin.php?page=rcp-members' );
?>
<div class="wrap">
<?php if(isset($_GET['edit_member'])) :
include('edit-member.php');
elseif(isset($_GET['view_member'])) :
include('view-member.php');
else : ?>
<h2><?php _e('Paid Subscribers', 'rcp'); ?></h2>
<?php
if(isset($_GET['status']) && strlen(trim($_GET['status'])) > 0) {
$status = urldecode($_GET['status']);
} else {
$status = 'active';
}
if(isset($_GET['order'])) {
$order = $_GET['order'];
} else {
$order = 'DESC';
}
if(isset($_GET['subscription']) && $_GET['subscription'] != 'all') {
$subscription_id = urldecode($_GET['subscription']);
} else {
$subscription_id = null;
}
// get subscriber count
$active_count = rcp_count_members($subscription_id, 'active');
$pending_count = rcp_count_members($subscription_id, 'pending');
$expired_count = rcp_count_members($subscription_id, 'expired');
$cancelled_count = rcp_count_members($subscription_id, 'cancelled');
$free_count = rcp_count_members($subscription_id, 'free');
$current_count = rcp_count_members($subscription_id, $status);
// pagination variables
if (isset($_GET['p'])) $page = $_GET['p']; else $page = 1;
$user = get_current_user_id();
$screen = get_current_screen();
$screen_option = $screen->get_option('per_page', 'option');
$per_page = get_user_meta($user, $screen_option, true);
if ( empty ( $per_page) || $per_page < 1 ) {
$per_page = $screen->get_option( 'per_page', 'default' );
}
$total_pages = 1;
$offset = $per_page * ($page-1);
$total_pages = ceil($current_count/$per_page);
?>
<ul class="subsubsub">
<li><?php _e('Status: ', 'rcp'); ?></li>
<li>
<a href="<?php echo add_query_arg('status', 'active'); ?>" title="<?php _e('View all active subscribers', 'rcp'); ?>" <?php echo (isset($_GET['status']) && $_GET['status'] == 'active') || !isset($_GET['status']) ? 'class="current"' : ''; ?>>
<?php _e('Active', 'rcp'); ?>
</a>(<?php echo $active_count; ?>)
</li>
<li>
<a href="<?php echo add_query_arg('status', 'pending'); ?>" title="<?php _e('View all pending subscribers', 'rcp'); ?>" <?php echo (isset($_GET['status']) && $_GET['status'] == 'pending') ? 'class="current"' : ''; ?>>
<?php _e('Pending', 'rcp'); ?>
</a>(<?php echo $pending_count; ?>)
</li>
<li>
<a href="<?php echo add_query_arg('status', 'expired'); ?>" title="<?php _e('View all expired subscribers', 'rcp'); ?>" <?php echo (isset($_GET['status']) && $_GET['status'] == 'expired') ? 'class="current"' : ''; ?>>
<?php _e('Expired', 'rcp'); ?>
</a>(<?php echo $expired_count; ?>)
</li>
<li>
<a href="<?php echo add_query_arg('status', 'cancelled'); ?>" title="<?php _e('View all cancelled subscribers', 'rcp'); ?>" <?php echo (isset($_GET['status']) && $_GET['status'] == 'cancelled') ? 'class="current"' : ''; ?>>
<?php _e('Cancelled', 'rcp'); ?>
</a>(<?php echo $cancelled_count; ?>)
</li>
<li>
<a href="<?php echo add_query_arg('status', 'free'); ?>" title="<?php _e('View all free members', 'rcp'); ?>" <?php echo (isset($_GET['status']) && $_GET['status'] == 'free') ? 'class="current"' : ''; ?>>
<?php _e('Free', 'rcp'); ?>
</a>(<?php echo $free_count; ?>)
</li>
</ul>
<form id="members-filter" action="" method="get">
<?php
$levels = rcp_get_subscription_levels('all', false);
if($levels) : ?>
<select name="subscription" id="rcp-subscription">
<option value="all"><?php _e('All Subscriptions', 'rcp'); ?></option>
<?php
foreach($levels as $level) :
echo '<option value="' . $level->id . '" ' . selected($subscription_id, $level->id, false) . '>' . utf8_decode($level->name) . '</option>';
endforeach;
?>
</select>
<?php endif; ?>
<select name="order" id="rcp-order">
<option value="DESC" <?php selected($order, 'DESC'); ?>><?php _e('Newest First', 'rcp'); ?></option>
<option value="ASC" <?php selected($order, 'ASC'); ?>><?php _e('Oldest First', 'rcp'); ?></option>
</select>
<input type="hidden" name="page" value="rcp-members"/>
<input type="hidden" name="status" value="<?php echo isset($_GET['status']) ? $_GET['status'] : 'active'; ?>"/>
<input type="submit" class="button-secondary" value="<?php _e('Filter', 'rcp'); ?>"/>
</form>
<table class="wp-list-table widefat fixed posts">
<thead>
<tr>
<th class="rcp-user-col"><?php _e('User', 'rcp'); ?></th>
<th class="rcp-id-col"><?php _e('ID', 'rcp'); ?></th>
<th class="rcp-email-col"><?php _e('Email', 'rcp'); ?></th>
<th class="rcp-sub-col"><?php _e('Subscription', 'rcp'); ?></th>
<th class="rcp-status-col"><?php _e('Status', 'rcp'); ?></th>
<th class="rcp-recurring-col"><?php _e('Recurring', 'rcp'); ?></th>
<th class="rcp-expiration-col"><?php _e('Expiration', 'rcp'); ?></th>
<th class="rcp-role-col"><?php _e('User Role', 'rcp'); ?></th>
<?php do_action('rcp_members_page_table_header'); ?>
<th class="rcp-actions-role"><?php _e('Actions', 'rcp'); ?></th>
</tr>
</thead>
<tfoot>
<tr>
<th><?php _e('User', 'rcp'); ?></th>
<th><?php _e('ID', 'rcp'); ?></th>
<th><?php _e('Email', 'rcp'); ?></th>
<th><?php _e('Subscription', 'rcp'); ?></th>
<th><?php _e('Status', 'rcp'); ?></th>
<th><?php _e('Recurring', 'rcp'); ?></th>
<th><?php _e('Expiration', 'rcp'); ?></th>
<th><?php _e('User Role', 'rcp'); ?></th>
<?php do_action('rcp_members_page_table_footer'); ?>
<th><?php _e('Actions', 'rcp'); ?></th>
</tr>
</tfoot>
<tbody>
<?php
if( isset($_GET['signup_method']) ) {
$method = $_GET['signup_method'] == 'live' ? 'live' : 'manual';
$members = get_users( array(
'meta_key' => 'rcp_signup_method',
'meta_value' => $method,
'number' => 999999
)
);
$per_page = 999999;
} else {
$members = rcp_get_members($status, $subscription_id, $offset, $per_page, $order);
}
if($members) :
$i = 1;
foreach( $members as $key => $member) : ?>
<tr class="rcp_row <?php if(rcp_is_odd($i)) { echo 'alternate'; } ?>">
<td><?php echo $member->user_login; ?></td>
<td><?php echo $member->ID; ?></td>
<td><?php echo $member->user_email; ?></td>
<td><?php echo utf8_decode(rcp_get_subscription($member->ID)); ?></td>
<td><?php echo rcp_print_status($member->ID); ?></td>
<td><?php echo rcp_is_recurring($member->ID) ? __('yes', 'rcp') : __('no', 'rcp'); ?>
<td><?php echo rcp_get_expiration_date($member->ID); ?></td>
<td><?php echo rcp_get_user_role($member->ID); ?></td>
<?php do_action('rcp_members_page_table_column', $member->ID); ?>
<td>
<a href="<?php echo add_query_arg('view_member', $member->ID, $current_page); ?>"><?php _e('Details', 'rcp'); ?></a> |
<a href="<?php echo add_query_arg('edit_member', $member->ID, $current_page); ?>"><?php _e('Edit', 'rcp'); ?></a>
<?php if(isset($_GET['status']) && $_GET['status'] == 'cancelled') { ?>
| <a href="<?php echo add_query_arg('activate_member', $member->ID, $current_page); ?>" class="rcp_activate"><?php _e('Activate', 'rcp'); ?></a>
<?php } elseif( (isset($_GET['status']) && $_GET['status'] == 'active') || !isset($_GET['status'])) { ?>
| <a href="<?php echo add_query_arg('deactivate_member', $member->ID, $current_page); ?>" class="rcp_deactivate"><?php _e('Deactivate', 'rcp'); ?></a>
<?php } ?>
</td>
</tr>
<?php $i++;
endforeach;
else : ?>
<tr><td colspan="9"><?php _e('No subscribers found', 'rcp'); ?></td></tr>
<?php endif; ?>
</table>
<?php if ($total_pages > 1 && !isset($_GET['signup_method']) ) : ?>
<div class="tablenav">
<div class="tablenav-pages alignright">
<?php
$query_string = $_SERVER['QUERY_STRING'];
$base = 'admin.php?' . remove_query_arg('p', $query_string) . '%_%';
echo paginate_links( array(
'base' => $base,
'format' => '&p=%#%',
'prev_text' => __('« Previous'),
'next_text' => __('Next »'),
'total' => $total_pages,
'current' => $page,
'end_size' => 1,
'mid_size' => 5,
));
?>
</div>
</div><!--end .tablenav-->
<?php endif; ?>
<?php do_action('rcp_members_below_table'); ?>
<h3><?php _e('Add New Subscription (for existing user)', 'rcp'); ?></h3>
<form id="rcp-add-new-member" action="" method="post">
<table class="form-table">
<tbody>
<tr class="form-field">
<th scope="row" valign="top">
<label for="rcp-username"><?php _e('Username', 'rcp'); ?></label>
</th>
<td>
<input type="text" name="user" id="rcp-user" class="regular-text rcp-user-search" style="width: 120px;"/>
<img class="rcp-ajax waiting" src="<?php echo admin_url('images/wpspin_light.gif'); ?>" style="display: none;"/>
<div id="rcp_user_search_results"></div>
<p class="description"><?php _e('Begin typing the user name to add a subscription to.', 'rcp'); ?></p>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top">
<label for="rcp-level"><?php _e('Subscription Level', 'rcp'); ?></label>
</th>
<td>
<select name="level" id="rcp-level">
<option value="choose"><?php _e('--choose--', 'rcp'); ?></option>
<?php
foreach( rcp_get_subscription_levels() as $level) :
echo '<option value="' . $level->id . '">' . utf8_decode($level->name) . '</option>';
endforeach;
?>
</select>
<p class="description"><?php _e('Choose the subscription level for this user', 'rcp'); ?></p>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top">
<label for="rcp-expiration"><?php _e('Expiration date', 'rcp'); ?></label>
</th>
<td>
<input name="expiration" id="rcp-expiration" type="text" style="width: 120px;" class="datepicker"/>
<p class="description"><?php _e('Enter the expiration date for this user in the format of yyyy-mm-dd', 'rcp'); ?></p>
</td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="hidden" name="rcp-action" value="add-subscription"/>
<input type="submit" value="<?php _e('Add User Subscription', 'rcp'); ?>" class="button-primary"/>
</p>
</form>
<?php endif; ?>
</div><!--end wrap-->
<?php
} | gpl-2.0 |
Lythimus/lptv | apache-solr-3.6.0/solr/client/ruby/flare/config/environments/production.rb | 1334 | # 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.
# Settings specified here will take precedence over those in config/environment.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Full error reports are disabled and caching is turned on
config.action_controller.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
| gpl-2.0 |
pamfilos/invenio | modules/websubmit/lib/websubmitadmincli.py | 22182 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN.
##
## Invenio 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.
##
## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
WebSubmitAdmin CLI tool.
Usage websubmitadmin [options]
Options:
-v, --verbose Verbose level (0=min, 2=default, 3=max).
-h, --help Prints this help
-d, --dump=DOCTYPE Dump given DOCTYPE from database
-c, --clean={y|n} Create dump that includes lines to remove
submission from database before
insertion (`y', default) or not (`n'). Default 'y'
-n, --no-fail-insert Create dump that does not fail when inserting
duplicate rows
-f, --diff=DOCTYPE Diff given DOCTYPE from database with standard input
-i, --ignore={d|o|p} Ignore some differences (d=date, o=order, p=page). Use with --diff
-m, --method=METHOD Type of dumps: NAMES (default) or RELATIONS:
- NAMES: includes functions and elements (including
definitions) with a name starting with doctype,
even if not used by the submission. Might then miss
functions and elements (mostly ``generic'' ones) and
add some unwanted elements.
- RELATIONS: include all functions and elements used
by the submission. Might leave aside
elements that are defined, but not
used.
Dump submission:
Eg: websubmitadmin --dump=DEMOART > DEMOART_db_dump.sql
Dump submission including all used functions and elements definitions:
Eg: websubmitadmin --dump=DEMOART -m relations > DEMOART_db_dump.sql
Diff submission with given dump:
Eg: websubmitadmin --diff=DEMOART < DEMOART_db_dump.sql
Diff between latest version in 'master' branch of your Git repo, with
version in database:
Eg: git show master:websubmit/DEMOART_db_dump.sql | ../websubmitadmin --diff=DEMOART | less -S
Diff between CVS version and submission in database, ignoring dates
and ordering of submission fields on the page:
Eg: cvs update -p DEMOART_db_dump.sql | ./websubmitadmin -i d,o --diff=DEMOART | less -S
"""
__revision__ = "$Id$"
import os
import sys
import getopt
import difflib
import re
import time
import tempfile
from MySQLdb.converters import conversions
from MySQLdb import escape, escape_string
from invenio.config import CFG_PREFIX, CFG_TMPDIR
from invenio.dbquery import run_sql, real_escape_string
from invenio.shellutils import run_shell_command
CFG_WEBSUBMIT_DUMPER_DEFAULT_METHOD = "NAMES"
CFG_WEBSUBMIT_DUMPER_DB_SCHEMA_VERSION = 1
def dump_submission(doctype, method=None, include_cleaning=True,
ignore_duplicate_insert=False):
"""Returns a .sql dump of submission with given doctype"""
def build_table_dump(table_name, rows_with_desc, ignore_duplicate_insert):
"Build a dump-like output from the given table and rows"
table_dump = ''
for row in rows_with_desc[0]:
table_dump += 'INSERT%s INTO %s VALUES (%s);\n' % \
(ignore_duplicate_insert and ' IGNORE' or '',
table_name,
','.join([escape(column, conversions) for column in row]))
return table_dump
if not method:
method = CFG_WEBSUBMIT_DUMPER_DEFAULT_METHOD
dump_header = "-- %s dump %s v%i\n" % (doctype,
time.strftime("%Y-%m-%d %H:%M:%S"),
CFG_WEBSUBMIT_DUMPER_DB_SCHEMA_VERSION)
if method == "NAMES":
dump_header += "-- Extra:NAMES (the following dump contains rows in sbmALLFUNCDESCR, sbmFUNDESC, sbmFIELD and sbmFIELDDESC tables which are not specific to this submission, but that include keyword %s)\n" % doctype
elif method == "RELATIONS":
dump_header += "-- Extra:RELATIONS (the following dump contains rows in sbmALLFUNCDESCR, sbmFUNDESC, sbmFIELD and sbmFIELDDESC tables that are not specific to doctype %s\n" % doctype
else:
dump_header += "-- Extra:None (the following dump only has rows specific to submission %s i.e. does not contains rows from sbmALLFUNCDESCR, sbmFUNDESC, sbmFIELD and sbmFIELDDESC tables\n" % doctype
if include_cleaning:
if method == 'NAMES':
dump_header += """
DELETE FROM sbmFUNDESC WHERE function LIKE '%(doctype)s%%';
DELETE FROM sbmFIELD WHERE subname LIKE '%%%(doctype)s';
DELETE FROM sbmFIELDDESC WHERE name LIKE '%(doctype)s%%';
DELETE FROM sbmALLFUNCDESCR WHERE function LIKE '%(doctype)s%%';
""" % {'doctype': escape_string(doctype)}
elif method == "RELATIONS":
dump_header += """
DELETE sbmALLFUNCDESCR.* FROM sbmALLFUNCDESCR, sbmFUNCTIONS WHERE sbmALLFUNCDESCR.function=sbmFUNCTIONS.function and sbmFUNCTIONS.doctype='%(doctype)s';
DELETE sbmFUNDESC.* FROM sbmFUNDESC, sbmFUNCTIONS WHERE sbmFUNDESC.function=sbmFUNCTIONS.function and sbmFUNCTIONS.doctype='%(doctype)s';
DELETE sbmFIELDDESC.* FROM sbmFIELDDESC, sbmFIELD, sbmIMPLEMENT WHERE sbmFIELD.fidesc=sbmFIELDDESC.name AND sbmFIELD.subname=sbmIMPLEMENT.subname AND sbmIMPLEMENT.docname='%(doctype)s';
DELETE sbmFIELD.* FROM sbmFIELD, sbmIMPLEMENT WHERE sbmFIELD.subname=sbmIMPLEMENT.subname AND sbmIMPLEMENT.docname='%(doctype)s';
""" % {'doctype': escape_string(doctype)}
dump_header += """DELETE FROM sbmDOCTYPE WHERE sdocname='%(doctype)s';
DELETE FROM sbmCATEGORIES WHERE doctype ='%(doctype)s';
DELETE FROM sbmFUNCTIONS WHERE doctype='%(doctype)s';
DELETE FROM sbmIMPLEMENT WHERE docname='%(doctype)s';
DELETE FROM sbmPARAMETERS WHERE doctype='%(doctype)s';
""" % {'doctype': escape_string(doctype)}
dump_output = ''
res = run_sql('SELECT * FROM sbmDOCTYPE WHERE sdocname=%s', (real_escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
dump_output += build_table_dump('sbmDOCTYPE', res, ignore_duplicate_insert)
res = run_sql('SELECT * FROM sbmCATEGORIES WHERE doctype=%s', (real_escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
dump_output += build_table_dump('sbmCATEGORIES', res, ignore_duplicate_insert)
# res = run_sql("SELECT * FROM sbmFIELD WHERE subname like '%%%s'" % (escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
# dump_output += build_table_dump('sbmFIELD', res)
# res = run_sql("SELECT * FROM sbmFIELDDESC WHERE name like '%s%%'" % (escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
# dump_output += build_table_dump('sbmFIELDDESC', res)
res = run_sql('SELECT * FROM sbmFUNCTIONS WHERE doctype=%s', (real_escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
dump_output += build_table_dump('sbmFUNCTIONS', res, ignore_duplicate_insert)
res = run_sql('SELECT * FROM sbmIMPLEMENT WHERE docname=%s', (real_escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
dump_output += build_table_dump('sbmIMPLEMENT', res, ignore_duplicate_insert)
res = run_sql('SELECT * FROM sbmPARAMETERS WHERE doctype=%s', (real_escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
dump_output += build_table_dump('sbmPARAMETERS', res, ignore_duplicate_insert)
if method == "NAMES":
res = run_sql("SELECT * FROM sbmALLFUNCDESCR WHERE function LIKE '%s%%'" % (real_escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
dump_output += build_table_dump('sbmALLFUNCDESCR', res, ignore_duplicate_insert)
res = run_sql("SELECT * FROM sbmFUNDESC WHERE function LIKE '%s%%'" % (real_escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
dump_output += build_table_dump('sbmFUNDESC', res, ignore_duplicate_insert)
res = run_sql("SELECT * FROM sbmFIELD WHERE subname LIKE '%%%s'" % (real_escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
dump_output += build_table_dump('sbmFIELD', res, ignore_duplicate_insert)
res = run_sql("SELECT * FROM sbmFIELDDESC WHERE name LIKE '%s%%'" % (real_escape_string(doctype),), with_desc=1) # kwalitee: disable=sql
dump_output += build_table_dump('sbmFIELDDESC', res, ignore_duplicate_insert)
elif method == "RELATIONS":
res = run_sql("SELECT DISTINCT sbmALLFUNCDESCR.* FROM sbmALLFUNCDESCR, sbmFUNCTIONS WHERE sbmALLFUNCDESCR.function=sbmFUNCTIONS.function and sbmFUNCTIONS.doctype=%s", \
(doctype,), with_desc=1)
dump_output += build_table_dump('sbmALLFUNCDESCR', res, ignore_duplicate_insert)
res = run_sql("SELECT DISTINCT sbmFUNDESC.* FROM sbmFUNDESC, sbmFUNCTIONS WHERE sbmFUNDESC.function=sbmFUNCTIONS.function and sbmFUNCTIONS.doctype=%s", \
(doctype,), with_desc=1)
dump_output += build_table_dump('sbmFUNDESC', res, ignore_duplicate_insert)
res = run_sql("SELECT DISTINCT sbmFIELD.* FROM sbmFIELD, sbmIMPLEMENT WHERE sbmFIELD.subname=sbmIMPLEMENT.subname AND sbmIMPLEMENT.docname=%s", \
(doctype,), with_desc=1)
dump_output += build_table_dump('sbmFIELD', res, ignore_duplicate_insert)
# check:
res = run_sql("SELECT DISTINCT sbmFIELDDESC.* FROM sbmFIELDDESC, sbmFIELD, sbmIMPLEMENT WHERE sbmFIELD.fidesc=sbmFIELDDESC.name AND sbmFIELD.subname=sbmIMPLEMENT.subname AND sbmIMPLEMENT.docname=%s", \
(doctype,), with_desc=1)
#res = run_sql("SELECT DISTINCT sbmFIELDDESC.* FROM sbmFIELDDESC, sbmFIELD, sbmIMPLEMENT WHERE sbmFIELD.fidesc=sbmFIELDDESC.name AND sbmFIELDDESC.name=sbmIMPLEMENT.subname AND sbmIMPLEMENT.docname=%s", \
# (doctype,), with_desc=1)
dump_output += build_table_dump('sbmFIELDDESC', res, ignore_duplicate_insert)
# Sort
dump_output_lines = dump_output.splitlines()
dump_output_lines.sort()
return dump_header + '\n'.join(dump_output_lines)
def remove_submission(doctype, method=CFG_WEBSUBMIT_DUMPER_DEFAULT_METHOD):
"Remove submission from database"
# NOT TESTED
if method == "NAMES":
run_sql("DELETE FROM sbmFUNDESC WHERE function LIKE '%s%%'" % (real_escape_string(doctype),)) # kwalitee: disable=sql
run_sql("DELETE FROM sbmFIELD WHERE subname LIKE '%%%s'" % (real_escape_string(doctype),)) # kwalitee: disable=sql
run_sql("DELETE FROM sbmFIELDDESC WHERE name LIKE '%s%%'" % (real_escape_string(doctype),)) # kwalitee: disable=sql
run_sql("DELETE FROM sbmALLFUNCDESCR WHERE function LIKE '%s%%'" % (real_escape_string(doctype),)) # kwalitee: disable=sql
elif method == "RELATIONS":
run_sql("DELETE sbmALLFUNCDESCR.* FROM sbmALLFUNCDESCR, sbmFUNCTIONS WHERE sbmALLFUNCDESCR.function=sbmFUNCTIONS.function and sbmFUNCTIONS.doctype=%s", (doctype,))
run_sql("DELETE sbmFUNDESC.* FROM sbmFUNDESC, sbmFUNCTIONS WHERE sbmFUNDESC.function=sbmFUNCTIONS.function and sbmFUNCTIONS.doctype=%s", (doctype,))
run_sql("DELETE sbmFIELDDESC.* FROM sbmFIELDDESC, sbmFIELD, sbmIMPLEMENT WHERE sbmFIELD.fidesc=sbmFIELDDESC.name AND sbmFIELD.subname=sbmIMPLEMENT.subname AND sbmIMPLEMENT.docname=%s", (doctype,))
run_sql("DELETE sbmFIELD.* FROM sbmFIELD, sbmIMPLEMENT WHERE sbmFIELD.subname=sbmIMPLEMENT.subname AND sbmIMPLEMENT.docname=%s", (doctype,))
run_sql("DELETE FROM sbmDOCTYPE WHERE sdocname=%s", (doctype,))
run_sql("DELETE FROM sbmCATEGORIES WHERE doctype=%s", (doctype,))
run_sql("DELETE FROM sbmFUNCTIONS WHERE doctype=%s", (doctype,))
run_sql("DELETE FROM sbmIMPLEMENT WHERE docname=%s", (doctype,))
run_sql("DELETE FROM sbmPARAMETERS WHERE doctype=%s", (doctype,))
re_method_pattern = re.compile("-- Extra:(?P<method>\S*)\s")
def load_submission(doctype, dump, method=None):
"Insert submission into database. Return tuple(error code, msg)"
# NOT TESTED
messages = []
def guess_dump_method(dump):
"""Guess which method was used to dump this file (i.e. if it contains all the submission rows or not)"""
match_obj = re_method_pattern.search(dump)
if match_obj:
return match_obj.group('method')
else:
return None
def guess_dump_has_delete_statements(dump):
"""Guess if given submission dump already contain delete statements"""
return "DELETE FROM sbmDOCTYPE WHERE sdocname".lower() in dump.lower()
if not method:
method = guess_dump_method(dump)
if method is None:
method = CFG_WEBSUBMIT_DUMPER_DEFAULT_METHOD
messages.append("WARNING: method could not be guessed. Using method %s" % method)
else:
messages.append("Used method %s to load data" % method)
(dump_code, dump_path) = tempfile.mkstemp(prefix=doctype, dir=CFG_TMPDIR)
dump_fd = open(dump_path, 'w')
dump_fd.write(dump)
dump_fd.close()
# We need to remove the submission. But let's create a backup first.
submission_backup = dump_submission(doctype, method)
submission_backup_path = "%s_db_dump%s.sql" % (doctype, time.strftime("%Y%m%d_%H%M%S"))
fd = file(os.path.join(CFG_TMPDIR, submission_backup_path), "w")
fd.write(submission_backup)
fd.close()
if not guess_dump_has_delete_statements(dump):
remove_submission(doctype, method)
# Load the dump
(exit_code, out_msg, err_msg) = run_shell_command("%s/bin/dbexec < %s", (CFG_PREFIX, os.path.abspath(dump_path)))
if exit_code:
messages.append("ERROR: failed to load submission:" + err_msg)
return (1, messages)
messages.append("Submission loaded. Previous submission saved to %s" % os.path.join(CFG_TMPDIR, submission_backup_path))
return (0, messages)
def diff_submission(submission1_dump, submission2_dump, verbose=2,
ignore_dates=False, ignore_positions=False, ignore_pages=False):
"Output diff between submissions"
def clean_line(line, ignore_dates, ignore_positions, ignore_pages):
"clean one line of the submission"
updated_line = line
if ignore_dates:
if line.startswith('insert into sbmfield values'): # kwalitee: disable=sql
args = updated_line.split(",")
args[-3] = ''
args[-4] = ''
updated_line = ','.join(real_escape_string(args))
elif line.startswith('insert into sbmfielddesc values'): # kwalitee: disable=sql
args = updated_line.split(",")
args[-4] = ''
args[-5] = ''
updated_line = ','.join(real_escape_string(args))
elif line.startswith('insert into sbmimplement values '): # kwalitee: disable=sql
args = updated_line.split(",")
args[-6] = ''
args[-7] = ''
updated_line = ','.join(real_escape_string(args))
if ignore_positions:
if line.startswith('INSERT INTO sbmFIELD VALUES'): # kwalitee: disable=sql
args = updated_line.split(",")
args[2] = ''
updated_line = ','.join(real_escape_string(args))
if ignore_pages:
if line.startswith('INSERT INTO sbmFIELD VALUES'): # kwalitee: disable=sql
args = updated_line.split(",")
args[1] = ''
updated_line = ','.join(real_escape_string(args))
if line.startswith('INSERT INTO sbmIMPLEMENT VALUES '): # kwalitee: disable=sql
args = updated_line.split(",")
args[4] = ''
updated_line = ','.join(real_escape_string(args))
return updated_line
file1 = [line.strip() for line in submission1_dump.splitlines() if line]
file2 = [line.strip() for line in submission2_dump.splitlines() if line]
file1 = [clean_line(line, ignore_dates, ignore_positions, ignore_pages) for line in file1]
file2 = [clean_line(line, ignore_dates, ignore_positions, ignore_pages) for line in file2]
file1.sort()
file2.sort()
d = difflib.Differ()
result = d.compare(file2, file1)
result = [line for line in result if not line.startswith(' ')]
if verbose > 1:
result = [line.rstrip().replace('? ', ' ', 1) for line in result]
else:
result = [line for line in result if not line.startswith('? ')]
return '\n'.join(result)
def usage(exitcode=1, msg=""):
"Print usage"
print __doc__
print msg
sys.exit(exitcode)
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "hv:i:d:l:f:r:m:c:n",
["help",
"verbose=",
"ignore=",
"dump=",
"load=",
"diff=",
"remove=",
"method=",
"clean=",
"no-fail-insert",
"yes-i-know"])
except getopt.GetoptError, err:
print err
usage(1)
_ignore_date = False
_ignore_position = False
_ignore_page = False
_doctype = None
_verbose = 2
_action = None
_method = None
_clean = True
_no_fail_insert = False
_yes_i_know = False
try:
for opt in opts:
if opt[0] in ["-h", "--help"]:
usage()
elif opt[0] in ["-v", "--verbose"]:
_verbose = opt[1]
elif opt[0] in ["-m", "--method"]:
_method = opt[1].upper()
if not _method in ["NAMES", "RELATIONS"]:
usage("Parameter --method must be 'NAMES' or 'RELATIONS'")
elif opt[0] in ["-c", "--clean"]:
_clean = opt[1].lower()
if not _clean in ["y", "n"]:
usage("Parameter --clean must be 'y' or 'n'")
_clean = _clean == 'y' and True or False
elif opt[0] in ["-n", "--no-fail-insert"]:
_no_fail_insert = True
elif opt[0] in ["--yes-i-know"]:
_yes_i_know = True
elif opt[0] in ["-i", "--ignore"]:
ignore = opt[1].split(',')
if 'd' in ignore:
_ignore_date = True
if 'p' in ignore:
_ignore_page = True
if 'o' in ignore:
_ignore_position = True
elif opt[0] in ["-d", "--dump"]:
if _action:
usage("Choose only one action among --dump, --load, --diff and --remove")
_action = 'dump'
_doctype = opt[1]
elif opt[0] in ["-l", "--load"]:
if _action:
usage("Choose only one action among --dump, --load, --diff and --remove")
_action = 'load'
_doctype = opt[1]
elif opt[0] in ["-f", "--diff"]:
if _action:
usage("Choose only one action among --dump, --load, --diff and --remove")
_action = 'diff'
_doctype = opt[1]
elif opt[0] in ["-r", "--remove"]:
if _action:
usage("Choose only one action among --dump, --load, --diff and --remove")
_action = 'remove'
_doctype = opt[1]
except StandardError, _exception:
print _exception
usage(1)
if not _action:
usage(1, 'You must specify an action among --dump, --load, --diff and --remove')
if not _doctype:
usage(1, 'You must specify a doctype')
if _action == 'dump':
print dump_submission(doctype=_doctype,
method=_method,
include_cleaning=_clean,
ignore_duplicate_insert=_no_fail_insert)
elif _action == 'load':
if _yes_i_know:
input_stream = sys.stdin.read()
(code, messages) = load_submission(doctype=_doctype, dump=input_stream, method=_method)
print '\n'.join(messages)
sys.exit(code)
else:
print "Loading submission dumps using this tool is experimental. Please use 'dbexec' instead, or run with '--yes-i-know' if you really want to proceed."
sys.exit(1)
elif _action == 'diff':
if not sys.stdin.isatty():
input_stream = sys.stdin.read()
dump1 = dump_submission(doctype=_doctype,
method=_method,
include_cleaning=_clean,
ignore_duplicate_insert=_no_fail_insert)
print diff_submission(dump1, input_stream, _verbose, _ignore_date, _ignore_position, _ignore_page)
elif _action == 'remove':
if not _method:
usage(1, 'You must specify option --method')
if _yes_i_know:
remove_submission(doctype=_doctype, method=_method)
else:
print "Removing submissions using this tool is experimental. Run with '--yes-i-know' if you really want to proceed."
sys.exit(1)
if __name__ == '__main__':
main()
| gpl-2.0 |
constellationsoftware/meteor | packages/stream/stream_tests.js | 301 | Tinytest.add("stream - status", function (test) {
// Very basic test. Just see that it runs and returns something. Not a
// lot of coverage, but enough that it would have caught a recent bug.
var status = Meteor.status();
test.equal(typeof status, "object");
test.isTrue(status.status);
});
| gpl-2.0 |
arturoc/ofForum | library/core/class.email.php | 11356 | <?php if (!defined('APPLICATION')) exit();
/**
* Object Representation of an email.
*
* All public methods return $this for
* chaining purposes. ie. $Email->Subject('Hi')->Message('Just saying hi!')-
* To('[email protected]')->Send();
*
* @author Mark O'Sullivan <[email protected]>
* @author Todd Burry <[email protected]>
* @copyright 2003 Vanilla Forums, Inc
* @license http://www.opensource.org/licenses/gpl-2.0.php GPL
* @package Garden
* @since 2.0
*/
class Gdn_Email extends Gdn_Pluggable {
/**
* @var PHPMailer
*/
public $PhpMailer;
/**
* @var boolean
*/
private $_IsToSet;
/**
*
* @var array Recipients that were skipped because they lack permission.
*/
public $Skipped = array();
/**
* Constructor
*/
function __construct() {
$this->PhpMailer = new PHPMailer();
$this->PhpMailer->CharSet = C('Garden.Charset', 'utf-8');
$this->PhpMailer->SingleTo = C('Garden.Email.SingleTo', FALSE);
$this->PhpMailer->PluginDir = CombinePaths(array(PATH_LIBRARY,'vendors/phpmailer/'));
$this->PhpMailer->Hostname = C('Garden.Email.Hostname', '');
$this->PhpMailer->Encoding = 'quoted-printable';
$this->Clear();
parent::__construct();
}
/**
* Adds to the "Bcc" recipient collection.
*
* @param mixed $RecipientEmail An email (or array of emails) to add to the "Bcc" recipient collection.
* @param string $RecipientName The recipient name associated with $RecipientEmail. If $RecipientEmail is
* an array of email addresses, this value will be ignored.
* @return Email
*/
public function Bcc($RecipientEmail, $RecipientName = '') {
ob_start();
$this->PhpMailer->AddBCC($RecipientEmail, $RecipientName);
ob_end_clean();
return $this;
}
/**
* Adds to the "Cc" recipient collection.
*
* @param mixed $RecipientEmail An email (or array of emails) to add to the "Cc" recipient collection.
* @param string $RecipientName The recipient name associated with $RecipientEmail. If $RecipientEmail is
* an array of email addresses, this value will be ignored.
* @return Email
*/
public function Cc($RecipientEmail, $RecipientName = '') {
ob_start();
$this->PhpMailer->AddCC($RecipientEmail, $RecipientName);
ob_end_clean();
return $this;
}
/**
* Clears out all previously specified values for this object and restores
* it to the state it was in when it was instantiated.
*
* @return Email
*/
public function Clear() {
$this->PhpMailer->ClearAllRecipients();
$this->PhpMailer->Body = '';
$this->PhpMailer->AltBody = '';
$this->From();
$this->_IsToSet = FALSE;
$this->MimeType(Gdn::Config('Garden.Email.MimeType', 'text/plain'));
$this->_MasterView = 'email.master';
$this->Skipped = array();
return $this;
}
/**
* Allows the explicit definition of the email's sender address & name.
* Defaults to the applications Configuration 'SupportEmail' & 'SupportName'
* settings respectively.
*
* @param string $SenderEmail
* @param string $SenderName
* @return Email
*/
public function From($SenderEmail = '', $SenderName = '', $bOverrideSender = FALSE) {
if ($SenderEmail == '') {
$SenderEmail = C('Garden.Email.SupportAddress', '');
if (!$SenderEmail) {
$SenderEmail = 'noreply@'.Gdn::Request()->Host();
}
}
if ($SenderName == '')
$SenderName = C('Garden.Email.SupportName', C('Garden.Title', ''));
if($this->PhpMailer->Sender == '' || $bOverrideSender) $this->PhpMailer->Sender = $SenderEmail;
ob_start();
$this->PhpMailer->SetFrom($SenderEmail, $SenderName, FALSE);
ob_end_clean();
return $this;
}
/**
* Allows the definition of a masterview other than the default:
* "email.master".
*
* @param string $MasterView
* @todo To implement
* @return Email
*/
public function MasterView($MasterView) {
return $this;
}
/**
* The message to be sent.
*
* @param string $Message The message to be sent.
* @param string $TextVersion Optional plaintext version of the message
* @return Email
*/
public function Message($Message) {
// htmlspecialchars_decode is being used here to revert any specialchar escaping done by Gdn_Format::Text()
// which, untreated, would result in ' in the message in place of single quotes.
if ($this->PhpMailer->ContentType == 'text/html') {
$TextVersion = FALSE;
if (stristr($Message, '<!-- //TEXT VERSION FOLLOWS//')) {
$EmailParts = explode('<!-- //TEXT VERSION FOLLOWS//', $Message);
$TextVersion = array_pop($EmailParts);
$Message = array_shift($EmailParts);
$TextVersion = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$TextVersion)));
$Message = trim($Message);
}
$this->PhpMailer->MsgHTML(htmlspecialchars_decode($Message,ENT_QUOTES));
if ($TextVersion !== FALSE && !empty($TextVersion)) {
$TextVersion = html_entity_decode($TextVersion);
$this->PhpMailer->AltBody = $TextVersion;
}
} else {
$this->PhpMailer->Body = htmlspecialchars_decode($Message,ENT_QUOTES);
}
return $this;
}
public static function GetTextVersion($Template) {
if (stristr($Template, '<!-- //TEXT VERSION FOLLOWS//')) {
$EmailParts = explode('<!-- //TEXT VERSION FOLLOWS//', $Template);
$TextVersion = array_pop($EmailParts);
$TextVersion = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$TextVersion)));
return $TextVersion;
}
return FALSE;
}
public static function GetHTMLVersion($Template) {
if (stristr($Template, '<!-- //TEXT VERSION FOLLOWS//')) {
$EmailParts = explode('<!-- //TEXT VERSION FOLLOWS//', $Template);
$TextVersion = array_pop($EmailParts);
$Message = array_shift($EmailParts);
$Message = trim($Message);
return $Message;
}
return $Template;
}
/**
* Sets the mime-type of the email.
*
* Only accept text/plain or text/html.
*
* @param string $MimeType The mime-type of the email.
* @return Email
*/
public function MimeType($MimeType) {
$this->PhpMailer->IsHTML($MimeType === 'text/html');
return $this;
}
/**
* @todo add port settings
*/
public function Send($EventName = '') {
if (Gdn::Config('Garden.Email.UseSmtp')) {
$this->PhpMailer->IsSMTP();
$SmtpHost = Gdn::Config('Garden.Email.SmtpHost', '');
$SmtpPort = Gdn::Config('Garden.Email.SmtpPort', 25);
if (strpos($SmtpHost, ':') !== FALSE) {
list($SmtpHost, $SmtpPort) = explode(':', $SmtpHost);
}
$this->PhpMailer->Host = $SmtpHost;
$this->PhpMailer->Port = $SmtpPort;
$this->PhpMailer->SMTPSecure = Gdn::Config('Garden.Email.SmtpSecurity', '');
$this->PhpMailer->Username = $Username = Gdn::Config('Garden.Email.SmtpUser', '');
$this->PhpMailer->Password = $Password = Gdn::Config('Garden.Email.SmtpPassword', '');
if(!empty($Username))
$this->PhpMailer->SMTPAuth = TRUE;
} else {
$this->PhpMailer->IsMail();
}
if($EventName != ''){
$this->EventArguments['EventName'] = $EventName;
$this->FireEvent('SendMail');
}
if (!empty($this->Skipped) && $this->PhpMailer->CountRecipients() == 0) {
// We've skipped all recipients.
return TRUE;
}
$this->PhpMailer->ThrowExceptions(TRUE);
if (!$this->PhpMailer->Send()) {
throw new Exception($this->PhpMailer->ErrorInfo);
}
return TRUE;
}
/**
* Adds subject of the message to the email.
*
* @param string $Subject The subject of the message.
*/
public function Subject($Subject) {
$this->PhpMailer->Subject = $Subject;
return $this;
}
public function AddTo($RecipientEmail, $RecipientName = ''){
ob_start();
$this->PhpMailer->AddAddress($RecipientEmail, $RecipientName);
ob_end_clean();
return $this;
}
/**
* Adds to the "To" recipient collection.
*
* @param mixed $RecipientEmail An email (or array of emails) to add to the "To" recipient collection.
* @param string $RecipientName The recipient name associated with $RecipientEmail. If $RecipientEmail is
* an array of email addresses, this value will be ignored.
*/
public function To($RecipientEmail, $RecipientName = '') {
if (is_string($RecipientEmail)) {
if (strpos($RecipientEmail, ',') > 0) {
$RecipientEmail = explode(',', $RecipientEmail);
// trim no need, PhpMailer::AddAnAddress() will do it
return $this->To($RecipientEmail, $RecipientName);
}
if ($this->PhpMailer->SingleTo) return $this->AddTo($RecipientEmail, $RecipientName);
if (!$this->_IsToSet){
$this->_IsToSet = TRUE;
$this->AddTo($RecipientEmail, $RecipientName);
} else
$this->Cc($RecipientEmail, $RecipientName);
return $this;
} elseif ((is_object($RecipientEmail) && property_exists($RecipientEmail, 'Email'))
|| (is_array($RecipientEmail) && isset($RecipientEmail['Email']))) {
$User = $RecipientEmail;
$RecipientName = GetValue('Name', $User);
$RecipientEmail = GetValue('Email', $User);
$UserID = GetValue('UserID', $User, FALSE);
if ($UserID !== FALSE) {
// Check to make sure the user can receive email.
if (!Gdn::UserModel()->CheckPermission($UserID, 'Garden.Email.View')) {
$this->Skipped[] = $User;
return $this;
}
}
return $this->To($RecipientEmail, $RecipientName);
} elseif ($RecipientEmail instanceof Gdn_DataSet) {
foreach($RecipientEmail->ResultObject() as $Object) $this->To($Object);
return $this;
} elseif (is_array($RecipientEmail)) {
$Count = count($RecipientEmail);
if (!is_array($RecipientName)) $RecipientName = array_fill(0, $Count, '');
if ($Count == count($RecipientName)) {
$RecipientEmail = array_combine($RecipientEmail, $RecipientName);
foreach($RecipientEmail as $Email => $Name) $this->To($Email, $Name);
} else
trigger_error(ErrorMessage('Size of arrays do not match', 'Email', 'To'), E_USER_ERROR);
return $this;
}
trigger_error(ErrorMessage('Incorrect first parameter ('.GetType($RecipientEmail).') passed to function.', 'Email', 'To'), E_USER_ERROR);
}
public function Charset($Use = ''){
if ($Use != '') {
$this->PhpMailer->CharSet = $Use;
return $this;
}
return $this->PhpMailer->CharSet;
}
} | gpl-2.0 |
amirchrist/phpwcms | include/inc_module/mod_glossary/inc/cnt.sql.php | 799 | <?php
/**
* phpwcms content management system
*
* @author Oliver Georgi <[email protected]>
* @copyright Copyright (c) 2002-2015, Oliver Georgi
* @license http://opensource.org/licenses/GPL-2.0 GNU GPL-2
* @link http://www.phpwcms.de
*
**/
// ----------------------------------------------------------------
// obligate check for phpwcms constants
if (!defined('PHPWCMS_ROOT')) {
die("You Cannot Access This Script Directly, Have a Nice Day.");
}
// ----------------------------------------------------------------
// Glossary module content part SQL UPDATE/INSERT
// usage:
// SQL .= "acontent_field = '".aporeplace($value)."', ";
if(isset($content['glossary']) && is_array($content['glossary'])) {
$SQL .= "acontent_form = '".aporeplace(serialize($content['glossary']))."'";
}
?> | gpl-2.0 |
amirus2303/projet-test-gulp | wp-content/themes/activebox/location.php | 896 | <section class="bg_blue">
<div class="container">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="row padding_top_70 padding_bottom_70 text-center">
<div class="col-xs-4">
<h3 class="light">Location</h3>
<p class="location"><?php the_field('adresse'); ?></p>
</div>
<div class="col-xs-4">
<h3 class="light margin_bottom_25">Share with Love</h3>
<p class="location"><i class="fa fa-facebook"></i><i class="fa fa-twitter"></i><i class="fa fa-linkedin-square"></i></p>
</div>
<div class="col-xs-4">
<h3 class="light">About ActiveBox</h3>
<p class="location"><?php the_field('texte_apropos'); ?></p>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
</section> | gpl-2.0 |
jgabriellima/lincsgp | application/models/DbTable/Orcamento.php | 125 | <?php
class Application_Model_DbTable_Orcamento extends Zend_Db_Table_Abstract
{
protected $_name = 'orcamento';
}
?> | gpl-2.0 |
gwupe/Gwupe | BlitsMeAgent/Exceptions/LoginException.cs | 747 | using System;
namespace Gwupe.Agent.Exceptions
{
public class LoginException : Exception
{
public bool AuthFailure;
public bool InvalidDetails;
public string Failure;
public const String INCORRECT_PASSWORD = "INCORRECT_PASSWORD";
public const String EMPTY_DETAILS = "EMPTY_DETAILS";
public LoginException(String message)
: base(message)
{
}
public LoginException(String message, string failure)
: base(message)
{
this.AuthFailure = failure.Equals(INCORRECT_PASSWORD);
this.InvalidDetails = failure.Equals(EMPTY_DETAILS);
this.Failure = failure;
}
}
}
| gpl-2.0 |
cblichmann/idajava | javasrc/src/de/blichmann/idajava/natives/loader_t.java | 1407 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.0
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package de.blichmann.idajava.natives;
public class loader_t {
private long swigCPtr;
protected boolean swigCMemOwn;
public loader_t(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
public static long getCPtr(loader_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
IdaJavaJNI.delete_loader_t(swigCPtr);
}
swigCPtr = 0;
}
}
public void setVersion(long value) {
IdaJavaJNI.loader_t_version_set(swigCPtr, this, value);
}
public long getVersion() {
return IdaJavaJNI.loader_t_version_get(swigCPtr, this);
}
public void setFlags(long value) {
IdaJavaJNI.loader_t_flags_set(swigCPtr, this, value);
}
public long getFlags() {
return IdaJavaJNI.loader_t_flags_get(swigCPtr, this);
}
public loader_t() {
this(IdaJavaJNI.new_loader_t(), true);
}
}
| gpl-2.0 |
tomlanyon/python-virtinst | virtinst/VirtualNetworkInterface.py | 13592 | #
# Copyright 2006-2009 Red Hat, Inc.
# Jeremy Katz <[email protected]>
#
# 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.
import logging
import libvirt
import _util
import VirtualDevice
import XMLBuilderDomain
from XMLBuilderDomain import _xml_property
from virtinst import _gettext as _
def _countMACaddr(vms, searchmac):
if not searchmac:
return
def count_cb(ctx):
c = 0
for mac in ctx.xpathEval("/domain/devices/interface/mac"):
macaddr = mac.xpathEval("attribute::address")[0].content
if macaddr and _util.compareMAC(searchmac, macaddr) == 0:
c += 1
return c
count = 0
for vm in vms:
xml = vm.XMLDesc(0)
count += _util.get_xml_path(xml, func=count_cb)
return count
class VirtualPort(XMLBuilderDomain.XMLBuilderDomain):
def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None):
XMLBuilderDomain.XMLBuilderDomain.__init__(self, conn, parsexml,
parsexmlnode, caps=caps)
self._type = None
self._managerid = None
self._typeid = None
self._typeidversion = None
self._instanceid = None
def get_type(self):
return self._type
def set_type(self, val):
self._type = val
type = _xml_property(get_type, set_type,
xpath="./virtualport/@type")
def get_managerid(self):
return self._managerid
def set_managerid(self, val):
self._managerid = val
managerid = _xml_property(get_managerid, set_managerid,
xpath="./virtualport/parameters/@managerid")
def get_typeid(self):
return self._typeid
def set_typeid(self, val):
self._typeid = val
typeid = _xml_property(get_typeid, set_typeid,
xpath="./virtualport/parameters/@typeid")
def get_typeidversion(self):
return self._typeidversion
def set_typeidversion(self, val):
self._typeidversion = val
typeidversion = _xml_property(get_typeidversion, set_typeidversion,
xpath="./virtualport/parameters/@typeidversion")
def get_instanceid(self):
return self._instanceid
def set_instanceid(self, val):
self._instanceid = val
instanceid = _xml_property(get_instanceid, set_instanceid,
xpath="./virtualport/parameters/@instanceid")
def _get_xml_config(self):
# FIXME: This should be implemented, currently we can only parse
return ""
class VirtualNetworkInterface(VirtualDevice.VirtualDevice):
_virtual_device_type = VirtualDevice.VirtualDevice.VIRTUAL_DEV_NET
TYPE_BRIDGE = "bridge"
TYPE_VIRTUAL = "network"
TYPE_USER = "user"
TYPE_ETHERNET = "ethernet"
TYPE_DIRECT = "direct"
network_types = [TYPE_BRIDGE, TYPE_VIRTUAL, TYPE_USER, TYPE_ETHERNET,
TYPE_DIRECT]
def get_network_type_desc(net_type):
"""
Return human readable description for passed network type
"""
desc = net_type.capitalize()
if net_type == VirtualNetworkInterface.TYPE_BRIDGE:
desc = _("Shared physical device")
elif net_type == VirtualNetworkInterface.TYPE_VIRTUAL:
desc = _("Virtual networking")
elif net_type == VirtualNetworkInterface.TYPE_USER:
desc = _("Usermode networking")
return desc
get_network_type_desc = staticmethod(get_network_type_desc)
def __init__(self, macaddr=None, type=TYPE_BRIDGE, bridge=None,
network=None, model=None, conn=None,
parsexml=None, parsexmlnode=None, caps=None):
VirtualDevice.VirtualDevice.__init__(self, conn, parsexml,
parsexmlnode, caps)
self._network = None
self._bridge = None
self._macaddr = None
self._type = None
self._model = None
self._target_dev = None
self._source_dev = None
self._source_mode = "vepa"
self._virtualport = VirtualPort(conn, parsexml, parsexmlnode, caps)
# Generate _random_mac
self._random_mac = None
self._default_bridge = None
if self._is_parse():
return
self.type = type
self.macaddr = macaddr
self.bridge = bridge
self.source_dev = bridge
self.network = network
self.model = model
if self.type == self.TYPE_VIRTUAL:
if network is None:
raise ValueError(_("A network name was not provided"))
def _generate_default_bridge(self):
ret = self._default_bridge
if ret is None:
ret = False
default = _util.default_bridge2(self.conn)
if default:
ret = default[1]
self._default_bridge = ret
return ret or None
def _generate_random_mac(self):
if self.conn and not self._random_mac:
found = False
for ignore in range(256):
self._random_mac = _util.randomMAC(self.conn.getType().lower(),
conn=self.conn)
ret = self.is_conflict_net(self.conn, self._random_mac)
if ret[1] is not None:
continue
found = True
break
if not found:
logging.debug("Failed to generate non-conflicting MAC")
return self._random_mac
def get_source(self):
"""
Convenince function, try to return the relevant <source> value
per the network type.
"""
if self.type == self.TYPE_VIRTUAL:
return self.network
if self.type == self.TYPE_BRIDGE:
return self.bridge
if self.type == self.TYPE_ETHERNET or self.type == self.TYPE_DIRECT:
return self.source_dev
if self.type == self.TYPE_USER:
return None
return self.network or self.bridge or self.source_dev
def set_source(self, newsource):
"""
Conveninece function, try to set the relevant <source> value
per the network type
"""
if self.type == self.TYPE_VIRTUAL:
self.network = newsource
elif self.type == self.TYPE_BRIDGE:
self.bridge = newsource
elif self.type == self.TYPE_ETHERNET or self.type == self.TYPE_DIRECT:
self.source_dev = newsource
return
source = property(get_source, set_source)
def _get_virtualport(self):
return self._virtualport
virtualport = property(_get_virtualport)
def get_type(self):
return self._type
def set_type(self, val):
if val not in self.network_types:
raise ValueError(_("Unknown network type %s") % val)
self._type = val
type = _xml_property(get_type, set_type,
xpath="./@type")
def get_macaddr(self):
# Don't generate a random MAC if parsing XML, since it can be slow
if not self._macaddr and not self._is_parse():
return self._generate_random_mac()
return self._macaddr
def set_macaddr(self, val):
_util.validate_macaddr(val)
self._macaddr = val
macaddr = _xml_property(get_macaddr, set_macaddr,
xpath="./mac/@address")
def get_network(self):
return self._network
def set_network(self, newnet):
def _is_net_active(netobj):
# Apparently the 'info' command was never hooked up for
# libvirt virNetwork python apis.
if not self.conn:
return True
return self.conn.listNetworks().count(netobj.name())
if newnet is not None and self.conn:
try:
net = self.conn.networkLookupByName(newnet)
except libvirt.libvirtError, e:
raise ValueError(_("Virtual network '%s' does not exist: %s") \
% (newnet, str(e)))
if not _is_net_active(net):
raise ValueError(_("Virtual network '%s' has not been "
"started.") % newnet)
self._network = newnet
network = _xml_property(get_network, set_network,
xpath="./source/@network")
def get_bridge(self):
if (not self._is_parse() and
not self._bridge and
self.type == self.TYPE_BRIDGE):
return self._generate_default_bridge()
return self._bridge
def set_bridge(self, val):
self._bridge = val
bridge = _xml_property(get_bridge, set_bridge,
xpath="./source/@bridge")
def get_model(self):
return self._model
def set_model(self, val):
self._model = val
model = _xml_property(get_model, set_model,
xpath="./model/@type")
def get_target_dev(self):
return self._target_dev
def set_target_dev(self, val):
self._target_dev = val
target_dev = _xml_property(get_target_dev, set_target_dev,
xpath="./target/@dev")
def get_source_dev(self):
return self._source_dev
def set_source_dev(self, val):
self._source_dev = val
source_dev = _xml_property(get_source_dev, set_source_dev,
xpath="./source/@dev")
def get_source_mode(self):
return self._source_mode
def set_source_mode(self, newmode):
self._source_mode = newmode
source_mode = _xml_property(get_source_mode, set_source_mode,
xpath="./source/@mode")
def is_conflict_net(self, conn, mac=None):
"""
@returns: a two element tuple:
first element is True if fatal collision occured
second element is a string description of the collision.
Non fatal collisions (mac addr collides with inactive guest) will
return (False, "description of collision")
"""
mac = mac or self.macaddr
if mac is None:
return (False, None)
vms, inactive_vm = _util.fetch_all_guests(conn)
# get the Host's NIC MAC address
hostdevs = []
if not self.is_remote():
hostdevs = _util.get_host_network_devices()
if (_countMACaddr(vms, mac) > 0 or
_countMACaddr(inactive_vm, mac) > 0):
return (True, _("The MAC address you entered is already in use "
"by another virtual machine."))
for dev in hostdevs:
host_macaddr = dev[4]
if mac.upper() == host_macaddr.upper():
return (True, _("The MAC address you entered conflicts with "
"a device on the physical host."))
return (False, None)
def setup_dev(self, conn=None, meter=None):
return self.setup(conn)
def setup(self, conn=None):
"""
DEPRECATED: Please use setup_dev instead
"""
# Access self.macaddr to generate a random one
if not self.conn and conn:
self.conn = conn
if not conn:
conn = self.conn
if self.macaddr:
ret, msg = self.is_conflict_net(conn)
if msg is not None:
if ret is False:
logging.warning(msg)
else:
raise RuntimeError(msg)
def _get_xml_config(self):
src_xml = ""
model_xml = ""
target_xml = ""
addr_xml = ""
if self.type == self.TYPE_BRIDGE:
src_xml = " <source bridge='%s'/>\n" % self.bridge
elif self.type == self.TYPE_VIRTUAL:
src_xml = " <source network='%s'/>\n" % self.network
elif self.type == self.TYPE_ETHERNET and self.source_dev:
src_xml = " <source dev='%s'/>\n" % self.source_dev
elif self.type == self.TYPE_DIRECT and self.source_dev:
src_xml = " <source dev='%s' mode='%s'/>\n" % (self.source_dev, self.source_mode)
if self.model:
model_xml = " <model type='%s'/>\n" % self.model
if self.address:
addr_xml = self.indent(self.address.get_xml_config(), 6)
if self.target_dev:
target_xml = " <target dev='%s'/>\n" % self.target_dev
xml = " <interface type='%s'>\n" % self.type
xml += src_xml
xml += " <mac address='%s'/>\n" % self.macaddr
xml += target_xml
xml += model_xml
xml += addr_xml
xml += " </interface>"
return xml
# Back compat class to avoid ABI break
class XenNetworkInterface(VirtualNetworkInterface):
pass
| gpl-2.0 |
leupibr/BakeryDMS | src/views/bootstrap/class.RewindWorkflow.php | 4863 | <?php
// BakeryDMS. PHP based document management system with workflow support.
// Copyright (C) 2002-2005 Markus Westphal
// Copyright (C) 2006-2008 Malcolm Cowe
// Copyright (C) 2010 Matteo Lucarelli
// Copyright (C) 2010 Uwe Steinmann
// Copyright (C) 2014-2015 Bruno Leupi, Tobias Maestrini
//
// 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 parent class.
*/
require_once("class.Bootstrap.php");
/**
* Class which outputs the html page for RewindWorkflow view
*/
class SeedDMS_View_RewindWorkflow extends SeedDMS_Bootstrap_Style {
function show() {
$dms = $this->params['dms'];
$user = $this->params['user'];
$folder = $this->params['folder'];
$document = $this->params['document'];
$latestContent = $document->getLatestContent();
$this->htmlStartPage(getMLText("document_title", array("documentname" => htmlspecialchars($document->getName()))));
$this->globalNavigation($folder);
$this->contentStart();
$this->pageNavigation($this->getFolderPathHTML($folder, true, $document), "view_document", $document);
$this->contentHeading(getMLText("rewind_workflow"));
$currentstate = $latestContent->getWorkflowState();
$wkflog = $latestContent->getWorkflowLog();
$workflow = $latestContent->getWorkflow();
$msg = "The document is currently in state: " . $currentstate->getName() . "<br />";
if ($wkflog) {
foreach ($wkflog as $entry) {
if ($entry->getTransition()->getNextState()->getID() == $currentstate->getID()) {
$enterdate = $entry->getDate();
$d = strptime($enterdate, '%Y-%m-%d %H:%M:%S');
$enterts = mktime($d['tm_hour'],
$d['tm_min'],
$d['tm_sec'],
$d['tm_mon'] + 1,
$d['tm_mday'],
$d['tm_year'] + 1900);
}
}
$msg .= "The state was entered at " . $enterdate . " which was ";
$msg .= getReadableDuration((time() - $enterts)) . " ago.<br />";
}
$msg .= "The document may stay in this state for " . $currentstate->getMaxTime() . " sec.";
$this->infoMsg($msg);
$this->contentContainerStart();
// Display the Workflow form.
?>
<div class="row-fluid">
<div class="span4">
<p><?php printMLText("rewind_workflow_warning"); ?></p>
<form method="post" action="../op/op.RewindWorkflow.php" name="form1" onsubmit="return checkForm();">
<?php echo createHiddenFieldWithKey('rewindworkflow'); ?>
<table>
<tr>
<td></td>
<td>
<input type='hidden' name='documentid' value='<?php echo $document->getId(); ?>'/>
<input type='hidden' name='version' value='<?php echo $latestContent->getVersion(); ?>'/>
<input type='submit' class="btn" value='<?php printMLText("rewind_workflow"); ?>'/>
</td>
</tr>
</table>
</form>
</div>
<div id="workflowgraph" class="span8">
<iframe src="out.WorkflowGraph.php?workflow=<?php echo $workflow->getID(); ?>"
width="100%"
height="400"
style="border: 1px solid #AAA;"></iframe>
</div>
</div>
<?php
$this->contentContainerEnd();
if ($wkflog) {
$this->contentContainerStart();
echo "<table class=\"table-condensed\">";
echo "<tr><th>" . getMLText('action') . "</th><th>Start state</th><th>End state</th><th>" . getMLText('date') . "</th><th>" . getMLText('user') . "</th><th>" . getMLText('comment') . "</th></tr>";
foreach ($wkflog as $entry) {
echo "<tr>";
echo "<td>" . getMLText('action_' . $entry->getTransition()->getAction()->getName()) . "</td>";
echo "<td>" . $entry->getTransition()->getState()->getName() . "</td>";
echo "<td>" . $entry->getTransition()->getNextState()->getName() . "</td>";
echo "<td>" . $entry->getDate() . "</td>";
echo "<td>" . $entry->getUser()->getFullname() . "</td>";
echo "<td>" . $entry->getComment() . "</td>";
echo "</tr>";
}
echo "</table>\n";
$this->contentContainerEnd();
}
$this->htmlEndPage();
}
}
?>
| gpl-2.0 |
oat-sa/qti-sdk | src/qtism/data/state/MatchTableEntryCollection.php | 1623 | <?php
/**
* 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; under version 2
* of the License (non-upgradable).
*
* 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.
*
* Copyright (c) 2013-2020 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
*
* @author Jérôme Bogaerts <[email protected]>
* @license GPLv2
*/
namespace qtism\data\state;
use InvalidArgumentException;
use qtism\data\QtiComponentCollection;
/**
* A collection of MatchTableEntry objects.
*/
class MatchTableEntryCollection extends QtiComponentCollection
{
/**
* Check if a given $value is an instance of MatchTableEntry.
*
* @param mixed $value
* @throws InvalidArgumentException If the given $value is not an instance of MatchTableEntry.
*/
protected function checkType($value)
{
if (!$value instanceof MatchTableEntry) {
$msg = "MatchTableEntryCollection only accepts to store MatchTableEntry objects, '" . gettype($value) . "' given.";
throw new InvalidArgumentException($msg);
}
}
}
| gpl-2.0 |
saikiran321/wordpress | wp-content/plugins/classi/library/widget/category_widget.php | 4333 | <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class CC_Widget_Categories extends WP_Widget {
function __construct() {
$widget_ops = array('classname' => 'cc_widget_categories', 'description' => __("A list or dropdown of categories for place"));
parent::__construct('custom-categories', __('Classicraft Categories'), $widget_ops);
}
function widget($args, $instance) {
extract($args);
$title = apply_filters('widget_title', empty($instance['title']) ? __('Classicraft Categories') : $instance['title'], $instance, $this->id_base);
$c = !empty($instance['count']) ? '1' : '0';
$h = !empty($instance['hierarchical']) ? '1' : '0';
$d = !empty($instance['dropdown']) ? '1' : '0';
echo $before_widget;
if ($title)
echo $before_title . $title . $after_title;
$cat_args = array('orderby' => 'name', 'show_count' => $c, 'hierarchical' => $h, 'taxonomy' => CUSTOM_CAT_TYPE, 'hide_empty' => 1,);
if ($d) {
$taxonomies = array(CUSTOM_CAT_TYPE);
$args = array('orderby' => 'count', 'hide_empty' => true);
echo cc_get_cate_dropdown($taxonomies, $args);
$cat_args['show_option_none'] = __('Select Category');
?>
<script type='text/javascript'>
/* <![CDATA[ */
var dropdown = document.getElementById("cat");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value != '' ) {
location.href = "<?php echo home_url(); ?>/?<?php echo CUSTOM_CAT_TYPE; ?>="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
/* ]]> */
</script>
<?php
} else {
?>
<ul>
<?php
$cat_args['title_li'] = '';
wp_list_categories($cat_args);
?>
</ul>
<?php
}
echo $after_widget;
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['count'] = !empty($new_instance['count']) ? 1 : 0;
$instance['hierarchical'] = !empty($new_instance['hierarchical']) ? 1 : 0;
$instance['dropdown'] = !empty($new_instance['dropdown']) ? 1 : 0;
return $instance;
}
function form($instance) {
//Defaults
$instance = wp_parse_args((array) $instance, array('title' => ''));
$title = esc_attr($instance['title']);
$count = isset($instance['count']) ? (bool) $instance['count'] : false;
$hierarchical = isset($instance['hierarchical']) ? (bool) $instance['hierarchical'] : false;
$dropdown = isset($instance['dropdown']) ? (bool) $instance['dropdown'] : false;
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>
<p><input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('dropdown'); ?>" name="<?php echo $this->get_field_name('dropdown'); ?>"<?php checked($dropdown); ?> />
<label for="<?php echo $this->get_field_id('dropdown'); ?>"><?php _e('Display as dropdown'); ?></label><br />
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>"<?php checked($count); ?> />
<label for="<?php echo $this->get_field_id('count'); ?>"><?php _e('Show post counts'); ?></label><br />
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('hierarchical'); ?>" name="<?php echo $this->get_field_name('hierarchical'); ?>"<?php checked($hierarchical); ?> />
<label for="<?php echo $this->get_field_id('hierarchical'); ?>"><?php _e('Show hierarchy'); ?></label></p>
<?php
}
}
register_widget('CC_Widget_Categories');
?> | gpl-2.0 |
Yamatoo/DiamondCore | src/server/game/Handlers/LFGHandler.cpp | 27458 | /*
* Copyright (C) 2013 DiamonEMU <http://diamondemu.freeforums.org/>
* 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 "LFGMgr.h"
#include "ObjectMgr.h"
#include "Group.h"
#include "Player.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "WorldSession.h"
void BuildPlayerLockDungeonBlock(WorldPacket& data, LfgLockMap const& lock)
{
data << uint32(lock.size()); // Size of lock dungeons
for (LfgLockMap::const_iterator it = lock.begin(); it != lock.end(); ++it)
{
data << uint32(it->first); // Dungeon entry (id + type)
data << uint32(it->second); // Lock status
data << uint32(0); // Unknown 4.2.2
data << uint32(0); // Unknown 4.2.2
}
}
void BuildPartyLockDungeonBlock(WorldPacket& data, const LfgLockPartyMap& lockMap)
{
data << uint8(lockMap.size());
for (LfgLockPartyMap::const_iterator it = lockMap.begin(); it != lockMap.end(); ++it)
{
data << uint64(it->first); // Player guid
BuildPlayerLockDungeonBlock(data, it->second);
}
}
void WorldSession::HandleLfgJoinOpcode(WorldPacket& recvData)
{
if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER) ||
(GetPlayer()->GetGroup() && GetPlayer()->GetGroup()->GetLeaderGUID() != GetPlayer()->GetGUID() &&
(GetPlayer()->GetGroup()->GetMembersCount() == MAXGROUPSIZE || !GetPlayer()->GetGroup()->isLFGGroup())))
{
recvData.rfinish();
return;
}
uint8 numDungeons;
uint32 roles;
recvData >> roles;
recvData.read_skip<uint16>(); // uint8 (always 0) - uint8 (always 0)
recvData >> numDungeons;
if (!numDungeons)
{
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_JOIN %s no dungeons selected", GetPlayerInfo().c_str());
recvData.rfinish();
return;
}
LfgDungeonSet newDungeons;
for (int8 i = 0; i < numDungeons; ++i)
{
uint32 dungeon;
recvData >> dungeon;
newDungeons.insert((dungeon & 0x00FFFFFF)); // remove the type from the dungeon entry
}
recvData.read_skip<uint32>(); // for 0..uint8 (always 3) { uint8 (always 0) }
std::string comment;
recvData >> comment;
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_JOIN %s roles: %u, Dungeons: %u, Comment: %s",
GetPlayerInfo().c_str(), roles, uint8(newDungeons.size()), comment.c_str());
sLFGMgr->JoinLfg(GetPlayer(), uint8(roles), newDungeons, comment);
}
void WorldSession::HandleLfgLeaveOpcode(WorldPacket& /*recvData*/)
{
Group* group = GetPlayer()->GetGroup();
uint64 guid = GetPlayer()->GetGUID();
uint64 gguid = group ? group->GetGUID() : guid;
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_LEAVE %s in group: %u",
GetPlayerInfo().c_str(), group ? 1 : 0);
// Check cheating - only leader can leave the queue
if (!group || group->GetLeaderGUID() == GetPlayer()->GetGUID())
sLFGMgr->LeaveLfg(gguid);
}
void WorldSession::HandleLfgProposalResultOpcode(WorldPacket& recvData)
{
uint32 lfgGroupID; // Internal lfgGroupID
bool accept; // Accept to join?
recvData >> lfgGroupID;
recvData >> accept;
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_PROPOSAL_RESULT %s proposal: %u accept: %u",
GetPlayerInfo().c_str(), lfgGroupID, accept ? 1 : 0);
sLFGMgr->UpdateProposal(lfgGroupID, GetPlayer()->GetGUID(), accept);
}
void WorldSession::HandleLfgSetRolesOpcode(WorldPacket& recvData)
{
uint8 roles;
recvData >> roles; // Player Group Roles
uint64 guid = GetPlayer()->GetGUID();
Group* group = GetPlayer()->GetGroup();
if (!group)
{
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_SET_ROLES %s Not in group",
GetPlayerInfo().c_str());
return;
}
uint64 gguid = group->GetGUID();
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_SET_ROLES: Group %u, Player %s, Roles: %u",
GUID_LOPART(gguid), GetPlayerInfo().c_str(), roles);
sLFGMgr->UpdateRoleCheck(gguid, guid, roles);
}
void WorldSession::HandleLfgSetCommentOpcode(WorldPacket& recvData)
{
std::string comment;
recvData >> comment;
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_SET_COMMENT %s comment: %s",
GetPlayerInfo().c_str(), comment.c_str());
sLFGMgr->SetComment(GetPlayer()->GetGUID(), comment);
}
void WorldSession::HandleLfgSetBootVoteOpcode(WorldPacket& recvData)
{
bool agree; // Agree to kick player
recvData >> agree;
uint64 guid = GetPlayer()->GetGUID();
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_SET_BOOT_VOTE %s agree: %u",
GetPlayerInfo().c_str(), agree ? 1 : 0);
sLFGMgr->UpdateBoot(guid, agree);
}
void WorldSession::HandleLfgTeleportOpcode(WorldPacket& recvData)
{
bool out;
recvData >> out;
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_TELEPORT %s out: %u",
GetPlayerInfo().c_str(), out ? 1 : 0);
sLFGMgr->TeleportPlayer(GetPlayer(), out, true);
}
void WorldSession::HandleLfgPlayerLockInfoRequestOpcode(WorldPacket& /*recvData*/)
{
uint64 guid = GetPlayer()->GetGUID();
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_PLAYER_LOCK_INFO_REQUEST %s",
GetPlayerInfo().c_str());
// Get Random dungeons that can be done at a certain level and expansion
LfgDungeonSet randomDungeons;
uint8 level = GetPlayer()->getLevel();
uint8 expansion = GetPlayer()->GetSession()->Expansion();
LFGDungeonContainer& LfgDungeons = sLFGMgr->GetLFGDungeonMap();
for (LFGDungeonContainer::const_iterator itr = LfgDungeons.begin(); itr != LfgDungeons.end(); ++itr)
{
LFGDungeonData const& dungeon = itr->second;
if ((dungeon.type == LFG_TYPE_RANDOM || (dungeon.seasonal && sLFGMgr->IsSeasonActive(dungeon.id)))
&& dungeon.expansion <= expansion && dungeon.minlevel <= level && level <= dungeon.maxlevel)
randomDungeons.insert(dungeon.Entry());
}
// Get player locked Dungeons
LfgLockMap const& lock = sLFGMgr->GetLockedDungeons(guid);
uint32 rsize = uint32(randomDungeons.size());
uint32 lsize = uint32(lock.size());
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_PLAYER_INFO %s", GetPlayerInfo().c_str());
WorldPacket data(SMSG_LFG_PLAYER_INFO, 1 + rsize * (4 + 1 + 4 + 4 + 4 + 4 + 1 + 4 + 4 + 4) + 4 + lsize * (1 + 4 + 4 + 4 + 4 + 1 + 4 + 4 + 4));
data << uint8(randomDungeons.size()); // Random Dungeon count
for (LfgDungeonSet::const_iterator it = randomDungeons.begin(); it != randomDungeons.end(); ++it)
{
data << uint32(*it); // Dungeon Entry (id + type)
LfgReward const* reward = sLFGMgr->GetRandomDungeonReward(*it, level);
Quest const* quest = NULL;
bool done = false;
if (reward)
{
quest = sObjectMgr->GetQuestTemplate(reward->firstQuest);
if (quest)
{
done = !GetPlayer()->CanRewardQuest(quest, false);
if (done)
quest = sObjectMgr->GetQuestTemplate(reward->otherQuest);
}
}
if (quest)
{
data << uint8(done);
data << uint32(quest->GetRewOrReqMoney());
data << uint32(quest->XPValue(GetPlayer()));
data << uint32(0);
data << uint32(0);
data << uint8(quest->GetRewItemsCount());
if (quest->GetRewItemsCount())
{
for (uint8 i = 0; i < QUEST_REWARDS_COUNT; ++i)
if (uint32 itemId = quest->RewardItemId[i])
{
ItemTemplate const* item = sObjectMgr->GetItemTemplate(itemId);
data << uint32(itemId);
data << uint32(item ? item->DisplayInfoID : 0);
data << uint32(quest->RewardItemIdCount[i]);
}
}
}
else
{
data << uint8(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint8(0);
}
}
BuildPlayerLockDungeonBlock(data, lock);
SendPacket(&data);
}
void WorldSession::HandleLfgPartyLockInfoRequestOpcode(WorldPacket& /*recvData*/)
{
uint64 guid = GetPlayer()->GetGUID();
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_PARTY_LOCK_INFO_REQUEST %s", GetPlayerInfo().c_str());
Group* group = GetPlayer()->GetGroup();
if (!group)
return;
// Get the locked dungeons of the other party members
LfgLockPartyMap lockMap;
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* plrg = itr->getSource();
if (!plrg)
continue;
uint64 pguid = plrg->GetGUID();
if (pguid == guid)
continue;
lockMap[pguid] = sLFGMgr->GetLockedDungeons(pguid);
}
uint32 size = 0;
for (LfgLockPartyMap::const_iterator it = lockMap.begin(); it != lockMap.end(); ++it)
size += 8 + 4 + uint32(it->second.size()) * (4 + 4 + 4 + 4);
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_PARTY_INFO %s", GetPlayerInfo().c_str());
WorldPacket data(SMSG_LFG_PARTY_INFO, 1 + size);
BuildPartyLockDungeonBlock(data, lockMap);
SendPacket(&data);
}
void WorldSession::HandleLfrJoinOpcode(WorldPacket& recvData)
{
uint32 entry; // Raid id to search
recvData >> entry;
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_LFR_JOIN %s dungeon entry: %u",
GetPlayerInfo().c_str(), entry);
//SendLfrUpdateListOpcode(entry);
}
void WorldSession::HandleLfrLeaveOpcode(WorldPacket& recvData)
{
uint32 dungeonId; // Raid id queue to leave
recvData >> dungeonId;
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_LFR_LEAVE %s dungeonId: %u",
GetPlayerInfo().c_str(), dungeonId);
//sLFGMgr->LeaveLfr(GetPlayer(), dungeonId);
}
void WorldSession::HandleLfgGetStatus(WorldPacket& /*recvData*/)
{
sLog->outDebug(LOG_FILTER_LFG, "CMSG_LFG_GET_STATUS %s", GetPlayerInfo().c_str());
uint64 guid = GetPlayer()->GetGUID();
LfgUpdateData updateData = sLFGMgr->GetLfgStatus(guid);
if (GetPlayer()->GetGroup())
{
SendLfgUpdateParty(updateData);
updateData.dungeons.clear();
SendLfgUpdatePlayer(updateData);
}
else
{
SendLfgUpdatePlayer(updateData);
updateData.dungeons.clear();
SendLfgUpdateParty(updateData);
}
}
void WorldSession::SendLfgUpdatePlayer(LfgUpdateData const& updateData)
{
bool queued = false;
uint8 size = uint8(updateData.dungeons.size());
switch (updateData.updateType)
{
case LFG_UPDATETYPE_JOIN_QUEUE:
case LFG_UPDATETYPE_ADDED_TO_QUEUE:
queued = true;
break;
case LFG_UPDATETYPE_UPDATE_STATUS:
queued = updateData.state == LFG_STATE_QUEUED;
break;
default:
break;
}
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_UPDATE_PLAYER %s updatetype: %u",
GetPlayerInfo().c_str(), updateData.updateType);
WorldPacket data(SMSG_LFG_UPDATE_PLAYER, 1 + 1 + (size > 0 ? 1 : 0) * (1 + 1 + 1 + 1 + size * 4 + updateData.comment.length()));
data << uint8(updateData.updateType); // Lfg Update type
data << uint8(size > 0); // Extra info
if (size)
{
data << uint8(queued); // Join the queue
data << uint8(0); // unk - Always 0
data << uint8(0); // unk - Always 0
data << uint8(size);
for (LfgDungeonSet::const_iterator it = updateData.dungeons.begin(); it != updateData.dungeons.end(); ++it)
data << uint32(*it);
data << updateData.comment;
}
SendPacket(&data);
}
void WorldSession::SendLfgUpdateParty(const LfgUpdateData& updateData)
{
bool join = false;
bool queued = false;
uint8 size = uint8(updateData.dungeons.size());
switch (updateData.updateType)
{
case LFG_UPDATETYPE_ADDED_TO_QUEUE: // Rolecheck Success
queued = true;
// no break on purpose
case LFG_UPDATETYPE_PROPOSAL_BEGIN:
join = true;
break;
case LFG_UPDATETYPE_UPDATE_STATUS:
join = updateData.state != LFG_STATE_ROLECHECK && updateData.state != LFG_STATE_NONE;
queued = updateData.state == LFG_STATE_QUEUED;
break;
default:
break;
}
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_UPDATE_PARTY %s updatetype: %u",
GetPlayerInfo().c_str(), updateData.updateType);
WorldPacket data(SMSG_LFG_UPDATE_PARTY, 1 + 1 + (size > 0 ? 1 : 0) * (1 + 1 + 1 + 1 + 1 + size * 4 + updateData.comment.length()));
data << uint8(updateData.updateType); // Lfg Update type
data << uint8(size > 0); // Extra info
if (size)
{
data << uint8(join); // LFG Join
data << uint8(queued); // Join the queue
data << uint8(0); // unk - Always 0
data << uint8(0); // unk - Always 0
for (uint8 i = 0; i < 3; ++i)
data << uint8(0); // unk - Always 0
data << uint8(size);
for (LfgDungeonSet::const_iterator it = updateData.dungeons.begin(); it != updateData.dungeons.end(); ++it)
data << uint32(*it);
data << updateData.comment;
}
SendPacket(&data);
}
void WorldSession::SendLfgRoleChosen(uint64 guid, uint8 roles)
{
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_ROLE_CHOSEN %s guid: %u roles: %u",
GetPlayerInfo().c_str(), GUID_LOPART(guid), roles);
WorldPacket data(SMSG_LFG_ROLE_CHOSEN, 8 + 1 + 4);
data << uint64(guid); // Guid
data << uint8(roles > 0); // Ready
data << uint32(roles); // Roles
SendPacket(&data);
}
void WorldSession::SendLfgRoleCheckUpdate(const LfgRoleCheck& roleCheck)
{
LfgDungeonSet dungeons;
if (roleCheck.rDungeonId)
dungeons.insert(roleCheck.rDungeonId);
else
dungeons = roleCheck.dungeons;
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_ROLE_CHECK_UPDATE %s", GetPlayerInfo().c_str());
WorldPacket data(SMSG_LFG_ROLE_CHECK_UPDATE, 4 + 1 + 1 + dungeons.size() * 4 + 1 + roleCheck.roles.size() * (8 + 1 + 4 + 1));
data << uint32(roleCheck.state); // Check result
data << uint8(roleCheck.state == LFG_ROLECHECK_INITIALITING);
data << uint8(dungeons.size()); // Number of dungeons
if (!dungeons.empty())
{
for (LfgDungeonSet::iterator it = dungeons.begin(); it != dungeons.end(); ++it)
{
LFGDungeonData const* dungeon = sLFGMgr->GetLFGDungeon(*it);
data << uint32(dungeon ? dungeon->Entry() : 0); // Dungeon
}
}
data << uint8(roleCheck.roles.size()); // Players in group
if (!roleCheck.roles.empty())
{
// Leader info MUST be sent 1st :S
uint64 guid = roleCheck.leader;
uint8 roles = roleCheck.roles.find(guid)->second;
data << uint64(guid); // Guid
data << uint8(roles > 0); // Ready
data << uint32(roles); // Roles
Player* player = ObjectAccessor::FindPlayer(guid);
data << uint8(player ? player->getLevel() : 0); // Level
for (LfgRolesMap::const_iterator it = roleCheck.roles.begin(); it != roleCheck.roles.end(); ++it)
{
if (it->first == roleCheck.leader)
continue;
guid = it->first;
roles = it->second;
data << uint64(guid); // Guid
data << uint8(roles > 0); // Ready
data << uint32(roles); // Roles
player = ObjectAccessor::FindPlayer(guid);
data << uint8(player ? player->getLevel() : 0);// Level
}
}
SendPacket(&data);
}
void WorldSession::SendLfgJoinResult(LfgJoinResultData const& joinData)
{
uint32 size = 0;
for (LfgLockPartyMap::const_iterator it = joinData.lockmap.begin(); it != joinData.lockmap.end(); ++it)
size += 8 + 4 + uint32(it->second.size()) * (4 + 4 + 4 + 4);
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_JOIN_RESULT %s checkResult: %u checkValue: %u",
GetPlayerInfo().c_str(), joinData.result, joinData.state);
WorldPacket data(SMSG_LFG_JOIN_RESULT, 4 + 4 + size);
data << uint32(joinData.result); // Check Result
data << uint32(joinData.state); // Check Value
if (!joinData.lockmap.empty())
BuildPartyLockDungeonBlock(data, joinData.lockmap);
SendPacket(&data);
}
void WorldSession::SendLfgQueueStatus(LfgQueueStatusData const& queueData)
{
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_QUEUE_STATUS %s dungeon: %u, waitTime: %d, "
"avgWaitTime: %d, waitTimeTanks: %d, waitTimeHealer: %d, waitTimeDps: %d, "
"queuedTime: %u, tanks: %u, healers: %u, dps: %u",
GetPlayerInfo().c_str(), queueData.dungeonId, queueData.waitTime, queueData.waitTimeAvg,
queueData.waitTimeTank, queueData.waitTimeHealer, queueData.waitTimeDps,
queueData.queuedTime, queueData.tanks, queueData.healers, queueData.dps);
WorldPacket data(SMSG_LFG_QUEUE_STATUS, 4 + 4 + 4 + 4 + 4 +4 + 1 + 1 + 1 + 4);
data << uint32(queueData.dungeonId); // Dungeon
data << int32(queueData.waitTimeAvg); // Average Wait time
data << int32(queueData.waitTime); // Wait Time
data << int32(queueData.waitTimeTank); // Wait Tanks
data << int32(queueData.waitTimeHealer); // Wait Healers
data << int32(queueData.waitTimeDps); // Wait Dps
data << uint8(queueData.tanks); // Tanks needed
data << uint8(queueData.healers); // Healers needed
data << uint8(queueData.dps); // Dps needed
data << uint32(queueData.queuedTime); // Player wait time in queue
SendPacket(&data);
}
void WorldSession::SendLfgPlayerReward(LfgPlayerRewardData const& rewardData)
{
if (!rewardData.rdungeonEntry || !rewardData.sdungeonEntry || !rewardData.quest)
return;
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_PLAYER_REWARD %s rdungeonEntry: %u, sdungeonEntry: %u, done: %u",
GetPlayerInfo().c_str(), rewardData.rdungeonEntry, rewardData.sdungeonEntry, rewardData.done);
uint8 itemNum = rewardData.quest->GetRewItemsCount();
WorldPacket data(SMSG_LFG_PLAYER_REWARD, 4 + 4 + 1 + 4 + 4 + 4 + 4 + 4 + 1 + itemNum * (4 + 4 + 4));
data << uint32(rewardData.rdungeonEntry); // Random Dungeon Finished
data << uint32(rewardData.sdungeonEntry); // Dungeon Finished
data << uint8(rewardData.done);
data << uint32(1);
data << uint32(rewardData.quest->GetRewOrReqMoney());
data << uint32(rewardData.quest->XPValue(GetPlayer()));
data << uint32(0);
data << uint32(0);
data << uint8(itemNum);
if (itemNum)
{
for (uint8 i = 0; i < QUEST_REWARDS_COUNT; ++i)
if (uint32 itemId = rewardData.quest->RewardItemId[i])
{
ItemTemplate const* item = sObjectMgr->GetItemTemplate(itemId);
data << uint32(itemId);
data << uint32(item ? item->DisplayInfoID : 0);
data << uint32(rewardData.quest->RewardItemIdCount[i]);
}
}
SendPacket(&data);
}
void WorldSession::SendLfgBootProposalUpdate(LfgPlayerBoot const& boot)
{
uint64 guid = GetPlayer()->GetGUID();
LfgAnswer playerVote = boot.votes.find(guid)->second;
uint8 votesNum = 0;
uint8 agreeNum = 0;
uint32 secsleft = uint8((boot.cancelTime - time(NULL)) / 1000);
for (LfgAnswerContainer::const_iterator it = boot.votes.begin(); it != boot.votes.end(); ++it)
{
if (it->second != LFG_ANSWER_PENDING)
{
++votesNum;
if (it->second == LFG_ANSWER_AGREE)
++agreeNum;
}
}
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_BOOT_PROPOSAL_UPDATE %s inProgress: %u - "
"didVote: %u - agree: %u - victim: %u votes: %u - agrees: %u - left: %u - "
"needed: %u - reason %s",
GetPlayerInfo().c_str(), uint8(boot.inProgress), uint8(playerVote != LFG_ANSWER_PENDING),
uint8(playerVote == LFG_ANSWER_AGREE), GUID_LOPART(boot.victim), votesNum, agreeNum,
secsleft, LFG_GROUP_KICK_VOTES_NEEDED, boot.reason.c_str());
WorldPacket data(SMSG_LFG_BOOT_PROPOSAL_UPDATE, 1 + 1 + 1 + 8 + 4 + 4 + 4 + 4 + boot.reason.length());
data << uint8(boot.inProgress); // Vote in progress
data << uint8(playerVote != LFG_ANSWER_PENDING); // Did Vote
data << uint8(playerVote == LFG_ANSWER_AGREE); // Agree
data << uint8(0); // Unknown 4.2.2
data << uint64(boot.victim); // Victim GUID
data << uint32(votesNum); // Total Votes
data << uint32(agreeNum); // Agree Count
data << uint32(secsleft); // Time Left
data << uint32(LFG_GROUP_KICK_VOTES_NEEDED); // Needed Votes
data << boot.reason.c_str(); // Kick reason
SendPacket(&data);
}
void WorldSession::SendLfgUpdateProposal(LfgProposal const& proposal)
{
uint64 guid = GetPlayer()->GetGUID();
uint64 gguid = proposal.players.find(guid)->second.group;
bool silent = !proposal.isNew && gguid == proposal.group;
uint32 dungeonEntry = proposal.dungeonId;
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_PROPOSAL_UPDATE %s state: %u",
GetPlayerInfo().c_str(), proposal.state);
// show random dungeon if player selected random dungeon and it's not lfg group
if (!silent)
{
LfgDungeonSet const& playerDungeons = sLFGMgr->GetSelectedDungeons(guid);
if (playerDungeons.find(proposal.dungeonId) == playerDungeons.end())
dungeonEntry = (*playerDungeons.begin());
}
if (LFGDungeonData const* dungeon = sLFGMgr->GetLFGDungeon(dungeonEntry))
dungeonEntry = dungeon->Entry();
WorldPacket data(SMSG_LFG_PROPOSAL_UPDATE, 4 + 1 + 4 + 4 + 1 + 1 + proposal.players.size() * (4 + 1 + 1 + 1 + 1 +1));
data << uint32(dungeonEntry); // Dungeon
data << uint8(proposal.state); // Proposal state
data << uint32(proposal.id); // Proposal ID
data << uint32(proposal.encounters); // encounters done
data << uint8(silent); // Show proposal window
data << uint8(proposal.players.size()); // Group size
for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it)
{
LfgProposalPlayer const& player = it->second;
data << uint32(player.role); // Role
data << uint8(it->first == guid); // Self player
if (!player.group) // Player not it a group
{
data << uint8(0); // Not in dungeon
data << uint8(0); // Not same group
}
else
{
data << uint8(player.group == proposal.group); // In dungeon (silent)
data << uint8(player.group == gguid); // Same Group than player
}
data << uint8(player.accept != LFG_ANSWER_PENDING);// Answered
data << uint8(player.accept == LFG_ANSWER_AGREE); // Accepted
}
SendPacket(&data);
}
void WorldSession::SendLfgLfrList(bool update)
{
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_LFR_LIST %s update: %u",
GetPlayerInfo().c_str(), update ? 1 : 0);
WorldPacket data(SMSG_LFG_UPDATE_SEARCH, 1);
data << uint8(update); // In Lfg Queue?
SendPacket(&data);
}
void WorldSession::SendLfgDisabled()
{
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_DISABLED %s", GetPlayerInfo().c_str());
WorldPacket data(SMSG_LFG_DISABLED, 0);
SendPacket(&data);
}
void WorldSession::SendLfgOfferContinue(uint32 dungeonEntry)
{
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_OFFER_CONTINUE %s dungeon entry: %u",
GetPlayerInfo().c_str(), dungeonEntry);
WorldPacket data(SMSG_LFG_OFFER_CONTINUE, 4);
data << uint32(dungeonEntry);
SendPacket(&data);
}
void WorldSession::SendLfgTeleportError(uint8 err)
{
sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_TELEPORT_DENIED %s reason: %u",
GetPlayerInfo().c_str(), err);
WorldPacket data(SMSG_LFG_TELEPORT_DENIED, 4);
data << uint32(err); // Error
SendPacket(&data);
}
/*
void WorldSession::SendLfrUpdateListOpcode(uint32 dungeonEntry)
{
sLog->outDebug(LOG_FILTER_PACKETIO, "SMSG_LFG_UPDATE_LIST %s dungeon entry: %u",
GetPlayerInfo().c_str(), dungeonEntry);
WorldPacket data(SMSG_LFG_UPDATE_LIST);
SendPacket(&data);
}
*/
| gpl-2.0 |
st4rdog/cmdos | Assets/_Scripts/Managers/Game/CursorManagerS.cs | 1488 | using UnityEngine;
using System.Collections;
public class CursorManagerS : MonoBehaviour {
public GameObject cursorMain;
public GameObject cursorInstance;
public float smoothSpeed = 50f;
public Vector3 cursorOffset;
public LayerMask layerMask;
//============================================
// EVENTS
//============================================
#region Events
//public delegate void StateHandler(GameObject thisGO, State state);
//public static event StateHandler StateChanged;
#endregion
#region Event Subscriptions
void OnEnable()
{
}
void OnDisable()
{
}
#endregion
//============================================
// FUNCTIONS
//============================================
void Start()
{
if (cursorMain)
cursorInstance = Instantiate(cursorMain, UICamera.lastHit.point, Quaternion.identity) as GameObject;
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, 500f, layerMask))
{
// LOCK TO NAVMESH
NavMeshHit navMeshHit;
if (NavMesh.SamplePosition(hitInfo.point, out navMeshHit, 500f, 1))
{
// POSITION 3D CURSOR
if (cursorInstance)
cursorInstance.transform.position = Vector3.Lerp(cursorInstance.transform.position, navMeshHit.position + cursorOffset, smoothSpeed * Time.deltaTime);
}
}
}
//============================================
// EVENT RECEIVERS
//============================================
} | gpl-2.0 |
enpitut/glasses | Calendar_html/sessionManager.php | 1466 | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
session_start();
session_regenerate_id();
$command = filter_input(INPUT_POST, "command");
if ($command == 'checkLogin') {
if (isset($_SESSION["user_id"])) {
echo $_SESSION["user_id"];
} else {
echo false;
}
} else if ($command == 'getUserId') {
if (isset($_SESSION["user_id"])) {
echo $_SESSION["user_id"];
} else {
echo false;
}
} else if ($command == 'checkIntro') {
if (isset($_SESSION["user_id"])) {
try {
$dbh = new PDO('mysql:host=mysql488.db.sakura.ne.jp;dbname=meganeshibu_db;charset=utf8', 'meganeshibu', 'DBmaster777', array(PDO::ATTR_EMULATE_PREPARES => false));
} catch (PDOException $e) {
exit('データベース接続失敗。' . $e->getMessage());
}
$flag = '';
$sql = "select Intro from UserTable where UserID = '" . $_SESSION["user_id"] . "'";
$stmt = $dbh->query($sql);
while ($row = $stmt->fetchObject()) {
$flag = $row->Intro;
}
if ($flag == 0) {
$sql = "update UserTable set Intro = 1 where UserID = '" . $_SESSION["user_id"] . "'";
$stmt = $dbh->query($sql);
}
echo $flag;
} else {
echo false;
}
} else {
echo false;
}
| gpl-2.0 |
zearan/icinga2 | lib/base/logger.cpp | 5950 | /******************************************************************************
* Icinga 2 *
* Copyright (C) 2012-2016 Icinga Development Team (https://www.icinga.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, write to the Free Software Foundation *
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/
#include "base/logger.hpp"
#include "base/logger.tcpp"
#include "base/application.hpp"
#include "base/streamlogger.hpp"
#include "base/configtype.hpp"
#include "base/utility.hpp"
#include "base/objectlock.hpp"
#include "base/context.hpp"
#include "base/scriptglobal.hpp"
#include <iostream>
using namespace icinga;
REGISTER_TYPE(Logger);
std::set<Logger::Ptr> Logger::m_Loggers;
boost::mutex Logger::m_Mutex;
bool Logger::m_ConsoleLogEnabled = true;
bool Logger::m_TimestampEnabled = true;
LogSeverity Logger::m_ConsoleLogSeverity = LogInformation;
INITIALIZE_ONCE([]() {
ScriptGlobal::Set("LogDebug", LogDebug);
ScriptGlobal::Set("LogNotice", LogNotice);
ScriptGlobal::Set("LogInformation", LogInformation);
ScriptGlobal::Set("LogWarning", LogWarning);
ScriptGlobal::Set("LogCritical", LogCritical);
});
/**
* Constructor for the Logger class.
*/
void Logger::Start(bool runtimeCreated)
{
ObjectImpl<Logger>::Start(runtimeCreated);
boost::mutex::scoped_lock lock(m_Mutex);
m_Loggers.insert(this);
}
void Logger::Stop(bool runtimeRemoved)
{
{
boost::mutex::scoped_lock lock(m_Mutex);
m_Loggers.erase(this);
}
ObjectImpl<Logger>::Stop(runtimeRemoved);
}
std::set<Logger::Ptr> Logger::GetLoggers(void)
{
boost::mutex::scoped_lock lock(m_Mutex);
return m_Loggers;
}
/**
* Writes a message to the application's log.
*
* @param severity The message severity.
* @param facility The log facility.
* @param message The message.
*/
void icinga::IcingaLog(LogSeverity severity, const String& facility,
const String& message)
{
LogEntry entry;
entry.Timestamp = Utility::GetTime();
entry.Severity = severity;
entry.Facility = facility;
entry.Message = message;
if (severity >= LogWarning) {
ContextTrace context;
if (context.GetLength() > 0) {
std::ostringstream trace;
trace << context;
entry.Message += "\nContext:" + trace.str();
}
}
for (const Logger::Ptr& logger : Logger::GetLoggers()) {
ObjectLock llock(logger);
if (!logger->IsActive())
continue;
if (entry.Severity >= logger->GetMinSeverity())
logger->ProcessLogEntry(entry);
}
if (Logger::IsConsoleLogEnabled() && entry.Severity >= Logger::GetConsoleLogSeverity())
StreamLogger::ProcessLogEntry(std::cout, entry);
}
/**
* Retrieves the minimum severity for this logger.
*
* @returns The minimum severity.
*/
LogSeverity Logger::GetMinSeverity(void) const
{
String severity = GetSeverity();
if (severity.IsEmpty())
return LogInformation;
else {
LogSeverity ls = LogInformation;
try {
ls = Logger::StringToSeverity(severity);
} catch (const std::exception&) { /* use the default level */ }
return ls;
}
}
/**
* Converts a severity enum value to a string.
*
* @param severity The severity value.
*/
String Logger::SeverityToString(LogSeverity severity)
{
switch (severity) {
case LogDebug:
return "debug";
case LogNotice:
return "notice";
case LogInformation:
return "information";
case LogWarning:
return "warning";
case LogCritical:
return "critical";
default:
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid severity."));
}
}
/**
* Converts a string to a severity enum value.
*
* @param severity The severity.
*/
LogSeverity Logger::StringToSeverity(const String& severity)
{
if (severity == "debug")
return LogDebug;
else if (severity == "notice")
return LogNotice;
else if (severity == "information")
return LogInformation;
else if (severity == "warning")
return LogWarning;
else if (severity == "critical")
return LogCritical;
else
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid severity: " + severity));
}
void Logger::DisableConsoleLog(void)
{
m_ConsoleLogEnabled = false;
}
void Logger::EnableConsoleLog(void)
{
m_ConsoleLogEnabled = true;
}
bool Logger::IsConsoleLogEnabled(void)
{
return m_ConsoleLogEnabled;
}
void Logger::SetConsoleLogSeverity(LogSeverity logSeverity)
{
m_ConsoleLogSeverity = logSeverity;
}
LogSeverity Logger::GetConsoleLogSeverity(void)
{
return m_ConsoleLogSeverity;
}
void Logger::DisableTimestamp(bool disable)
{
m_TimestampEnabled = !disable;
}
bool Logger::IsTimestampEnabled(void)
{
return m_TimestampEnabled;
}
void Logger::ValidateSeverity(const String& value, const ValidationUtils& utils)
{
ObjectImpl<Logger>::ValidateSeverity(value, utils);
try {
StringToSeverity(value);
} catch (...) {
BOOST_THROW_EXCEPTION(ValidationError(this, boost::assign::list_of("severity"), "Invalid severity specified: " + value));
}
}
| gpl-2.0 |
netroby/jdk9-shenandoah-hotspot | src/share/vm/gc_implementation/shared/gcUtil.hpp | 7756 | /*
* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_GC_IMPLEMENTATION_SHARED_GCUTIL_HPP
#define SHARE_VM_GC_IMPLEMENTATION_SHARED_GCUTIL_HPP
#include "memory/allocation.hpp"
#include "runtime/timer.hpp"
#include "utilities/debug.hpp"
#include "utilities/globalDefinitions.hpp"
#include "utilities/ostream.hpp"
// Catch-all file for utility classes
// A weighted average maintains a running, weighted average
// of some float value (templates would be handy here if we
// need different types).
//
// The average is adaptive in that we smooth it for the
// initial samples; we don't use the weight until we have
// enough samples for it to be meaningful.
//
// This serves as our best estimate of a future unknown.
//
class AdaptiveWeightedAverage : public CHeapObj<mtGC> {
private:
float _average; // The last computed average
unsigned _sample_count; // How often we've sampled this average
unsigned _weight; // The weight used to smooth the averages
// A higher weight favors the most
// recent data.
bool _is_old; // Has enough historical data
const static unsigned OLD_THRESHOLD = 100;
protected:
float _last_sample; // The last value sampled.
void increment_count() {
_sample_count++;
if (!_is_old && _sample_count > OLD_THRESHOLD) {
_is_old = true;
}
}
void set_average(float avg) { _average = avg; }
// Helper function, computes an adaptive weighted average
// given a sample and the last average
float compute_adaptive_average(float new_sample, float average);
public:
// Input weight must be between 0 and 100
AdaptiveWeightedAverage(unsigned weight, float avg = 0.0) :
_average(avg), _sample_count(0), _weight(weight), _last_sample(0.0),
_is_old(false) {
}
void clear() {
_average = 0;
_sample_count = 0;
_last_sample = 0;
_is_old = false;
}
// Useful for modifying static structures after startup.
void modify(size_t avg, unsigned wt, bool force = false) {
assert(force, "Are you sure you want to call this?");
_average = (float)avg;
_weight = wt;
}
// Accessors
float average() const { return _average; }
unsigned weight() const { return _weight; }
unsigned count() const { return _sample_count; }
float last_sample() const { return _last_sample; }
bool is_old() const { return _is_old; }
// Update data with a new sample.
void sample(float new_sample);
static inline float exp_avg(float avg, float sample,
unsigned int weight) {
assert(0 <= weight && weight <= 100, "weight must be a percent");
return (100.0F - weight) * avg / 100.0F + weight * sample / 100.0F;
}
static inline size_t exp_avg(size_t avg, size_t sample,
unsigned int weight) {
// Convert to float and back to avoid integer overflow.
return (size_t)exp_avg((float)avg, (float)sample, weight);
}
// Printing
void print_on(outputStream* st) const;
void print() const;
};
// A weighted average that includes a deviation from the average,
// some multiple of which is added to the average.
//
// This serves as our best estimate of an upper bound on a future
// unknown.
class AdaptivePaddedAverage : public AdaptiveWeightedAverage {
private:
float _padded_avg; // The last computed padded average
float _deviation; // Running deviation from the average
unsigned _padding; // A multiple which, added to the average,
// gives us an upper bound guess.
protected:
void set_padded_average(float avg) { _padded_avg = avg; }
void set_deviation(float dev) { _deviation = dev; }
public:
AdaptivePaddedAverage() :
AdaptiveWeightedAverage(0),
_padded_avg(0.0), _deviation(0.0), _padding(0) {}
AdaptivePaddedAverage(unsigned weight, unsigned padding) :
AdaptiveWeightedAverage(weight),
_padded_avg(0.0), _deviation(0.0), _padding(padding) {}
// Placement support
void* operator new(size_t ignored, void* p) throw() { return p; }
// Allocator
void* operator new(size_t size) throw() { return CHeapObj<mtGC>::operator new(size); }
// Accessor
float padded_average() const { return _padded_avg; }
float deviation() const { return _deviation; }
unsigned padding() const { return _padding; }
void clear() {
AdaptiveWeightedAverage::clear();
_padded_avg = 0;
_deviation = 0;
}
// Override
void sample(float new_sample);
// Printing
void print_on(outputStream* st) const;
void print() const;
};
// A weighted average that includes a deviation from the average,
// some multiple of which is added to the average.
//
// This serves as our best estimate of an upper bound on a future
// unknown.
// A special sort of padded average: it doesn't update deviations
// if the sample is zero. The average is allowed to change. We're
// preventing the zero samples from drastically changing our padded
// average.
class AdaptivePaddedNoZeroDevAverage : public AdaptivePaddedAverage {
public:
AdaptivePaddedNoZeroDevAverage(unsigned weight, unsigned padding) :
AdaptivePaddedAverage(weight, padding) {}
// Override
void sample(float new_sample);
// Printing
void print_on(outputStream* st) const;
void print() const;
};
// Use a least squares fit to a set of data to generate a linear
// equation.
// y = intercept + slope * x
class LinearLeastSquareFit : public CHeapObj<mtGC> {
double _sum_x; // sum of all independent data points x
double _sum_x_squared; // sum of all independent data points x**2
double _sum_y; // sum of all dependent data points y
double _sum_xy; // sum of all x * y.
double _intercept; // constant term
double _slope; // slope
// The weighted averages are not currently used but perhaps should
// be used to get decaying averages.
AdaptiveWeightedAverage _mean_x; // weighted mean of independent variable
AdaptiveWeightedAverage _mean_y; // weighted mean of dependent variable
public:
LinearLeastSquareFit(unsigned weight);
void update(double x, double y);
double y(double x);
double slope() { return _slope; }
// Methods to decide if a change in the dependent variable will
// achieve a desired goal. Note that these methods are not
// complementary and both are needed.
bool decrement_will_decrease();
bool increment_will_decrease();
};
#endif // SHARE_VM_GC_IMPLEMENTATION_SHARED_GCUTIL_HPP
| gpl-2.0 |
joomla-framework/cache | Tests/NoneTest.php | 3003 | <?php
/**
* @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Cache\Tests;
use Joomla\Cache;
use Joomla\Test\TestHelper;
use PHPUnit\Framework\TestCase;
/**
* Tests for the Joomla\Cache\None class.
*
* @since 1.0
*/
class NoneTest extends TestCase
{
/**
* @var Cache\None
* @since 1.0
*/
private $instance;
/**
* Tests for the correct Psr\Cache return values.
*
* @return void
*
* @coversNothing
* @since 1.0
*/
public function testPsrCache()
{
$this->assertInternalType('boolean', $this->instance->clear(), 'Checking clear.');
$this->assertInstanceOf('\Psr\Cache\CacheItemInterface', $this->instance->get('foo'), 'Checking get.');
$this->assertInternalType('array', $this->instance->getMultiple(array('foo')), 'Checking getMultiple.');
$this->assertInternalType('boolean', $this->instance->remove('foo'), 'Checking remove.');
$this->assertInternalType('array', $this->instance->removeMultiple(array('foo')), 'Checking removeMultiple.');
$this->assertInternalType('boolean', $this->instance->set('for', 'bar'), 'Checking set.');
$this->assertInternalType('boolean', $this->instance->setMultiple(array('foo' => 'bar')), 'Checking setMultiple.');
}
/**
* Tests the Joomla\Cache\None::clear method.
*
* @return void
*
* @covers Joomla\Cache\None::clear
* @since 1.0
*/
public function testClear()
{
$this->instance->clear();
}
/**
* Tests the Joomla\Cache\None::get method.
*
* @return void
*
* @covers Joomla\Cache\None::get
* @since 1.0
*/
public function testGet()
{
$this->instance->set('foo', 'bar');
$item = $this->instance->get('foo');
$this->assertNull($item->getValue());
$this->assertFalse($item->isHit());
}
/**
* Tests the Joomla\Cache\None::remove method.
*
* @return void
*
* @covers Joomla\Cache\None::remove
* @since 1.0
*/
public function testRemove()
{
$this->instance->remove('foo');
}
/**
* Tests the Joomla\Cache\None::set method.
*
* @return void
*
* @covers Joomla\Cache\None::set
* @since 1.0
*/
public function testSet()
{
$this->instance->set('foo', 'bar');
$item = $this->instance->get('foo');
$this->assertNull($item->getValue());
$this->assertFalse($item->isHit());
}
/**
* Tests the Joomla\Cache\None::exists method.
*
* @return void
*
* @covers Joomla\Cache\None::exists
* @since 1.0
*/
public function testExists()
{
$this->assertFalse(TestHelper::invoke($this->instance, 'exists', 'foo'));
$this->instance->set('foo', 'bar');
$this->assertFalse(TestHelper::invoke($this->instance, 'exists', 'foo'));
}
/**
* Setup the tests.
*
* @return void
*
* @since 1.0
*/
protected function setUp()
{
parent::setUp();
try
{
$this->instance = new Cache\None;
}
catch (\Exception $e)
{
$this->markTestSkipped();
}
}
}
| gpl-2.0 |
gratefulfrog/lib | python/pymol/gui.py | 1493 | #A* -------------------------------------------------------------------
#B* This file contains source code for the PyMOL computer program
#C* Copyright (c) Schrodinger, LLC.
#D* -------------------------------------------------------------------
#E* It is unlawful to modify or remove this copyright notice.
#F* -------------------------------------------------------------------
#G* Please see the accompanying LICENSE file for further information.
#H* -------------------------------------------------------------------
#I* Additional authors of this source file include:
#-*
#-*
#-*
#Z* -------------------------------------------------------------------
# abstract (external or internal) gui control interface
if __name__=='pymol.gui':
import pymol
import cmd
# external gui control
def ext_hide(_self=cmd):
pymol = _self._pymol
if pymol._ext_gui != None:
pymol._ext_gui.fifo.put('self.root.withdraw()')
else:
pass
def ext_show(_self=cmd):
pymol = _self._pymol
if pymol._ext_gui != None:
pymol._ext_gui.fifo.put('self.root.deiconify()')
else:
pass
# common actions
def save_as(_self=cmd):
pymol = _self._pymol
if pymol._ext_gui != None:
pymol._ext_gui.fifo.put('self.skin.session_save_as()')
else:
pass
def save_image(_self=cmd):
pymol = _self._pymol
if pymol._ext_gui != None:
pymol._ext_gui.fifo.put('self.skin.file_save_png()')
else:
pass
| gpl-2.0 |
sebhz/caprice32 | src/argparse.cpp | 4790 | #include "argparse.h"
#include <getopt.h>
#include <iostream>
#include <fstream>
#include "SDL.h"
#include "cap32.h"
#include "keyboard.h"
#include "stringutils.h"
#include "log.h"
extern bool log_verbose;
const struct option long_options[] =
{
{"autocmd", required_argument, nullptr, 'a'},
{"cfg_file", required_argument, nullptr, 'c'},
{"version", no_argument, nullptr, 'V'},
{"help", no_argument, nullptr, 'h'},
{"verbose", no_argument, nullptr, 'v'},
{nullptr, 0, nullptr, 0},
};
CapriceArgs::CapriceArgs()
{
}
void usage(std::ostream &os, char *progPath, int errcode)
{
std::string progname, dirname;
stringutils::splitPath(progPath, dirname, progname);
os << "Usage: " << progname << " [options] <slotfile(s)>\n";
os << "\nSupported options are:\n";
os << " -a/--autocmd=<command>: execute command as soon as the emulator starts.\n";
os << " -c/--cfg_file=<file>: use <file> as the emulator configuration file instead of the default.\n";
os << " -h/--help: shows this help\n";
os << " -V/--version: outputs version and exit\n";
os << " -v/--verbose: be talkative\n";
os << "\nslotfiles is an optional list of files giving the content of the various CPC ports.\n";
os << "Ports files are identified by their extension. Supported formats are .dsk (disk), .cdt or .voc (tape), .cpr (cartridge), .sna (snapshot), or .zip (archive containing one or more of the supported ports files).\n";
os << "\nExample: " << progname << " sorcery.dsk\n";
os << "\nPress F1 when the emulator is running to show the in-application option menu.\n";
os << "\nSee https://github.com/ColinPitrat/caprice32 or check the man page (man cap32) for more extensive information.\n";
exit(errcode);
}
std::string cap32_keystroke(CAP32_KEYS key) {
return std::string("\f") + char(key);
}
std::string cpc_keystroke(CPC_KEYS key) {
return std::string("\a") + char(key);
}
std::string replaceCap32Keys(std::string command)
{
static std::map<std::string, std::string> keyNames = {
{ "CAP32_EXIT", cap32_keystroke(CAP32_EXIT) },
{ "CAP32_FPS", cap32_keystroke(CAP32_FPS) },
{ "CAP32_FULLSCRN", cap32_keystroke(CAP32_FULLSCRN) },
{ "CAP32_GUI", cap32_keystroke(CAP32_GUI) },
{ "CAP32_VKBD", cap32_keystroke(CAP32_VKBD) },
{ "CAP32_JOY", cap32_keystroke(CAP32_JOY) },
{ "CAP32_MF2STOP", cap32_keystroke(CAP32_MF2STOP) },
{ "CAP32_RESET", cap32_keystroke(CAP32_RESET) },
{ "CAP32_SCRNSHOT", cap32_keystroke(CAP32_SCRNSHOT) },
{ "CAP32_SPEED", cap32_keystroke(CAP32_SPEED) },
{ "CAP32_TAPEPLAY", cap32_keystroke(CAP32_TAPEPLAY) },
{ "CAP32_DEBUG", cap32_keystroke(CAP32_DEBUG) },
{ "CAP32_WAITBREAK", cap32_keystroke(CAP32_WAITBREAK) },
{ "CAP32_DELAY", cap32_keystroke(CAP32_DELAY) },
{ "CPC_F1", cpc_keystroke(CPC_F1) },
{ "CPC_F2", cpc_keystroke(CPC_F2) },
};
for (const auto& elt : keyNames)
{
size_t pos;
while ((pos = command.find(elt.first)) != std::string::npos)
{
command.replace(pos, elt.first.size(), elt.second);
LOG_VERBOSE("Recognized keyword: " << elt.first);
}
}
return command;
}
void parseArguments(int argc, char **argv, std::vector<std::string>& slot_list, CapriceArgs& args)
{
int option_index = 0;
int c;
optind = 0; // To please test framework, when this function is called multiple times !
while(true) {
c = getopt_long (argc, argv, "a:c:hvV",
long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch (c)
{
case 'a':
LOG_VERBOSE("Append to autocmd: " << optarg);
args.autocmd += replaceCap32Keys(optarg);
args.autocmd += "\n";
break;
case 'c':
args.cfgFilePath = optarg;
break;
case 'h':
usage(std::cout, argv[0], 0);
break;
case 'v':
log_verbose = true;
break;
case 'V':
std::cout << "Caprice32 " << VERSION_STRING;
#ifdef HASH
std::cout << (std::string(HASH).empty()?"":"-"+std::string(HASH));
#endif
std::cout << "\n";
std::cout << "Compiled with:"
#ifdef HAVE_GL
<< " HAVE_GL"
#endif
#ifdef DEBUG
<< " DEBUG"
#endif
#ifdef WITH_IPF
<< " WITH_IPF"
#endif
<< "\n";
exit(0);
break;
case '?':
default:
usage(std::cerr, argv[0], 1);
break;
}
}
/* All remaining command line arguments will go to the slot content list */
slot_list.assign(argv+optind, argv+argc);
}
| gpl-2.0 |
outersky/sep | src/main/java/cn/hillwind/sep/RowHandler.java | 167 | package cn.hillwind.sep;
import java.util.List;
/**
*
*/
public interface RowHandler<T> {
void process(String sheetName, Row row) ;
List<T> getResult();
}
| gpl-2.0 |
jhagon/lab_marks | app/controllers/pages_controller.rb | 2994 | class PagesController < ApplicationController
before_filter :authenticate, :only => [:statistics, :marklist]
def home
@title="Home"
end
def contact
@title="Contact"
end
def about
@title="About"
end
def help
@title="Help"
end
def statistics
@title="Statistics"
@sheets = Sheet.all
@experiments = Experiment.all
@markers = Marker.all
@average = overall_average
end
def upload
@title="Upload Data"
end
def marklist
@students = Student.paginate(:page => params[:page]).per_page(12).all(
:order => "last ASC")
@experiments = Experiment.all(
:order => "title ASC")
respond_to do |format|
format.html
format.xls
end
end
end
def overall_average
sum = 0.0
n_sheets = Sheet.all.count
for sheet in Sheet.all
mark1 = sheet.mark1
mark2 = sheet.mark2
mark3 = sheet.mark3
mark4 = sheet.mark4
scale = sheet.marker.scaling
sum = sum + scale * (mark1 + mark2 + mark3 +mark4)
end
if n_sheets == 0
overall_average = nil
else
overall_average = sum/n_sheets
end
end
def marker_average(marker_id)
marker_sheets = Sheet.where("marker_id = #{marker_id}")
sum1 = marker_sheets.sum("mark1")
sum2 = marker_sheets.sum("mark2")
sum3 = marker_sheets.sum("mark3")
sum4 = marker_sheets.sum("mark4")
n_sheets = marker_sheets.count
if (n_sheets == 0)
marker_average = nil
else
scale = Marker.find(marker_id).scaling
marker_average = scale*(sum1+sum2+sum3+sum4)/n_sheets
end
end
def marker_experiment_average(marker_id, experiment_id)
sheets = Sheet.where(
"marker_id = #{marker_id} AND experiment_id = #{experiment_id}")
sum1 = sheets.sum("mark1")
sum2 = sheets.sum("mark2")
sum3 = sheets.sum("mark3")
sum4 = sheets.sum("mark4")
n_sheets = sheets.count
if (n_sheets == 0)
marker_experiment_average = nil
else
scale = Marker.find(marker_id).scaling
marker_experiment_average = scale*(sum1+sum2+sum3+sum4)/n_sheets
end
end
def experiment_average(experiment_id)
sum = 0.0
n_markers = 0 # markers who have actually marked
for marker in Marker.all
unless marker_experiment_average(marker.id, experiment_id).nil?
n_markers = n_markers + 1
sum = sum + marker_experiment_average(marker.id, experiment_id)
end
end
if (n_markers == 0)
experiment_average = nil
else
experiment_average = sum/n_markers
end
end
def student_experiment_mark(student_id,experiment_id)
sheet = Sheet.where(
"student_id = #{student_id} AND experiment_id = #{experiment_id}")
if sheet.empty?
return ""
else
student_experiment_mark =
(sheet.total_mark*1.0*sheet.marker.scaling*100/(MARK_UNIT*4))
end
end
private
def authenticate
deny_access unless signed_in? && is_admin?
end
| gpl-2.0 |
repunyc/repu.nyc | wp-content/plugins/wysija-newsletters/views/front.php | 378 | <?php
defined('WYSIJA') or die('Restricted access');
class WYSIJA_view_front extends WYSIJA_view{
var $controller='';
function WYSIJA_view_front(){
}
/**
* deprecated, but kept for conflict with plugin Magic action box
* until it's fixed.
* @param type $print
*/
function addScripts($print=true){
}
} | gpl-2.0 |
lakers/RobloxWiki | skins/chameleon/components/TabList.php | 2837 | <?php
/**
* File holding the TabList class
*
* @copyright (C) 2013, Stephan Gambke
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License, version 3 (or later)
*
* This file is part of the MediaWiki extension Chameleon.
* The Chameleon extension is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The Chameleon extension 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/>.
*
* @file
* @ingroup Skins
*/
namespace skins\chameleon\components;
/**
* The TabList class.
*
* A unordered list containing content navigation links (Page, Discussion, Edit, History, Move, ...)
*
* The tab list is a list of lists: '<ul id="p-contentnavigation">
*
* @ingroup Skins
*/
class TabList extends Component {
/**
* Builds the HTML code for this component
*
* @return String the HTML code
*/
public function getHtml() {
$ret = $this->indent() . '<!-- Content navigation -->' .
$this->indent() . '<ul class="list-inline p-contentnavigation text-center ' . $this->getClass() . '" id="p-contentnavigation">';
$navigation = $this->getSkinTemplate()->data[ 'content_navigation' ];
$this->indent( 1 );
foreach ( $navigation as $category => $tabs ) {
// TODO: visually group all links of one category (e.g. some space between categories)
if ( empty( $tabs ) ) {
continue;
}
// output the name of the current category (e.g. 'namespaces', 'views', ...)
$ret .= $this->indent() . '<!-- ' . $category . ' -->' .
$this->indent() . '<li id="p-' . $category . '" >' .
$this->indent( 1 ) . '<ul class="list-inline" >';
$this->indent( 1 );
foreach ( $tabs as $key => $tab ) {
// skip redundant links (i.e. the 'view' link)
// TODO: make this dependent on an option
if ( array_key_exists( 'redundant', $tab ) && $tab[ 'redundant' ] === true ) {
continue;
}
// apply a link class if specified, e.g. for the currently active namespace
$options = array();
if ( array_key_exists( 'class', $tab ) ) {
$options[ 'link-class' ] = $tab[ 'class' ];
}
$ret .= $this->indent() . $this->getSkinTemplate()->makeListItem( $key, $tab, $options );
}
$ret .= $this->indent( -1 ) . '</ul>' .
$this->indent( -1 ) . '</li>';
}
$ret .= $this->indent( -1 ) . '</ul>' . "\n";
return $ret;
}
}
| gpl-2.0 |
arnaudchenyensu/I9-App | twitter-like/app/routes.php | 2165 | <?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', array('as' => 'home', function()
{
if (Auth::check()) {
$user = Auth::user();
return View::make('home')
->with('followings', $user->followings)
->with('tweets', $user->tweets)
->with('followers', $user->followers);
}
return View::make('login');
}));
Route::get('/logout', function()
{
Auth::logout();
return Redirect::route('home')
->with('message', 'You are successfully logged out.');
});
Route::get('/tweets', function()
{
if (Auth::check()) {
return Auth::User()->tweets;
}
});
Route::get('/settings', function()
{
if (Auth::check()) {
return View::make('settings')
->with('user', Auth::user());
}
});
Route::get('/followers', function()
{
$user = Auth::user();
$followers = $user->followers;
foreach ($followers as $follower) {
echo $follower->username.'</br>';
}
});
Route::get('/followings', function()
{
$user = Auth::user();
$followings = $user->followings;
foreach ($followings as $following) {
echo $following->username.'</br>';
}
});
/**
* Login the user.
*
* @return Response
*/
Route::post('/login', function()
{
$username_login = array(
'username' => Input::get('login'),
'password' => Input::get('password')
);
$email_login = array(
'email' => Input::get('login'),
'password' => Input::get('password')
);
if (Auth::attempt($username_login) || Auth::attempt($email_login)) {
return Redirect::route('home')
->with('message', 'You are successfully logged in.');
} else {
// authentication failure! lets go back to the login page
return Redirect::route('home')
->with('message', 'Your username/password combination was incorrect.');
}
});
Route::resource('users', 'UserController');
Route::resource('tweets', 'TweetController');
| gpl-2.0 |
tube42/9P | core/src/se/tube42/p9/view/StarItem.java | 1843 | package se.tube42.p9.view;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.audio.*;
import com.badlogic.gdx.Input.*;
import se.tube42.lib.tweeny.*;
import se.tube42.lib.ks.*;
import se.tube42.lib.scene.*;
import se.tube42.lib.item.*;
import se.tube42.lib.util.*;
import se.tube42.lib.service.*;
import se.tube42.p9.data.*;
import se.tube42.p9.logic.*;
import static se.tube42.p9.data.Constants.*;
public class StarItem extends SpriteItem implements TweenListener
{
public StarItem()
{
super(Assets.tex_icons, 0);
setVisible(false);
setColor(Constants.COLOR_FG);
}
// ----------------------------------------
public void setVisible(boolean vis)
{
if(vis)
flags |= BaseItem.FLAG_VISIBLE;
else
flags &= ~BaseItem.FLAG_VISIBLE;
}
public void show(boolean got)
{
setVisible(true);
setIndex(got ? ICONS_STAR1 : ICONS_STAR0);
if(got) {
pause(ITEM_S, 1, 0.8f)
.tail(1.1f).configure(0.1f, null)
.tail(1.0f).configure(0.1f, null)
.tail(1.1f).configure(0.1f, null)
.tail(1.0f).configure(0.1f, null)
.tail(1.1f).configure(0.1f, null)
.tail(1.0f).configure(0.3f, null);
}
set(ITEM_A, 0, 1).configure(0.5f, null)
.pause(3)
.tail(0).configure(0.7f, null)
.finish(this, 0);
set(ITEM_A, 0, 1).configure(0.5f, null)
.pause(3)
.tail(0).configure(0.7f, null)
.finish(this, 0);
}
public void onFinish(Item item, int index, int msg)
{
setVisible(false);
}
}
| gpl-2.0 |
zanderkyle/zandergraphics | administrator/components/com_phocafont/views/phocafontfont/tmpl/edit.php | 1970 | <?php defined('_JEXEC') or die;
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
JHtml::_('behavior.keepalive');
JHtml::_('formbehavior.chosen', 'select');
$class = $this->t['n'] . 'RenderAdminView';
$r = new $class();
?>
<script type="text/javascript">
Joomla.submitbutton = function(task){
if (task == '<?php echo $this->t['task'] ?>.cancel' || document.formvalidator.isValid(document.id('adminForm'))) {
Joomla.submitform(task, document.getElementById('adminForm'));
}
else {
alert('<?php echo $this->escape(JText::_('JGLOBAL_VALIDATION_FORM_FAILED'));?>');
}
}
</script><?php
echo $r->startForm($this->t['o'], $this->t['task'], $this->item->id, 'adminForm', 'adminForm');
// First Column
echo '<div class="span10 form-horizontal">';
$tabs = array (
'general' => JText::_($this->t['l'].'_GENERAL_OPTIONS'),
'publishing' => JText::_($this->t['l'].'_PUBLISHING_OPTIONS')
);
echo $r->navigation($tabs);
echo '<div class="tab-content">'. "\n";
echo '<div class="tab-pane active" id="general">'."\n";
$formArray = array ('title', 'alternative', 'format');
echo $r->group($this->form, $formArray);
if ($this->item->format == 'externalfonttype' || $this->item->id == 0) {
$formArray = array('variant', 'subset' );
echo $r->group($this->form, $formArray);
}
$formArray = array('ordering' );
echo $r->group($this->form, $formArray);
echo '</div>'. "\n";
echo '<div class="tab-pane" id="publishing">'."\n";
foreach($this->form->getFieldset('publish') as $field) {
echo '<div class="control-group">';
if (!$field->hidden) {
echo '<div class="control-label">'.$field->label.'</div>';
}
echo '<div class="controls">';
echo $field->input;
echo '</div></div>';
}
echo '</div>';
echo '</div>';//end tab content
echo '</div>';//end span10
// Second Column
echo '<div class="span2"></div>';//end span2
echo $r->formInputs();
echo $r->endForm();
?>
| gpl-2.0 |
kaluli/Wordpress-Site | original/wp-content/themes/realhomes/template-parts/carousel_partners.php | 2604 | <?php
$show_partners = get_option('theme_show_partners');
if($show_partners == 'true'){
?>
<div class="container page-carousel">
<div class="row">
<div class="span12">
<section class="brands-carousel clearfix">
<h3><span><?php echo $partners_title = get_option('theme_partners_title'); ?></span></h3>
<ul class="brands-carousel-list clearfix">
<?php
$partners_query_args = array(
'post_type' => 'partners',
'posts_per_page' => -1
);
$partners_query = new WP_Query( $partners_query_args );
if ( $partners_query->have_posts() ) :
while ( $partners_query->have_posts() ) :
$partners_query->the_post();
$post_meta_data = get_post_custom($post->ID);
$partner_url = '';
if( !empty($post_meta_data['REAL_HOMES_partner_url'][0]) ) {
$partner_url = $post_meta_data['REAL_HOMES_partner_url'][0];
}
?>
<li>
<a target="_blank" href="<?php echo $partner_url; ?>" title="<?php the_title();?>">
<?php
$thumb_title = trim(strip_tags( get_the_title($post->ID)));
the_post_thumbnail('partners-logo',array(
'alt' => $thumb_title,
'title' => $thumb_title
));
?>
</a>
</li>
<?php
endwhile;
wp_reset_query();
endif;
?>
</ul>
</section>
</div>
</div>
</div>
<?php
}
?> | gpl-2.0 |
gitpan/hyperic-sigar | bindings/java/src/org/hyperic/sigar/cmd/Iostat.java | 5603 | /*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.sigar.cmd;
import java.util.ArrayList;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemMap;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.DiskUsage;
import org.hyperic.sigar.shell.FileCompleter;
import org.hyperic.sigar.util.GetlineCompleter;
/**
* Report filesytem disk space usage.
*/
public class Iostat extends SigarCommandBase {
private static final String OUTPUT_FORMAT =
"%-15s %-15s %10s %10s %7s %7s %5s %5s";
private static final String[] HEADER = new String[] {
"Filesystem",
"Mounted on",
"Reads",
"Writes",
"R-bytes",
"W-bytes",
"Queue",
"Svctm",
};
private GetlineCompleter completer;
public Iostat(Shell shell) {
super(shell);
setOutputFormat(OUTPUT_FORMAT);
this.completer = new FileCompleter(shell);
}
public Iostat() {
super();
setOutputFormat(OUTPUT_FORMAT);
}
public GetlineCompleter getCompleter() {
return this.completer;
}
protected boolean validateArgs(String[] args) {
return args.length <= 1;
}
public String getSyntaxArgs() {
return "[filesystem]";
}
public String getUsageShort() {
return "Report filesystem disk i/o";
}
public void printHeader() {
printf(HEADER);
}
private String svctm(double val) {
return sprintf("%3.2f", new Object[] { new Double(val) });
}
public void output(String[] args) throws SigarException {
if (args.length == 1) {
String arg = args[0];
if ((arg.indexOf('/') != -1) || (arg.indexOf('\\') != -1)) {
outputFileSystem(arg);
}
else {
outputDisk(arg);
}
}
else {
FileSystem[] fslist = this.proxy.getFileSystemList();
printHeader();
for (int i=0; i<fslist.length; i++) {
if (fslist[i].getType() == FileSystem.TYPE_LOCAL_DISK) {
output(fslist[i]);
}
}
}
}
public void outputFileSystem(String arg) throws SigarException {
FileSystemMap mounts = this.proxy.getFileSystemMap();
String name = FileCompleter.expand(arg);
FileSystem fs = mounts.getMountPoint(name);
if (fs != null) {
printHeader();
output(fs);
return;
}
throw new SigarException(arg +
" No such file or directory");
}
public void outputDisk(String name) throws SigarException {
DiskUsage disk =
this.sigar.getDiskUsage(name);
ArrayList items = new ArrayList();
printHeader();
items.add(name);
items.add("-");
items.add(String.valueOf(disk.getReads()));
items.add(String.valueOf(disk.getWrites()));
if (disk.getReadBytes() == Sigar.FIELD_NOTIMPL) {
items.add("-");
items.add("-");
}
else {
items.add(Sigar.formatSize(disk.getReadBytes()));
items.add(Sigar.formatSize(disk.getWriteBytes()));
}
if (disk.getQueue() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(disk.getQueue()));
}
if (disk.getServiceTime() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(disk.getServiceTime()));
}
printf(items);
}
public void output(FileSystem fs) throws SigarException {
FileSystemUsage usage =
this.sigar.getFileSystemUsage(fs.getDirName());
ArrayList items = new ArrayList();
items.add(fs.getDevName());
items.add(fs.getDirName());
items.add(String.valueOf(usage.getDiskReads()));
items.add(String.valueOf(usage.getDiskWrites()));
if (usage.getDiskReadBytes() == Sigar.FIELD_NOTIMPL) {
items.add("-");
items.add("-");
}
else {
items.add(Sigar.formatSize(usage.getDiskReadBytes()));
items.add(Sigar.formatSize(usage.getDiskWriteBytes()));
}
if (usage.getDiskQueue() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(usage.getDiskQueue()));
}
if (usage.getDiskServiceTime() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(usage.getDiskServiceTime()));
}
printf(items);
}
public static void main(String[] args) throws Exception {
new Iostat().processCommand(args);
}
}
| gpl-2.0 |
fgx/fgx | src/mpmap/mpmapwidget.cpp | 3713 | // -=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-
// FGx FlightGear Launcher // mpmapwidget.cpp
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-
// (c) 2010-2012
// Yves Sablonier, Pete Morgan
// Geoff McLane
// GNU GPLv2, see main.cpp and shipped licence.txt for further information
#include <QDesktopServices>
#include <QtCore/QString>
#include <QtCore/QVariant>
#include <QtGui/QCloseEvent>
#include <QtGui/QVBoxLayout>
#include <QtGui/QToolBar>
#include <QtGui/QLabel>
#include <QtGui/QComboBox>
#include "mpmap/mpmapwidget.h"
#include "panes/coresettingswidget.h"
#include "launcher/launcherwindow.h"
MpMapWidget::MpMapWidget(MainObject *mOb, QWidget *parent) :
QWidget(parent)
{
mainObject = mOb;
setProperty("settings_namespace", QVariant("mpmap_window"));
mainObject->settings->restoreWindow(this);
setWindowTitle(tr("Multi Player Map"));
setWindowIcon(QIcon(":/icon/mpmap"));
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->setContentsMargins(0,0,0,0);
mainLayout->setSpacing(0);
//** Toolbar
QToolBar *toolbar = new QToolBar();
mainLayout->addWidget(toolbar, 1);
//** Select server
QLabel *lblSelectServer = new QLabel(tr("Select Server:"));
toolbar->addWidget(lblSelectServer);
comboServer = new QComboBox();
toolbar->addWidget(comboServer);
//**get callsign
//**add callsign to url
comboServer->addItem("MpMap-01", QVariant("http://mpmap01.flightgear.org/"));
comboServer->addItem("MpMap-02", QVariant("http://mpmap02.flightgear.org/"));
comboServer->setCurrentIndex(0);
connect(comboServer, SIGNAL(currentIndexChanged(int)), this, SLOT(on_combo_server()) );
//=============================================================
//== Cache
//qDebug() << QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
networkDiskCache = new QNetworkDiskCache(this);
networkDiskCache->setCacheDirectory(QDesktopServices::storageLocation(QDesktopServices::CacheLocation));
networkCookieJar = new QNetworkCookieJar(this);
//== Browser
webView = new QWebView(this);
mainLayout->addWidget(webView, 100);
webView->page()->networkAccessManager()->setCache(networkDiskCache);
webView->page()->networkAccessManager()->setCookieJar(networkCookieJar);
connect(webView, SIGNAL(loadStarted()), this, SLOT(start_progress()));
connect(webView, SIGNAL(loadProgress(int)), this, SLOT(update_progress(int)));
connect(webView, SIGNAL(loadFinished(bool)), this, SLOT(end_progress(bool)));
//*** Status Bar
statusBar = new QStatusBar(this);
mainLayout->addWidget(statusBar);
statusBar->showMessage("Idle");
//** Progress Bar
progressBar = new QProgressBar();
progressBar->setVisible(false);
statusBar->addPermanentWidget(progressBar);
//*** Initialise
on_combo_server();
}
//=============================================================
//== Progress Slots
void MpMapWidget::start_progress(){
progressBar->setVisible(true);
}
void MpMapWidget::update_progress(int v){
progressBar->setValue(v);
}
void MpMapWidget::end_progress(bool Ok){
Q_UNUSED(Ok);
progressBar->setVisible(false);
statusBar->showMessage( webView->url().toString() );
}
void MpMapWidget::on_combo_server(){
QUrl server_url( comboServer->itemData(comboServer->currentIndex()).toString() );
server_url.addQueryItem("follow", mainObject->settings->value("callsign").toString() );
webView->load( server_url );
statusBar->showMessage(QString("Loading: ").append( server_url.toString()) );
}
//** Overide the closeEvent
void MpMapWidget::closeEvent(QCloseEvent *event)
{
mainObject->settings->saveWindow(this);
Q_UNUSED(event);
}
| gpl-2.0 |
killbug2004/reko | src/Arch/X86/X86Rewriter.cs | 21190 | #region License
/*
* Copyright (C) 1999-2015 John Källén.
*
* 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 this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#endregion
using Decompiler.Core;
using Decompiler.Core.Expressions;
using Decompiler.Core.Rtl;
using Decompiler.Core.Lib;
using Decompiler.Core.Machine;
using Decompiler.Core.Operators;
using Decompiler.Core.Types;
using System;
using System.Collections.Generic;
using System.Text;
using IEnumerable = System.Collections.IEnumerable;
using IEnumerator = System.Collections.IEnumerator;
namespace Decompiler.Arch.X86
{
/// <summary>
/// Rewrites x86 instructions into a stream of low-level RTL-like instructions.
/// </summary>
public partial class X86Rewriter : IEnumerable<RtlInstructionCluster>
{
private IRewriterHost host;
private IntelArchitecture arch;
private Frame frame;
private LookaheadEnumerator<IntelInstruction> dasm;
private RtlEmitter emitter;
private OperandRewriter orw;
private IntelInstruction instrCur;
private RtlInstructionCluster ric;
private X86State state;
public X86Rewriter(
IntelArchitecture arch,
IRewriterHost host,
X86State state,
ImageReader rdr,
Frame frame)
{
if (host == null)
throw new ArgumentNullException("host");
this.arch = arch;
this.host = host;
this.frame = frame;
this.state = state;
this.dasm = new LookaheadEnumerator<IntelInstruction>(arch.CreateDisassembler(rdr));
}
/// <summary>
/// Iterator that yields one RtlIntructionCluster for each x86 instruction.
/// </summary>
/// <returns></returns>
public IEnumerator<RtlInstructionCluster> GetEnumerator()
{
while (dasm.MoveNext())
{
instrCur = dasm.Current;
ric = new RtlInstructionCluster(instrCur.Address, instrCur.Length);
emitter = new RtlEmitter(ric.Instructions);
orw = arch.ProcessorMode.CreateOperandRewriter(arch, frame, host);
switch (instrCur.code)
{
default:
throw new AddressCorrelatedException(
instrCur.Address,
"Rewriting x86 opcode '{0}' is not supported yet.",
instrCur.code);
case Opcode.aaa: RewriteAaa(); break;
case Opcode.aam: RewriteAam(); break;
case Opcode.adc: RewriteAdcSbb(BinaryOperator.IAdd); break;
case Opcode.add: RewriteAddSub(BinaryOperator.IAdd); break;
case Opcode.and: RewriteLogical(BinaryOperator.And); break;
case Opcode.arpl: RewriteArpl(); break;
case Opcode.bsr: RewriteBsr(); break;
case Opcode.bswap: RewriteBswap(); break;
case Opcode.bt: RewriteBt(); break;
case Opcode.btr: RewriteBtr(); break;
case Opcode.bts: RewriteBts(); break;
case Opcode.call: RewriteCall(instrCur.op1, instrCur.op1.Width); break;
case Opcode.cbw: RewriteCbw(); break;
case Opcode.clc: RewriteSetFlag(FlagM.CF, Constant.False()); break;
case Opcode.cld: RewriteSetFlag(FlagM.DF, Constant.False()); break;
case Opcode.cli: RewriteCli(); break;
case Opcode.cmc: emitter.Assign(orw.FlagGroup(FlagM.CF), emitter.Not(orw.FlagGroup(FlagM.CF))); break;
case Opcode.cmova: RewriteConditionalMove(ConditionCode.UGT, instrCur.op1, instrCur.op2); break;
case Opcode.cmovbe: RewriteConditionalMove(ConditionCode.ULE, instrCur.op1, instrCur.op2); break;
case Opcode.cmovc: RewriteConditionalMove(ConditionCode.ULT, instrCur.op1, instrCur.op2); break;
case Opcode.cmovge: RewriteConditionalMove(ConditionCode.GE, instrCur.op1, instrCur.op2); break;
case Opcode.cmovg: RewriteConditionalMove(ConditionCode.GT, instrCur.op1, instrCur.op2); break;
case Opcode.cmovl: RewriteConditionalMove(ConditionCode.LT, instrCur.op1, instrCur.op2); break;
case Opcode.cmovle: RewriteConditionalMove(ConditionCode.LE, instrCur.op1, instrCur.op2); break;
case Opcode.cmovnc: RewriteConditionalMove(ConditionCode.UGE, instrCur.op1, instrCur.op2); break;
case Opcode.cmovno: RewriteConditionalMove(ConditionCode.NO, instrCur.op1, instrCur.op2); break;
case Opcode.cmovns: RewriteConditionalMove(ConditionCode.NS, instrCur.op1, instrCur.op2); break;
case Opcode.cmovnz: RewriteConditionalMove(ConditionCode.NE, instrCur.op1, instrCur.op2); break;
case Opcode.cmovo: RewriteConditionalMove(ConditionCode.OV, instrCur.op1, instrCur.op2); break;
case Opcode.cmovpe: RewriteConditionalMove(ConditionCode.PE, instrCur.op1, instrCur.op2); break;
case Opcode.cmovpo: RewriteConditionalMove(ConditionCode.PO, instrCur.op1, instrCur.op2); break;
case Opcode.cmovs: RewriteConditionalMove(ConditionCode.SG, instrCur.op1, instrCur.op2); break;
case Opcode.cmovz: RewriteConditionalMove(ConditionCode.EQ, instrCur.op1, instrCur.op2); break;
case Opcode.cmpxchg: RewriteCmpxchg(); break;
case Opcode.cmp: RewriteCmp(); break;
case Opcode.cmps: RewriteStringInstruction(); break;
case Opcode.cmpsb: RewriteStringInstruction(); break;
case Opcode.cpuid: RewriteCpuid(); break;
case Opcode.cvttsd2si: RewriteCvttsd2si(); break;
case Opcode.cwd: RewriteCwd(); break;
case Opcode.daa: EmitDaaDas("__daa"); break;
case Opcode.das: EmitDaaDas("__das"); break;
case Opcode.dec: RewriteIncDec(-1); break;
case Opcode.div: RewriteDivide(Operator.UDiv, Domain.UnsignedInt); break;
case Opcode.enter: RewriteEnter(); break;
case Opcode.fadd: EmitCommonFpuInstruction(Operator.FAdd, false, false); break;
case Opcode.faddp: EmitCommonFpuInstruction(Operator.FAdd, false, true); break;
case Opcode.fchs: EmitFchs(); break;
case Opcode.fclex: RewriteFclex(); break;
case Opcode.fcom: RewriteFcom(0); break;
case Opcode.fcomp: RewriteFcom(1); break;
case Opcode.fcompp: RewriteFcom(2); break;
case Opcode.fcos: RewriteFUnary("cos"); break;
case Opcode.fdiv: EmitCommonFpuInstruction(Operator.FDiv, false, false); break;
case Opcode.fdivp: EmitCommonFpuInstruction(Operator.FDiv, false, true); break;
case Opcode.fiadd: EmitCommonFpuInstruction(Operator.FAdd, false, false, PrimitiveType.Real64); break;
case Opcode.fimul: EmitCommonFpuInstruction(Operator.FMul, false, false, PrimitiveType.Real64); break;
case Opcode.fisub: EmitCommonFpuInstruction(Operator.FSub, false, false, PrimitiveType.Real64); break;
case Opcode.fisubr: EmitCommonFpuInstruction(Operator.FSub, true, false, PrimitiveType.Real64); break;
case Opcode.fidiv: EmitCommonFpuInstruction(Operator.FDiv, false, false, PrimitiveType.Real64); break;
case Opcode.fdivr: EmitCommonFpuInstruction(Operator.FDiv, true, false); break;
case Opcode.fdivrp: EmitCommonFpuInstruction(Operator.FDiv, true, true); break;
case Opcode.fild: RewriteFild(); break;
case Opcode.fistp: RewriteFistp(); break;
case Opcode.fld: RewriteFld(); break;
case Opcode.fld1: RewriteFldConst(1.0); break;
case Opcode.fldcw: RewriteFldcw(); break;
case Opcode.fldln2: RewriteFldConst(Constant.Ln2()); break;
case Opcode.fldpi: RewriteFldConst(Constant.Pi()); break;
case Opcode.fldz: RewriteFldConst(0.0); break;
case Opcode.fmul: EmitCommonFpuInstruction(Operator.FMul, false, false); break;
case Opcode.fmulp: EmitCommonFpuInstruction(Operator.FMul, false, true); break;
case Opcode.fpatan: RewriteFpatan(); break;
case Opcode.frndint: RewriteFUnary("__rndint"); break;
case Opcode.fsin: RewriteFUnary("sin"); break;
case Opcode.fsincos: RewriteFsincos(); break;
case Opcode.fsqrt: RewriteFUnary("sqrt"); break;
case Opcode.fst: RewriteFst(false); break;
case Opcode.fstcw: RewriterFstcw(); break;
case Opcode.fstp: RewriteFst(true); break;
case Opcode.fstsw: RewriteFstsw(); break;
case Opcode.fsub: EmitCommonFpuInstruction(Operator.ISub, false, false); break;
case Opcode.fsubp: EmitCommonFpuInstruction(Operator.ISub, false, true); break;
case Opcode.fsubr: EmitCommonFpuInstruction(Operator.ISub, true, false); break;
case Opcode.fsubrp: EmitCommonFpuInstruction(Operator.ISub, true, true); break;
case Opcode.ftst: RewriteFtst(); break;
case Opcode.fucompp: RewriteFcom(2); break;
case Opcode.fxam: RewriteFxam(); break;
case Opcode.fxch: RewriteExchange(); break;
case Opcode.fyl2x: RewriteFyl2x(); break;
case Opcode.hlt: RewriteHlt(); break;
case Opcode.idiv: RewriteDivide(Operator.SDiv, Domain.SignedInt); break;
case Opcode.@in: RewriteIn(); break;
case Opcode.imul: RewriteMultiply(Operator.SMul, Domain.SignedInt); break;
case Opcode.inc: RewriteIncDec(1); break;
case Opcode.insb: RewriteStringInstruction(); break;
case Opcode.ins: RewriteStringInstruction(); break;
case Opcode.@int: RewriteInt(); break;
case Opcode.iret: RewriteIret(); break;
case Opcode.jmp: RewriteJmp(); break;
case Opcode.ja: RewriteConditionalGoto(ConditionCode.UGT, instrCur.op1); break;
case Opcode.jbe: RewriteConditionalGoto(ConditionCode.ULE, instrCur.op1); break;
case Opcode.jc: RewriteConditionalGoto(ConditionCode.ULT, instrCur.op1); break;
case Opcode.jcxz: RewriteJcxz(); break;
case Opcode.jge: RewriteConditionalGoto(ConditionCode.GE, instrCur.op1); break;
case Opcode.jg: RewriteConditionalGoto(ConditionCode.GT, instrCur.op1); break;
case Opcode.jl: RewriteConditionalGoto(ConditionCode.LT, instrCur.op1); break;
case Opcode.jle: RewriteConditionalGoto(ConditionCode.LE, instrCur.op1); break;
case Opcode.jnc: RewriteConditionalGoto(ConditionCode.UGE, instrCur.op1); break;
case Opcode.jno: RewriteConditionalGoto(ConditionCode.NO, instrCur.op1); break;
case Opcode.jns: RewriteConditionalGoto(ConditionCode.NS, instrCur.op1); break;
case Opcode.jnz: RewriteConditionalGoto(ConditionCode.NE, instrCur.op1); break;
case Opcode.jo: RewriteConditionalGoto(ConditionCode.OV, instrCur.op1); break;
case Opcode.jpe: RewriteConditionalGoto(ConditionCode.PE, instrCur.op1); break;
case Opcode.jpo: RewriteConditionalGoto(ConditionCode.PO, instrCur.op1); break;
case Opcode.js: RewriteConditionalGoto(ConditionCode.SG, instrCur.op1); break;
case Opcode.jz: RewriteConditionalGoto(ConditionCode.EQ, instrCur.op1); break;
case Opcode.lahf: RewriteLahf(); break;
case Opcode.lds: RewriteLxs(Registers.ds); break;
case Opcode.lea: RewriteLea(); break;
case Opcode.leave: RewriteLeave(); break;
case Opcode.les: RewriteLxs(Registers.es); break;
case Opcode.lfs: RewriteLxs(Registers.fs); break;
case Opcode.lgs: RewriteLxs(Registers.gs); break;
case Opcode.@lock: RewriteLock(); break;
case Opcode.lods: RewriteStringInstruction(); break;
case Opcode.lodsb: RewriteStringInstruction(); break;
case Opcode.loop: RewriteLoop(0, ConditionCode.EQ); break;
case Opcode.loope: RewriteLoop(FlagM.ZF, ConditionCode.EQ); break;
case Opcode.loopne: RewriteLoop(FlagM.ZF, ConditionCode.NE); break;
case Opcode.lss: RewriteLxs(Registers.ss); break;
case Opcode.mov: RewriteMov(); break;
case Opcode.movd: RewriteMovzx(); break;
case Opcode.movdqa: RewriteMov(); break;
case Opcode.movq: RewriteMov(); break;
case Opcode.movs: RewriteStringInstruction(); break;
case Opcode.movsb: RewriteStringInstruction(); break;
case Opcode.movsx: RewriteMovsx(); break;
case Opcode.movzx: RewriteMovzx(); break;
case Opcode.mul: RewriteMultiply(Operator.UMul, Domain.UnsignedInt); break;
case Opcode.neg: RewriteNeg(); break;
case Opcode.nop: continue;
case Opcode.not: RewriteNot(); break;
case Opcode.or: RewriteLogical(BinaryOperator.Or); break;
case Opcode.@out: RewriteOut(); break;
case Opcode.@outs: RewriteStringInstruction(); break;
case Opcode.@outsb: RewriteStringInstruction(); break;
case Opcode.palignr: RewritePalignr(); break;
case Opcode.pop: RewritePop(); break;
case Opcode.popa: RewritePopa(); break;
case Opcode.popf: RewritePopf(); break;
case Opcode.pshufd: RewritePshufd(); break;
case Opcode.punpcklbw: RewritePunpcklbw(); break;
case Opcode.punpcklwd: RewritePunpcklwd(); break;
case Opcode.push: RewritePush(); break;
case Opcode.pusha: RewritePusha(); break;
case Opcode.pushf: RewritePushf(); break;
case Opcode.pxor: RewritePxor(); break;
case Opcode.rcl: RewriteRotation(PseudoProcedure.RolC, true, true); break;
case Opcode.rcr: RewriteRotation(PseudoProcedure.RorC, true, false); break;
case Opcode.rol: RewriteRotation(PseudoProcedure.Rol, false, true); break;
case Opcode.ror: RewriteRotation(PseudoProcedure.Ror, false, false); break;
case Opcode.rdtsc: RewriteRdtsc(); break;
case Opcode.rep: RewriteRep(); break;
case Opcode.repne: RewriteRep(); break;
case Opcode.ret: RewriteRet(); break;
case Opcode.retf: RewriteRet(); break;
case Opcode.sahf: emitter.Assign(orw.FlagGroup(IntelInstruction.DefCc(instrCur.code)), orw.AluRegister(Registers.ah)); break;
case Opcode.sar: RewriteBinOp(Operator.Sar); break;
case Opcode.sbb: RewriteAdcSbb(BinaryOperator.ISub); break;
case Opcode.scas: RewriteStringInstruction(); break;
case Opcode.scasb: RewriteStringInstruction(); break;
case Opcode.seta: RewriteSet(ConditionCode.UGT); break;
case Opcode.setc: RewriteSet(ConditionCode.ULT); break;
case Opcode.setbe: RewriteSet(ConditionCode.ULE); break;
case Opcode.setg: RewriteSet(ConditionCode.GT); break;
case Opcode.setge: RewriteSet(ConditionCode.GE); break;
case Opcode.setl: RewriteSet(ConditionCode.LT); break;
case Opcode.setle: RewriteSet(ConditionCode.LE); break;
case Opcode.setnc: RewriteSet(ConditionCode.UGE); break;
case Opcode.setns: RewriteSet(ConditionCode.NS); break;
case Opcode.setnz: RewriteSet(ConditionCode.NE); break;
case Opcode.seto: RewriteSet(ConditionCode.OV); break;
case Opcode.sets: RewriteSet(ConditionCode.SG); break;
case Opcode.setz: RewriteSet(ConditionCode.EQ); break;
case Opcode.shl: RewriteBinOp(BinaryOperator.Shl); break;
case Opcode.shld: RewriteShxd("__shld"); break;
case Opcode.shr: RewriteBinOp(BinaryOperator.Shr); break;
case Opcode.shrd: RewriteShxd("__shrd"); break;
case Opcode.stc: RewriteSetFlag(FlagM.CF, Constant.True()); break;
case Opcode.std: RewriteSetFlag(FlagM.DF, Constant.True()); break;
case Opcode.sti: break; //$TODO:
case Opcode.stos: RewriteStringInstruction(); break;
case Opcode.stosb: RewriteStringInstruction(); break;
case Opcode.sub: RewriteAddSub(BinaryOperator.ISub); break;
case Opcode.test: RewriteTest(); break;
case Opcode.wait: break; // used to slow down FPU.
case Opcode.xadd: RewriteXadd(); break;
case Opcode.xchg: RewriteExchange(); break;
case Opcode.xgetbv: RewriteXgetbv(); break;
case Opcode.xlat: RewriteXlat(); break;
case Opcode.xor: RewriteLogical(BinaryOperator.Xor); break;
}
yield return ric;
}
}
//$TODO: common code.
public Expression PseudoProc(string name, DataType retType, params Expression[] args)
{
var ppp = host.EnsurePseudoProcedure(name, retType, args.Length);
return PseudoProc(ppp, retType, args);
}
public Expression PseudoProc(PseudoProcedure ppp, DataType retType, params Expression[] args)
{
if (args.Length != ppp.Arity)
throw new ArgumentOutOfRangeException(
string.Format("Pseudoprocedure {0} expected {1} arguments, but was passed {2}.",
ppp.Name,
ppp.Arity,
args.Length));
return emitter.Fn(new ProcedureConstant(arch.PointerType, ppp), retType, args);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[Flags]
public enum CopyFlags
{
ForceBreak = 1,
EmitCc = 2,
SetCfIf0 = 4,
}
/// <summary>
/// Breaks up very common case of x86:
/// <code>
/// op [memaddr], reg
/// </code>
/// into the equivalent:
/// <code>
/// tmp := [memaddr] op reg;
/// store([memaddr], tmp);
/// </code>
/// </summary>
/// <param name="opDst"></param>
/// <param name="src"></param>
/// <param name="forceBreak">if true, forcibly splits the assignments in two if the destination is a memory store.</param>
/// <returns>Returns the destination of the copy.</returns>
public void EmitCopy(MachineOperand opDst, Expression src, CopyFlags flags)
{
Expression dst = SrcOp(opDst);
Identifier idDst = dst as Identifier;
if (idDst != null || (flags & CopyFlags.ForceBreak) == 0)
{
emitter.Assign(dst, src);
}
else
{
Identifier tmp = frame.CreateTemporary(opDst.Width);
emitter.Assign(tmp, src);
var ea = orw.CreateMemoryAccess(instrCur, (MemoryOperand)opDst, state);
emitter.Assign(ea, tmp);
dst = tmp;
}
if ((flags & CopyFlags.EmitCc) != 0)
{
EmitCcInstr(dst, IntelInstruction.DefCc(instrCur.code));
}
if ((flags & CopyFlags.SetCfIf0) != 0)
{
emitter.Assign(orw.FlagGroup(FlagM.CF), emitter.Eq0(dst));
}
}
private Expression SrcOp(MachineOperand opSrc)
{
return orw.Transform(instrCur, opSrc, opSrc.Width, state);
}
private Expression SrcOp(MachineOperand opSrc, PrimitiveType dstWidth)
{
return orw.Transform(instrCur, opSrc, dstWidth, state);
}
}
}
| gpl-2.0 |
ruuk/script.module.sharesocial | oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py | 8446 | # -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749.grant_types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import unicode_literals, absolute_import
import json
from oauthlib.common import log
from .base import GrantTypeBase
from .. import errors
from ..request_validator import RequestValidator
class ResourceOwnerPasswordCredentialsGrant(GrantTypeBase):
"""`Resource Owner Password Credentials Grant`_
The resource owner password credentials grant type is suitable in
cases where the resource owner has a trust relationship with the
client, such as the device operating system or a highly privileged
application. The authorization server should take special care when
enabling this grant type and only allow it when other flows are not
viable.
This grant type is suitable for clients capable of obtaining the
resource owner's credentials (username and password, typically using
an interactive form). It is also used to migrate existing clients
using direct authentication schemes such as HTTP Basic or Digest
authentication to OAuth by converting the stored credentials to an
access token::
+----------+
| Resource |
| Owner |
| |
+----------+
v
| Resource Owner
(A) Password Credentials
|
v
+---------+ +---------------+
| |>--(B)---- Resource Owner ------->| |
| | Password Credentials | Authorization |
| Client | | Server |
| |<--(C)---- Access Token ---------<| |
| | (w/ Optional Refresh Token) | |
+---------+ +---------------+
Figure 5: Resource Owner Password Credentials Flow
The flow illustrated in Figure 5 includes the following steps:
(A) The resource owner provides the client with its username and
password.
(B) The client requests an access token from the authorization
server's token endpoint by including the credentials received
from the resource owner. When making the request, the client
authenticates with the authorization server.
(C) The authorization server authenticates the client and validates
the resource owner credentials, and if valid, issues an access
token.
.. _`Resource Owner Password Credentials Grant`: http://tools.ietf.org/html/rfc6749#section-4.3
"""
def __init__(self, request_validator=None):
self.request_validator = request_validator or RequestValidator()
def create_token_response(self, request, token_handler,
require_authentication=True):
"""Return token or error in json format.
If the access token request is valid and authorized, the
authorization server issues an access token and optional refresh
token as described in `Section 5.1`_. If the request failed client
authentication or is invalid, the authorization server returns an
error response as described in `Section 5.2`_.
.. _`Section 5.1`: http://tools.ietf.org/html/rfc6749#section-5.1
.. _`Section 5.2`: http://tools.ietf.org/html/rfc6749#section-5.2
"""
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Cache-Control': 'no-store',
'Pragma': 'no-cache',
}
try:
if require_authentication:
log.debug('Authenticating client, %r.', request)
if not self.request_validator.authenticate_client(request):
log.debug('Client authentication failed, %r.', request)
raise errors.InvalidClientError(request=request)
else:
if not hasattr(request.client, 'client_id'):
raise NotImplementedError(
'Authenticate client must set the '
'request.client.client_id attribute '
'in authenticate_client.')
else:
log.debug('Client authentication disabled, %r.', request)
log.debug('Validating access token request, %r.', request)
self.validate_token_request(request)
except errors.OAuth2Error as e:
log.debug('Client error in token request, %s.', e)
return headers, e.json, e.status_code
token = token_handler.create_token(request, refresh_token=True)
log.debug('Issuing token %r to client id %r (%r) and username %s.',
token, request.client_id, request.client, request.username)
return headers, json.dumps(token), 200
def validate_token_request(self, request):
"""
The client makes a request to the token endpoint by adding the
following parameters using the "application/x-www-form-urlencoded"
format per Appendix B with a character encoding of UTF-8 in the HTTP
request entity-body:
grant_type
REQUIRED. Value MUST be set to "password".
username
REQUIRED. The resource owner username.
password
REQUIRED. The resource owner password.
scope
OPTIONAL. The scope of the access request as described by
`Section 3.3`_.
If the client type is confidential or the client was issued client
credentials (or assigned other authentication requirements), the
client MUST authenticate with the authorization server as described
in `Section 3.2.1`_.
The authorization server MUST:
o require client authentication for confidential clients or for any
client that was issued client credentials (or with other
authentication requirements),
o authenticate the client if client authentication is included, and
o validate the resource owner password credentials using its
existing password validation algorithm.
Since this access token request utilizes the resource owner's
password, the authorization server MUST protect the endpoint against
brute force attacks (e.g., using rate-limitation or generating
alerts).
.. _`Section 3.3`: http://tools.ietf.org/html/rfc6749#section-3.3
.. _`Section 3.2.1`: http://tools.ietf.org/html/rfc6749#section-3.2.1
"""
for param in ('grant_type', 'username', 'password'):
if not getattr(request, param):
raise errors.InvalidRequestError(
'Request is missing %s parameter.' % param, request=request)
for param in ('grant_type', 'username', 'password', 'scope'):
if param in request.duplicate_params:
raise errors.InvalidRequestError(state=request.state,
description='Duplicate %s parameter.' % param, request=request)
# This error should rarely (if ever) occur if requests are routed to
# grant type handlers based on the grant_type parameter.
if not request.grant_type == 'password':
raise errors.UnsupportedGrantTypeError(request=request)
log.debug('Validating username %s and password %s.',
request.username, request.password)
if not self.request_validator.validate_user(request.username,
request.password, request.client, request):
raise errors.InvalidGrantError('Invalid credentials given.', request=request)
else:
if not hasattr(request.client, 'client_id'):
raise NotImplementedError(
'Validate user must set the '
'request.client.client_id attribute '
'in authenticate_client.')
log.debug('Authorizing access to user %r.', request.user)
# Ensure client is authorized use of this grant type
self.validate_grant_type(request)
if request.client:
request.client_id = request.client_id or request.client.client_id
self.validate_scopes(request)
| gpl-2.0 |
silasakk/dev-df | wp-content/themes/dongfeng/template-parts/content-none.php | 1139 | <?php
/**
* Template part for displaying a message that posts cannot be found.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package dongfeng
*/
?>
<section class="no-results not-found">
<header class="page-header">
<h1 class="page-title"><?php esc_html_e( 'Nothing Found', 'dongfeng' ); ?></h1>
</header><!-- .page-header -->
<div class="page-content">
<?php
if ( is_home() && current_user_can( 'publish_posts' ) ) : ?>
<p><?php printf( wp_kses( __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'dongfeng' ), array( 'a' => array( 'href' => array() ) ) ), esc_url( admin_url( 'post-new.php' ) ) ); ?></p>
<?php elseif ( is_search() ) : ?>
<p><?php esc_html_e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'dongfeng' ); ?></p>
<?php
get_search_form();
else : ?>
<p><?php esc_html_e( 'It seems we can’t find what you’re looking for. Perhaps searching can help.', 'dongfeng' ); ?></p>
<?php
get_search_form();
endif; ?>
</div><!-- .page-content -->
</section><!-- .no-results -->
| gpl-2.0 |
GeoTechSystems/GeoTechMobile | app/src/main/java/com/jhlabs/map/proj/DenoyerProjection.java | 1473 | /*
Copyright 2006 Jerry Huxtable
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.
*/
/*
* This file was semi-automatically converted from the public-domain USGS PROJ source.
*/
package com.jhlabs.map.proj;
import com.vividsolutions.jts.geom.Coordinate;
public class DenoyerProjection extends Projection {
public final static double C0 = 0.95;
public final static double C1 = -.08333333333333333333;
public final static double C3 = 0.00166666666666666666;
public final static double D1 = 0.9;
public final static double D5 = 0.03;
public Coordinate project(double lplam, double lpphi, Coordinate out) {
out.y = lpphi;
out.x = lplam;
double aphi = Math.abs(lplam);
out.x *= Math.cos((C0 + aphi * (C1 + aphi * aphi * C3)) *
(lpphi * (D1 + D5 * lpphi * lpphi * lpphi * lpphi)));
return out;
}
public boolean parallelsAreParallel() {
return true;
}
public boolean hasInverse() {
return false;
}
public String toString() {
return "Denoyer Semi-elliptical";
}
}
| gpl-2.0 |
genesint/UHRC | sites/all/modules/custom/drpl01/views/admin-recommendation-table.tpl.php | 3396 | <?php
$IFRAME = isset($_GET['IFRAME']) ? $_GET['IFRAME'] : "";
$SEARCH = isset($_GET['SEARCH']) ? $_GET['SEARCH'] : "";
?>
<script>
function download_file(otype) {
var ids = parent.jQuery("#iframe-dashboard").contents().find(".ohrc-id");
var qq = "";
for (var i = 0; i < ids.length; i++) {
qq += ids[i].value + "|";
}
window.location = 'download-' + otype + '?qq=' + qq;
}
</script>
<script>
jQuery(document).ready(function() {
jQuery('#recommendation').dataTable({
"oLanguage": {
"sProcessing": '<i class="fa fa-2x fa-spinner fa-spin"></i>'
},
"lengthMenu": [[10, 25, 50,100,500,1000], [10, 25, 50,100,500,1000]],
"fnServerParams": function(aoData) {
aoData.push({"name": "SEARCH", "value": "<?php echo $SEARCH; ?>"});
},
"bProcessing": true,
"bServerSide": true,
"searching": true,
//"bInfo": false,
"aoColumnDefs": [
{"bSearchable": false, "bVisible": false, "aTargets": [0]},
{"bSearchable": false, "bVisible": false, "aTargets": [1]},
{"bSearchable": false, "bSortable": false, "aTargets": [2]},
{"bSearchable": false, "bSortable": false, "aTargets": [3]},
{"bSearchable": false, "bSortable": false, "aTargets": [4]},
{"bSearchable": false, "bSortable": false, "aTargets": [5]},
{"bSearchable": false, "bSortable": false, "aTargets": [6]},
{"bSearchable": false, "bSortable": false, "aTargets": [7]},
{"bSearchable": false, "bSortable": false, "aTargets": [8]},
{"bSearchable": false, "bSortable": false, "aTargets": [9]},
{"bSearchable": false, "bSortable": false, "aTargets": [10]},
{"bSearchable": false, "bSortable": false, "aTargets": [11]},
{"bSearchable": false, "bSortable": false, "aTargets": [12]}
],
"sAjaxSource": "admin-recommendation-data"
});
});
</script>
<div id='ohrc-ms-div'>
<div class="btn-group">
<a class="btn btn-primary" href="#"><i class="fa fa-download fa-fw"></i> Export</a>
<a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#">
<span class="fa fa-caret-down"></span></a>
<ul class="dropdown-menu">
<li><a href="#" onclick="download_file('excel');"><i class="fa fa-columns fa-fw"></i> Excel</a></li>
<li><a href="#" onclick="download_file('word');"><i class="fa fa-file-text-o fa-fw"></i> Word</a></li>
</ul>
</div>
</div>
<div id="dynamic">
<table class="display table table-bordered" id="recommendation" width="100%">
<thead>
<tr>
<th >nid</th>
<th >Title</th>
<th style="width:100px">Actions</th>
<th >Recommendation</th>
<th >Thematic area</th>
<th >Mechanism and year</th>
<th >Next State Report deadline</th>
<th >MDA</th>
<th >Indicators</th>
<th >Baseline</th>
<th >Target</th>
<th >Means of verification</th>
<th >Status of implementation</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th ></th>
<th ></th>
<th ></th>
<th ></th>
<th ></th>
<th ></th>
<th ></th>
<th ></th>
<th ></th>
<th ></th>
<th ></th>
<th ></th>
<th ></th>
</tr>
</tfoot>
</table>
</div>
| gpl-2.0 |
NeXXEnt/WMS-Official | wms30/views/shipping/take/bin.php | 961 | <div class="background"></div>
<div class="modal draggable modal-form" id="take-bin">
<div class="close-modal">
<a class="button negative" href="/shipping/items"><img src="/pics/icons/cross.png">Close</a>
</div>
<h1>Take</h1>
<h2>From: <?= $warehouse->name ?></h2>
<hr>
<?= form_open("/shipping/items/-1/3"); ?>
<div>
<?= form_fieldset('Step 2'); ?>
<?= form_hidden('method', 'bin') ?>
<?= dump_debug($bin) ?>
<?= form_radio('bin_id', '0') ?> <?= form_input('binAddress', set_value('binAddress'), 'maxlength="15"');?><br>
<?php foreach(Bins::get_infinite_bins($warehouse->warehouse_id) as $bin):?>
<?= form_radio('bin_id', $bin->bin_id); ?><?= $bin->binAddress; ?><br>
<?php endforeach; ?>
<?= form_fieldset_close(); ?>
</div>
<div>
<input type="reset" class="button negative" value="Reset">
<input type="submit" class="button positive" value="Submit">
</div>
<?= form_close(); ?>
</div> | gpl-2.0 |
rtdean93/engagepeeps | accounts/plugins/feed_reader/feed_reader_controller.php | 627 | <?php
/**
* Feed Reader parent controller for all Feed Reader child controllers to inherit from
*
* @package blesta
* @subpackage blesta.plugins.feed_reader
* @copyright Copyright (c) 2010, Phillips Data, Inc.
* @license http://www.blesta.com/license/ The Blesta License Agreement
* @link http://www.blesta.com/ Blesta
*/
class FeedReaderController extends AppController {
public function preAction() {
parent::preAction();
// Override default view directory
$this->view->view = "default";
$this->structure->view = "default";
//$this->view->setDefaultViewPath("FeedReader");
}
}
?> | gpl-2.0 |
GeneSurvey/TcgaGSData | src/org/mda/bcb/tcgagsdata/neighbors/FN_RNASeq.java | 995 | /*
TcgaGSData Copyright 2014, 2015, 2016 University of Texas MD Anderson Cancer Center
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/>.
*/
package org.mda.bcb.tcgagsdata.neighbors;
/**
*
* @author linux
*/
public class FN_RNASeq extends FindRNASeqNeighbors_Mixin
{
public FN_RNASeq(String theZipFile)
{
super("data/rnaseqMap.tsv", theZipFile);
if (false==theZipFile.equals(M_PATH))
{
M_PATH = theZipFile;
}
}
}
| gpl-2.0 |
jyhong836/CellularAutomata3D | src/com/cellular3d/CA3DClientConfigureJDialog.java | 2547 | package com.cellular3d;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.Window;
import javax.swing.JDialog;
public class CA3DClientConfigureJDialog extends JDialog {
public CA3DClientConfigureJDialog() {
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Frame owner) {
super(owner);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Dialog owner) {
super(owner);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Window owner) {
super(owner);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Frame owner, boolean modal) {
super(owner, modal);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Frame owner, String title) {
super(owner, title);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Dialog owner, boolean modal) {
super(owner, modal);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Dialog owner, String title) {
super(owner, title);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Window owner, ModalityType modalityType) {
super(owner, modalityType);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Window owner, String title) {
super(owner, title);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Frame owner, String title, boolean modal) {
super(owner, title, modal);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Dialog owner, String title, boolean modal) {
super(owner, title, modal);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Window owner, String title,
ModalityType modalityType) {
super(owner, title, modalityType);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Frame owner, String title, boolean modal,
GraphicsConfiguration gc) {
super(owner, title, modal, gc);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Dialog owner, String title,
boolean modal, GraphicsConfiguration gc) {
super(owner, title, modal, gc);
// TODO Auto-generated constructor stub
}
public CA3DClientConfigureJDialog(Window owner, String title,
ModalityType modalityType, GraphicsConfiguration gc) {
super(owner, title, modalityType, gc);
// TODO Auto-generated constructor stub
}
}
| gpl-2.0 |
educatorplugin/ibeducator | includes/functions.php | 21580 | <?php
/**
* Get the plugin's settings.
*
* @return array
*/
function ib_edu_get_settings() {
return get_option( 'ib_educator_settings', array() );
}
/**
* Get the plugin's option.
*
* @param string $option_key
* @param string $option_section
* @return mixed
*/
function ib_edu_get_option( $option_key, $option_section ) {
$options = null;
switch ( $option_section ) {
case 'settings':
$options = get_option( 'ib_educator_settings' );
break;
case 'learning':
$options = get_option( 'ib_educator_learning' );
break;
case 'taxes':
$options = get_option( 'ib_educator_taxes' );
break;
case 'email':
$options = get_option( 'ib_educator_email' );
break;
case 'memberships':
$options = get_option( 'ib_educator_memberships' );
break;
}
if ( is_array( $options ) && isset( $options[ $option_key ] ) ) {
return $options[ $option_key ];
}
return null;
}
/**
* Get breadcrumbs HTML.
*
* @param string $sep
* @return string
*/
function ib_edu_breadcrumbs( $sep = ' » ' ) {
$breadcrumbs = array();
$is_lesson = is_singular( 'ib_educator_lesson' );
$is_course = is_singular( 'ib_educator_course' );
if ( $is_course || $is_lesson ) {
$student_courses_page_id = ib_edu_page_id( 'student_courses' );
if ( $student_courses_page_id ) {
$page = get_post( $student_courses_page_id );
if ( $page ) {
$breadcrumbs[] = '<a href="' . get_permalink( $page->ID ) . '">' . esc_html( $page->post_title ) . '</a>';
}
}
}
if ( $is_lesson ) {
$course_id = ib_edu_get_course_id( get_the_ID() );
if ( $course_id ) {
$course = get_post( $course_id );
if ( $course ) {
$breadcrumbs[] = '<a href="' . get_permalink( $course->ID ) . '">' . esc_html( $course->post_title ) . '</a>';
}
}
}
$breadcrumbs[] = '<span>' . get_the_title() . '</span>';
echo implode( $sep, $breadcrumbs );
}
/**
* Get educator API url (can be used to process payment notifications from payment gateways).
*
* @param string $request
* @return string
*/
function ib_edu_request_url( $request ) {
$scheme = parse_url( get_option( 'home' ), PHP_URL_SCHEME );
return esc_url_raw( add_query_arg( array( 'edu-request' => $request ), home_url( '/', $scheme ) ) );
}
/**
* Get price of a course.
*
* @param int $course_id
* @return float
*/
function ib_edu_get_course_price( $course_id ) {
return (float) get_post_meta( $course_id, '_ibedu_price', true );
}
/**
* Get the list of available currencies.
*
* @return array
*/
function ib_edu_get_currencies() {
return apply_filters( 'ib_educator_currencies', array(
'AUD' => __( 'Australian Dollars', 'ibeducator' ),
'AZN' => __( 'Azerbaijani Manat', 'ibeducator' ),
'BRL' => __( 'Brazilian Real', 'ibeducator' ),
'CAD' => __( 'Canadian Dollars', 'ibeducator' ),
'CNY' => __( 'Chinese Yuan', 'ibeducator' ),
'CZK' => __( 'Czech Koruna', 'ibeducator' ),
'DKK' => __( 'Danish Krone', 'ibeducator' ),
'EUR' => __( 'Euros', 'ibeducator' ),
'HKD' => __( 'Hong Kong Dollar', 'ibeducator' ),
'HUF' => __( 'Hungarian Forint', 'ibeducator' ),
'INR' => __( 'Indian Rupee', 'ibeducator' ),
'IRR' => __( 'Iranian Rial', 'ibeducator' ),
'ILS' => __( 'Israeli Shekel', 'ibeducator' ),
'JPY' => __( 'Japanese Yen', 'ibeducator' ),
'MYR' => __( 'Malaysian Ringgits', 'ibeducator' ),
'MXN' => __( 'Mexican Peso', 'ibeducator' ),
'NZD' => __( 'New Zealand Dollar', 'ibeducator' ),
'NOK' => __( 'Norwegian Krone', 'ibeducator' ),
'PHP' => __( 'Philippine Pesos', 'ibeducator' ),
'PLN' => __( 'Polish Zloty', 'ibeducator' ),
'GBP' => __( 'Pounds Sterling', 'ibeducator' ),
'RUB' => __( 'Russian Rubles', 'ibeducator' ),
'SGD' => __( 'Singapore Dollar', 'ibeducator' ),
'SEK' => __( 'Swedish Krona', 'ibeducator' ),
'KRW' => __( 'South Korean Won', 'ibeducator' ),
'CHF' => __( 'Swiss Franc', 'ibeducator' ),
'TWD' => __( 'Taiwan New Dollars', 'ibeducator' ),
'THB' => __( 'Thai Baht', 'ibeducator' ),
'TRY' => __( 'Turkish Lira', 'ibeducator' ),
'USD' => __( 'US Dollars', 'ibeducator' ),
'UAH' => __( 'Ukrainian Hryvnia', 'ibeducator' ),
) );
}
/**
* Get current currency.
*
* @return string
*/
function ib_edu_get_currency() {
$settings = ib_edu_get_settings();
if ( isset( $settings['currency'] ) ) {
$currency = $settings['currency'];
} else {
$currency = 'USD';
}
return apply_filters( 'ib_educator_currency', $currency );
}
/**
* Get currency symbol.
*
* @param string $currency
* @return string
*/
function ib_edu_get_currency_symbol( $currency ) {
switch ( $currency ) {
case 'USD':
case 'AUD':
case 'CAD':
case 'HKD':
case 'MXN':
case 'NZD':
case 'SGD':
$cs = "$";
break;
case 'BRL': $cs = "R$"; break;
case 'CNY': $cs = "¥"; break;
case 'CZK': $cs = "Kč"; break;
case 'DKK': $cs = "kr"; break;
case 'EUR': $cs = "€"; break;
case 'HUF': $cs = "Ft"; break;
case 'INR': $cs = "₹"; break;
case 'IRR': $cs = "﷼"; break;
case 'ILS': $cs = "₪"; break;
case 'JPY': $cs = "¥"; break;
case 'MYR': $cs = "RM"; break;
case 'NOK': $cs = "kr"; break;
case 'PHP': $cs = "₱"; break;
case 'PLN': $cs = "zł"; break;
case 'GBP': $cs = "£"; break;
case 'RUB': $cs = "руб."; break;
case 'SEK': $cs = "kr"; break;
case 'CHF': $cs = "CHF"; break;
case 'TWD': $cs = "NT$"; break;
case 'THB': $cs = "฿"; break;
case 'TRY': $cs = "TL"; break;
case 'UAH': $cs = "₴"; break;
default: $cs = $currency;
}
return apply_filters( 'ib_educator_currency_symbol', $cs, $currency );
}
/**
* Format course price.
*
* @param float $price
* @return string
*/
function ib_edu_format_course_price( $price ) {
return ib_edu_format_price( $price );
}
/**
* Format price.
*
* @param float $price
* @return string
*/
function ib_edu_format_price( $price, $apply_filters = true, $symbol = true ) {
$settings = ib_edu_get_settings();
$currency = ib_edu_get_currency();
$decimal_point = ! empty( $settings['decimal_point'] ) ? esc_html( $settings['decimal_point'] ) : '.';
$thousands_sep = ! empty( $settings['thousands_sep'] ) ? esc_html( $settings['thousands_sep'] ) : ',';
$formatted = number_format( $price, 2, $decimal_point, $thousands_sep );
$formatted = ib_edu_strip_zeroes( $formatted, $decimal_point );
if ( $symbol ) {
$currency_symbol = ib_edu_get_currency_symbol( $currency );
} else {
$currency_symbol = preg_replace( '/[^a-z]+/i', '', $currency );
}
if ( isset( $settings['currency_position'] ) && 'after' == $settings['currency_position'] ) {
$formatted = "$formatted $currency_symbol";
} else {
$formatted = "$currency_symbol $formatted";
}
if ( $apply_filters ) {
return apply_filters( 'ib_educator_format_price', $formatted, $currency, $price );
}
return $formatted;
}
/**
* Remove trailing zeroes from a number.
*
* @param mixed $number
* @param string $decimal_point
* @return string
*/
function ib_edu_strip_zeroes( $number, $decimal_point ) {
return preg_replace( '/' . preg_quote( $decimal_point, '/' ) . '0+$/', '', $number );
}
/**
* Format grade.
*
* @param int|float $grade
* @return string
*/
function ib_edu_format_grade( $grade ) {
$formatted = (float) round( $grade, 2 );
return apply_filters( 'ib_educator_format_grade', $formatted . '%', $grade );
}
/**
* Get permalink endpoint URL.
*
* @param string $endpoint
* @param string $value
* @param string $url
* @return string
*/
function ib_edu_get_endpoint_url( $endpoint, $value, $url ) {
if ( get_option( 'permalink_structure' ) ) {
// Pretty permalinks.
$url = trailingslashit( $url ) . $endpoint . '/' . $value;
} else {
// Basic permalinks.
$url = add_query_arg( $endpoint, $value, $url );
}
return $url;
}
/**
* Get educator page id.
*
* @param string $page_name
* @return int
*/
function ib_edu_page_id( $page_name ) {
$settings = get_option( 'ib_educator_settings', array() );
$page_name .= '_page';
if ( isset( $settings[ $page_name ] ) && is_numeric( $settings[ $page_name ] ) ) {
return $settings[ $page_name ];
}
return 0;
}
/**
* Get course access status message for a student.
*
* @param string $access_status
* @return string
*/
function ib_edu_get_access_status_message( $access_status ) {
$message = '';
switch ( $access_status ) {
case 'pending_entry':
$message = '<p>' . __( 'Your registration is pending.', 'ibeducator' ) . '</p>';
break;
case 'pending_payment':
$message = '<p>' . __( 'The payment for this course is pending.', 'ibeducator' ) . '</p>';
break;
case 'inprogress':
$message = '<p>' . __( 'You are registered for this course.', 'ibeducator' ) . '</p>';
break;
}
return $message;
}
/**
* Get the course ID for a lesson.
*
* @param int $lesson_id
* @return int
*/
function ib_edu_get_course_id( $lesson_id = null ) {
// Is this function called inside the loop?
if ( ! $lesson_id ) {
$lesson_id = get_the_ID();
}
$course_id = get_post_meta( $lesson_id, '_ibedu_course', true );
return is_numeric( $course_id ) ? $course_id : 0;
}
/**
* Check if the current user can view the lesson.
*
* @param int $lesson_id
* @return bool
*/
function ib_edu_student_can_study( $lesson_id ) {
$lesson_access = ib_edu_lesson_access( $lesson_id );
$user_id = get_current_user_id();
$access = false;
if ( 'public' == $lesson_access ) {
$access = true;
} elseif ( $user_id ) {
if ( 'logged_in' == $lesson_access ) {
$access = true;
} else {
$course_id = ib_edu_get_course_id( $lesson_id );
if ( $course_id ) {
$access_status = IB_Educator::get_instance()->get_access_status( $course_id, $user_id );
if ( in_array( $access_status, array( 'inprogress', 'course_complete' ) ) ) {
$access = true;
}
}
}
}
return $access;
}
/**
* Pass the message from the back-end to a template.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
function ib_edu_message( $key, $value = null ) {
static $messages = array();
if ( is_null( $value ) ) {
return isset( $messages[ $key ] ) ? $messages[ $key ] : null;
}
$messages[ $key ] = $value;
}
/**
* Get available course difficulty levels.
*
* @since 1.0.0
* @return array
*/
function ib_edu_get_difficulty_levels() {
return array(
'beginner' => __( 'Beginner', 'ibeducator' ),
'intermediate' => __( 'Intermediate', 'ibeducator' ),
'advanced' => __( 'Advanced', 'ibeducator' ),
);
}
/**
* Get course difficulty.
*
* @since 1.0.0
* @param int $course_id
* @return null|array
*/
function ib_edu_get_difficulty( $course_id ) {
$difficulty = get_post_meta( $course_id, '_ib_educator_difficulty', true );
if ( $difficulty ) {
$levels = ib_edu_get_difficulty_levels();
return array(
'key' => $difficulty,
'label' => ( isset( $levels[ $difficulty ] ) ) ? $levels[ $difficulty ] : '',
);
}
return null;
}
/**
* Get database table names.
*
* @since 1.0.0
* @param string $key
* @return string
*/
function ib_edu_table_names() {
global $wpdb;
$prefix = $wpdb->prefix . 'ibeducator_';
return array(
'payments' => $prefix . 'payments',
'entries' => $prefix . 'entries',
'questions' => $prefix . 'questions',
'choices' => $prefix . 'choices',
'answers' => $prefix . 'answers',
'grades' => $prefix . 'grades',
'members' => $prefix . 'members',
'tax_rates' => $prefix . 'tax_rates',
'payment_lines' => $prefix . 'payment_lines',
);
}
/**
* Can the current user edit a given lesson?
*
* @param int $lesson_id
* @return bool
*/
function ib_edu_user_can_edit_lesson( $lesson_id ) {
if ( current_user_can( 'manage_educator' ) ) return true;
$course_id = ib_edu_get_course_id( $lesson_id );
if ( $course_id ) {
$api = IB_Educator::get_instance();
return in_array( $course_id, $api->get_lecturer_courses( get_current_user_id() ) );
}
return false;
}
/**
* Send email notification.
*
* @param string $to
* @param string $template
* @param array $subject_vars
* @param array $template_vars
*/
function ib_edu_send_notification( $to, $template, $subject_vars, $template_vars ) {
// Set default template vars.
$template_vars['login_link'] = apply_filters( 'ib_educator_login_url', wp_login_url() );
// Send email.
$email = new Edr_EmailAgent();
$email->set_template( $template );
$email->parse_subject( $subject_vars );
$email->parse_template( $template_vars );
$email->add_recipient( $to );
$email->send();
}
/**
* Check if the lesson has a quiz attached.
*
* @param int $lesson_id
* @return bool
*/
function ib_edu_has_quiz( $lesson_id ) {
return get_post_meta( $lesson_id, '_ibedu_quiz', true ) ? true : false;
}
/**
* Get HTML for the course price widget.
*
* @param int $course_id
* @param int $user_id
* @param string $before
* @param string $after
* @return string
*/
function ib_edu_get_price_widget( $course_id, $user_id, $before = '<div class="ib-edu-course-price">', $after = '</div>' ) {
// Registration allowed?
if ( 'closed' == ib_edu_registration( $course_id ) ) {
return '';
}
// Check membership.
$membership_access = Edr_Memberships::get_instance()->membership_can_access( $course_id, $user_id );
/**
* Filter the course price widget.
*
* @since 1.3.2
*
* @param bool $membership_access Whether the user's current membership allows him/her to take the course.
*/
$output = apply_filters( 'ib_educator_course_price_widget', null, $membership_access, $course_id, $user_id );
if ( null !== $output ) {
return $output;
}
// Generate the widget.
$output = $before;
if ( $membership_access ) {
$register_url = ib_edu_get_endpoint_url( 'edu-action', 'join', get_permalink( $course_id ) );
$output .= '<form action="' . esc_url( $register_url ) . '" method="post">';
$output .= '<input type="hidden" name="_wpnonce" value="' . wp_create_nonce( 'ib_educator_join' ) . '">';
$output .= '<input type="submit" class="ib-edu-button" value="' . __( 'Join', 'ibeducator' ) . '">';
$output .= '</form>';
} else {
$price = ib_edu_get_course_price( $course_id );
$price = ( 0 == $price ) ? __( 'Free', 'ibeducator' ) : ib_edu_format_course_price( $price );
$register_url = ib_edu_get_endpoint_url( 'edu-course', $course_id, get_permalink( ib_edu_page_id( 'payment' ) ) );
$output .= '<span class="price">' . $price . '</span><a href="' . esc_url( $register_url )
. '" class="ib-edu-button">' . __( 'Register', 'ibeducator' ) . '</a>';
}
$output .= $after;
return $output;
}
/**
* Output the default page title based on the page context.
*/
function ib_edu_page_title() {
$title = '';
if ( is_post_type_archive( array( 'ib_educator_course', 'ib_educator_lesson' ) ) ) {
$title = post_type_archive_title( '', false );
} elseif ( is_tax() ) {
$title = single_term_title( '', false );
}
$title = apply_filters( 'ib_educator_page_title', $title );
echo $title;
}
/**
* Get the adjacent lesson.
*
* @param bool $previous
* @return mixed If global post object is not set returns null, if post is not found, returns empty string, else returns WP_Post.
*/
function ib_edu_get_adjacent_lesson( $previous = true ) {
global $wpdb;
if ( ! $lesson = get_post() ) {
return null;
}
$course_id = ib_edu_get_course_id( $lesson->ID );
$cmp = $previous ? '<' : '>';
$order = $previous ? 'DESC' : 'ASC';
$join = "INNER JOIN $wpdb->postmeta pm ON pm.post_id = p.ID";
$where = $wpdb->prepare( "WHERE p.post_type = 'ib_educator_lesson' AND p.post_status = 'publish' AND p.menu_order $cmp %d AND pm.meta_key = '_ibedu_course' AND pm.meta_value = %d", $lesson->menu_order, $course_id );
$sort = "ORDER BY p.menu_order $order";
$query = "SELECT p.ID FROM $wpdb->posts as p $join $where $sort LIMIT 1";
$result = $wpdb->get_var( $query );
if ( null === $result ) {
return '';
}
return get_post( $result );
}
/**
* Get the adjacent lesson's link.
*
* @param string $dir
* @param string $format
* @param string $title
* @return string
*/
function ib_edu_get_adjacent_lesson_link( $dir = 'previous', $format, $title ) {
$previous = ( 'previous' == $dir ) ? true : false;
if ( ! $lesson = ib_edu_get_adjacent_lesson( $previous ) ) {
return '';
}
$url = apply_filters( "ib_educator_{$dir}_lesson_url", get_permalink( $lesson->ID ), get_the_ID() );
$title = str_replace( '%title', esc_html( $lesson->post_title ), $title );
$link = '<a href="' . esc_url( $url ) . '">' . $title . '</a>';
return str_replace( '%link', $link, $format );
}
/**
* Are we on the payment page?
*
* @return bool
*/
function ib_edu_is_payment() {
return is_page( ib_edu_page_id( 'payment' ) );
}
/**
* Find out whether to collect billing data or not.
*
* @param mixed $object
* @return bool
*/
function ib_edu_collect_billing_data( $object ) {
if ( is_numeric( $object ) ) {
$object = get_post( $object );
}
$result = false;
if ( $object ) {
$price = null;
if ( 'ib_edu_membership' == $object->post_type ) {
$price = Edr_Memberships::get_instance()->get_price( $object->ID );
} elseif ( 'ib_educator_course' == $object->post_type ) {
$price = ib_edu_get_course_price( $object->ID );
}
if ( $price && ib_edu_get_option( 'enable', 'taxes' ) ) {
$result = true;
}
}
return $result;
}
/**
* Get the business location.
*
* @param string $part
* @return mixed
*/
function ib_edu_get_location( $part = null ) {
$result = array('', '');
if ( $location = ib_edu_get_option( 'location', 'settings' ) ) {
$delimiter = strpos( $location, ';' );
if ( false === $delimiter ) {
$result[0] = $location;
} else {
$result[0] = substr( $location, 0, $delimiter );
$result[1] = substr( $location, $delimiter + 1 );
}
}
if ( 'country' == $part ) {
return $result[0];
} elseif ( 'state' == $part ) {
return $result[1];
}
return $result;
}
/**
* Get registration status for a given course.
*
* @param int $course_id
* @return string
*/
function ib_edu_registration( $course_id ) {
return get_post_meta( $course_id, '_ib_educator_register', true );
}
/**
* Get lesson's access.
*
* @param int $lesson_id
* @return string
*/
function ib_edu_lesson_access( $lesson_id ) {
return get_post_meta( $lesson_id, '_ib_educator_access', true );
}
/**
* Get a purchase link.
* Currently, supports memberships only.
*
* @param array $atts
* @return string
*/
function ib_edu_purchase_link( $atts ) {
$atts = wp_parse_args( $atts, array(
'object_id' => null,
'type' => null,
'text' => __( 'Purchase', 'ib-educator' ),
'class' => array(),
) );
// Add default class.
array_push( $atts['class'], 'edu-purchase-link' );
$html = apply_filters( 'ib_edu_pre_purchase_link', null, $atts );
if ( ! is_null( $html ) ) {
return $html;
}
if ( 'membership' == $atts['type'] ) {
$html = sprintf(
'<a href="%s" class="%s">%s</a>',
esc_url( ib_edu_get_endpoint_url( 'edu-membership', $atts['object_id'], get_permalink( ib_edu_page_id( 'payment' ) ) ) ),
esc_attr( implode( ' ', $atts['class'] ) ),
$atts['text']
);
}
return $html;
}
/**
* Get a payment.
*
* @param int|object|null $data
* @return IB_Educator_Payment
*/
function edr_get_payment( $data = null ) {
return new IB_Educator_Payment( $data );
}
/**
* Get the available payment statuses.
*
* @return array
*/
function edr_get_payment_statuses() {
return array(
'pending' => __( 'Pending', 'ibeducator' ),
'complete' => __( 'Complete', 'ibeducator' ),
'failed' => __( 'Failed', 'ibeducator' ),
'cancelled' => __( 'Cancelled', 'ibeducator' ),
);
}
/**
* Get the available payment types.
*
* @return array
*/
function edr_get_payment_types() {
return array(
'course' => __( 'Course', 'ibeducator' ),
'membership' => __( 'Membership', 'ibeducator' ),
);
}
/**
* Get an entry.
*
* @param int|object|null $data
* @return IB_Educator_Entry
*/
function edr_get_entry( $data = null ) {
return new IB_Educator_Entry( $data );
}
/**
* Get the available entry statuses.
*
* @return array
*/
function edr_get_entry_statuses() {
return array(
'pending' => __( 'Pending', 'ibeducator' ),
'inprogress' => __( 'In progress', 'ibeducator' ),
'complete' => __( 'Complete', 'ibeducator' ),
'cancelled' => __( 'Cancelled', 'ibeducator' ),
'paused' => __( 'Paused', 'ibeducator' ),
);
}
/**
* Get the available entry origins.
*
* @return array
*/
function edr_get_entry_origins() {
return apply_filters( 'ib_educator_entry_origins', array(
'payment' => __( 'Payment', 'ibeducator' ),
'membership' => __( 'Membership', 'ibeducator' ),
) );
}
/**
* Get a question.
*
* @param int|object|null $data
* @return IB_Educator_Question
*/
function edr_get_question( $data = null ) {
return new IB_Educator_Question( $data );
}
/**
* Trigger deprecated function error.
*
* @param string $function
* @param string $version
* @param string $replacement
*/
function _ib_edu_deprecated_function( $function, $version, $replacement = null ) {
if ( WP_DEBUG && current_user_can( 'manage_options' ) ) {
if ( ! is_null( $replacement ) ) {
trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since Educator version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
} else {
trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since Educator version %2$s with no alternative available.'), $function, $version ) );
}
}
}
| gpl-2.0 |
xpander54/wp-drz | wp-content/themes/everything/drone/tpl/theme-options.php | 527 | <?php
?>
<div class="wrap">
<h2><?php echo get_admin_page_title(); ?></h2>
<?php settings_errors('general'); ?>
<form method="post" action="<?php echo self::WP_THEME_OPTIONS_URI; ?>">
<?php settings_fields($this->theme->id); ?>
<div class="drone-theme-options">
<?php echo $group->html()->html(); ?>
<p class="submit">
<input id="submit" name="submit" type="submit" value="<?php _e('Save Changes', $this->domain); ?>" class="button-primary" disabled />
</p>
</div>
</form>
</div> | gpl-2.0 |
tdalman/crossfire | utils/cre/CREPrePostPanel.cpp | 14561 | #include "CREPrePostPanel.h"
#include "CRERulePanel.h"
#include <QtGui>
#include "QuestConditionScript.h"
#include "QuestManager.h"
#include "Quest.h"
CRESubItemList::CRESubItemList(QWidget* parent) : CRESubItemWidget(parent)
{
QGridLayout* layout = new QGridLayout(this);
mySubItems = new QListWidget(this);
connect(mySubItems, SIGNAL(currentRowChanged(int)), this, SLOT(currentSubItemChanged(int)));
layout->addWidget(mySubItems, 0, 0, 1, 2);
QPushButton* addSubItem = new QPushButton(tr("add"), this);
connect(addSubItem, SIGNAL(clicked(bool)), this, SLOT(onAddSubItem(bool)));
layout->addWidget(addSubItem, 1, 0);
QPushButton* delSubItem = new QPushButton(tr("delete"), this);
connect(delSubItem, SIGNAL(clicked(bool)), this, SLOT(onDeleteSubItem(bool)));
layout->addWidget(delSubItem, 1, 1);
myItemEdit = new QLineEdit(this);
connect(myItemEdit, SIGNAL(textChanged(const QString&)), this, SLOT(subItemChanged(const QString&)));
layout->addWidget(myItemEdit, 2, 0, 1, 2);
}
void CRESubItemList::setData(const QStringList& data)
{
myData = data;
myData.takeFirst();
mySubItems->clear();
mySubItems->addItems(myData);
myItemEdit->clear();
}
void CRESubItemList::currentSubItemChanged(int)
{
if (mySubItems->currentItem())
myItemEdit->setText(mySubItems->currentItem()->text());
}
void CRESubItemList::onAddSubItem(bool)
{
myData.append("(item)");
mySubItems->addItem("(item)");
mySubItems->setCurrentRow(myData.size() - 1);
emit dataModified(myData);
}
void CRESubItemList::onDeleteSubItem(bool)
{
if (mySubItems->currentRow() < 0)
return;
myData.removeAt(mySubItems->currentRow());
delete mySubItems->takeItem(mySubItems->currentRow());
mySubItems->setCurrentRow(0);
emit dataModified(myData);
}
void CRESubItemList::subItemChanged(const QString& text)
{
if (mySubItems->currentRow() < 0)
return;
myData[mySubItems->currentRow()] = text;
mySubItems->currentItem()->setText(text);
emit dataModified(myData);
}
CRESubItemConnection::CRESubItemConnection(QWidget* parent) : CRESubItemWidget(parent)
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(new QLabel(tr("Connection number:"), this));
myEdit = new QLineEdit(this);
myEdit->setValidator(new QIntValidator(1, 65000, myEdit));
connect(myEdit, SIGNAL(textChanged(const QString&)), this, SLOT(editChanged(const QString&)));
layout->addWidget(myEdit);
myWarning = new QLabel(this);
myWarning->setVisible(false);
layout->addWidget(myWarning);
layout->addStretch();
}
void CRESubItemConnection::setData(const QStringList& data)
{
if (data.size() < 2)
{
showWarning(tr("Not enough arguments"));
return;
}
bool ok = false;
int value = data[1].toInt(&ok);
if (!ok || value <= 0 || value > 65000)
{
showWarning(tr("Invalid number %1, must be a number between 1 and 65000").arg(data[1]));
value = 1;
}
myWarning->setVisible(false);
myEdit->setText(QString::number(value));
}
void CRESubItemConnection::showWarning(const QString& warning)
{
myWarning->setText(warning);
myWarning->setVisible(true);
}
void CRESubItemConnection::editChanged(const QString& text)
{
bool ok = false;
int value = text.toInt(&ok);
if (!ok || value <= 0 || value > 65000)
{
showWarning(tr("Invalid number %1, must be a number between 1 and 65000").arg(text));
return;
}
myWarning->setVisible(false);
emit dataModified(QStringList(text));
}
CRESubItemQuest::CRESubItemQuest(bool isPre, const QuestManager* quests, QWidget* parent) : CRESubItemWidget(parent)
{
myQuests = quests;
myIsPre = isPre;
myInit = true;
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(new QLabel(tr("Quest:"), this));
myQuestList = new QComboBox(this);
layout->addWidget(myQuestList);
if (isPre)
{
myAtStep = new QRadioButton(tr("at step"), this);
layout->addWidget(myAtStep);
myFromStep = new QRadioButton(tr("from step"), this);
layout->addWidget(myFromStep);
myStepRange = new QRadioButton(tr("from step to step"), this);
layout->addWidget(myStepRange);
connect(myAtStep, SIGNAL(toggled(bool)), this, SLOT(checkToggled(bool)));
connect(myFromStep, SIGNAL(toggled(bool)), this, SLOT(checkToggled(bool)));
connect(myStepRange, SIGNAL(toggled(bool)), this, SLOT(checkToggled(bool)));
}
else
{
layout->addWidget(new QLabel(tr("new step:"), this));
myAtStep = NULL;
myFromStep = NULL;
}
myFirstStep = new QComboBox(this);
layout->addWidget(myFirstStep);
if (isPre)
{
mySecondStep = new QComboBox(this);
layout->addWidget(mySecondStep);
}
else
mySecondStep = NULL;
layout->addStretch();
connect(myQuestList, SIGNAL(currentIndexChanged(int)), this, SLOT(selectedQuestChanged(int)));
foreach(const Quest* quest, quests->quests())
{
myQuestList->addItem(quest->title() + " [" + quest->code() + "]", quest->code());
}
connect(myFirstStep, SIGNAL(currentIndexChanged(int)), this, SLOT(selectedStepChanged(int)));
if (mySecondStep)
connect(mySecondStep, SIGNAL(currentIndexChanged(int)), this, SLOT(selectedStepChanged(int)));
myInit = false;
}
void CRESubItemQuest::setData(const QStringList& data)
{
if (data.size() < 3)
return;
int index = myQuestList->findData(data[1], Qt::UserRole);
if (index == -1)
{
return;
}
myInit = true;
myQuestList->setCurrentIndex(index);
if (!myIsPre)
{
myFirstStep->setCurrentIndex(myFirstStep->findData(data[2], Qt::UserRole));
myInit = false;
return;
}
QString steps = data[2];
int idx = steps.indexOf('-');
if (idx == -1)
{
int start = 0;
if (steps.startsWith('='))
{
myAtStep->setChecked(true);
start = 1;
}
else
myFromStep->setChecked(true);
myFirstStep->setCurrentIndex(myFirstStep->findData(steps.mid(start), Qt::UserRole));
}
else
{
myStepRange->setChecked(true);
myFirstStep->setCurrentIndex(myFirstStep->findData(steps.left(idx), Qt::UserRole));
mySecondStep->setCurrentIndex(mySecondStep->findData(steps.mid(idx + 1), Qt::UserRole));
}
myInit = false;
}
void CRESubItemQuest::selectedQuestChanged(int index)
{
myFirstStep->clear();
if (myIsPre)
myFirstStep->addItem("(not started)", "0");
if (mySecondStep)
mySecondStep->clear();
if (index < 0 || index >= myQuests->quests().size())
return;
const Quest* quest = myQuests->quests()[index];
QString desc;
foreach (const QuestStep* step, quest->steps())
{
desc = tr("%1 (%2)").arg(QString::number(step->step()), step->description().left(30));
if (step->isCompletion())
desc += " (end)";
myFirstStep->addItem(desc, QString::number(step->step()));
if (mySecondStep)
mySecondStep->addItem(desc, QString::number(step->step()));
}
}
void CRESubItemQuest::updateData()
{
if (myInit)
return;
QStringList data;
data << myQuestList->itemData(myQuestList->currentIndex(), Qt::UserRole).toString();
if (myIsPre)
{
QString value;
if (myStepRange->isChecked())
{
value = myFirstStep->itemData(myFirstStep->currentIndex(), Qt::UserRole).toString();
value += "-";
value += mySecondStep->itemData(mySecondStep->currentIndex(), Qt::UserRole).toString();
}
else
{
if (myAtStep->isChecked())
value = "=";
value += myFirstStep->itemData(myFirstStep->currentIndex(), Qt::UserRole).toString();
}
data << value;
}
else
{
data << myFirstStep->itemData(myFirstStep->currentIndex(), Qt::UserRole).toString();
}
emit dataModified(data);
}
void CRESubItemQuest::checkToggled(bool checked)
{
if (checked == false)
return;
mySecondStep->setEnabled(myStepRange->isChecked());
updateData();
}
void CRESubItemQuest::selectedStepChanged(int index)
{
if (index == -1)
return;
updateData();
}
CRESubItemToken::CRESubItemToken(bool isPre, QWidget* parent) : CRESubItemWidget(parent)
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(new QLabel(tr("Token:"), this));
myToken = new QLineEdit(this);
layout->addWidget(myToken);
connect(myToken, SIGNAL(textChanged(const QString&)), this, SLOT(tokenChanged(const QString&)));
if (isPre)
{
layout->addWidget(new QLabel(tr("Values the token can be (one per line):"), this));
myValues = new QTextEdit(this);
myValues->setAcceptRichText(false);
layout->addWidget(myValues);
connect(myValues, SIGNAL(textChanged()), this, SLOT(valuesChanged()));
myValue = NULL;
}
else
{
layout->addWidget(new QLabel(tr("Value to set for the token:"), this));
myValue = new QLineEdit(this);
layout->addWidget(myValue);
connect(myValue, SIGNAL(textChanged(const QString&)), this, SLOT(tokenChanged(const QString&)));
myValues = NULL;
}
layout->addStretch();
}
void CRESubItemToken::setData(const QStringList& data)
{
QStringList copy(data);
if (data.size() < 2)
{
myToken->clear();
if (myValues != NULL)
myValues->clear();
if (myValue != NULL)
myValue->clear();
return;
}
copy.removeFirst();
myToken->setText(copy.takeFirst());
if (myValues != NULL)
myValues->setText(copy.join("\n"));
else if (copy.size() > 0)
myValue->setText(copy[0]);
else
myValue->clear();
}
void CRESubItemToken::updateData()
{
QStringList values;
values.append(myToken->text());
if (myValues != NULL)
values.append(myValues->toPlainText().split("\n"));
else
values.append(myValue->text());
emit dataModified(values);
}
void CRESubItemToken::tokenChanged(const QString&)
{
updateData();
}
void CRESubItemToken::valuesChanged()
{
updateData();
}
CREPrePostPanel::CREPrePostPanel(bool isPre, const QList<QuestConditionScript*> scripts, const QuestManager* quests, QWidget* parent) : QWidget(parent)
{
QGridLayout* layout = new QGridLayout(this);
myItems = new QListWidget(this);
connect(myItems, SIGNAL(currentRowChanged(int)), this, SLOT(currentItemChanged(int)));
layout->addWidget(myItems, 0, 0, 3, 2);
QPushButton* addItem = new QPushButton(tr("add"), this);
connect(addItem, SIGNAL(clicked(bool)), this, SLOT(onAddItem(bool)));
layout->addWidget(addItem, 3, 0);
QPushButton* delItem = new QPushButton(tr("delete"), this);
connect(delItem, SIGNAL(clicked(bool)), this, SLOT(onDeleteItem(bool)));
layout->addWidget(delItem, 3, 1);
layout->addWidget(new QLabel(tr("Script:"), this), 0, 2);
myChoices = new QComboBox(this);
connect(myChoices, SIGNAL(currentIndexChanged(int)), this, SLOT(currentChoiceChanged(int)));
mySubItemsStack = new QStackedWidget(this);
for(int script = 0; script < scripts.size(); script++)
{
myChoices->addItem(scripts[script]->name());
myChoices->setItemData(script, scripts[script]->comment(), Qt::ToolTipRole);
mySubWidgets.append(createSubItemWidget(isPre, scripts[script], quests));
mySubItemsStack->addWidget(mySubWidgets.last());
connect(mySubWidgets.last(), SIGNAL(dataModified(const QStringList&)), this, SLOT(subItemChanged(const QStringList&)));
}
layout->addWidget(myChoices, 0, 3);
layout->addWidget(mySubItemsStack, 1, 2, 3, 2);
}
CREPrePostPanel::~CREPrePostPanel()
{
}
QList<QStringList> CREPrePostPanel::getData()
{
return myData;
}
void CREPrePostPanel::setData(const QList<QStringList> data)
{
myItems->clear();
myData = data;
foreach(QStringList list, data)
{
if (list.size() > 0)
myItems->addItem(list[0]);
else
myItems->addItem(tr("(empty)"));
}
}
void CREPrePostPanel::onAddItem(bool)
{
myData.append(QStringList("quest"));
myItems->addItem("quest");
myItems->setCurrentRow(myData.size() - 1);
emit dataModified();
}
void CREPrePostPanel::onDeleteItem(bool)
{
if (myItems->currentRow() < 0 || myItems->currentRow() >= myData.size())
return;
myData.removeAt(myItems->currentRow());
delete myItems->takeItem(myItems->currentRow());
myItems->setCurrentRow(0);
emit dataModified();
}
void CREPrePostPanel::currentItemChanged(int index)
{
if (index < 0 || index >= myData.size())
return;
QStringList data = myData[index];
if (data.size() == 0)
return;
myChoices->setCurrentIndex(myChoices->findText(data[0]));
mySubWidgets[myChoices->currentIndex()]->setData(data);
}
void CREPrePostPanel::currentChoiceChanged(int)
{
if (myItems->currentRow() < 0 || myItems->currentRow() >= myData.size())
return;
QStringList& data = myData[myItems->currentRow()];
if (data.size() == 0)
data.append(myChoices->currentText());
else
data[0] = myChoices->currentText();
myItems->currentItem()->setText(data[0]);
mySubItemsStack->setCurrentIndex(myChoices->currentIndex());
mySubWidgets[myChoices->currentIndex()]->setData(data);
emit dataModified();
}
void CREPrePostPanel::subItemChanged(const QStringList& data)
{
if (myItems->currentRow() < 0 || myItems->currentRow() >= myData.size())
return;
QStringList& item = myData[myItems->currentRow()];
while (item.size() > 1)
item.removeLast();
item.append(data);
emit dataModified();
}
CRESubItemWidget* CREPrePostPanel::createSubItemWidget(bool isPre, const QuestConditionScript* script, const QuestManager* quests)
{
if (!isPre && script->name() == "connection")
return new CRESubItemConnection(this);
if (script->name() == "quest")
return new CRESubItemQuest(isPre, quests, this);
if (script->name() == "token" || script->name() == "settoken" || script->name() == "npctoken" || script->name() == "setnpctoken")
return new CRESubItemToken(isPre, this);
return new CRESubItemList(this);
}
| gpl-2.0 |
studio-montana/custom | core/tools/gallery/load.php | 1649 | <?php
/**
* @package Custom
* @author Sébastien Chandonay www.seb-c.com / Cyril Tissot www.cyriltissot.com
* License: GPL2
* Text Domain: custom
*
* Copyright 2016 Sébastien Chandonay (email : please contact me from my website)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
defined('ABSPATH') or die("Go Away!");
/**
* CONSTANTS
*/
define('GALLERY_TOOL_NAME', 'gallery');
function tool_gallery_get_name($tool_name = ""){
return __("Gallery", CUSTOM_PLUGIN_TEXT_DOMAIN);
}
add_filter("custom_get_tool_name_".GALLERY_TOOL_NAME, "tool_gallery_get_name", 1, 1);
function tool_gallery_get_description($tool_description = ""){
return __("customize wp gallery appearence", CUSTOM_PLUGIN_TEXT_DOMAIN);
}
add_filter("custom_get_tool_description_".GALLERY_TOOL_NAME, "tool_gallery_get_description", 1, 1);
function tool_gallery_activate(){
require_once (CUSTOM_PLUGIN_PATH.CUSTOM_PLUGIN_TOOLS_FOLDER.GALLERY_TOOL_NAME.'/'.GALLERY_TOOL_NAME.'.php');
}
add_action("custom_tool_activate_".GALLERY_TOOL_NAME, "tool_gallery_activate"); | gpl-2.0 |
hassankbrian/LoveItLocal | wp-content/plugins/wc-shortcodes/includes/templates/nav-filtering.php | 1378 | <?php
$args = array(
'orderby' => 'name',
);
$taxonomy = $atts['taxonomy'];
$whitelist = $atts['terms'];
if ( ! empty( $taxonomy ) ) {
$terms = get_terms( $taxonomy, $args );
if ( ! is_wp_error( $terms ) || empty( $terms ) ) {
$links = array();
$links[] = "<a href='#' data-filter='*' title='All Tags' class='wc-shortcodes-term wc-shortcodes-all-tags wc-shortcodes-term-active'>" . __( 'All', 'wordpresscanvas' ) . "</a>";
if ( ! is_array( $whitelist ) || empty( $whitelist ) ) {
foreach ( $terms as $term ) {
$term_link = get_term_link( $term );
$links[] = "<a href='#' data-filter='.wc-shortcodes-filter-{$term->slug}' title='{$term->name} Tag' class='wc-shortcodes-term wc-shortcodes-term-slug-{$term->slug}'>" . $term->name . "</a>";
}
}
else {
foreach ( $terms as $term ) {
if ( in_array( $term->slug, $whitelist ) ) {
$term_link = get_term_link( $term );
$links[] = "<a href='#' data-filter='.wc-shortcodes-filter-{$term->slug}' title='{$term->name} Tag' class='wc-shortcodes-term wc-shortcodes-term-slug-{$term->slug}'>" . $term->name . "</a>";
}
}
}
?>
<?php if ( sizeof( $links ) > 2 ) : ?>
<nav class="wc-shortcodes-filtering wc-shortcodes-nav-<?php echo $taxonomy; ?>">
<?php echo implode( "<span class='tag-divider'>/</span>", $links ); ?>
</nav>
<?php endif; ?>
<?php
}
}
| gpl-2.0 |
mviitanen/marsmod | mcp/temp/src/minecraft/net/minecraft/block/BlockWoodSlab.java | 1875 | package net.minecraft.block;
import java.util.List;
import java.util.Random;
import net.minecraft.block.BlockSlab;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class BlockWoodSlab extends BlockSlab {
public static final String[] field_150005_b = new String[]{"oak", "spruce", "birch", "jungle", "acacia", "big_oak"};
private static final String __OBFID = "CL_00000337";
public BlockWoodSlab(boolean p_i45437_1_) {
super(p_i45437_1_, Material.field_151575_d);
this.func_149647_a(CreativeTabs.field_78030_b);
}
public IIcon func_149691_a(int p_149691_1_, int p_149691_2_) {
return Blocks.field_150344_f.func_149691_a(p_149691_1_, p_149691_2_ & 7);
}
public Item func_149650_a(int p_149650_1_, Random p_149650_2_, int p_149650_3_) {
return Item.func_150898_a(Blocks.field_150376_bx);
}
protected ItemStack func_149644_j(int p_149644_1_) {
return new ItemStack(Item.func_150898_a(Blocks.field_150376_bx), 2, p_149644_1_ & 7);
}
public String func_150002_b(int p_150002_1_) {
if(p_150002_1_ < 0 || p_150002_1_ >= field_150005_b.length) {
p_150002_1_ = 0;
}
return super.func_149739_a() + "." + field_150005_b[p_150002_1_];
}
public void func_149666_a(Item p_149666_1_, CreativeTabs p_149666_2_, List p_149666_3_) {
if(p_149666_1_ != Item.func_150898_a(Blocks.field_150373_bw)) {
for(int var4 = 0; var4 < field_150005_b.length; ++var4) {
p_149666_3_.add(new ItemStack(p_149666_1_, 1, var4));
}
}
}
public void func_149651_a(IIconRegister p_149651_1_) {}
}
| gpl-2.0 |
hydrodog/LiquiZ | LiquiZ/src/org/adastraeducation/liquiz/Audio.java | 759 | package org.adastraeducation.liquiz;
public class Audio implements Displayable {
private String source;
private String type;
public Audio(String source){
this.source = source;
}
public Audio(String source, String type){
this.source = source;
}
//<source src="horse.ogg" type="audio/ogg">
//<source src="horse.mp3" type="audio/mpeg">
public void writeHTML(StringBuilder b){
b.append("<audio controls>");
b.append("<source src=\"" + source + "\"type =\""+ type + "\">");
b.append("</audio>");
}
// to do : how to represent image in JavaScript
public void writeJS(StringBuilder b){
b.append("new Audio(1, \"" + source + "\")");
}
public void writeXML(StringBuilder b) {
b.append("<A correct=\"" + source + "\"> </A>");
}
}
| gpl-2.0 |
BartDM/GreenshotPlugin | Greenshot/Memento/IMemento.cs | 1766 | /*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
*
* 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 1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*/
using System;
using Greenshot.Configuration;
namespace Greenshot.Memento {
/// <summary>
/// Description of IMemento.
/// </summary>
public interface IMemento : IDisposable {
/// <summary>
/// Restores target to the state memorized by this memento.
/// </summary>
/// <returns>
/// A memento of the state before restoring
/// </returns>
IMemento Restore();
/// <summary>
/// Try to merge the current memento with another, preventing loads of items on the stack
/// </summary>
/// <param name="other">The memento to try to merge with</param>
/// <returns></returns>
bool Merge(IMemento other);
/// <summary>
/// Returns the language key for the action which is performed
/// </summary>
LangKey ActionLanguageKey {
get;
}
}
}
| gpl-2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.