text stringlengths 2 1.04M | meta dict |
|---|---|
Persistent<FunctionTemplate> CascadeClassifierWrap::constructor;
void
CascadeClassifierWrap::Init(Handle<Object> target) {
NanScope();
Local<FunctionTemplate> ctor = NanNew<FunctionTemplate>(CascadeClassifierWrap::New);
NanAssignPersistent(constructor, ctor);
ctor->InstanceTemplate()->SetInternalFieldCount(1);
ctor->SetClassName(NanNew("CascadeClassifier"));
// Prototype
//Local<ObjectTemplate> proto = constructor->PrototypeTemplate();
NODE_SET_PROTOTYPE_METHOD(ctor, "detectMultiScale", DetectMultiScale);
target->Set(NanNew("CascadeClassifier"), ctor->GetFunction());
};
NAN_METHOD(CascadeClassifierWrap::New) {
NanScope();
if (args.This()->InternalFieldCount() == 0)
NanThrowTypeError("Cannot instantiate without new");
CascadeClassifierWrap *pt = new CascadeClassifierWrap(*args[0]);
pt->Wrap(args.This());
NanReturnValue( args.This() );
}
CascadeClassifierWrap::CascadeClassifierWrap(v8::Value* fileName){
std::string filename;
filename = std::string(*NanAsciiString(fileName->ToString()));
if (!cc.load(filename.c_str())){
NanThrowTypeError("Error loading file");
}
}
class AsyncDetectMultiScale : public NanAsyncWorker {
public:
AsyncDetectMultiScale(NanCallback *callback, CascadeClassifierWrap *cc, Matrix* im, double scale, int neighbors, int minw, int minh) : NanAsyncWorker(callback), cc(cc), im(im), scale(scale), neighbors(neighbors), minw(minw), minh(minh) {}
~AsyncDetectMultiScale() {}
void Execute () {
try {
std::vector<cv::Rect> objects;
cv::Mat gray;
if(this->im->mat.channels() != 1) {
cvtColor(this->im->mat, gray, CV_BGR2GRAY);
} else {
gray = this->im->mat;
}
equalizeHist( gray, gray);
this->cc->cc.detectMultiScale(gray, objects, this->scale, this->neighbors, 0 | CV_HAAR_SCALE_IMAGE, cv::Size(this->minw, this->minh));
res = objects;
}
catch( cv::Exception& e ){
SetErrorMessage(e.what());
}
}
void HandleOKCallback () {
NanScope();
// this->matrix->Unref();
Handle<Value> argv[2];
v8::Local<v8::Array> arr = NanNew<v8::Array>(this->res.size());
for(unsigned int i = 0; i < this->res.size(); i++ ){
v8::Local<v8::Object> x = NanNew<v8::Object>();
x->Set(NanNew("x"), NanNew<Number>(this->res[i].x));
x->Set(NanNew("y"), NanNew<Number>(this->res[i].y));
x->Set(NanNew("width"), NanNew<Number>(this->res[i].width));
x->Set(NanNew("height"), NanNew<Number>(this->res[i].height));
arr->Set(i, x);
}
argv[0] = NanNull();
argv[1] = arr;
TryCatch try_catch;
callback->Call(2, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
}
private:
CascadeClassifierWrap *cc;
Matrix* im;
double scale;
int neighbors;
int minw;
int minh;
std::vector<cv::Rect> res;
};
NAN_METHOD(CascadeClassifierWrap::DetectMultiScale){
NanScope();
CascadeClassifierWrap *self = ObjectWrap::Unwrap<CascadeClassifierWrap>(args.This());
if (args.Length() < 2){
NanThrowTypeError("detectMultiScale takes at least 2 args");
}
Matrix *im = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
REQ_FUN_ARG(1, cb);
double scale = 1.1;
if (args.Length() > 2 && args[2]->IsNumber())
scale = args[2]->NumberValue();
int neighbors = 2;
if (args.Length() > 3 && args[3]->IsInt32())
neighbors = args[3]->IntegerValue();
int minw = 30;
int minh = 30;
if (args.Length() > 5 && args[4]->IsInt32() && args[5]->IsInt32()){
minw = args[4]->IntegerValue();
minh = args[5]->IntegerValue();
}
NanCallback *callback = new NanCallback(cb.As<Function>());
NanAsyncQueueWorker( new AsyncDetectMultiScale(callback, self, im, scale, neighbors, minw, minh) );
NanReturnUndefined();
}
| {
"content_hash": "d96fbfd4a933fa01a1bb94c146b480f3",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 242,
"avg_line_length": 26.67361111111111,
"alnum_prop": 0.6448841447539703,
"repo_name": "shobhitchittora/ImageProcAPI",
"id": "3950c0436161f6eaacae2e9010b1cd6a22fddea4",
"size": "3935",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/opencv/src/CascadeClassifierWrap.cc",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "218"
},
{
"name": "HTML",
"bytes": "2429"
},
{
"name": "JavaScript",
"bytes": "12559"
}
],
"symlink_target": ""
} |
SRAM cells
----------
The SKY130 process currently supports only single-port SRAM’s, which are contained in hard-IP libraries. These cells are constructed with smaller design rules (Table 9), along with OPC (optical proximity correction) techniques, to achieve small memory cells. Use of the memory cells or their devices outside the specific IP is prohibited. The schematic for the SRAM is shown below in Figure 10. This cell is available in the S8 IP offerings and is monitored at e-test through the use of “pinned out” devices within the specific arrays.
|figure-10-schematics-of-the-single-port-sram|
**Figure 10. Schematics of the Single Port SRAM.**
A Dual-Port SRAM is currently being designed using a similar approach. Compilers for the SP and DP SRAM’s will be available end-2019.
Operating Voltages where SPICE models are valid
- :math:`V_{DS} = 0` to 1.8V
- :math:`V_{GS} = 0` to 1.8V
- :math:`V_{BS} = 0` to -1.8V
Details
~~~~~~~
N-pass FET (SRAM)
^^^^^^^^^^^^^^^^^
Spice Model Information
~~~~~~~~~~~~~~~~~~~~~~~
- Cell Name: :cell:`sky130_fd_pr__nfet_01v8`
- Model Name (SRAM): :model:`sky130_fd_pr__special_nfet_pass`
.. include:: special_sram-table0.rst
N-latch FET (SRAM)
^^^^^^^^^^^^^^^^^^
Spice Model Information
~~~~~~~~~~~~~~~~~~~~~~~
- Cell Name: :cell:`sky130_fd_pr__nfet_01v8`
- Model Name (SRAM): :model:`sky130_fd_pr__special_nfet_latch`
.. include:: special_sram-table1.rst
P-latch FET (SRAM)
^^^^^^^^^^^^^^^^^^
Spice Model Information
~~~~~~~~~~~~~~~~~~~~~~~
- Cell Name: :cell:`sky130_fd_pr__pfet_01v8`
- Model Name (SRAM): :model:`sky130_fd_pr__special_pfet_pass`
.. include:: special_sram-table2.rst
.. |figure-10-schematics-of-the-single-port-sram| image:: figure-10-schematics-of-the-single-port-sram.svg
| {
"content_hash": "40059de4c094620750e21c5c1878176b",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 535,
"avg_line_length": 27.765625,
"alnum_prop": 0.6713562183455262,
"repo_name": "google/skywater-pdk",
"id": "b2790cf5314c9c2b2e5924be8bbb1dafe88a2ecb",
"size": "1785",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/rules/device-details/special_sram/index.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "4844"
},
{
"name": "Python",
"bytes": "78457"
}
],
"symlink_target": ""
} |
import functools
import netaddr
from neutron_lib.api import validators
from neutron_lib import constants
from neutron_lib import exceptions as n_exc
from oslo_config import cfg
from oslo_db import exception as db_exc
from oslo_log import helpers as log_helpers
from oslo_log import log as logging
from oslo_utils import excutils
import six
import sqlalchemy as sa
from sqlalchemy import exc as sql_exc
from sqlalchemy import orm
from neutron._i18n import _, _LI
from neutron.api.v2 import attributes
from neutron.common import _deprecate
from neutron.common import constants as n_const
from neutron.common import utils as n_utils
from neutron.db import api as db_api
from neutron.db.availability_zone import router as router_az_db
from neutron.db import common_db_mixin
from neutron.db import l3_dvr_db
from neutron.db.l3_dvr_db import is_distributed_router
from neutron.db.models import agent as agent_model
from neutron.db.models import l3 as l3_models
from neutron.db.models import l3_attrs
from neutron.db.models import l3ha as l3ha_model
from neutron.extensions import l3
from neutron.extensions import l3_ext_ha_mode as l3_ha
from neutron.extensions import portbindings
from neutron.extensions import providernet
from neutron.plugins.common import utils as p_utils
_deprecate._moved_global('L3HARouterAgentPortBinding', new_module=l3ha_model)
_deprecate._moved_global('L3HARouterNetwork', new_module=l3ha_model)
_deprecate._moved_global('L3HARouterVRIdAllocation', new_module=l3ha_model)
VR_ID_RANGE = set(range(1, 255))
MAX_ALLOCATION_TRIES = 10
UNLIMITED_AGENTS_PER_ROUTER = 0
LOG = logging.getLogger(__name__)
L3_HA_OPTS = [
cfg.BoolOpt('l3_ha',
default=False,
help=_('Enable HA mode for virtual routers.')),
cfg.IntOpt('max_l3_agents_per_router',
default=3,
help=_("Maximum number of L3 agents which a HA router will be "
"scheduled on. If it is set to 0 then the router will "
"be scheduled on every agent.")),
cfg.IntOpt('min_l3_agents_per_router',
default=n_const.DEFAULT_MINIMUM_AGENTS_FOR_HA,
help=_("DEPRECATED: Minimum number of L3 agents that have to "
"be available in order to allow a new HA router to be "
"scheduled. This option is deprecated in the Newton "
"release and will be removed for the Ocata release "
"where the scheduling of new HA routers will always "
"be allowed."),
deprecated_for_removal=True),
cfg.StrOpt('l3_ha_net_cidr',
default=n_const.L3_HA_NET_CIDR,
help=_('Subnet used for the l3 HA admin network.')),
cfg.StrOpt('l3_ha_network_type', default='',
help=_("The network type to use when creating the HA network "
"for an HA router. By default or if empty, the first "
"'tenant_network_types' is used. This is helpful when "
"the VRRP traffic should use a specific network which "
"is not the default one.")),
cfg.StrOpt('l3_ha_network_physical_name', default='',
help=_("The physical network name with which the HA network "
"can be created."))
]
cfg.CONF.register_opts(L3_HA_OPTS)
class L3_HA_NAT_db_mixin(l3_dvr_db.L3_NAT_with_dvr_db_mixin,
router_az_db.RouterAvailabilityZoneMixin):
"""Mixin class to add high availability capability to routers."""
extra_attributes = (
l3_dvr_db.L3_NAT_with_dvr_db_mixin.extra_attributes +
router_az_db.RouterAvailabilityZoneMixin.extra_attributes + [
{'name': 'ha', 'default': cfg.CONF.l3_ha},
{'name': 'ha_vr_id', 'default': 0}])
def _verify_configuration(self):
self.ha_cidr = cfg.CONF.l3_ha_net_cidr
try:
net = netaddr.IPNetwork(self.ha_cidr)
except netaddr.AddrFormatError:
raise l3_ha.HANetworkCIDRNotValid(cidr=self.ha_cidr)
if ('/' not in self.ha_cidr or net.network != net.ip):
raise l3_ha.HANetworkCIDRNotValid(cidr=self.ha_cidr)
self._check_num_agents_per_router()
def _check_num_agents_per_router(self):
max_agents = cfg.CONF.max_l3_agents_per_router
min_agents = cfg.CONF.min_l3_agents_per_router
if (max_agents != UNLIMITED_AGENTS_PER_ROUTER
and max_agents < min_agents):
raise l3_ha.HAMaximumAgentsNumberNotValid(
max_agents=max_agents, min_agents=min_agents)
if min_agents < n_const.MINIMUM_MINIMUM_AGENTS_FOR_HA:
raise l3_ha.HAMinimumAgentsNumberNotValid()
def __init__(self):
self._verify_configuration()
super(L3_HA_NAT_db_mixin, self).__init__()
def get_ha_network(self, context, tenant_id):
return (context.session.query(l3ha_model.L3HARouterNetwork).
filter(l3ha_model.L3HARouterNetwork.tenant_id == tenant_id).
first())
def _get_allocated_vr_id(self, context, network_id):
with context.session.begin(subtransactions=True):
query = (context.session.query(
l3ha_model.L3HARouterVRIdAllocation).
filter(l3ha_model.L3HARouterVRIdAllocation.network_id ==
network_id))
allocated_vr_ids = set(a.vr_id for a in query) - set([0])
return allocated_vr_ids
@db_api.retry_if_session_inactive()
def _allocate_vr_id(self, context, network_id, router_id):
# TODO(kevinbenton): let decorator handle duplicate retry
# like in review.openstack.org/#/c/367179/1/neutron/db/l3_hamode_db.py
for count in range(MAX_ALLOCATION_TRIES):
try:
# NOTE(kevinbenton): we disallow subtransactions because the
# retry logic will bust any parent transactions
with context.session.begin():
allocated_vr_ids = self._get_allocated_vr_id(context,
network_id)
available_vr_ids = VR_ID_RANGE - allocated_vr_ids
if not available_vr_ids:
raise l3_ha.NoVRIDAvailable(router_id=router_id)
allocation = l3ha_model.L3HARouterVRIdAllocation()
allocation.network_id = network_id
allocation.vr_id = available_vr_ids.pop()
context.session.add(allocation)
return allocation.vr_id
except db_exc.DBDuplicateEntry:
LOG.info(_LI("Attempt %(count)s to allocate a VRID in the "
"network %(network)s for the router %(router)s"),
{'count': count, 'network': network_id,
'router': router_id})
raise l3_ha.MaxVRIDAllocationTriesReached(
network_id=network_id, router_id=router_id,
max_tries=MAX_ALLOCATION_TRIES)
@db_api.retry_if_session_inactive()
def _delete_vr_id_allocation(self, context, ha_network, vr_id):
with context.session.begin(subtransactions=True):
context.session.query(
l3ha_model.L3HARouterVRIdAllocation).filter_by(
network_id=ha_network.network_id, vr_id=vr_id).delete()
def _set_vr_id(self, context, router, ha_network):
router.extra_attributes.ha_vr_id = self._allocate_vr_id(
context, ha_network.network_id, router.id)
def _create_ha_subnet(self, context, network_id, tenant_id):
args = {'network_id': network_id,
'tenant_id': '',
'name': n_const.HA_SUBNET_NAME % tenant_id,
'ip_version': 4,
'cidr': cfg.CONF.l3_ha_net_cidr,
'enable_dhcp': False,
'gateway_ip': None}
return p_utils.create_subnet(self._core_plugin, context,
{'subnet': args})
def _create_ha_network_tenant_binding(self, context, tenant_id,
network_id):
with context.session.begin():
ha_network = l3ha_model.L3HARouterNetwork(
tenant_id=tenant_id, network_id=network_id)
context.session.add(ha_network)
# we need to check if someone else just inserted at exactly the
# same time as us because there is no constrain in L3HARouterNetwork
# that prevents multiple networks per tenant
with context.session.begin(subtransactions=True):
items = (context.session.query(l3ha_model.L3HARouterNetwork).
filter_by(tenant_id=tenant_id).all())
if len(items) > 1:
# we need to throw an error so our network is deleted
# and the process is started over where the existing
# network will be selected.
raise db_exc.DBDuplicateEntry(columns=['tenant_id'])
return ha_network
def _add_ha_network_settings(self, network):
if cfg.CONF.l3_ha_network_type:
network[providernet.NETWORK_TYPE] = cfg.CONF.l3_ha_network_type
if cfg.CONF.l3_ha_network_physical_name:
network[providernet.PHYSICAL_NETWORK] = (
cfg.CONF.l3_ha_network_physical_name)
def _create_ha_network(self, context, tenant_id):
admin_ctx = context.elevated()
args = {'network':
{'name': n_const.HA_NETWORK_NAME % tenant_id,
'tenant_id': '',
'shared': False,
'admin_state_up': True}}
self._add_ha_network_settings(args['network'])
creation = functools.partial(p_utils.create_network,
self._core_plugin, admin_ctx, args)
content = functools.partial(self._create_ha_network_tenant_binding,
admin_ctx, tenant_id)
deletion = functools.partial(self._core_plugin.delete_network,
admin_ctx)
network, ha_network = common_db_mixin.safe_creation(
context, creation, deletion, content, transaction=False)
try:
self._create_ha_subnet(admin_ctx, network['id'], tenant_id)
except Exception:
with excutils.save_and_reraise_exception():
self._core_plugin.delete_network(admin_ctx, network['id'])
return ha_network
def get_number_of_agents_for_scheduling(self, context):
"""Return the number of agents on which the router will be scheduled.
Raises an exception if there are not enough agents available to honor
the min_agents config parameter. If the max_agents parameter is set to
0 all the agents will be used.
"""
min_agents = cfg.CONF.min_l3_agents_per_router
num_agents = len(self.get_l3_agents(context, active=True,
filters={'agent_modes': [constants.L3_AGENT_MODE_LEGACY,
constants.L3_AGENT_MODE_DVR_SNAT]}))
max_agents = cfg.CONF.max_l3_agents_per_router
if max_agents:
if max_agents > num_agents:
LOG.info(_LI("Number of active agents lower than "
"max_l3_agents_per_router. L3 agents "
"available: %s"), num_agents)
else:
num_agents = max_agents
if num_agents < min_agents:
raise l3_ha.HANotEnoughAvailableAgents(min_agents=min_agents,
num_agents=num_agents)
return num_agents
def _create_ha_port_binding(self, context, router_id, port_id):
try:
with context.session.begin():
routerportbinding = l3_models.RouterPort(
port_id=port_id, router_id=router_id,
port_type=constants.DEVICE_OWNER_ROUTER_HA_INTF)
context.session.add(routerportbinding)
portbinding = l3ha_model.L3HARouterAgentPortBinding(
port_id=port_id, router_id=router_id)
context.session.add(portbinding)
return portbinding
except db_exc.DBReferenceError as e:
with excutils.save_and_reraise_exception() as ctxt:
if isinstance(e.inner_exception, sql_exc.IntegrityError):
ctxt.reraise = False
LOG.debug(
'Failed to create HA router agent PortBinding, '
'Router %s has already been removed '
'by concurrent operation', router_id)
raise l3.RouterNotFound(router_id=router_id)
def add_ha_port(self, context, router_id, network_id, tenant_id):
# NOTE(kevinbenton): we have to block any ongoing transactions because
# our exception handling will try to delete the port using the normal
# core plugin API. If this function is called inside of a transaction
# the exception will mangle the state, cause the delete call to fail,
# and end up relying on the DB rollback to remove the port instead of
# proper delete_port call.
if context.session.is_active:
raise RuntimeError(_('add_ha_port cannot be called inside of a '
'transaction.'))
args = {'tenant_id': '',
'network_id': network_id,
'admin_state_up': True,
'device_id': router_id,
'device_owner': constants.DEVICE_OWNER_ROUTER_HA_INTF,
'name': n_const.HA_PORT_NAME % tenant_id}
creation = functools.partial(p_utils.create_port, self._core_plugin,
context, {'port': args})
content = functools.partial(self._create_ha_port_binding, context,
router_id)
deletion = functools.partial(self._core_plugin.delete_port, context,
l3_port_check=False)
port, bindings = common_db_mixin.safe_creation(context, creation,
deletion, content,
transaction=False)
return bindings
def _create_ha_interfaces(self, context, router, ha_network):
admin_ctx = context.elevated()
num_agents = self.get_number_of_agents_for_scheduling(context)
port_ids = []
try:
for index in range(num_agents):
binding = self.add_ha_port(admin_ctx, router.id,
ha_network.network['id'],
router.tenant_id)
port_ids.append(binding.port_id)
except Exception:
with excutils.save_and_reraise_exception():
for port_id in port_ids:
self._core_plugin.delete_port(admin_ctx, port_id,
l3_port_check=False)
def _delete_ha_interfaces(self, context, router_id):
admin_ctx = context.elevated()
device_filter = {'device_id': [router_id],
'device_owner':
[constants.DEVICE_OWNER_ROUTER_HA_INTF]}
ports = self._core_plugin.get_ports(admin_ctx, filters=device_filter)
for port in ports:
self._core_plugin.delete_port(admin_ctx, port['id'],
l3_port_check=False)
def delete_ha_interfaces_on_host(self, context, router_id, host):
admin_ctx = context.elevated()
port_ids = (binding.port_id for binding
in self.get_ha_router_port_bindings(admin_ctx,
[router_id], host))
for port_id in port_ids:
self._core_plugin.delete_port(admin_ctx, port_id,
l3_port_check=False)
def _notify_ha_interfaces_updated(self, context, router_id,
schedule_routers=True):
self.l3_rpc_notifier.routers_updated(
context, [router_id], shuffle_agents=True,
schedule_routers=schedule_routers)
@classmethod
def _is_ha(cls, router):
ha = router.get('ha')
if not validators.is_attr_set(ha):
ha = cfg.CONF.l3_ha
return ha
def _get_device_owner(self, context, router=None):
"""Get device_owner for the specified router."""
router_is_uuid = isinstance(router, six.string_types)
if router_is_uuid:
router = self._get_router(context, router)
if is_ha_router(router) and not is_distributed_router(router):
return constants.DEVICE_OWNER_HA_REPLICATED_INT
return super(L3_HA_NAT_db_mixin,
self)._get_device_owner(context, router)
@n_utils.transaction_guard
def _create_ha_interfaces_and_ensure_network(self, context, router_db):
"""Attach interfaces to a network while tolerating network deletes."""
creator = functools.partial(self._create_ha_interfaces,
context, router_db)
dep_getter = functools.partial(self.get_ha_network,
context, router_db.tenant_id)
dep_creator = functools.partial(self._create_ha_network,
context, router_db.tenant_id)
dep_deleter = functools.partial(self._delete_ha_network, context)
dep_id_attr = 'network_id'
return n_utils.create_object_with_dependency(
creator, dep_getter, dep_creator, dep_id_attr, dep_deleter)
def _process_extra_attr_router_create(self, context, router_db,
router_res):
router_res['ha'] = self._is_ha(router_res)
super(L3_HA_NAT_db_mixin, self)._process_extra_attr_router_create(
context, router_db, router_res)
@db_api.retry_if_session_inactive()
def create_router(self, context, router):
is_ha = self._is_ha(router['router'])
if is_ha:
# we set the allocating status to hide it from the L3 agents
# until we have created all of the requisite interfaces/networks
router['router']['status'] = n_const.ROUTER_STATUS_ALLOCATING
router_dict = super(L3_HA_NAT_db_mixin,
self).create_router(context, router)
if is_ha:
try:
router_db = self._get_router(context, router_dict['id'])
# the following returns interfaces and the network we only
# care about the network
ha_network = self._create_ha_interfaces_and_ensure_network(
context, router_db)[1]
self._set_vr_id(context, router_db, ha_network)
router_dict['ha_vr_id'] = router_db.extra_attributes.ha_vr_id
self.schedule_router(context, router_dict['id'])
router_dict['status'] = self._update_router_db(
context, router_dict['id'],
{'status': n_const.ROUTER_STATUS_ACTIVE})['status']
self._notify_ha_interfaces_updated(context, router_db.id,
schedule_routers=False)
except Exception:
with excutils.save_and_reraise_exception():
self.delete_router(context, router_dict['id'])
return router_dict
@db_api.retry_if_session_inactive()
def _update_router_db(self, context, router_id, data):
router_db = self._get_router(context, router_id)
original_distributed_state = router_db.extra_attributes.distributed
original_ha_state = router_db.extra_attributes.ha
requested_ha_state = data.pop('ha', None)
requested_distributed_state = data.get('distributed', None)
# cvr to dvrha
if not original_distributed_state and not original_ha_state:
if (requested_ha_state is True and
requested_distributed_state is True):
raise l3_ha.UpdateToDvrHamodeNotSupported()
# cvrha to any dvr...
elif not original_distributed_state and original_ha_state:
if requested_distributed_state is True:
raise l3_ha.DVRmodeUpdateOfHaNotSupported()
# dvr to any ha...
elif original_distributed_state and not original_ha_state:
if requested_ha_state is True:
raise l3_ha.HAmodeUpdateOfDvrNotSupported()
#dvrha to any cvr...
elif original_distributed_state and original_ha_state:
if requested_distributed_state is False:
raise l3_ha.DVRmodeUpdateOfDvrHaNotSupported()
#elif dvrha to dvr
if requested_ha_state is False:
raise l3_ha.HAmodeUpdateOfDvrHaNotSupported()
ha_changed = (requested_ha_state is not None and
requested_ha_state != original_ha_state)
if ha_changed:
if router_db.admin_state_up:
msg = _('Cannot change HA attribute of active routers. Please '
'set router admin_state_up to False prior to upgrade.')
raise n_exc.BadRequest(resource='router', msg=msg)
if requested_ha_state:
# This will throw HANotEnoughAvailableAgents if there aren't
# enough l3 agents to handle this router.
self.get_number_of_agents_for_scheduling(context)
# set status to ALLOCATING so this router is no longer
# provided to agents while its interfaces are being re-configured.
# Keep in mind that if we want conversion to be hitless, this
# status cannot be used because agents treat hidden routers as
# deleted routers.
data['status'] = n_const.ROUTER_STATUS_ALLOCATING
with context.session.begin(subtransactions=True):
router_db = super(L3_HA_NAT_db_mixin, self)._update_router_db(
context, router_id, data)
if not ha_changed:
return router_db
ha_network = self.get_ha_network(context,
router_db.tenant_id)
router_db.extra_attributes.ha = requested_ha_state
if not requested_ha_state:
self._delete_vr_id_allocation(
context, ha_network, router_db.extra_attributes.ha_vr_id)
router_db.extra_attributes.ha_vr_id = None
# The HA attribute has changed. First unbind the router from agents
# to force a proper re-scheduling to agents.
# TODO(jschwarz): This will have to be more selective to get HA + DVR
# working (Only unbind from dvr_snat nodes).
self._unbind_ha_router(context, router_id)
if requested_ha_state:
ha_network = self._create_ha_interfaces_and_ensure_network(
context, router_db)[1]
self._set_vr_id(context, router_db, ha_network)
else:
self._delete_ha_interfaces(context, router_db.id)
# always attempt to cleanup the network as the router is
# deleted. the core plugin will stop us if its in use
self.safe_delete_ha_network(context, ha_network,
router_db.tenant_id)
self.schedule_router(context, router_id)
router_db = super(L3_HA_NAT_db_mixin, self)._update_router_db(
context, router_id, {'status': n_const.ROUTER_STATUS_ACTIVE})
self._notify_ha_interfaces_updated(context, router_db.id,
schedule_routers=False)
return router_db
def _delete_ha_network(self, context, net):
admin_ctx = context.elevated()
self._core_plugin.delete_network(admin_ctx, net.network_id)
def safe_delete_ha_network(self, context, ha_network, tenant_id):
try:
# reference the attr inside the try block before we attempt
# to delete the network and potentially invalidate the
# relationship
net_id = ha_network.network_id
self._delete_ha_network(context, ha_network)
except (n_exc.NetworkNotFound,
orm.exc.ObjectDeletedError):
LOG.debug(
"HA network for tenant %s was already deleted.", tenant_id)
except sa.exc.InvalidRequestError:
LOG.info(_LI("HA network %s can not be deleted."), net_id)
except n_exc.NetworkInUse:
# network is still in use, this is normal so we don't
# log anything
pass
else:
LOG.info(_LI("HA network %(network)s was deleted as "
"no HA routers are present in tenant "
"%(tenant)s."),
{'network': net_id, 'tenant': tenant_id})
@db_api.retry_if_session_inactive()
def delete_router(self, context, id):
router_db = self._get_router(context, id)
super(L3_HA_NAT_db_mixin, self).delete_router(context, id)
if router_db.extra_attributes.ha:
ha_network = self.get_ha_network(context,
router_db.tenant_id)
if ha_network:
self._delete_vr_id_allocation(
context, ha_network, router_db.extra_attributes.ha_vr_id)
# always attempt to cleanup the network as the router is
# deleted. the core plugin will stop us if its in use
self.safe_delete_ha_network(context, ha_network,
router_db.tenant_id)
def _unbind_ha_router(self, context, router_id):
for agent in self.get_l3_agents_hosting_routers(context, [router_id]):
self.remove_router_from_l3_agent(context, agent['id'], router_id)
def get_ha_router_port_bindings(self, context, router_ids, host=None):
if not router_ids:
return []
query = context.session.query(l3ha_model.L3HARouterAgentPortBinding)
if host:
query = query.join(agent_model.Agent).filter(
agent_model.Agent.host == host)
query = query.filter(
l3ha_model.L3HARouterAgentPortBinding.router_id.in_(router_ids))
return query.all()
@staticmethod
def _check_router_agent_ha_binding(context, router_id, agent_id):
query = context.session.query(l3ha_model.L3HARouterAgentPortBinding)
query = query.filter(
l3ha_model.L3HARouterAgentPortBinding.router_id == router_id,
l3ha_model.L3HARouterAgentPortBinding.l3_agent_id == agent_id)
return query.first() is not None
def _get_bindings_and_update_router_state_for_dead_agents(self, context,
router_id):
"""Return bindings. In case if dead agents were detected update router
states on this agent.
"""
with context.session.begin(subtransactions=True):
bindings = self.get_ha_router_port_bindings(context, [router_id])
dead_agents = [
binding.agent for binding in bindings
if binding.state == n_const.HA_ROUTER_STATE_ACTIVE and
not (binding.agent.is_active and binding.agent.admin_state_up)]
for dead_agent in dead_agents:
self.update_routers_states(
context, {router_id: n_const.HA_ROUTER_STATE_STANDBY},
dead_agent.host)
if dead_agents:
return self.get_ha_router_port_bindings(context, [router_id])
return bindings
def get_l3_bindings_hosting_router_with_ha_states(
self, context, router_id):
"""Return a list of [(agent, ha_state), ...]."""
bindings = self._get_bindings_and_update_router_state_for_dead_agents(
context, router_id)
return [(binding.agent, binding.state) for binding in bindings
if binding.agent is not None]
def get_active_host_for_ha_router(self, context, router_id):
bindings = self.get_l3_bindings_hosting_router_with_ha_states(
context, router_id)
# TODO(amuller): In case we have two or more actives, this method
# needs to return the last agent to become active. This requires
# timestamps for state changes. Otherwise, if a host goes down
# and another takes over, we'll have two actives. In this case,
# if an interface is added to a router, its binding might be wrong
# and l2pop would not work correctly.
return next(
(agent.host for agent, state in bindings
if state == n_const.HA_ROUTER_STATE_ACTIVE),
None)
@log_helpers.log_method_call
def _process_sync_ha_data(self, context, routers, host, agent_mode):
routers_dict = dict((router['id'], router) for router in routers)
bindings = self.get_ha_router_port_bindings(context,
routers_dict.keys(),
host)
for binding in bindings:
port = binding.port
if not port:
# Filter the HA router has no ha port here
LOG.info(_LI("HA router %s is missing HA router port "
"bindings. Skipping it."),
binding.router_id)
routers_dict.pop(binding.router_id)
continue
port_dict = self._core_plugin._make_port_dict(port)
router = routers_dict.get(binding.router_id)
router[constants.HA_INTERFACE_KEY] = port_dict
router[n_const.HA_ROUTER_STATE_KEY] = binding.state
for router in routers_dict.values():
interface = router.get(constants.HA_INTERFACE_KEY)
if interface:
self._populate_mtu_and_subnets_for_ports(context, [interface])
# If this is a DVR+HA router, but the agent is question is in 'dvr'
# mode (as opposed to 'dvr_snat'), then we want to always return it
# even though it's missing the '_ha_interface' key.
return [r for r in list(routers_dict.values())
if (agent_mode == constants.L3_AGENT_MODE_DVR or
not r.get('ha') or r.get(constants.HA_INTERFACE_KEY))]
@log_helpers.log_method_call
def get_ha_sync_data_for_host(self, context, host, agent,
router_ids=None, active=None):
agent_mode = self._get_agent_mode(agent)
dvr_agent_mode = (agent_mode in [constants.L3_AGENT_MODE_DVR_SNAT,
constants.L3_AGENT_MODE_DVR])
if (dvr_agent_mode and n_utils.is_extension_supported(
self, constants.L3_DISTRIBUTED_EXT_ALIAS)):
# DVR has to be handled differently
sync_data = self._get_dvr_sync_data(context, host, agent,
router_ids, active)
else:
sync_data = super(L3_HA_NAT_db_mixin, self).get_sync_data(context,
router_ids, active)
return self._process_sync_ha_data(context, sync_data, host, agent_mode)
@classmethod
def _set_router_states(cls, context, bindings, states):
for binding in bindings:
try:
with context.session.begin(subtransactions=True):
binding.state = states[binding.router_id]
except (orm.exc.StaleDataError, orm.exc.ObjectDeletedError):
# Take concurrently deleted routers in to account
pass
@db_api.retry_if_session_inactive()
def update_routers_states(self, context, states, host):
"""Receive dict of router ID to state and update them all."""
bindings = self.get_ha_router_port_bindings(
context, router_ids=states.keys(), host=host)
self._set_router_states(context, bindings, states)
self._update_router_port_bindings(context, states, host)
def _update_router_port_bindings(self, context, states, host):
admin_ctx = context.elevated()
device_filter = {'device_id': list(states.keys()),
'device_owner':
[constants.DEVICE_OWNER_HA_REPLICATED_INT,
constants.DEVICE_OWNER_ROUTER_SNAT]}
ports = self._core_plugin.get_ports(admin_ctx, filters=device_filter)
active_ports = (port for port in ports
if states[port['device_id']] == n_const.HA_ROUTER_STATE_ACTIVE)
for port in active_ports:
port[portbindings.HOST_ID] = host
try:
self._core_plugin.update_port(admin_ctx, port['id'],
{attributes.PORT: port})
except (orm.exc.StaleDataError, orm.exc.ObjectDeletedError,
n_exc.PortNotFound):
# Take concurrently deleted interfaces in to account
pass
def is_ha_router(router):
"""Return True if router to be handled is ha."""
try:
# See if router is a DB object first
requested_router_type = router.extra_attributes.ha
except AttributeError:
# if not, try to see if it is a request body
requested_router_type = router.get('ha')
if validators.is_attr_set(requested_router_type):
return requested_router_type
return cfg.CONF.l3_ha
def is_ha_router_port(device_owner, router_id):
session = db_api.get_session()
if device_owner == constants.DEVICE_OWNER_HA_REPLICATED_INT:
return True
elif device_owner == constants.DEVICE_OWNER_ROUTER_SNAT:
query = session.query(l3_attrs.RouterExtraAttributes)
query = query.filter_by(ha=True)
query = query.filter(l3_attrs.RouterExtraAttributes.router_id ==
router_id)
return bool(query.limit(1).count())
else:
return False
_deprecate._MovedGlobals()
| {
"content_hash": "e3f921591fc5abced1c5bf45c2b12737",
"timestamp": "",
"source": "github",
"line_count": 757,
"max_line_length": 79,
"avg_line_length": 45.65785997357992,
"alnum_prop": 0.5801001070508925,
"repo_name": "sebrandon1/neutron",
"id": "96328bbc0ee992112a2d9ac8f861f31f769fd117",
"size": "35172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "neutron/db/l3_hamode_db.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "1047"
},
{
"name": "Python",
"bytes": "9903006"
},
{
"name": "Shell",
"bytes": "14339"
}
],
"symlink_target": ""
} |
package com.davidbracewell.cache;
import com.davidbracewell.conversion.Cast;
import com.davidbracewell.function.Unchecked;
import com.davidbracewell.logging.Logger;
import com.davidbracewell.reflection.Reflect;
import com.davidbracewell.reflection.ReflectionUtils;
import com.davidbracewell.string.StringUtils;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.Value;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Wraps an object automatically caching calls to methods with the <code>Cached</code> annotation.
*
* @param <T> the type parameter
* @author David B. Bracewell
*/
public class CacheProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(CacheProxy.class);
private final T object;
private final Map<String, CacheInfo> cachedMethods = new HashMap<>();
private final String defaultCacheName;
private final KeyMaker defaultKeyMaker;
protected CacheProxy(T object, String cacheName) throws Exception {
this.object = object;
Reflect r = Reflect.onObject(object).allowPrivilegedAccess();
if (r.getReflectedClass().isAnnotationPresent(Cached.class)) {
Cached cached = r.getReflectedClass().getAnnotation(Cached.class);
defaultCacheName = StringUtils.firstNonNullOrBlank(cacheName, cached.name(), CacheManager.GLOBAL_CACHE);
defaultKeyMaker = cached.keyMaker() == KeyMaker.DefaultKeyMaker.class
? new KeyMaker.HashCodeKeyMaker()
: Reflect.onClass(cached.keyMaker()).create().get();
} else {
defaultCacheName = StringUtils.firstNonNullOrBlank(cacheName, CacheManager.GLOBAL_CACHE);
defaultKeyMaker = new KeyMaker.HashCodeKeyMaker();
}
r.getMethods().forEach(Unchecked.consumer(method -> {
if (method.isAnnotationPresent(Cached.class)) {
Cached cached = method.getAnnotation(Cached.class);
KeyMaker keyMaker = cached.keyMaker() == KeyMaker.DefaultKeyMaker.class
? defaultKeyMaker
: Reflect.onClass(cached.keyMaker()).create().get();
cachedMethods.put(createMethodKey(method),
new CacheInfo(
CacheManager.get(
StringUtils.firstNonNullOrBlank(cached.name(), defaultCacheName)),
keyMaker)
);
}
}));
}
private String createMethodKey(Method method) {
return method.getName() + "::" + method.getParameterTypes().length + "::" + Arrays.toString(
method.getParameterTypes());
}
/**
* Creates a proxy object that automatically caches calls to methods with the <code>Cached</code> annotation.
*
* @param <T> The type of the object
* @param object The object being wrapped
* @return The wrapped object
*/
public static <T> T cache(Object object) {
return cache(object, null);
}
@SneakyThrows
public static <T> T cache(@NonNull Object object, String defaultCacheName) {
return Cast.as(Proxy.newProxyInstance(object.getClass().getClassLoader(),
ReflectionUtils.getAncestorInterfaces(object).toArray(new Class[1]),
new CacheProxy<>(object, defaultCacheName)
)
);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final String methodKey = createMethodKey(method);
//If this is a cached method then do the caching...
if (cachedMethods.containsKey(methodKey)) {
CacheInfo cacheInfo = cachedMethods.get(methodKey);
Object key = cacheInfo.getKeyMaker().make(object.getClass(), method, args);
try {
return cacheInfo.getCache().get(key, Unchecked.supplier(() -> method.invoke(object, args)));
} catch (RuntimeException e) {
throw e.getCause();
}
}
//Otherwise just invoke it
return method.invoke(object, args);
}
@Value
private static class CacheInfo implements Serializable {
private static final long serialVersionUID = 1L;
public Cache<Object, Object> cache;
public KeyMaker keyMaker;
}
}//END OF CacheProxy
| {
"content_hash": "561ce8a2b964c879ebea8efc3738fcde",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 115,
"avg_line_length": 39.46218487394958,
"alnum_prop": 0.6411839863713799,
"repo_name": "dbracewell/mango",
"id": "fdde38b82b58ded009e9e2aaf806399097d21d12",
"size": "5537",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/davidbracewell/cache/CacheProxy.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1720396"
},
{
"name": "JavaScript",
"bytes": "29"
},
{
"name": "Lex",
"bytes": "4744"
}
],
"symlink_target": ""
} |
'use strict';
let vm = require('vm'),
fs = require('fs'),
_ = require('lodash'),
yaml = require('js-yaml'),
blessed = require('blessed'),
Promise = require('bluebird'),
cmd = require('commander'),
contrib = require('blessed-contrib');
let conf = require('./conf').conf;
let Iconv = require('iconv').Iconv;
let iconv = new Iconv('GBK', 'UTF-8//TRANSLIT//IGNORE');
let request = Promise.promisifyAll(require('request'), {multiArgs:true});
let table = null;
let screen = blessed.screen({ fullUnicode:true });
const MSG = {
INPUT_ERROR : '输入错误,当前只支持通过证券代码看盘,请检查后重新输入!',
TOO_MANY_SYMS : '输入的股票太多,一次最多支持盯盘25只股票!',
SYMBOL_NOT_EXIST : '该股票代码不存在:',
};
// A client error like 400 Bad Request happened
let ClientError = e => (e.code >= 400 && e.code < 500 || e.code === 'ENOTFOUND');
// Set current data source
let src = (cmd.data || '').toUpperCase();
let source = (src === 'SINA' || src === 'TENCENT') ? src : conf.dataSource;
let ds = conf.provider[source];
/**
* Check validity of input symbols, and return a valid symbols array if there is.
* @param {String} syms Input symbols' string.
* @return {Array} Array of input symbols
*/
let getValidSymbols = function getValidSymbols(syms){
// When no symbols were provided, use symbols from watchList or holded symbols.
if(syms === true){
let Common = require('./common').Common;
let yamlConf = yaml.safeLoad(fs.readFileSync(Common.getSymbolFilePath(), 'utf8'));
if(!cmd.hold && yamlConf.watchList && yamlConf.watchList.length > 0){
syms = _.map(yamlConf.watchList, 'code').join(',');
} else {
syms = _.filter(yamlConf.symbols, s => s.hold);
syms = _.map(syms, 'code').join(',');
}
}
let symbols = syms.replace(/,/g, ',');
let valid = /^[0-9,]+$/.test(symbols);
if(!valid){
console.error(MSG.INPUT_ERROR.error);
return false;
}
symbols = _.trimEnd(symbols, ',').split(',');
if(symbols.length>conf.chunkSize){
console.error(MSG.TOO_MANY_SYMS.error);
return false;
}
return symbols;
};
/**
* Init table layout and screen keyboard event
*/
let initUI = function initUI(){
table = contrib.table({
keys : true,
fg : 'white',
selectedFg : 'black',
selectedBg : 'cyan',
interactive : true,
label : '股票列表',
width : '55%',
height : '80%',
border : { type: 'line', fg: 'cyan' },
columnSpacing : 5,
columnWidth : [10, 7, 7, 7, 9],
});
/* eslint no-process-exit:0 */
screen.key(['escape', 'q', 'C-c'], () => process.exit(0) );
};
/**
* Update table data
* @param {Array} queryResults New table data to be updated
*/
let updateData = function updateData(queryResults){
let queryData = [];
_.each(queryResults, q => {
// Fix the padding of company name
q.name = (q.name.length === 3) ? ` ${q.name}`:q.name;
q.price = q.price.toFixed(2);
q.inc = q.inc.toFixed(2);
q.incPct = `${q.incPct.toFixed(2)} %`;
queryData.push([q.name, q.code, q.price, q.inc, q.incPct]);
});
table.setData({
headers : ['公司', '代码', '当前价', '涨跌', '涨跌%'],
data : queryData,
});
table.focus();
screen.append(table);
screen.render();
};
/**
* Query and refresh price data
* @param {Array} syms Symbols' code array
* @param {String} query Query string
*/
let refreshData = function refreshData(syms, query){
// symbol query results
let queryResults = [];
return request.getAsync(ds.url + query, { encoding:null }).spread((resp, body) => {
body = iconv.convert(body).toString();
vm.runInThisContext(body);
_.each(syms, s => {
let localVar = ds.flag + conf.market[s.substr(0,3)] + s;
if(body.indexOf(localVar) < 0 || body.indexOf(`${localVar}="";`) >= 0){
console.error(MSG.SYMBOL_NOT_EXIST.error, s.em);
return false;
}
let res = {};
let splits = vm.runInThisContext(ds.flag + conf.market[s.substr(0,3)] + s).split(ds.sep);
res.name = splits[ds.nameIdx];
res.code = s;
// 对于停牌股票价格以上个交易日收盘价格为准
res.close = +splits[ds.closeIdx];
res.price = +splits[ds.priceIdx] || res.close;
res.inc = res.price - res.close;
res.incPct = ((res.price - res.close)/res.close) * 100;
queryResults.push(res);
});
updateData(queryResults);
// FIXME: fix 'ENOTFOUND' error
}).catch(ClientError, () => {
process.exit(1);
});
};
/**
* Query symbols' price info
* @param {Array} syms Symbols array to query
* @return {Array} Basic info array of queried symbols
*/
let querySymbols = function querySymbols(syms){
let query = _.map(syms, x => conf.market[x.substr(0,3)] + x).join(',');
refreshData(syms, query);
setInterval(refreshData.bind(this, syms, query), 3600);
};
/**
* Do the query action.
* @param {String} syms Input symbols' string.
*/
let doWatch = function doWatch(syms){
initUI();
Promise
.resolve(syms)
.then(getValidSymbols)
.then(querySymbols);
};
// star -w 002625,600588,601179,600415,600816,600880,600703,000861,600410,000768,000712,600118,600893,002456,000902,000725,000002,000100
exports.Watch = {
doWatch,
};
| {
"content_hash": "b80515bcd7af8ac2b489ace56405673e",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 136,
"avg_line_length": 31.262569832402235,
"alnum_prop": 0.5643316654753395,
"repo_name": "hustcer/star",
"id": "952afad124533abeda638a594800f9f60e8ba45a",
"size": "5884",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/watch.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "74734"
}
],
"symlink_target": ""
} |
$!APP_NAME!$
====
[](https://travis-ci.org/hmrc/$!APP_NAME!$) [  ](https://bintray.com/hmrc/releases/$!APP_NAME!$/_latestVersion)
| {
"content_hash": "2a84b4476e553473ec59d658fd6da9be",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 277,
"avg_line_length": 98.66666666666667,
"alnum_prop": 0.6891891891891891,
"repo_name": "hmrc/sbt-templates",
"id": "3d3c6abff8e76fef9aa1cbda8cf9e29fc1954224",
"size": "297",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "templates/library/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "52240"
},
{
"name": "Scala",
"bytes": "2752"
}
],
"symlink_target": ""
} |
package me.Jasch.EasySocket.WebSocket;
import me.Jasch.EasySocket.Exceptions.*;
import me.Jasch.EasySocket.Message.MType;
import me.Jasch.EasySocket.Message.Message;
import org.apache.commons.lang.RandomStringUtils;
import org.java_websocket.WebSocket;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
/**
* Utility functions for the WebSocket server.
* @author jasch
* @version 0.1.0
* @since 0.1.0
*/
public class WSUtils {
private static final Logger log = LoggerFactory.getLogger(WSUtils.class); // logger instance
/**
* Generates a unique, 8 character alphanumeric ID for a connection.
* @return Unique ID
*/
@NotNull
public static String generateConnectionId() {
// just a wrapper that assigns the correct HashMap
return generateConnectionId(Server.conns);
}
/**
* Generates a unique, 8 character alphanumeric ID for a connection.
* @param chm connection hashmap the ID will be generated for.
* @return Unique ID
*/
@NotNull
public static String generateConnectionId(HashMap<String, Connection> chm) {
String cID;
do {
cID = RandomStringUtils.randomAlphanumeric(8);
} while (chm.containsKey(cID));
if (log.isDebugEnabled()) {log.debug("Generated connection ID: {}", cID);}
return cID;
}
/**
* Checks whether a connection ID is known.
* @param cID The connection ID to check.
* @return True if cID is known, false otherwise.
*/
@NotNull
public static boolean validCID(String cID) {
return Server.conns.containsKey(cID);
}
/**
* Checks the answer for a CIS message.
* @param msg The received message.
* @return True if the connection ID was set correctly, false otherwise.
*/
@NotNull
public static Boolean checkCISInformation(Message msg) {
// Return null if supplied cID is not known.
// if (!Server.conns.containsKey(msg.cID)) { throw new UnknownConnectionIDException();}
Connection c = Server.conns.get(msg.cID);
return (c.getState() == ConnectionState.CIDSENT);
}
/**
* Terminates a WebSocket connection.
* @param ws The affected WebSocket.
*/
public static void terminateConnection(WebSocket ws) {
if (log.isDebugEnabled()) {
log.debug("Terminating connection. Remote: {}", ws.getRemoteSocketAddress().getAddress().getHostAddress());
}
ws.close();
}
/**
* Terminates a WebSocket connection and removes it from the list of active connections.
* @param ws The affected WebSocket.
* @param cID The affected connection ID.
*/
public static void terminateConnection(WebSocket ws, String cID) {
Message msg = null;
try {
msg = new Message(MType.ERR, cID, "GenericError");
} catch (UnknownConnectionIDException e) {
log.error("This should not happen!"); // TODO: better handle this!
}
ws.send(msg.toString());
ws.close();
if (Server.conns.containsKey(cID)) {
Server.conns.remove(cID);
}
}
/**
* Sends protocol information and saves state to connection.
* @param ws The affected WebSocket.
* @param cID The affected Connection ID.
* @param protocolName The protocol name.
*/
public static void sendProtocolInformation(WebSocket ws, String cID, String protocolName) {
Message msg = null;
try {
msg = new Message(MType.PRT, cID, protocolName);
} catch (UnknownConnectionIDException e) {
// This should never happen!
log.error("This should never happen!"); // TODO: handle this better!
}
ws.send(msg.toString());
if (Server.conns.containsKey(cID)) {
Server.conns.get(cID).setState(ConnectionState.PRTSENT);
}
}
/**
* Checks if the returned protocol information is good.
* @param msg The received message.
* @param protocolName The expected protocol name.
* @return True if the received protocol information matches the expected information.
*/
@NotNull
public static Boolean checkPRTInformation(Message msg, String protocolName) {
// Throw exception if connection ID is unknown.
// if (!Server.conns.containsKey(msg.cID)) { throw new UnknownConnectionIDException(); }
Connection c = Server.conns.get(msg.cID);
return c.getState() == ConnectionState.PRTSENT && msg.payload.equals(protocolName);
}
}
| {
"content_hash": "21fdf4ef5f7eab6a03e810ea0d017b89",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 119,
"avg_line_length": 33.48201438848921,
"alnum_prop": 0.6465406102277611,
"repo_name": "jaschmedia/EasySocket",
"id": "99f11997875f477f95f68891a92a03cd963e5c8f",
"size": "4654",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/me/Jasch/EasySocket/WebSocket/WSUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "678"
},
{
"name": "Java",
"bytes": "36334"
},
{
"name": "JavaScript",
"bytes": "5548"
}
],
"symlink_target": ""
} |
using System;
using StructureMap.Graph;
namespace StructureMap.Configuration
{
public interface IProfileBuilder
{
void AddProfile(string profileName);
void OverrideProfile(TypePath typePath, string instanceKey);
void SetDefaultProfileName(string profileName);
}
public interface IGraphBuilder
{
PluginGraph PluginGraph { get; }
void AddAssembly(string assemblyName);
void AddRegistry(string registryTypeName);
void FinishFamilies();
IProfileBuilder GetProfileBuilder();
void ConfigureFamily(TypePath pluginTypePath, Action<PluginFamily> action);
void WithSystemObject<T>(InstanceMemento memento, string context, Action<T> action);
void WithType(TypePath path, string context, Action<Type> action);
}
} | {
"content_hash": "2e55f8f55f715ec9f77ce1f1d7c47e9c",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 92,
"avg_line_length": 28.275862068965516,
"alnum_prop": 0.7097560975609756,
"repo_name": "hp4711/structuremap",
"id": "a918b6bda1cc55032e084987fc1ea8e8caa12b28",
"size": "820",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/StructureMap/Configuration/IGraphBuilder.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3109"
},
{
"name": "C#",
"bytes": "1439075"
},
{
"name": "CSS",
"bytes": "6356"
},
{
"name": "HTML",
"bytes": "1520677"
},
{
"name": "JavaScript",
"bytes": "1385"
},
{
"name": "PHP",
"bytes": "47"
},
{
"name": "XSLT",
"bytes": "3143"
}
],
"symlink_target": ""
} |
package com.github.cafaudit.auditmonkey;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.hpe.caf.auditing.AuditChannel;
public class MonkeyFactoryTest
{
private AuditChannel channel;
private MonkeyConfig monkeyConfig;
@Before
public void setUp() {
System.setProperty(MonkeyConstants.CAF_AUDIT_MODE, MonkeyConstants.ELASTICSEARCH);
monkeyConfig = new MonkeyConfig();
}
@After
public void tearDown()
{
System.clearProperty(MonkeyConstants.CAF_AUDIT_MODE);
}
@Test
public void shouldReturnStandardMonkey() {
monkeyConfig.setMonkeyMode(MonkeyConstants.CAF_AUDIT_STANDARD_MONKEY);
Monkey monkey = MonkeyFactory.selectMonkey(channel, monkeyConfig);
assertTrue(monkey instanceof StandardMonkey);
}
@Test
public void shouldReturnRandomMonkey() {
monkeyConfig.setMonkeyMode(MonkeyConstants.CAF_AUDIT_RANDOM_MONKEY);
Monkey monkey = MonkeyFactory.selectMonkey(channel, monkeyConfig);
assertTrue(monkey instanceof RandomMonkey);
}
@Test
public void shouldReturnNull() {
monkeyConfig.setMonkeyMode("blah");
Monkey monkey = MonkeyFactory.selectMonkey(channel, monkeyConfig);
assertNull(monkey);
}
}
| {
"content_hash": "4378e3e5621b851b0834eedd17ee3388",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 90,
"avg_line_length": 28.18,
"alnum_prop": 0.7054648687012065,
"repo_name": "CAFAudit/audit-service",
"id": "b06793403dedf4d2a3c11926257cbe52d6d531ee",
"size": "2035",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "caf-audit-monkey/src/test/java/com/github/cafaudit/auditmonkey/MonkeyFactoryTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "306852"
},
{
"name": "JavaScript",
"bytes": "1071"
},
{
"name": "Limbo",
"bytes": "3340"
},
{
"name": "Shell",
"bytes": "2490"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DesignScriptStudio.Graph.Core;
namespace DesignScriptStudio.Graph.Ui
{
/// <summary>
/// Interaction logic for GraphCanvas.xaml
/// </summary>
public partial class GraphCanvas : UserControl
{
private string startupFile = String.Empty;
private GraphControl graphControl = null;
private GraphVisualHost visualHost = null;
internal CustomTextBox textbox = null;
//zoom and pan info
private double sliderValue;
private double scrollHorizontalOffset;
private double scrollVerticalOffset;
bool ignoreMouseMoveEvent = false;
#region Public Class Operational Methods
public GraphCanvas()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(OnGraphCanvasLoaded);
}
public GraphCanvas(GraphControl graphControl)
{
InitializeComponent();
this.graphControl = graphControl;
this.Loaded += new RoutedEventHandler(OnGraphCanvasLoaded);
}
public GraphCanvas(GraphControl graphControl, string startupFile)
{
InitializeComponent();
this.startupFile = startupFile;
this.graphControl = graphControl;
this.Loaded += new RoutedEventHandler(OnGraphCanvasLoaded);
}
#endregion
#region Public Class Properties
internal string FilePath
{
get
{
IGraphController graphController = visualHost.Controller;
return graphController.FilePath;
}
}
internal GraphVisualHost VisualHost { get { return visualHost; } }
internal IGraphController Controller { get { return visualHost.Controller; } }
#endregion
#region Private Event Handlers
private void OnGraphCanvasLoaded(object sender, RoutedEventArgs e)
{
visualHost = new GraphVisualHost(this, this.graphControl, this.startupFile);
visualHost.IsInRecordingMode = graphControl.IsInRecordingMode;
graphCanvas.Children.Add(visualHost);
graphControl.GraphControllerLoaded(this.Controller.Identifier);
graphCanvas.KeyDown += new KeyEventHandler(OnCanvasKeyDown);
graphCanvas.KeyUp += new KeyEventHandler(OnCanvasKeyUp);
graphCanvas.MouseMove += new MouseEventHandler(OnCanvasMouseMove);
graphCanvas.MouseDown += OnCanvasMouseButtonDown;
graphCanvas.PreviewMouseDown += OnCanvasPreviewMouseDown;
graphCanvas.MouseUp += OnCanvasMouseButtonUp;
//for libraryview
graphCanvas.AllowDrop = true;
graphCanvas.Drop += new DragEventHandler(OnCanvasDrop);
//for Zoom and Pan
graphCanvas.MouseWheel += OnMouseWheel;
//if (!string.IsNullOrEmpty(this.startupFile))
// this.visualHost.HandleZoomToFit();
graphCanvas.Focus();
}
void OnCanvasKeyDown(object sender, KeyEventArgs e)
{
if (visualHost != null)
visualHost.HandleKeyDown(sender, e);
}
void OnCanvasKeyUp(object sender, KeyEventArgs e)
{
if (visualHost != null)
visualHost.HandleKeyUp(sender, e);
}
void OnCanvasMouseMove(object sender, MouseEventArgs e)
{
if (Application.Current != null && Application.Current.MainWindow != null)
{
if (Application.Current.MainWindow.IsActive == false)
return;
}
if (ignoreMouseMoveEvent != false)
return;
if (visualHost != null)
visualHost.HandleMouseMove(sender, e);
}
private void OnCanvasPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
this.visualHost.HandlePreviewMouseDown();
// this.graphCanvas.Focus();
}
private void OnCanvasMouseButtonDown(object sender, MouseButtonEventArgs e)
{
this.graphCanvas.Focus();
if (visualHost != null)
{
switch (e.ChangedButton)
{
case MouseButton.Left:
visualHost.HandleMouseLeftButtonDown(sender, e);
ignoreMouseMoveEvent = true;
Mouse.Capture((UIElement)sender);
ignoreMouseMoveEvent = false;
return;
case MouseButton.Right:
visualHost.HandleMouseRightButtonDown(sender, e);
ignoreMouseMoveEvent = true;
Mouse.Capture((UIElement)sender);
ignoreMouseMoveEvent = false;
return;
case MouseButton.Middle:
visualHost.HandleMouseMiddleButtonDown(sender, e);
ignoreMouseMoveEvent = true;
Mouse.Capture((UIElement)sender);
ignoreMouseMoveEvent = false;
return;
}
}
}
private void OnCanvasMouseButtonUp(object sender, MouseButtonEventArgs e)
{
ignoreMouseMoveEvent = true;
((UIElement)sender).ReleaseMouseCapture();
ignoreMouseMoveEvent = false;
if (visualHost != null)
{
switch (e.ChangedButton)
{
case MouseButton.Left:
visualHost.HandleMouseLeftButtonUp(sender, e);
return;
case MouseButton.Right:
visualHost.HandleMouseRightButtonUp(sender, e);
return;
case MouseButton.Middle:
visualHost.HandleMouseMiddleButtonUp(sender, e);
return;
}
}
}
void OnMouseWheel(object sender, MouseWheelEventArgs e)
{
if (visualHost != null)
visualHost.HandleMouseWheel(sender, e);
}
internal void OnZoomToFitClick()
{
if (visualHost != null)
visualHost.HandleZoomToFit();
}
internal void OnZoomInClick()
{
if (visualHost != null)
visualHost.HandleZoomIn();
}
internal void OnZoomOutClick()
{
if (visualHost != null)
visualHost.HandleZoomOut();
}
internal void OnPanClick()
{
if (visualHost != null)
visualHost.HandleTogglePan();
}
internal void AddTextbox(UIElement textbox)
{
graphCanvas.Children.Add(textbox);
textbox.SetValue(Panel.ZIndexProperty, 6500);
}
internal void RemoveTextBox(UIElement textbox)
{
graphCanvas.Children.Remove(textbox);
}
void OnCanvasDrop(object sender, DragEventArgs e)
{
if (visualHost != null)
{
LibraryItem draggedItem = (LibraryItem)e.Data.GetData("DesignScriptStudio.Graph.Core.LibraryItem");
visualHost.HandleDrop(sender, draggedItem, e);
graphCanvas.Focus();
}
}
#endregion
#region Internal Helper Methods
internal void SetZoomAndPanInfo(double sliderValue, double horizontalOffset, double verticalOffset)
{
this.sliderValue = sliderValue;
this.scrollHorizontalOffset = horizontalOffset;
this.scrollVerticalOffset = verticalOffset;
}
internal void GetZoomAndPanInfo(out double sliderValue, out double horizontalOffset, out double verticalOffset)
{
sliderValue = this.sliderValue;
horizontalOffset = this.scrollHorizontalOffset;
verticalOffset = this.scrollVerticalOffset;
}
#endregion
}
}
| {
"content_hash": "cef2394233879f7cfaf7e9a43c57e306",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 119,
"avg_line_length": 33.71923076923077,
"alnum_prop": 0.554693737880689,
"repo_name": "DynamoDS/designscript-archive",
"id": "6597815b8e2f9fc4a56685c81a850d2af28e7755",
"size": "8769",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "UIs/Studio/DesignScriptStudio.Graph.Ui/GraphCanvas.xaml.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2452899"
},
{
"name": "C#",
"bytes": "17936156"
},
{
"name": "C++",
"bytes": "116035"
},
{
"name": "CSS",
"bytes": "3042"
},
{
"name": "Perl",
"bytes": "35814"
},
{
"name": "Shell",
"bytes": "25984"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using QuickGraph.Algorithms.ShortestPath;
namespace QuickGraph.Algorithms.Observers
{
/// <summary>
/// A distance recorder for directed tree builder algorithms
/// </summary>
/// <typeparam name="TVertex">type of a vertex</typeparam>
/// <typeparam name="TEdge">type of an edge</typeparam>
#if !SILVERLIGHT
[Serializable]
#endif
public sealed class VertexDistanceRecorderObserver<TVertex, TEdge>
: IObserver<ITreeBuilderAlgorithm<TVertex, TEdge>>
where TEdge : IEdge<TVertex>
{
private readonly IDistanceRelaxer distanceRelaxer;
private readonly Func<TEdge, double> edgeWeights;
private readonly IDictionary<TVertex, double> distances;
public VertexDistanceRecorderObserver(Func<TEdge, double> edgeWeights)
: this(edgeWeights, DistanceRelaxers.EdgeShortestDistance, new Dictionary<TVertex, double>())
{ }
public VertexDistanceRecorderObserver(
Func<TEdge, double> edgeWeights,
IDistanceRelaxer distanceRelaxer,
IDictionary<TVertex, double> distances)
{
Contract.Requires(edgeWeights != null);
Contract.Requires(distanceRelaxer != null);
Contract.Requires(distances != null);
this.edgeWeights = edgeWeights;
this.distanceRelaxer = distanceRelaxer;
this.distances = distances;
}
public IDistanceRelaxer DistanceRelaxer
{
get { return this.distanceRelaxer; }
}
public Func<TEdge, double> EdgeWeights
{
get { return this.edgeWeights; }
}
public IDictionary<TVertex, double> Distances
{
get { return this.distances; }
}
public IDisposable Attach(ITreeBuilderAlgorithm<TVertex, TEdge> algorithm)
{
algorithm.TreeEdge += this.TreeEdge;
return new DisposableAction(() => algorithm.TreeEdge -= this.TreeEdge);
}
private void TreeEdge(TEdge edge)
{
var source = edge.Source;
var target = edge.Target;
double sourceDistance;
if (!this.distances.TryGetValue(source, out sourceDistance))
this.distances[source] = sourceDistance = this.distanceRelaxer.InitialDistance;
this.distances[target] = this.DistanceRelaxer.Combine(sourceDistance, this.edgeWeights(edge));
}
}
}
| {
"content_hash": "9eb62142d7c0cf0e063b4257b10fec6f",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 106,
"avg_line_length": 34.37837837837838,
"alnum_prop": 0.6407232704402516,
"repo_name": "ezg/PanoramicDataWin8",
"id": "a1a1ccf390faf6de0d834bb18997a26377f4554e",
"size": "2546",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PanoramicDataWin8/utils/GraphSharpUWP/QuickGraph/Algorithms/Observers/VertexDistanceRecorderObserver.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "3887897"
},
{
"name": "Python",
"bytes": "92784"
},
{
"name": "Smalltalk",
"bytes": "94796"
}
],
"symlink_target": ""
} |
<?php
namespace yii\filters;
use Yii;
use yii\base\ActionFilter;
use yii\base\InvalidConfigException;
use yii\web\Request;
use yii\web\Response;
/**
* Cors 过滤工具 [Cross Origin Resource Sharing](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing).
*
* 请务必仔细阅读 CORS 能做的和不能做的事情。CORS 不保护您的 API,
* 但是允许开发人员授予对第三方代码的访问权限(来自外部域的 Ajax 调用)。
*
* 您可以通过将 CORS 筛选器作为行为附加到控制器或模块来使用 CORS 筛选器,如下所示:
*
* ```php
* public function behaviors()
* {
* return [
* 'corsFilter' => [
* 'class' => \yii\filters\Cors::className(),
* ],
* ];
* }
* ```
*
* CORS 过滤器可以专门用于限制参数,如下所示,
* [MDN CORS Information](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
*
* ```php
* public function behaviors()
* {
* return [
* 'corsFilter' => [
* 'class' => \yii\filters\Cors::className(),
* 'cors' => [
* // restrict access to
* 'Origin' => ['http://www.myserver.com', 'https://www.myserver.com'],
* // Allow only POST and PUT methods
* 'Access-Control-Request-Method' => ['POST', 'PUT'],
* // Allow only headers 'X-Wsse'
* 'Access-Control-Request-Headers' => ['X-Wsse'],
* // Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
* 'Access-Control-Allow-Credentials' => true,
* // Allow OPTIONS caching
* 'Access-Control-Max-Age' => 3600,
* // Allow the X-Pagination-Current-Page header to be exposed to the browser.
* 'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
* ],
*
* ],
* ];
* }
* ```
*
* 有关如何将 CORS 过滤器添加到控制器的详细信息,
* 请参见 [Guide on REST controllers](guide:rest-controllers#cors)。
*
* @author Philippe Gaultier <pgaultier@gmail.com>
* @since 2.0
*/
class Cors extends ActionFilter
{
/**
* @var Request 当前请求。如果未设置,将使用 `request` 应用程序组件。
*/
public $request;
/**
* @var Response 要发送的响应。如果未设置,将使用 `response` 应用程序组件。
*/
public $response;
/**
* @var array 定义特定操作的特定 CORS 规则
*/
public $actions = [];
/**
* @var array 为CORS请求处理的 Basic headers。
*/
public $cors = [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => null,
'Access-Control-Max-Age' => 86400,
'Access-Control-Expose-Headers' => [],
];
/**
* {@inheritdoc}
*/
public function beforeAction($action)
{
$this->request = $this->request ?: Yii::$app->getRequest();
$this->response = $this->response ?: Yii::$app->getResponse();
$this->overrideDefaultSettings($action);
$requestCorsHeaders = $this->extractHeaders();
$responseCorsHeaders = $this->prepareHeaders($requestCorsHeaders);
$this->addCorsHeaders($this->response, $responseCorsHeaders);
if ($this->request->isOptions && $this->request->headers->has('Access-Control-Request-Method')) {
// it is CORS preflight request, respond with 200 OK without further processing
$this->response->setStatusCode(200);
return false;
}
return true;
}
/**
* 覆盖特定操作的设置。
* @param \yii\base\Action $action 要覆盖的操作设置
*/
public function overrideDefaultSettings($action)
{
if (isset($this->actions[$action->id])) {
$actionParams = $this->actions[$action->id];
$actionParamsKeys = array_keys($actionParams);
foreach ($this->cors as $headerField => $headerValue) {
if (in_array($headerField, $actionParamsKeys)) {
$this->cors[$headerField] = $actionParams[$headerField];
}
}
}
}
/**
* 从请求中提取 CORS 标头。
* @return array 要处理的 CORS 标头
*/
public function extractHeaders()
{
$headers = [];
foreach (array_keys($this->cors) as $headerField) {
$serverField = $this->headerizeToPhp($headerField);
$headerData = isset($_SERVER[$serverField]) ? $_SERVER[$serverField] : null;
if ($headerData !== null) {
$headers[$headerField] = $headerData;
}
}
return $headers;
}
/**
* 对于每个 CORS 头创建特定的响应。
* @param array $requestHeaders 我们检测到的 CORS headers
* @return array CORS headers 准备发送
*/
public function prepareHeaders($requestHeaders)
{
$responseHeaders = [];
// handle Origin
if (isset($requestHeaders['Origin'], $this->cors['Origin'])) {
if (in_array($requestHeaders['Origin'], $this->cors['Origin'], true)) {
$responseHeaders['Access-Control-Allow-Origin'] = $requestHeaders['Origin'];
}
if (in_array('*', $this->cors['Origin'], true)) {
// Per CORS standard (https://fetch.spec.whatwg.org), wildcard origins shouldn't be used together with credentials
if (isset($this->cors['Access-Control-Allow-Credentials']) && $this->cors['Access-Control-Allow-Credentials']) {
if (YII_DEBUG) {
throw new InvalidConfigException("Allowing credentials for wildcard origins is insecure. Please specify more restrictive origins or set 'credentials' to false in your CORS configuration.");
} else {
Yii::error("Allowing credentials for wildcard origins is insecure. Please specify more restrictive origins or set 'credentials' to false in your CORS configuration.", __METHOD__);
}
} else {
$responseHeaders['Access-Control-Allow-Origin'] = '*';
}
}
}
$this->prepareAllowHeaders('Headers', $requestHeaders, $responseHeaders);
if (isset($requestHeaders['Access-Control-Request-Method'])) {
$responseHeaders['Access-Control-Allow-Methods'] = implode(', ', $this->cors['Access-Control-Request-Method']);
}
if (isset($this->cors['Access-Control-Allow-Credentials'])) {
$responseHeaders['Access-Control-Allow-Credentials'] = $this->cors['Access-Control-Allow-Credentials'] ? 'true' : 'false';
}
if (isset($this->cors['Access-Control-Max-Age']) && $this->request->getIsOptions()) {
$responseHeaders['Access-Control-Max-Age'] = $this->cors['Access-Control-Max-Age'];
}
if (isset($this->cors['Access-Control-Expose-Headers'])) {
$responseHeaders['Access-Control-Expose-Headers'] = implode(', ', $this->cors['Access-Control-Expose-Headers']);
}
return $responseHeaders;
}
/**
* 处理经典 CORS 请求以避免重复代码。
* @param string $type 我们将处理的头部类型
* @param array $requestHeaders 客户端请求 CORS 标头
* @param array $responseHeaders 发送到客户端的 CORS 响应标头
*/
protected function prepareAllowHeaders($type, $requestHeaders, &$responseHeaders)
{
$requestHeaderField = 'Access-Control-Request-' . $type;
$responseHeaderField = 'Access-Control-Allow-' . $type;
if (!isset($requestHeaders[$requestHeaderField], $this->cors[$requestHeaderField])) {
return;
}
if (in_array('*', $this->cors[$requestHeaderField])) {
$responseHeaders[$responseHeaderField] = $this->headerize($requestHeaders[$requestHeaderField]);
} else {
$requestedData = preg_split('/[\\s,]+/', $requestHeaders[$requestHeaderField], -1, PREG_SPLIT_NO_EMPTY);
$acceptedData = array_uintersect($requestedData, $this->cors[$requestHeaderField], 'strcasecmp');
if (!empty($acceptedData)) {
$responseHeaders[$responseHeaderField] = implode(', ', $acceptedData);
}
}
}
/**
* 将 CORS 标头添加到响应中。
* @param Response $response
* @param array $headers 已计算的 CORS 标头
*/
public function addCorsHeaders($response, $headers)
{
if (empty($headers) === false) {
$responseHeaders = $response->getHeaders();
foreach ($headers as $field => $value) {
$responseHeaders->set($field, $value);
}
}
}
/**
* 将任何字符串(包括带 HTTP 前缀的 php headers)转换为头格式。
*
* 例如:
* - X-PINGOTHER -> X-Pingother
* - X_PINGOTHER -> X-Pingother
* @param string $string 要转换的字符串
* @return string 结果是 "header" 格式
*/
protected function headerize($string)
{
$headers = preg_split('/[\\s,]+/', $string, -1, PREG_SPLIT_NO_EMPTY);
$headers = array_map(function ($element) {
return str_replace(' ', '-', ucwords(strtolower(str_replace(['_', '-'], [' ', ' '], $element))));
}, $headers);
return implode(', ', $headers);
}
/**
* 将任何字符串(包括带 HTTP 前缀的 php headers)转换为头格式。
*
* 例如:
* - X-Pingother -> HTTP_X_PINGOTHER
* - X PINGOTHER -> HTTP_X_PINGOTHER
* @param string $string 要转换的字符串
* @return string 结果是 "php $_SERVER header" 格式
*/
protected function headerizeToPhp($string)
{
return 'HTTP_' . strtoupper(str_replace([' ', '-'], ['_', '_'], $string));
}
}
| {
"content_hash": "6db4367c8f293143ace18e2a3a6d1d9e",
"timestamp": "",
"source": "github",
"line_count": 270,
"max_line_length": 213,
"avg_line_length": 35,
"alnum_prop": 0.5632804232804233,
"repo_name": "yiichina/yii2",
"id": "71dace6aa13c8d282af8c70a94f41bd8a322e9fe",
"size": "10364",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework/filters/Cors.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1085"
},
{
"name": "CSS",
"bytes": "20"
},
{
"name": "Dockerfile",
"bytes": "3197"
},
{
"name": "HTML",
"bytes": "13353"
},
{
"name": "Hack",
"bytes": "4107"
},
{
"name": "JavaScript",
"bytes": "269260"
},
{
"name": "PHP",
"bytes": "6776439"
},
{
"name": "PLSQL",
"bytes": "20402"
},
{
"name": "Ruby",
"bytes": "207"
},
{
"name": "Shell",
"bytes": "5392"
},
{
"name": "TSQL",
"bytes": "85286"
}
],
"symlink_target": ""
} |
setTimeout(function(){
(function(){
id = Ti.App.Properties.getString("tisink", "");
var param, xhr;
file = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,"examples/table_view_api_controls.js");
text = (file.read()).text
xhr = Titanium.Network.createHTTPClient();
xhr.open("POST", "http://tisink.nodester.com/");
xhr.setRequestHeader("content-type", "application/json");
param = {
data: text,
file: "table_view_api_controls.js",
id: id
};
xhr.send(JSON.stringify(param));
})();
},0);
//TISINK----------------
// create table view data object
var data = [];
var ts1 = new Date().getTime();
function rightButtonClickHandler(e)
{
Ti.API.info("button click on row. index = "+e.index+", row = "+e.source.row+", section = "+e.source.section+",rightButton = "+rightButton);
}
function rowClickHandler(e)
{
Ti.API.info("row click on row. index = "+e.index+", row = "+e.row+", section = "+e.section+", source="+e.source);
}
function sectionClickHandler(e)
{
Ti.API.info("row click on section. index = "+e.index+", row = "+e.row+", section = "+e.section+", source="+e.source);
}
for (var c=0;c<10;c++)
{
data[c] = Ti.UI.createTableViewSection({headerTitle:'Group '+(c+1)});
for (var x=0;x<40;x++)
{
var label = Ti.UI.createLabel({
text:'Group '+(c+1)+', Row '+(x+1)+"\nThis is another line.\nCool",
height:'auto',
width:'auto',
left:10
});
var rightButton = Titanium.UI.createButton({
style:Titanium.UI.iPhone.SystemButton.INFO_DARK,
right:10,
row:x,
section:c
});
rightButton.addEventListener('click',rightButtonClickHandler);
var row = Ti.UI.createTableViewRow({height:'auto',className:'row'});
row.add(label);
row.add(rightButton);
data[c].add(row);
row.addEventListener('click',rowClickHandler);
}
data[c].addEventListener('click',sectionClickHandler);
}
var ts2 = new Date().getTime();
// create table view
var tableview = Titanium.UI.createTableView({
data:data,
style: Titanium.UI.iPhone.TableViewStyle.GROUPED,
//rowHeight:80,
minRowHeight:80
//maxRowHeight:500,
});
// create table view event listener
tableview.addEventListener('click', function(e)
{
Ti.API.info("row click on table view. index = "+e.index+", row = "+e.row+", section = "+e.section+", source="+e.source);
// event data
var index = e.index;
var section = e.section;
var row = e.row;
var rowdata = e.rowData;
Titanium.UI.createAlertDialog({title:'Table View',message:'row ' + row + ' index ' + index + ' section ' + section + ' row data ' + rowdata}).show();
});
// add table view to the window
Titanium.UI.currentWindow.add(tableview);
// this is simply a little window we show
// that displays the time it took to build the table and show it
var messageWin = Titanium.UI.createWindow({
height:30,
width:200,
bottom:70,
borderRadius:10,
touchEnabled:false,
opacity:0,
orientationModes : [
Titanium.UI.PORTRAIT,
Titanium.UI.UPSIDE_PORTRAIT,
Titanium.UI.LANDSCAPE_LEFT,
Titanium.UI.LANDSCAPE_RIGHT
]
});
var messageView = Titanium.UI.createView({
height:30,
width:200,
borderRadius:10,
backgroundColor:'#000',
opacity:0.7,
touchEnabled:false
});
var messageLabel = Titanium.UI.createLabel({
text:(ts2-ts1)+' ms',
color:'#fff',
width:200,
height:'auto',
font:{
fontFamily:'Helvetica Neue',
fontSize:13
},
textAlign:'center'
});
messageWin.add(messageView);
messageWin.add(messageLabel);
messageWin.open();
messageWin.animate({opacity:1,duration:800});
// close timer window after 4 seconds
setTimeout(function()
{
messageWin.animate({opacity:0,duration:800},function()
{
messageWin.close();
messageWin=null;
});
},4000);
// make sure to close window if this window is closed
Ti.UI.currentWindow.addEventListener('close',function()
{
if (messageWin)
{
messageWin.close();
}
}); | {
"content_hash": "04aa2ac83b8fcae07eff060999e39b19",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 151,
"avg_line_length": 24.8,
"alnum_prop": 0.6758584807492196,
"repo_name": "steerapi/KichenSinkLive",
"id": "5af05b32eb08f1cb991a7484eb49bac94fc4db2f",
"size": "3844",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Resources/examples/table_view_api_controls.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "628304"
},
{
"name": "Python",
"bytes": "321"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Qi4CS.Extensions.Configuration.Instance;
using System.Reflection;
using Qi4CS.Core.API.Model;
using Qi4CS.Core.API.Instance;
using Qi4CS.Core.SPI.Instance;
using System.Xml.Linq;
using CommonUtils;
using System.IO;
using System.Xml.XPath;
namespace Qi4CS.Extensions.Configuration.XML
{
/// <summary>
/// This enumeration describes whether XML serializer requests stream for serializing or deserializing.
/// </summary>
public enum SerializationAction
{
/// <summary>
/// XML serializer requests stream for serializing.
/// </summary>
SERIALIZING,
/// <summary>
/// XML serializer requests stream for deserializing.
/// </summary>
DESERIALIZING
}
/// <summary>
/// This is callback which will be used to get stream to write data to when serializing or deserializing.
/// </summary>
public interface StreamCallback
{
/// <summary>
/// This method should check whether it is possible to serialize or deserialize given configuration to given resource (usually file name).
/// </summary>
/// <param name="resource">The textual resource identifier, usually file path.</param>
/// <param name="serializationAction">Whether to serialize or deserialize the configuration.</param>
/// <param name="stream">If <c>true</c> is returned, then this should contain the stream which can be read or written, depending on whether deserializing or serializing process is in question. If return value is not <c>true</c>, this value is ignored.</param>
/// <returns><c>true</c> if it is possible to serialize or deserialize to given <paramref name="resource"/>; <c>false</c> otherwise.</returns>
Boolean TryGetStreamFor( String resource, SerializationAction serializationAction, out Stream stream );
}
internal class XMLConfigurationSerializer : ConfigurationSerializer
{
// private static readonly PropertyInfo LIST_ITEM_PROPERTY = TypeUtil.LoadPropertyOrThrow( typeof( IList<> ), "Item" );
// private static readonly MethodInfo LIST_ITEM_GETTER = LIST_ITEM_PROPERTY.GetGetMethod();
// private static readonly MethodInfo LIST_ITEM_SETTER = LIST_ITEM_PROPERTY.GetSetMethod();
private static readonly ConstructorInfo LIST_CTOR = typeof( List<> ).LoadConstructorOrThrow( 0 );
private static readonly MethodInfo LIST_ADD_METHOD = typeof( ICollection<> ).LoadMethodOrThrow( "Add", 1 );
private static readonly PropertyInfo DIC_ITEM_PROPERTY = typeof( IDictionary<,> ).LoadPropertyOrThrow( "Item" );
private static readonly MethodInfo DIC_ITEM_GETTER = DIC_ITEM_PROPERTY.GetGetMethod();
// private static readonly MethodInfo DIC_ITEM_SETTER = DIC_ITEM_PROPERTY.GetSetMethod();
private static readonly ConstructorInfo DIC_CTOR = typeof( Dictionary<,> ).LoadConstructorOrThrow( 0 );
private static readonly MethodInfo DIC_ADD_METHOD = typeof( IDictionary<,> ).LoadMethodOrThrow( "Add", 2 );
private static readonly PropertyInfo DIC_KEYS_PROPERTY = typeof( IDictionary<,> ).LoadPropertyOrThrow( "Keys" );
private static readonly MethodInfo DIC_KEYS_GETTER = DIC_KEYS_PROPERTY.GetGetMethod();
#pragma warning disable 649
[Uses]
private StreamCallback _streamCallback;
[Structure]
private StructureServiceProvider _ssp;
[Structure]
private ApplicationSPI _application;
[Uses]
private IList<XMLConfigurationSerializerHelper> _customSerializers;
#pragma warning restore 649
public virtual Object Deserialize( Type type, Qi4CSConfigurationResource resource )
{
var xmlResource = (XMLConfigurationResource) resource;
Stream fs; XDocument doc;
if ( this._streamCallback.TryGetStreamFor( xmlResource.DocumentResource, SerializationAction.DESERIALIZING, out fs ) )
{
using ( fs )
{
doc = XDocument.Load( fs );
}
}
else
{
throw new NotSupportedException( "Can not get stream for " + xmlResource.DocumentResource + "." );
}
XElement element;
var xpath = xmlResource.XPath;
if ( String.IsNullOrEmpty( xpath ) )
{
element = doc.Root;
}
else
{
// Get the actual element to deserialize from
element = doc.XPathSelectElement( xpath );
CheckForXPathElement( xpath, element );
}
Boolean dummy;
return this.Deserialize( type, element, null, out dummy );
}
public virtual void Serialize( Object contents, Qi4CSConfigurationResource resource )
{
var xmlResource = (XMLConfigurationResource) resource;
Stream fs;
XDocument existingFullDoc = null;
var xpath = xmlResource.XPath;
if ( !String.IsNullOrEmpty( xpath ) )
{
if ( this._streamCallback.TryGetStreamFor( xmlResource.DocumentResource, SerializationAction.DESERIALIZING, out fs ) )
{
using ( fs )
{
existingFullDoc = XDocument.Load( fs );
}
}
else
{
throw new NotSupportedException( "Can not get stream for " + xmlResource.DocumentResource + "." );
}
}
if ( this._streamCallback.TryGetStreamFor( xmlResource.DocumentResource, SerializationAction.SERIALIZING, out fs ) )
{
using ( fs )
{
var existingElement = existingFullDoc == null ? null : existingFullDoc.XPathSelectElement( xpath );
if ( existingFullDoc != null )
{
CheckForXPathElement( xpath, existingElement );
}
var type = this._application.GetCompositeInstance( contents ).ModelInfo.Model.PublicTypes.First();
var element = this.Serialize( contents, type, existingElement == null ? type.Name : existingElement.Name.LocalName, null );
if ( existingElement == null )
{
element.Save( fs );
}
else
{
existingElement.ReplaceWith( element );
existingFullDoc.Save( fs );
}
}
}
else
{
throw new NotSupportedException( "Can not get stream for " + xmlResource.DocumentResource + "." );
}
}
private Object Deserialize( Type type, XElement element, Object curVal, out Boolean replace )
{
replace = true;
if ( type.IsNullable( out type ) && String.IsNullOrEmpty( element.Value ) )
{
return null;
}
else if ( type.IsEnum )
{
return Enum.Parse( type, element.Value, true );
}
else
{
switch ( Type.GetTypeCode( type ) )
{
case TypeCode.Boolean:
Boolean parsedBool;
return Boolean.TryParse( element.Value, out parsedBool ) && parsedBool;
case TypeCode.Byte:
return Byte.Parse( element.Value );
case TypeCode.Char:
Char c;
if ( Char.TryParse( element.Value, out c ) )
{
return c;
}
else
{
throw new InvalidOperationException( "Failed to parse " + element.Value + " as character." );
}
case TypeCode.DateTime:
return DateTime.Parse( element.Value );
case TypeCode.Decimal:
return Decimal.Parse( element.Value );
case TypeCode.Double:
return Double.Parse( element.Value );
case TypeCode.Int16:
return Int16.Parse( element.Value );
case TypeCode.Int32:
return Int32.Parse( element.Value );
case TypeCode.Int64:
return Int64.Parse( element.Value );
case TypeCode.SByte:
return SByte.Parse( element.Value );
case TypeCode.Single:
return Single.Parse( element.Value );
case TypeCode.String:
return element.Value;
case TypeCode.UInt16:
return UInt16.Parse( element.Value );
case TypeCode.UInt32:
return UInt32.Parse( element.Value );
case TypeCode.UInt64:
return UInt64.Parse( element.Value );
case TypeCode.Object:
if ( typeof( System.Text.RegularExpressions.Regex ).Equals( type ) )
{
return new System.Text.RegularExpressions.Regex( element.Value );
}
// TODO parse XElement here.
else
{
var isGeneric = type.IsGenericType;
Object result;
if ( type.IsArray && type.GetArrayRank() == 1 )
{
var itemType = type.GetElementType();
var len = element.Elements().Count();
replace = curVal == null;
result = curVal ?? Array.CreateInstance( itemType, len );
var idx = 0;
foreach ( var el in element.Elements() )
{
Boolean dummy;
( (Array) result ).SetValue( this.Deserialize( itemType, el, null, out dummy ), idx );
++idx;
}
}
else if ( isGeneric && typeof( IList<> ).Equals( type.GetGenericTypeDefinition() ) )
{
var itemType = type.GetGenericArguments()[0];
replace = curVal == null;
result = curVal ?? ( (ConstructorInfo) MethodBase.GetMethodFromHandle( LIST_CTOR.MethodHandle, typeof( List<> ).MakeGenericType( itemType ).TypeHandle ) )
.Invoke( null );
var addMethod = MethodBase.GetMethodFromHandle( LIST_ADD_METHOD.MethodHandle, type.TypeHandle );
foreach ( var el in element.Elements() )
{
Boolean dummy;
addMethod.Invoke( result, new[] { this.Deserialize( itemType, el, null, out dummy ) } );
}
}
else if ( isGeneric && typeof( IDictionary<,> ).Equals( type.GetGenericTypeDefinition() ) )
{
var itemType = type.GetGenericArguments()[1];
replace = curVal == null;
result = curVal ?? ( (ConstructorInfo) MethodBase.GetMethodFromHandle( DIC_CTOR.MethodHandle, typeof( Dictionary<,> ).MakeGenericType( typeof( String ), itemType ).TypeHandle ) )
.Invoke( null );
var addMethod = MethodBase.GetMethodFromHandle( DIC_ADD_METHOD.MethodHandle, type.TypeHandle );
foreach ( var el in element.Elements() )
{
Boolean dummy;
addMethod.Invoke( result, new[] { el.Name.LocalName, this.Deserialize( itemType, el, null, out dummy ) } );
}
}
else
{
// Check custom serializers
result = null;
var deserialized = false;
foreach ( var cs in this._customSerializers )
{
if ( cs.CanDeserialize( element, type ) )
{
result = cs.Deserialize( element, type );
deserialized = true;
break;
}
}
if ( !deserialized )
{
// Parse recursively all content.
var resultBuilder = this._ssp.NewPlainCompositeBuilder( type );
var proto = resultBuilder.PrototypeFor( type );
foreach ( var prop in proto.GetType().GetAllParentTypes( false ).SelectMany( t => t.GetProperties( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.DeclaredOnly ) ) )
{
var propElement = element.Element( prop.Name );
if ( propElement != null )
{
Boolean replaceThis;
var newVal = this.Deserialize( prop.PropertyType, propElement, prop.GetGetMethod().Invoke( proto, null ), out replaceThis );
if ( replaceThis )
{
prop.GetSetMethod().Invoke( proto, new[] { newVal } );
}
}
}
result = resultBuilder.InstantiateWithType( type );
}
}
return result;
}
default:
throw new NotSupportedException( "Unsupported type code: " + Type.GetTypeCode( type ) + "." );
}
}
}
private XElement Serialize( Object obj, Type type, String elName, PropertyInfo currentProperty )
{
XElement result;
if ( obj != null )
{
result = new XElement( elName );
if ( typeof( System.Text.RegularExpressions.Regex ).Equals( type ) )
{
type = typeof( String );
}
type.IsNullable( out type );
switch ( Type.GetTypeCode( type ) )
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
result.Value = obj.ToStringSafe();
break;
case TypeCode.String:
result.Value = obj.ToStringSafe();
break;
case TypeCode.Object:
var isGeneric = type.IsGenericType;
if ( type.IsArray && type.GetArrayRank() == 1 )
{
var itemType = type.GetElementType();
foreach ( var item in (Array) obj )
{
result.AddIfNotNull( this.Serialize( item, itemType, GetItemTypeName( itemType, currentProperty ), null ) );
}
}
else if ( isGeneric && typeof( IList<> ).Equals( type.GetGenericTypeDefinition() ) )
{
var itemType = type.GetGenericArguments()[0];
foreach ( var item in (System.Collections.IEnumerable) obj )
{
result.AddIfNotNull( this.Serialize( item, itemType, GetItemTypeName( itemType, currentProperty ), null ) );
}
}
else if ( isGeneric && typeof( IDictionary<,> ).Equals( type.GetGenericTypeDefinition() ) )
{
var itemType = type.GetGenericArguments()[1];
var itemGetter = MethodBase.GetMethodFromHandle( DIC_ITEM_GETTER.MethodHandle, type.TypeHandle );
foreach ( var key in (System.Collections.IEnumerable) MethodBase.GetMethodFromHandle( DIC_KEYS_GETTER.MethodHandle, type.TypeHandle ).Invoke( obj, null ) )
{
result.AddIfNotNull( this.Serialize( itemGetter.Invoke( obj, new[] { key } ), itemType, key.ToString(), null ) );
}
}
else
{
// Check custom serializers
var serialized = false;
foreach ( var cs in this._customSerializers )
{
if ( cs.CanSerialize( obj, type ) )
{
cs.Serialize( obj, type, result );
serialized = true;
break;
}
}
if ( !serialized )
{
// Serialize recursively all properties
// Assume that this is Qi4CS composite instance -> get properties of all parent types (since this type is Qi4CS generated)
foreach ( var prop in obj.GetType().GetAllParentTypes( false ).SelectMany( t => t.GetProperties( BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly ) ) )
{
result.AddIfNotNull( this.Serialize( prop.GetGetMethod().Invoke( obj, null ), prop.PropertyType, prop.Name, prop ) );
}
}
}
break;
default:
throw new NotSupportedException( "Unsupported type code: " + Type.GetTypeCode( type ) + "." );
}
}
else
{
result = null;
}
return result;
}
private static String GetItemTypeName( Type itemType, PropertyInfo currentProperty )
{
//var ca = currentProperty == null ? null : currentProperty.GetCustomAttributes( true ).OfType<ListOrArrayElementNameAttribute>().FirstOrDefault();
return /*ca == null || String.IsNullOrEmpty( ca.ElementName ) ?*/ itemType.Name/* : ca.ElementName*/;
}
private static void CheckForXPathElement( String xpath, XElement element )
{
if ( element == null )
{
throw new NotSupportedException( "Could not find element with XPath \"" + xpath + "\"." );
}
}
}
/// <summary>
/// This interface provides required callbacks for XML configuration serializer to serialize custom types.
/// Typically each instance of this interface is provided for each type that needs to be serialized.
/// </summary>
public interface XMLConfigurationSerializerHelper
{
/// <summary>
/// Checks whether this <see cref="XMLConfigurationSerializerHelper"/> can serialize given object.
/// </summary>
/// <param name="obj">The object to serialize.</param>
/// <param name="type">The type of the object.</param>
/// <returns><c>true</c> if this <see cref="XMLConfigurationSerializerHelper"/> can serialize given object; <c>false</c> otherwise.</returns>
Boolean CanSerialize( Object obj, Type type );
/// <summary>
/// Performs serialization of the object with given parent <see cref="XElement"/>.
/// </summary>
/// <param name="obj">The object to serialize.</param>
/// <param name="type">The type of the object.</param>
/// <param name="parent">The parent <see cref="XElement"/>.</param>
void Serialize( Object obj, Type type, XElement parent );
/// <summary>
/// Checks whether this <see cref="XMLConfigurationSerializerHelper"/> can deserialize object of given type from given <see cref="XElement"/>.
/// </summary>
/// <param name="element">The <see cref="XElement"/> containing serialized data.</param>
/// <param name="type">The deserialized object type.</param>
/// <returns><c>true</c> if this <see cref="XMLConfigurationSerializerHelper"/> can deserialize object of given type from given <see cref="XElement"/>; <c>false</c> otherwise.</returns>
Boolean CanDeserialize( XElement element, Type type );
/// <summary>
/// Performs deserialization of the given <see cref="XElement"/> into object of given type.
/// </summary>
/// <param name="element">The <see cref="XElement"/> containing serialized data.</param>
/// <param name="type">The type of the object.</param>
/// <returns>Deserialized object of given type.</returns>
Object Deserialize( XElement element, Type type );
}
/// <summary>
/// This is helper class implementing <see cref="XMLConfigurationSerializerHelper"/> but performing all of its functionality through callbacks provided to constructor.
/// </summary>
public sealed class XMLConfigurationSerializerWithCallbacks : XMLConfigurationSerializerHelper
{
private readonly Func<Object, Type, Boolean> _canSerialize;
private readonly Action<Object, Type, XElement> _serialize;
private readonly Func<XElement, Type, Boolean> _canDeserialize;
private readonly Func<XElement, Type, Object> _deserialize;
/// <summary>
/// Creates new instance of <see cref="XMLConfigurationSerializerWithCallbacks"/> with given callbacks.
/// </summary>
/// <param name="canSerialize">The implementation for <see cref="XMLConfigurationSerializerHelper.CanSerialize"/> method.</param>
/// <param name="serialize">The implementation for <see cref="XMLConfigurationSerializerHelper.Serialize"/> method.</param>
/// <param name="canDeserialize">The implementation for <see cref="XMLConfigurationSerializerHelper.CanDeserialize"/> method.</param>
/// <param name="deserialize">The implementation for <see cref="XMLConfigurationSerializerHelper.Deserialize"/> method.</param>
/// <exception cref="ArgumentNullException">If any of <paramref name="canSerialize"/>, <paramref name="serialize"/>, <paramref name="canDeserialize"/>, or <paramref name="deserialize"/> is <c>null</c>.</exception>
public XMLConfigurationSerializerWithCallbacks(
Func<Object, Type, Boolean> canSerialize,
Action<Object, Type, XElement> serialize,
Func<XElement, Type, Boolean> canDeserialize,
Func<XElement, Type, Object> deserialize
)
{
ArgumentValidator.ValidateNotNull( "Serialization check callback", canSerialize );
ArgumentValidator.ValidateNotNull( "Serialization callback", serialize );
ArgumentValidator.ValidateNotNull( "Deserialization check callback", canDeserialize );
ArgumentValidator.ValidateNotNull( "Deserialization callback", deserialize );
this._canSerialize = canSerialize;
this._serialize = serialize;
this._canDeserialize = canDeserialize;
this._deserialize = deserialize;
}
/// <inheritdoc />
public Boolean CanSerialize( Object obj, Type type )
{
return this._canSerialize( obj, type );
}
/// <inheritdoc />
public void Serialize( Object obj, Type type, XElement parent )
{
this._serialize( obj, type, parent );
}
/// <inheritdoc />
public Boolean CanDeserialize( XElement element, Type type )
{
return this._canDeserialize( element, type );
}
/// <inheritdoc />
public Object Deserialize( XElement element, Type type )
{
return this._deserialize( element, type );
}
}
/// <summary>
/// This is default implementation for <see cref="StreamCallback"/> that will use file system to open streams.
/// </summary>
public class DotNETStreamHelper : StreamCallback
{
/// <inheritdoc />
public Boolean TryGetStreamFor( String resource, SerializationAction serializationAction, out Stream stream )
{
var retVal = SerializationAction.SERIALIZING == serializationAction ? true : File.Exists( resource );
var isSerializing = SerializationAction.SERIALIZING == serializationAction;
stream = retVal ? new FileStream(
resource,
isSerializing ? FileMode.Create : FileMode.Open,
isSerializing ? FileAccess.Write : FileAccess.Read,
isSerializing ? FileShare.None : FileShare.Read ) : null;
return retVal;
}
}
}
public static partial class E_Qi4CSConfigurationXML
{
internal static void AddIfNotNull( this XContainer container, XElement element )
{
if ( element != null )
{
container.Add( element );
}
}
}
| {
"content_hash": "025f2b8f2a0a682c07a63e24047903fc",
"timestamp": "",
"source": "github",
"line_count": 568,
"max_line_length": 265,
"avg_line_length": 45.346830985915496,
"alnum_prop": 0.5420662344217106,
"repo_name": "CometaSolutions/Qi4CS",
"id": "eb1c8ff5b64070e20b4c83eea572c70e398dd658",
"size": "26418",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Source/Qi4CS.Extensions.Configuration.XML/XMLConfigurationSerializer.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "2307526"
}
],
"symlink_target": ""
} |
package org.apache.tamaya.core;
import org.apache.tamaya.Configuration;
import org.apache.tamaya.PropertySource;
import org.apache.tamaya.core.properties.PropertySourceBuilder;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
/**
* Accessor that provides useful functions along with configuration.
*/
public final class ConfigurationFunctions {
/**
* Private singleton constructor.
*/
private ConfigurationFunctions() {
}
/**
* Creates a ConfigOperator that creates a Configuration containing only keys
* that are contained in the given area (non recursive). Hereby
* the area key is stripped away fromMap the resulting key.
*
* @param areaKey the area key, not null
* @return the area configuration, with the areaKey stripped away.
*/
public static UnaryOperator<PropertySource> selectArea(String areaKey) {
return selectArea(areaKey, true);
}
/**
* Creates a ConfigOperator that creates a Configuration containing only keys
* that are contained in the given area (non recursive).
*
* @param areaKey the area key, not null
* @param stripKeys if set to true, the area key is stripped away fromMap the resulting key.
* @return the area configuration, with the areaKey stripped away.
*/
public static UnaryOperator<PropertySource> selectArea(String areaKey, boolean stripKeys) {
return config -> {
Map<String, String> area = new HashMap<>();
area.putAll(
config.getProperties().entrySet().stream()
.filter(e -> isKeyInArea(e.getKey(), areaKey))
.collect(Collectors.toMap(
e -> stripKeys ? e.getKey().substring(areaKey.length() + 1) : e.getKey(),
Map.Entry::getValue)));
return Configuration.from(PropertySourceBuilder.of("area: " + areaKey).addMap(area).build());
};
}
/**
* Calculates the current area key and compares it with the given key.
*
* @param key the fully qualified entry key, not null
* @param areaKey the area key, not null
* @return true, if the entry is exact in this area
*/
public static boolean isKeyInArea(String key, String areaKey) {
int lastIndex = key.lastIndexOf('.');
String curAreaKey = lastIndex > 0 ? key.substring(0, lastIndex) : "";
return curAreaKey.equals(areaKey);
}
/**
* Return a query to evaluate the set with all fully qualifies area names. This method should return the areas as accurate as possible,
* but may not provide a complete set of areas that are finally accessible, especially when the underlying storage
* does not support key iteration.
*
* @return s set with all areas, never {@code null}.
*/
public static Function<PropertySource,Set<String>> getAreas() {
return config -> {
final Set<String> areas = new HashSet<>();
config.getProperties().keySet().forEach(s -> {
int index = s.lastIndexOf('.');
if (index > 0) {
areas.add(s.substring(0, index));
} else {
areas.add("<root>");
}
});
return areas;
};
}
/**
* Return a query to evaluate the set with all fully qualified area names, containing the transitive closure also including all
* subarea names, regardless if properties are accessible or not. This method should return the areas as accurate
* as possible, but may not provide a complete set of areas that are finally accessible, especially when the
* underlying storage does not support key iteration.
*
* @return s set with all transitive areas, never {@code null}.
*/
public static Function<PropertySource,Set<String>> getTransitiveAreas() {
return config -> {
final Set<String> transitiveAreas = new HashSet<>();
config.query(getAreas()).forEach(s -> {
int index = s.lastIndexOf('.');
if (index < 0) {
transitiveAreas.add("<root>");
} else {
while (index > 0) {
s = s.substring(0, index);
transitiveAreas.add(s);
index = s.lastIndexOf('.');
}
}
});
return transitiveAreas;
};
}
/**
* Return a query to evaluate the set with all fully qualified area names, containing only the
* areas that match the predicate and have properties attached. This method should return the areas as accurate as possible,
* but may not provide a complete set of areas that are finally accessible, especially when the underlying storage
* does not support key iteration.
*
* @param predicate A predicate to deternine, which areas should be returned, not {@code null}.
* @return s set with all areas, never {@code null}.
*/
public static Function<PropertySource,Set<String>> getAreas(final Predicate<String> predicate) {
return config -> config.query(getAreas()).stream().filter(predicate)
.collect(Collectors.toCollection(TreeSet::new));
}
/**
* Return a query to evaluate the set with all fully qualified area names, containing the transitive closure also including all
* subarea names, regardless if properties are accessible or not. This method should return the areas as accurate as possible,
* but may not provide a complete set of areas that are finally accessible, especially when the underlying storage
* does not support key iteration.
*
* @param predicate A predicate to deternine, which areas should be returned, not {@code null}.
* @return s set with all transitive areas, never {@code null}.
*/
public static Function<PropertySource,Set<String>> getTransitiveAreas(Predicate<String> predicate) {
return config -> config.query(getTransitiveAreas()).stream().filter(predicate)
.collect(Collectors.toCollection(TreeSet::new));
}
/**
* Return a query to evaluate to evaluate if an area exists. In case where the underlying storage implementation does not allow
* querying the keys available, {@code false} should be returned.
*
* @param areaKey the configuration area (sub)path.
* @return {@code true}, if such a node exists.
*/
public static Function<PropertySource,Boolean> containsArea(String areaKey) {
return config -> config.query(getAreas()).contains(areaKey);
}
/**
* Creates a ConfigOperator that creates a Configuration containing only keys
* that are contained in the given area (recursive). Hereby
* the area key is stripped away fromMap the resulting key.
*
* @param areaKey the area key, not null
* @return the area configuration, with the areaKey stripped away.
*/
public static UnaryOperator<PropertySource> selectAreaRecursive(String areaKey) {
return selectAreaRecursive(areaKey, true);
}
/**
* Creates a ConfigOperator that creates a Configuration containing only keys
* that are contained in the given area (recursive).
*
* @param areaKey the area key, not null
* @param stripKeys if set to true, the area key is stripped away fromMap the resulting key.
* @return the area configuration, with the areaKey stripped away.
*/
public static UnaryOperator<PropertySource> selectAreaRecursive(String areaKey, boolean stripKeys) {
return config -> {
Map<String, String> area = new HashMap<>();
String lookupKey = areaKey + '.';
area.putAll(
config.getProperties().entrySet().stream()
.filter(e -> e.getKey().startsWith(lookupKey))
.collect(Collectors.toMap(
e -> stripKeys ? e.getKey().substring(areaKey.length() + 1) : e.getKey(),
Map.Entry::getValue)));
return Configuration.from(PropertySourceBuilder.of("area (recursive): " + areaKey).addMap(area).build());
};
}
}
| {
"content_hash": "05112a8202bf3818bcaa965c0f86bd77",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 139,
"avg_line_length": 44.031088082901555,
"alnum_prop": 0.6281477994822311,
"repo_name": "johnament/tamaya",
"id": "1ddc301c354ccc2e1cae003815c14eb6f73b8f9a",
"size": "9305",
"binary": false,
"copies": "1",
"ref": "refs/heads/0.1-prototype",
"path": "core/src/main/java/org/apache/tamaya/core/ConfigurationFunctions.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "790672"
}
],
"symlink_target": ""
} |
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
#Parts for building a Mapserver URL
# Example: http://localhost/cgi-bin/mapserv.fcgi?map=/home/pi/code/rails/dummy/mapconfig/maps.example.com/naturalearth.map)
MAPSERV_SERVER = 'http://localhost' #nil for current application server
MAPSERV_URL = '/cgi-bin/mapserv.fcgi'
MAPSERV_CGI_URL = '/cgi-bin/mapserv'
MAPPATH = '/home/pi/code/rails/dummy/mapconfig'
MAPSERV_REDIRECT = true # Redirect public WMS to MAPSERV_SERVER URL
#Internal URL of print servlet (nil: print-standalone)
PRINT_URL = nil #'http://localhost:8080/mapfish_print/print/myapp'
| {
"content_hash": "328d0f2718e6dca005138920d1dd91ad",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 123,
"avg_line_length": 38.80769230769231,
"alnum_prop": 0.749587049884374,
"repo_name": "mapfish-appserver/gb_mapfish_appserver",
"id": "74ff7c0eb05a1b30ef9686fd4ae35ea3f13f8f8b",
"size": "3027",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/dummy/config/environments/production.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "147565"
},
{
"name": "HTML",
"bytes": "60273"
},
{
"name": "JavaScript",
"bytes": "394323"
},
{
"name": "Ruby",
"bytes": "225697"
}
],
"symlink_target": ""
} |
#include "InsertLineSegment.hh"
// #define USE_CDM 1
#include "Discretization/AddInteriorPoint.hh"
#if USE_CDM
#include "Discretization/ConstrainedDelaunayMesh.hh"
#else
#include "Discretization/DiscretizePolygon.hh"
#endif
#include "Discretization/RemoveBoundedRegion.hh"
#include "Shape/LineSegment.hh"
#include "Shape/LineSegmentUtilities.hh"
#include "Shape/Triangle.hh"
#include "Shape/TriangleUtilities.hh"
#include <array>
#include <cassert>
#include <map>
#include <vector>
#include <utility>
namespace Delaunay
{
namespace Discretization
{
namespace
{
const Mesh::Edge* GetEdge(const Mesh::Vertex* v1, const Mesh::Vertex* v2)
{
assert(v1);
assert(v2);
for (auto edge : v1->edges)
if (&edge->A() == v2 || &edge->B() == v2)
return edge;
return nullptr;
}
}
const Mesh::Edge* InsertLineSegment::operator()(const Shape::LineSegment& l,
Mesh::Mesh& mesh)
{
// TODO: deal with the case where l lies on preexisting edges (Touches() returns
// false, so 0 triangles are described as between the two points in this case)
// First, add the two points of the line segment
AddInteriorPoint addInteriorPoint;
const Mesh::Vertex* v1 = addInteriorPoint(l.A, mesh);
const Mesh::Vertex* v2 = addInteriorPoint(l.B, mesh);
if (v1 == nullptr || v2 == nullptr)
return nullptr;
// If there is already an edge present, mark it as a boundary and return
if (const Mesh::Edge* edge = GetEdge(v1,v2))
{
const_cast<Mesh::Edge*>(edge)->boundary = true;
return edge;
}
// Collect all of the triangles that contain the line
std::set<const Mesh::Triangle*> intersected(
this->FindContainingTriangles(l, mesh));
// Construct the containing polygon as the union of the containing triangles,
// and mark the polygon edges as boundary edges
std::set<Mesh::Edge*> temporaryBoundaries;
Shape::Polygon polygon(std::move(this->PolygonFromTriangleSet(intersected)));
for (Shape::PointList::const_iterator it = polygon.GetPoints().begin();
it != polygon.GetPoints().end(); ++it)
{
Shape::PointList::const_iterator next = std::next(it);
if (next == polygon.GetPoints().end())
next = polygon.GetPoints().begin();
const Mesh::Edge* edge =
GetEdge(static_cast<const Mesh::Vertex*>(&(*it).get()),
static_cast<const Mesh::Vertex*>(&(*next).get()));
if (!edge->boundary)
{
Mesh::Edge* e = const_cast<Mesh::Edge*>(edge);
e->boundary = true;
temporaryBoundaries.insert(e);
}
}
// Split the containing polygon along the edge we wish to insert
std::pair<Shape::Polygon,Shape::Polygon> polygons(
BisectPolygon(polygon, *v1, *v2));
// Identify the polygon's orientation
const Mesh::Edge* edge =
GetEdge(static_cast<const Mesh::Vertex*>(&(*polygon.GetPoints().begin()).get()),
static_cast<const Mesh::Vertex*>(&(*std::next(polygon.GetPoints().begin())).get()));
bool isCCW =
Shape::Dot(edge->B() - edge->A(),
*std::next(polygon.GetPoints().begin()) - *polygon.GetPoints().begin()) > 0.;
// Remove the containing polygon from the mesh
RemoveBoundedRegion removeBoundedRegion;
removeBoundedRegion(*edge, isCCW, mesh);
// Insert the bisected polygons into the mesh
#if USE_CDM
ConstrainedDelaunayMesh discretizePolygon;
#else
DiscretizePolygon discretizePolygon;
#endif
discretizePolygon(polygons.first, mesh);
discretizePolygon(polygons.second, mesh);
for (auto& e : temporaryBoundaries)
{
e->boundary = false;
}
return GetEdge(v1,v2);
}
Shape::Polygon InsertLineSegment::PolygonFromTriangleSet(
const Mesh::TriangleSet& triangleSet) const
{
typedef std::pair<const Mesh::Vertex*, const Mesh::Vertex*> OrderedEdge;
typedef std::map<OrderedEdge,std::size_t> EdgeHistogram;
typedef std::multimap<const Mesh::Vertex*, const Mesh::Vertex*> EdgeMap;
EdgeHistogram edgeCounter;
EdgeMap edges;
for (auto& triangle : triangleSet)
{
std::array<OrderedEdge,3> triEdges;
if (Shape::Orientation(triangle->AB().A(), triangle->AB().B(),
triangle->AC().B()) == 1)
{
triEdges[0] = std::make_pair(&triangle->AB().A(), &triangle->AB().B());
triEdges[1] = std::make_pair(&triangle->AB().B(), &triangle->AC().B());
triEdges[2] = std::make_pair(&triangle->AC().B(), &triangle->AB().A());
}
else
{
triEdges[0] = std::make_pair(&triangle->AB().A(), &triangle->AC().B());
triEdges[1] = std::make_pair(&triangle->AC().B(), &triangle->AB().B());
triEdges[2] = std::make_pair(&triangle->AB().B(), &triangle->AB().A());
}
for (auto& e : triEdges)
{
OrderedEdge eInv(e.second, e.first);
++(edgeCounter[e]);
if (edgeCounter[eInv] == 0)
{
edges.insert(e);
}
else if (edgeCounter[e] == 1)
{
std::pair<EdgeMap::iterator,
EdgeMap::iterator> range = edges.equal_range(eInv.first);
for (EdgeMap::iterator it = range.first; it != range.second; ++it)
{
if (it->second == eInv.second)
{
edges.erase(it);
break;
}
}
}
}
}
assert(!edges.empty());
Shape::PointList polyVertices;
EdgeMap::iterator edgeIt = edges.begin();
OrderedEdge edge = *(edgeIt);
const Mesh::Vertex* const firstVtx = edge.first;
do
{
polyVertices.push_back(
std::cref(static_cast<const Shape::Point&>(*edge.first)));
edgeIt = edges.find(edge.second);
edge = *(edgeIt);
edges.erase(edgeIt);
}
while (edge.first != firstVtx);
assert(edges.empty());
return Shape::Polygon(polyVertices);
}
namespace
{
bool Touches(const Shape::LineSegment& l, const Shape::Triangle& t)
{
return (Shape::Intersect(l, t) || Shape::Contains(t, l));
}
}
std::set<const Mesh::Triangle*> InsertLineSegment::FindContainingTriangles(
const Shape::LineSegment& l, Delaunay::Mesh::Mesh& mesh) const
{
const Mesh::Triangle* t1 = mesh.FindContainingTriangle(l.A);
std::set<const Mesh::Triangle*> intersected;
if (Touches(l, *t1))
intersected.insert(t1);
std::set<const Mesh::Triangle*> toSearch;
std::set<const Mesh::Triangle*> searched;
toSearch.insert(t1);
while (!toSearch.empty())
{
auto triIt = toSearch.begin();
const Mesh::Triangle* triangle = *triIt;
searched.insert(triangle);
toSearch.erase(triIt);
for (auto t : triangle->A().triangles)
{
if (searched.find(t) != searched.end())
continue;
if (Touches(l, *t))
{
intersected.insert(t);
toSearch.insert(t);
}
}
for (auto t : triangle->B().triangles)
{
if (searched.find(t) != searched.end())
continue;
if (Touches(l, *t))
{
intersected.insert(t);
toSearch.insert(t);
}
}
for (auto t : triangle->C().triangles)
{
if (searched.find(t) != searched.end())
continue;
if (Touches(l, *t))
{
intersected.insert(t);
toSearch.insert(t);
}
}
}
return intersected;
}
std::pair<Shape::Polygon,Shape::Polygon> InsertLineSegment::BisectPolygon(
const Shape::Polygon& p, const Mesh::Vertex& v1, const Mesh::Vertex& v2) const
{
Shape::PointList::const_iterator it1, it2;
std::size_t i1 = 0;
std::size_t i2 = 0;
for (it1 = p.GetPoints().begin(); *it1 != v1; ++it1, ++i1)
assert(it1 != p.GetPoints().end());
for (it2 = p.GetPoints().begin(); *it2 != v2; ++it2, ++i2)
assert(it2 != p.GetPoints().end());
if (i1 > i2)
std::swap(it1,it2);
Shape::PointList p1(it1,std::next(it2));
Shape::PointList p2(it2,p.GetPoints().end());
p2.insert(p2.end(), p.GetPoints().begin(), std::next(it1));
return std::make_pair(Shape::Polygon(p1),Shape::Polygon(p2));
}
}
}
| {
"content_hash": "36ca42a49f8e74e2557e963f65349ff7",
"timestamp": "",
"source": "github",
"line_count": 293,
"max_line_length": 96,
"avg_line_length": 26.747440273037544,
"alnum_prop": 0.626387648334822,
"repo_name": "tjcorona/Delaunay",
"id": "7dcacb486f7b5d5e6dfed013ebcc039d248c631a",
"size": "8468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/Discretization/InsertLineSegment.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "289964"
},
{
"name": "CMake",
"bytes": "14570"
}
],
"symlink_target": ""
} |
class OfferEvent < ActiveRecord::Base
belongs_to :offer
validates :offer, presence: true
validates :status, presence: true,
inclusion: { in: %w(CREATED SENT WITHDRAWN RETURNED RESENT ACCEPTED REJECTED) }
validates :description, presence: true
validates :created_at, presence: true
end
| {
"content_hash": "997975103697506e8c09565618884941",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 100,
"avg_line_length": 35.22222222222222,
"alnum_prop": 0.7097791798107256,
"repo_name": "talosdigital/TDJobs",
"id": "eb7618c6f6849b8314c20bf42bde00a9540bf919",
"size": "380",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/offer_event.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "242711"
}
],
"symlink_target": ""
} |
---
layout: post
title: "Présentation de la librairie PHP Xpression"
lang: fr
permalink: /fr/presentation-php-xpression/
excerpt: "En tant que développeur nous avons tous déjà eu besoin de filtrer un jeu de donnés (array, collection, API etc...). Nous allons découvrir la librairie Xpression qui va nous permettre de filtrer différents contenus avec une syntaxe simplifiée."
authors:
- amoutte
categories:
- php
- library
- symfony
- query
- filter
- querybuilder
- doctrine
- orm
- odm
- expression
- collection
tags:
- php
- library
- symfony
- query
- filter
- doctrine
- querybuilder
- orm
- odm
- expression
- collection
cover: /assets/2018-07-11-xpression/cover.jpg
---
## Présentation de Xpression
[**Xpression**](https://github.com/Symftony/Xpression) est un parser qui convertit une expression textuelle ([DSL](https://fr.wikipedia.org/wiki/Langage_d%C3%A9di%C3%A9)) en une expression logicielle (**pattern spécification**).
Nous allons voir ce que permet de faire la librairie et comment l'utiliser.
## La syntaxe
Voici plusieurs exemples d'expressions que nous pouvons écrire :
L'âge doit être égal à `26`.
{% raw %}
```
age=26
```
{% endraw %}
L'âge doit être supérieur à `20` (inclus) et inférieur à `30` (exclus).
{% raw %}
```
age≥20&age<30
```
{% endraw %}
Voici la liste des opérateurs supportés par les différents bridges :
Opérateur | Syntaxes | Exemples | ORM | ODM | ArrayCollection | Closure |
-------- | ------ | ------- | --- | --- | --------------- | ------- |
égal | `=` | `param=value` | X | X | X | X |
différent de | `!=` `≠` | `param!=value` `param≠value` | X | X | X | X |
plus grand que | `>` | `param>value` | X | X | X | X |
plus grand ou égal | `>=` `≥` | `param>=value` `param≥value` | X | X | X | X |
plus petit que | `<` | `param<value` | X | X | X | X |
plus petit ou égal | `<=` `≤` | `param<=value` `param≤value` | X | X | X | X |
dans | `[` `]` | `param[value1,value2]` | X | X | X | X |
contient | `{% raw %}{{{% endraw %}` `{% raw %}}}{% endraw %}` | `{% raw %}param{{value}}{% endraw %}` | X | X | | X |
ne contient pas | `{% raw %}!{{{% endraw %}` `{% raw %}}}{% endraw %}` | `{% raw %}param!{{value}}{% endraw %}` | X | X | | X |
et | `&` | `param>1¶m<10` | X | X | X | X |
non et | `!&` | `param>1!¶m<10` | | X | | X |
ou | <code>|</code> | <code>param>1|param<10</code> | X | X | X | X |
non ou | <code>!|</code> | <code>param>1!|param<10</code> | | | | X |
ou exclusif | <code>^|</code> `⊕` | <code>param>1^|param<10</code> `param>1⊕param<10` | | | | X |
> Eh oui, la librairie fournit aussi des bridges vers doctrine `ORM`, `ODM` et `common` (pour filter les collections).
#### Précédence des opérateurs de composition
Il faut faire attention à la priorité des opérateurs de compositions (`&`, `!&`, `|`, `!|`, `⊕`).
Les grandes priorités sont prises en compte en premier.
- `et`: 15
- `non et`: 14
- `ou`: 10
- `ou exclusif`: 9
- `not or`: 8
Pour gérer correctement vos expressions vous pouvez utiliser les parenthèses `(` `)`.
Par exemple, cette expression sélectionnera les `Raccoon` ou les `Schizo` qui ont plus de 100 points.
`planet='Raccoon'|name='Schizo'&point>100` est identique à `planet='Raccoon'|(name='Schizo'&point>100)`
Alors que l'expression suivante sélectionnera les astronautes `Raccoon` qui ont plus de 100 points ou les `Schizo` qui on plus de 100 points.
`(planet='Raccoon'|name='Schizo')&point>100`
## Utilisation
Nous allons maintenant voir dans quels cas nous pourrions utiliser cette librairie.
### Spécification
Afin d'avoir une spécification nous allons utiliser la classe `ClosureExpressionBuilder`.
En effet cette classe fabrique une callback qui peut être utilisée comme une spécification.
{% raw %}
```php
<?php
use Symftony\Xpression\Expr\ClosureExpressionBuilder;
use Symftony\Xpression\Parser;
// classe avec des getter
class Astronaut {
private $name;
private $planet;
private $points;
private $rank;
public function __construct($name, $planet, $points, $rank)
{
$this->name = $name;
$this->planet = $planet;
$this->points = $points;
$this->rank = $rank;
}
public function getName()
{
return $this->name;
}
public function getPlanet()
{
return $this->planet;
}
public function getPoints()
{
return $this->points;
}
public function getRank()
{
return $this->rank;
}
}
// objet avec des propriétés publiques
$astronaut1 = new \stdClass();
$astronaut1->name = 'Mehdy';
$astronaut1->planet = 'Raccoons of Asgard';
$astronaut1->points = 675;
$astronaut1->rank = 'Captain';
$query = 'planet{{Raccoons}}|points≥1000';
$parser = new Parser(new ClosureExpressionBuilder());
$specification = $parser->parse($query);
$specification(['name' => 'Arnaud', 'planet' => 'Duck Invaders', 'points' => 785, 'rank' => 'Fleet Captain']); // false
$specification($astronaut1);// true
$specification(new Astronaut('Ilan', 'Donut Factory', 1325, 'Commodore')); // true
```
{% endraw %}
Comme vous pouvez le voir, la spécification est appelable avec un array associatif, des objets avec des attributs publics mais aussi avec des objets qui ont des getters.
### Filtrer un jeu de donnés
Nous allons dans un premier temps filtrer un tableau de données.
Pour ce faire nous allons encore utiliser `ClosureExpressionBuilder`
Nous allons utiliser ces données pour les exemples suivants :
{% raw %}
```php
<?php
$astronauts = [
['name' => 'Jonathan', 'planet' => 'Duck Invaders', 'points' => 5505, 'rank' => 'Fleet Admiral'],
['name' => 'Thierry', 'planet' => 'Duck Invaders', 'points' => 2555, 'rank'=> 'Vice Admiral'],
['name' => 'Vincent', 'planet' => 'Donut Factory', 'points' => 1885, 'rank' => 'Rear Admiral'],
['name' => 'Rémy', 'planet' => 'Schizo Cats', 'points' => 1810, 'rank' => 'Rear Admiral'],
['name' => 'Charles Eric', 'planet' => 'Donut Factory', 'points' => 1385, 'rank' => 'Commodore'],
['name' => 'Ilan', 'planet' => 'Donut Factory', 'points' => 1325, 'rank' => 'Commodore'],
['name' => 'Alexandre', 'planet' => 'Schizo Cats', 'points' => 1135, 'rank' => 'Commodore'],
['name' => 'Noel', 'planet' => 'Duck Invaders', 'points' => 960, 'rank' => 'Fleet Captain'],
['name' => 'Damien', 'planet' => 'Donut Factory', 'points' => 925, 'rank' => 'Fleet Captain'],
['name' => 'Quentin', 'planet' => 'Donut Factory', 'points' => 910, 'rank' => 'Fleet Captain'],
['name' => 'Martin', 'planet' => 'Schizo Cats', 'points' => 860, 'rank' => 'Fleet Captain'],
['name' => 'Carl', 'planet' => 'Donut Factory', 'points' => 800, 'rank' => 'Fleet Captain'],
['name' => 'Arnaud', 'planet' => 'Duck Invaders', 'points' => 785, 'rank' => 'Fleet Captain'],
['name' => 'Alexandre', 'planet' => 'Donut Factory', 'points' => 785, 'rank' => 'Fleet Captain'],
['name' => 'Thibaud', 'planet' => 'Raccoons of Asgard', 'points' => 760, 'rank' => 'Fleet Captain'],
['name' => 'Romain', 'planet' => 'Donut Factory', 'points' => 735, 'rank' => 'Captain'],
['name' => 'Julie', 'planet' => 'Donut Factory', 'points' => 735, 'rank' => 'Captain'],
['name' => 'Cedric', 'planet' => 'Donut Factory', 'points' => 700, 'rank' => 'Captain'],
['name' => 'Mehdy', 'planet' => 'Raccoons of Asgard', 'points' => 675, 'rank' => 'Captain'],
['name' => 'Romain', 'planet' => 'Raccoons of Asgard', 'points' => 550, 'rank' => 'Captain'],
];
```
{% endraw %}
Je veux récupérer les astronautes dont la planète contient 'Raccoons'.
{% raw %}
```php
<?php
use Symftony\Xpression\Expr\ClosureExpressionBuilder;
use Symftony\Xpression\Parser;
// jeu de données
$astronauts = [...];
$query = 'planet{{Raccoons}}';
$parser = new Parser(new ClosureExpressionBuilder());
$expression = $parser->parse($query);
$filteredAstronauts = array_filter($astronauts, $expression);
// le tableau ne contient que les astronautes dont la planète contient 'Raccoons'
// $filteredAstronauts = [
// ['name' => 'Thibaud', 'planet' => 'Raccoons of Asgard', 'points' => 760, 'rank' => 'Fleet Captain'],
// ['name' => 'Mehdy', 'planet' => 'Raccoons of Asgard', 'points' => 675, 'rank' => 'Captain'],
// ['name' => 'Romain', 'planet' => 'Raccoons of Asgard', 'points' => 550, 'rank' => 'Captain'],
// ];
```
{% endraw %}
> La subtilité dans l'exemple précédent c'est que l'on utilise `$expression` dans un `array_filter`.
Maintenant je veux sélectionner les astronautes qui ont plus de 1000 points mais aussi les `Raccoons`.
{% raw %}
```php
<?php
use Symftony\Xpression\Expr\ClosureExpressionBuilder;
use Symftony\Xpression\Parser;
// jeu de données
$astronauts = [...];
$query = 'planet{{Raccoons}}|points≥1000';
$parser = new Parser(new ClosureExpressionBuilder());
$expression = $parser->parse($query);
$filteredAstronauts = array_filter($astronauts, $expression);
// le tableau contient tous les astronautes qui ont au moins 1000 points, mais aussi les 'Raccoons'
// $filteredAstronauts = [
// ['name' => 'Jonathan', 'planet' => 'Duck Invaders', 'points' => 5505, 'rank' => 'Fleet Admiral'],
// ['name' => 'Thierry', 'planet' => 'Duck Invaders', 'points' => 2555, 'rank'=> 'Vice Admiral'],
// ['name' => 'Vincent', 'planet' => 'Donut Factory', 'points' => 1885, 'rank' => 'Rear Admiral'],
// ['name' => 'Rémy', 'planet' => 'Schizo Cats', 'points' => 1810, 'rank' => 'Rear Admiral'],
// ['name' => 'Charles Eric', 'planet' => 'Donut Factory', 'points' => 1385, 'rank' => 'Commodore'],
// ['name' => 'Ilan', 'planet' => 'Donut Factory', 'points' => 1325, 'rank' => 'Commodore'],
// ['name' => 'Alexandre', 'planet' => 'Schizo Cats', 'points' => 1135, 'rank' => 'Commodore'],
// ['name' => 'Thibaud', 'planet' => 'Raccoons of Asgard', 'points' => 760, 'rank' => 'Fleet Captain'],
// ['name' => 'Mehdy', 'planet' => 'Raccoons of Asgard', 'points' => 675, 'rank' => 'Captain'],
// ['name' => 'Romain', 'planet' => 'Raccoons of Asgard', 'points' => 550, 'rank' => 'Captain'],
// ];
```
{% endraw %}
### Filtrer une ArrayCollection
Pour filtrer une ArrayCollection il suffit d'utiliser le bridge `Symftony\Xpression\Bridge\Doctrine\Common\ExpressionBuilderAdapter`.
{% raw %}
```php
<?php
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\ExpressionBuilder;
use Symftony\Xpression\Bridge\Doctrine\Common\ExpressionBuilderAdapter;
use Symftony\Xpression\Parser;
// jeu de données
$astronauts = [...];
// on wrap l'array dans une `ArrayCollection`
$astronauts = new ArrayCollection($astronauts);
$parser = new Parser(new ExpressionBuilderAdapter(new ExpressionBuilder()));
$expression = $parser->parse($query);
$filteredAstronauts = $astronauts->matching(new Criteria($expression));
```
{% endraw %}
> ℹ️ Les `ArrayCollection` sont les objets utilisés par doctrine pour les relations (oneToMany, manyToMany etc...).
> Pour filtrer une `Collection` vous pouvez utiliser `ClosureExpressionBuilder` vu précédemment et l'injecter dans `Collection::filter(Closure $p)`.
### Filtrer des données stockées en base
#### Doctrine ODM
Bien, maintenant imaginons que ces données soient dans une base de données MongoDB.
> Accrochez-vous, ça va être compliqué !
{% raw %}
```php
<?php
use Doctrine\Common\EventManager;
use Doctrine\MongoDB\Connection;
use Doctrine\MongoDB\Database;
use Symftony\Xpression\Bridge\Doctrine\MongoDb\ExprBuilder;
use Symftony\Xpression\Expr\ClosureExpressionBuilder;
use Symftony\Xpression\Parser;
// Initialisation de la connexion
$connection = new Connection('mongodb://localhost');
$database = $connection->selectDatabase('eleven-labs');
$collection = $database->selectCollection('astronauts');
$query = 'planet{{Raccoons}}|points≥1000';
$parser = new Parser(new ExprBuilder());
$queryBuilder = $parser->parse($query);
$astronauts = $collection->createQueryBuilder()->setQueryArray($queryBuilder->getQuery())->getQuery()->execute();
// $astronauts est un Doctrine\MongoDB\Cursor
// iterator_to_array($astronauts) = [
// ['name' => 'Jonathan', 'planet' => 'Duck Invaders', 'points' => 5505, 'rank' => 'Fleet Admiral'],
// ['name' => 'Thierry', 'planet' => 'Duck Invaders', 'points' => 2555, 'rank'=> 'Vice Admiral'],
// ['name' => 'Vincent', 'planet' => 'Donut Factory', 'points' => 1885, 'rank' => 'Rear Admiral'],
// ['name' => 'Rémy', 'planet' => 'Schizo Cats', 'points' => 1810, 'rank' => 'Rear Admiral'],
// ['name' => 'Charles Eric', 'planet' => 'Donut Factory', 'points' => 1385, 'rank' => 'Commodore'],
// ['name' => 'Ilan', 'planet' => 'Donut Factory', 'points' => 1325, 'rank' => 'Commodore'],
// ['name' => 'Alexandre', 'planet' => 'Schizo Cats', 'points' => 1135, 'rank' => 'Commodore'],
// ['name' => 'Thibaud', 'planet' => 'Raccoons of Asgard', 'points' => 760, 'rank' => 'Fleet Captain'],
// ['name' => 'Mehdy', 'planet' => 'Raccoons of Asgard', 'points' => 675, 'rank' => 'Captain'],
// ['name' => 'Romain', 'planet' => 'Raccoons of Asgard', 'points' => 550, 'rank' => 'Captain'],
// ];
```
{% endraw %}
> Ha bah non ! C'est super simple en fait
#### Doctrine ORM
Et pour doctrine/orm alors ?
{% raw %}
```php
<?php
use Doctrine\ORM\Tools\Setup;
use Symftony\Xpression\Bridge\Doctrine\ORM\ExprAdapter;
use Symftony\Xpression\Expr\MapperExpressionBuilder;
use Symftony\Xpression\Parser;
// dans cet exemple j'utilise l'annotation reader pour la configuration de mon schéma
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/Orm/Entity"), true, null, null, false);
$entityManager = EntityManager::create(array(
// votre configuration d'accès à votre base de donnés
'driver' => 'pdo_sqlite',
'path' => __DIR__ . '/ORM/astronauts.sqlite',
), $config);
$query = 'planet{{Raccoons}}|points≥1000';
// utilisation de MapperExpressionBuilder pour ajouter dynamiquement l'alias `a` aux champs de la query
$parser = new Parser(new MapperExpressionBuilder(new ExprAdapter(new Expr()), ['*' => 'a.%s']));
$expression = $parser->parse($query);
$qb = $entityManager->getRepository('Example\Orm\Entity\Product')->createQueryBuilder('a');
$astronauts = $qb->where($expression)->getQuery()->execute();
// $astronauts = [
// ['name' => 'Jonathan', 'planet' => 'Duck Invaders', 'points' => 5505, 'rank' => 'Fleet Admiral'],
// ['name' => 'Thierry', 'planet' => 'Duck Invaders', 'points' => 2555, 'rank'=> 'Vice Admiral'],
// ['name' => 'Vincent', 'planet' => 'Donut Factory', 'points' => 1885, 'rank' => 'Rear Admiral'],
// ['name' => 'Rémy', 'planet' => 'Schizo Cats', 'points' => 1810, 'rank' => 'Rear Admiral'],
// ['name' => 'Charles Eric', 'planet' => 'Donut Factory', 'points' => 1385, 'rank' => 'Commodore'],
// ['name' => 'Ilan', 'planet' => 'Donut Factory', 'points' => 1325, 'rank' => 'Commodore'],
// ['name' => 'Alexandre', 'planet' => 'Schizo Cats', 'points' => 1135, 'rank' => 'Commodore'],
// ['name' => 'Thibaud', 'planet' => 'Raccoons of Asgard', 'points' => 760, 'rank' => 'Fleet Captain'],
// ['name' => 'Mehdy', 'planet' => 'Raccoons of Asgard', 'points' => 675, 'rank' => 'Captain'],
// ['name' => 'Romain', 'planet' => 'Raccoons of Asgard', 'points' => 550, 'rank' => 'Captain'],
// ];
```
{% endraw %}
⚠️ Lorsque l'on crée un queryBuilder avec l'ORM il faut spécifier un alias `EntityRepository::createQueryBuilder($alias)`. C'est pourquoi il ne reconnait pas le champ `planet` dans la query.
La première solution serait d'écrire les champs avec l'alias dans la query initiale ce qui donnerait `a.planet{{Raccoons}}|a.points≥1000`. Le problème de cet approche c'est que des informations de structure de base de données leakent dans la query.
La seconde solution est d'utiliser la classe `MapperExpressionBuilder`. En effet cette classe va décorer l'`ExpressionBuilder` pour ajouter les alias directement au moment où le queryBuilder va être configuré.
Dans l'exemple suivant on indique que tous les champs (`*`) de la query sont préfixés avec `a.`.
{% raw %}
```php
$parser = new Parser(
new MapperExpressionBuilder(
new ExprAdapter(new Expr()),
['*' => 'a.%s']
)
);
```
{% endraw %}
### Filtrer un endpoint d'API
Actuellement si vous voulez filtrer votre API vous pouvez :
- utiliser GraphQL.
> Ce n'est pas la solution la plus légère à implementer. N'est pas forcément adaptée pour faire uniquement du filtrage de données.
- récupérer les paramètres de requête manuellement et fabriquer votre query avec tous un tas de condition
> la syntaxe http des paramètres n'est pas lisible et peut devenir très lourde pour des requêtes complexes.
Bonne nouvelle ! Si votre API utilise une des sources de données vu précédemment, vous pouvez filtrer les données à l'aide d'`Xpression`.
> Gardez à l'esprit que Xpression remplit un rôle différent de GraphQL
Nous allons voir un exemple d'utilisation du [Bundle Xpression](https://github.com/Symftony/Xpression-Bundle).
Installez le bundle via `composer require symftony/xpression-bundle` puis ajoutez-le dans symfony (AppKernel.php ou bundle.php).
Il faut également activer la correction de querystring pour que les caractères réservés soient correctement utilisés.
{% raw %}
```php
<?php
// public/index.php ou web/app.php (web/app_dev.php)
// ...
\Symftony\Xpression\QueryStringParser::correctServerQueryString(); // ajoutez cette ligne juste avant la création de la Requete
$request = Request::createFromGlobals();
// ...
```
{% endraw %}
Pour l'utiliser il vous suffit uniquement d'ajouter l'annotation `@Xpression(expressionBuilder="odm")` au-dessus du controller que vous souhaitez filtrer.
{% raw %}
```php
<?php
namespace App\Controller;
use App\Document\Astronaut;
use App\Repository\AstronautsRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symftony\XpressionBundle\Annotations\Xpression;
class AstronautController extends AbstractController
{
/**
* @Xpression(expressionBuilder="odm")
*
* @return JsonResponse
*/
public function list(AstronautsRepository $astronautsRepository, $query = null)
{
$qb = $astronautsRepository->createQueryBuilder();
if (null !== $query) {
$qb->setQueryArray($query->getQuery());
}
return $this->json($qb->getQuery()->execute());
}
}
```
{% endraw %}
Vous pouvez également configurer les options suivantes :
- source (la source de la query (request, query, attributes, cookies, files, server, headers default: query))
- sourceName (le nom du param, dans la source, qui contient l'expression default:query)
- targetName (le nom de l'argument a injecter dans le controller default:query)
- expressionBuilder (le nom de l'expressionBuilder à utiliser *requis*)
Maintenant vous pouvez vous rendre sur votre URL et y ajouter votre Xpression dans `query`.
{% raw %}
```
http://localhost/astronauts/list?query={planet{{Raccoons}}|points≥1000}
```
{% endraw %}
### Mots de la fin
Je vais m'arrêter là pour la présentation de cette librairie PHP.
Je vous invite à tester la librairie et à y contribuer (idée, bugs, features, documentation, etc).
Voici une petite liste des futures ajouts dans la librairie :
- fixer l'utilisation des paramètres de query (placeholder).
- créer d'autre bridges.
- refacto le coeur de la librairie afin d'être extensible (pouvoir ajouter des syntaxes).
- implémenter un builder de query en PHP et JS afin de pouvoir créer directement le query textuel.
### Liens utiles
- [Demo Xpression](http://symftony-xpression.herokuapp.com/)
- [Code source Xpression](https://github.com/Symftony/Xpression)
- [Code source Xpression-bundle](https://github.com/Symftony/Xpression-Bundle)
| {
"content_hash": "0c8d63fc13f0649d3b4c14b58f165d5e",
"timestamp": "",
"source": "github",
"line_count": 503,
"max_line_length": 253,
"avg_line_length": 39.64811133200795,
"alnum_prop": 0.6525597954169383,
"repo_name": "eleven-labs/eleven-labs.github.io",
"id": "c7af5c5732dde79a2a88e7838d177f696c50d1b1",
"size": "20116",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/fr/2018-07-11-xpression.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15106"
},
{
"name": "HTML",
"bytes": "36927"
},
{
"name": "JavaScript",
"bytes": "4311"
},
{
"name": "Ruby",
"bytes": "3753"
},
{
"name": "Shell",
"bytes": "4627"
}
],
"symlink_target": ""
} |
EPUBJS.reader.BookmarksController = function() {
var reader = this;
var book = this.book;
var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;
var eventName = supportsTouch?"touchstart":"click";
var $bookmarks = $("#bookmarksView"),
$list = $bookmarks.find("#bookmarks");
var docfrag = document.createDocumentFragment();
var show = function() {
$bookmarks.show();
};
var hide = function() {
$bookmarks.hide();
};
var hashCode = function(s) {
var hash = 0, i, chr, len;
if (s.length == 0) return hash;
for (i = 0, len = s.length; i < len; i++) {
chr = s.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash.toString();
};
var createBookmarkItem = function(bm) {
var listitem = document.createElement("li"),
link = document.createElement("a"),
rm = document.createElement("div");
listitem.id = "bookmark-"+hashCode(bm.cfi);
listitem.classList.add('list_item');
link.textContent = bm.text || "";
link.href = bm.cfi;
link.classList.add('bookmark_link');
link.addEventListener(eventName, function(event){
var cfi = this.getAttribute('href');
book.gotoCfi(cfi);
event.preventDefault();
}, false);
rm.classList.add('bookmark_remove');
rm.innerHTML = " ";
rm.setAttribute('data-cfi', bm.cfi);
rm.addEventListener(eventName, function(event){
var cfi = this.getAttribute('data-cfi');
reader.removeBookmark(cfi);
}, false);
listitem.appendChild(rm);
listitem.appendChild(link);
return listitem;
};
this.settings.bookmarks.forEach(function(bm) {
var bookmark = createBookmarkItem(bm);
docfrag.appendChild(bookmark);
});
$list.append(docfrag);
this.on("reader:bookmarked", function(bm) {
var item = createBookmarkItem(bm);
$list.append(item);
});
this.on("reader:unbookmarked", function(index, cfi) {
var $item = $("#bookmark-"+hashCode(cfi) );
$item.remove();
});
return {
"show" : show,
"hide" : hide
};
}; | {
"content_hash": "a6b95d5bef3d9271a2786fec8497a9ee",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 76,
"avg_line_length": 23.953488372093023,
"alnum_prop": 0.6388349514563106,
"repo_name": "adn-tm/epub.js",
"id": "af4c1490cb2644a79532659392c54d263b24b238",
"size": "2060",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "reader_src/controllers/bookmarks_controller.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "43480"
},
{
"name": "HTML",
"bytes": "1360872"
},
{
"name": "JavaScript",
"bytes": "1121105"
}
],
"symlink_target": ""
} |
Nothing to see here, move along.
In all seriousness, the subcommand part of bini is designed to have the commands wrapped in a gem. This is a gem with a few fake commands, so I can test bini properly.
There is literally, nothing to see here.
Move along :wink:
| {
"content_hash": "a99bee65eefde51c26e3bbe65e625661",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 168,
"avg_line_length": 37.714285714285715,
"alnum_prop": 0.7613636363636364,
"repo_name": "erniebrodeur/bini-test-subcommand",
"id": "31a10edf0bcaefeba50291224b192fe7bac4ce9f",
"size": "290",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "1097"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>cats-in-zfc: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.12.2 / cats-in-zfc - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
cats-in-zfc
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-09-24 11:57:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-24 11:57:39 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.12.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/cats-in-zfc"
license: "LGPL 2"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/CatsInZFC"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [
"keyword:set theory"
"keyword:ordinal numbers"
"keyword:cardinal numbers"
"keyword:category theory"
"keyword:functors"
"keyword:natural transformation"
"keyword:limit"
"keyword:colimit"
"category:Mathematics/Logic/Set theory"
"category:Mathematics/Category Theory"
"date:2004-10-10"
]
authors: [ "Carlos Simpson <carlos@math.unice.fr>" ]
bug-reports: "https://github.com/coq-contribs/cats-in-zfc/issues"
dev-repo: "git+https://github.com/coq-contribs/cats-in-zfc.git"
synopsis: "Category theory in ZFC"
description: """
In a ZFC-like environment augmented by reference to the
ambient type theory, we develop some basic set theory, ordinals, cardinals
and transfinite induction, and category theory including functors,
natural transformations, limits and colimits, functor categories,
and the theorem that functor_cat a b has (co)limits if b does."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/cats-in-zfc/archive/v8.5.0.tar.gz"
checksum: "md5=c3a5b3529803919d553d498becba3a4a"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-cats-in-zfc.8.5.0 coq.8.12.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.12.2).
The following dependencies couldn't be met:
- coq-cats-in-zfc -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-cats-in-zfc.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "79fa1c6257a765b42788a5acc6f010de",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 159,
"avg_line_length": 40.80790960451977,
"alnum_prop": 0.552955835525405,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "923ee3945fae66bf0328dc790a241be62204967b",
"size": "7248",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.12.2/cats-in-zfc/8.5.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
namespace Chamilo\Core\Repository\Component;
use Chamilo\Core\Repository\Manager;
use Chamilo\Libraries\Architecture\Application\ApplicationConfiguration;
use Chamilo\Libraries\Architecture\Application\ApplicationFactory;
use Chamilo\Libraries\Architecture\Interfaces\ApplicationSupport;
/**
*
* @package core\repository
* @author Hans De Bisschop <hans.de.bisschop@ehb.be>
* @author Magali Gillard <magali.gillard@ehb.be>
* @author Eduard Vossen <eduard.vossen@ehb.be>
*/
class UserViewComponent extends Manager implements ApplicationSupport
{
/**
* Runs this component and displays its output.
*/
public function run()
{
$factory = new ApplicationFactory(
\Chamilo\Core\Repository\UserView\Manager::context(),
new ApplicationConfiguration($this->getRequest(), $this->get_user(), $this));
return $factory->run();
}
}
| {
"content_hash": "914152b4a3aa0da065a28956a4f56dc9",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 89,
"avg_line_length": 31.03448275862069,
"alnum_prop": 0.7233333333333334,
"repo_name": "cosnicsTHLU/cosnics",
"id": "31695d961b7c7b972f1bf25f100df0d178651d1a",
"size": "900",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Chamilo/Core/Repository/Component/UserViewComponent.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "86189"
},
{
"name": "C#",
"bytes": "23363"
},
{
"name": "CSS",
"bytes": "1135928"
},
{
"name": "CoffeeScript",
"bytes": "17503"
},
{
"name": "Gherkin",
"bytes": "24033"
},
{
"name": "HTML",
"bytes": "542339"
},
{
"name": "JavaScript",
"bytes": "5296016"
},
{
"name": "Makefile",
"bytes": "3221"
},
{
"name": "PHP",
"bytes": "21903304"
},
{
"name": "Ruby",
"bytes": "618"
},
{
"name": "Shell",
"bytes": "6385"
},
{
"name": "Smarty",
"bytes": "15750"
},
{
"name": "XSLT",
"bytes": "44115"
}
],
"symlink_target": ""
} |
command -v brew > /dev/null && \
_LOCAL_SDK=$(brew --prefix)/Caskroom/google-cloud-sdk/latest/google-cloud-sdk
[ -d "${_LOCAL_SDK}" ] || _LOCAL_SDK=$(local_lib_path google-cloud-sdk)
[ -f "${_LOCAL_SDK}/completion.bash.inc" ] && . "${_LOCAL_SDK}/completion.bash.inc"
unset _LOCAL_SDK
| {
"content_hash": "1d8d93b872132ccf2b9d461684c27629",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 83,
"avg_line_length": 57.6,
"alnum_prop": 0.6458333333333334,
"repo_name": "memes/home",
"id": "fe318ae3d83714cb6d67f627fda841b99bd0ffa3",
"size": "335",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": ".profile.d/google-cloud-sdk/completion.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "261"
},
{
"name": "Shell",
"bytes": "48769"
}
],
"symlink_target": ""
} |
class CoronaRenderer;
class RoundCorners : public Corona::Abstract::Map, Corona::RoundEdgesShader
{
public:
CoronaRenderer *coronaRenderer;
Corona::ColorOrMap normalCamera;
RoundCorners();
RoundCorners(MObject sObject);
~RoundCorners();
Corona::String mapName = "RoundCorners";
int samplesCount = 10;
float radius = 0.01f;
virtual Corona::Rgb evalColor(const Corona::IShadeContext& context, Corona::TextureCache* cache, float& outAlpha);
virtual float evalMono(const Corona::IShadeContext& context, Corona::TextureCache* cache, float& outAlpha);
virtual Corona::Dir evalBump(const Corona::IShadeContext&, Corona::TextureCache*);
//virtual void renderTo(Corona::Bitmap<Corona::Rgb>& output){};
virtual void getChildren(Corona::Stack<Corona::Resource*>&) {}
virtual bool exportMap(Corona::IResourceManager& resourceManager, Corona::XmlWriterNode& outXml) const { return true; };
virtual Corona::String name() const { return mapName; };
};
#endif | {
"content_hash": "602fb023d6f4366f1b97ce97c5af4f2b",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 121,
"avg_line_length": 37.03846153846154,
"alnum_prop": 0.7653167185877466,
"repo_name": "haggi/OpenMaya",
"id": "0c498fecdbd8e9d793cd6f3be832816236628a67",
"size": "1141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/mayaToCorona/src/Corona/CoronaRoundCorners.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AMPL",
"bytes": "5333"
},
{
"name": "Batchfile",
"bytes": "587"
},
{
"name": "C",
"bytes": "246300"
},
{
"name": "C++",
"bytes": "4178594"
},
{
"name": "Mathematica",
"bytes": "12660820"
},
{
"name": "Objective-C",
"bytes": "316"
},
{
"name": "Python",
"bytes": "1583249"
}
],
"symlink_target": ""
} |
How to get students in that mode where everything they read or learn is
productive? Avoid brute force techniques:
- Deadlines
- Tests
- Set curriculum
# What things can I do to learn something?
- Have a project (hobby or real world, not throw-away)
- Split concept into small parts and master them within the context of a project
## Examples of learning things:
- Programming languages
- Programming concepts (concurrency, immutability, functional programming)
- Electronics
## Self directed learning
- You don't know what you don't know yet
- If you try to learn it in the context of a class/curriculum, it might help
teach the right things, but you still don't know why you need to know, so you
don't care
- You need to both 1) know what to learn 2) know why you need it
- Need is a great motivator.
- Curiosity is a secondary motivator: when you come across something
interesting, go on a rabbit trail. Go deep. Become aware of the entire field.
## School does not equip you for the real world
- Technology changes so fast, most of what you learn in (already outdated)
classes are no longer relevant.
- So you must know how to learn, or learn to learn very quickly. But first you
need to learn how to learn how to learn :)
## Persistence and repetition
## Write-once-read-never notes
| {
"content_hash": "12f924d585373d0464ab67ad10022082",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 80,
"avg_line_length": 29.84090909090909,
"alnum_prop": 0.7532368621477532,
"repo_name": "devth/devth.github.com",
"id": "9030d18981c0e758cdfa5adf2833bbf4b8f5b83f",
"size": "1313",
"binary": false,
"copies": "1",
"ref": "refs/heads/source",
"path": "_wip/learning_mode.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "49893"
},
{
"name": "Elm",
"bytes": "934"
},
{
"name": "HTML",
"bytes": "21557"
},
{
"name": "Java",
"bytes": "3833"
},
{
"name": "JavaScript",
"bytes": "13662"
},
{
"name": "Makefile",
"bytes": "118"
},
{
"name": "Ruby",
"bytes": "2703"
},
{
"name": "Scala",
"bytes": "25843"
},
{
"name": "XSLT",
"bytes": "20993"
}
],
"symlink_target": ""
} |
package org.bzewdu.tools.perftrend.util;
import java.io.*;
public class ExternalCmd {
private static Runtime m_runtime;
private String[] cmd_v;
private Writer owriter;
private Writer ewriter;
private OutputStream ostream;
private OutputStream estream;
private File ofile;
private boolean ofile_append;
private int rc;
/**
*
* @param cmd
*/
private void init(final String[] cmd) {
this.rc = 0;
this.cmd_v = cmd;
this.ewriter = null;
this.owriter = null;
this.estream = null;
this.ostream = null;
this.ofile = null;
this.ofile_append = false;
}
/**
*
* @param cmd
* @param out
* @param err
*/
private void init(final String[] cmd, final Writer out, final Writer err) {
this.init(cmd);
this.ewriter = err;
this.owriter = out;
}
/**
*
* @param cmd
* @param out
* @param err
*/
private void init(final String[] cmd, final OutputStream out, final OutputStream err) {
this.init(cmd);
this.estream = err;
this.ostream = out;
}
/**
*
* @param cmd
*/
public ExternalCmd(final String[] cmd) {
super();
this.init(cmd, new StringWriter(), new StringWriter());
}
/**
*
* @param cmd
* @param out
* @param err
*/
public ExternalCmd(final String[] cmd, final Writer out, final Writer err) {
super();
this.init(cmd, out, err);
}
/**
*
* @param cmd
* @param out
* @param err
*/
public ExternalCmd(final String[] cmd, final OutputStream out, final OutputStream err) {
super();
this.init(cmd, out, err);
}
/**
*
* @param cmd
* @param outfile
*/
public ExternalCmd(final String[] cmd, final File outfile) {
super();
this.init(cmd);
this.ofile = outfile;
}
public ExternalCmd(final String[] cmd, final File outfile, final boolean append) {
super();
this.init(cmd);
this.ofile = outfile;
this.ofile_append = append;
}
public int rc() {
return this.rc;
}
/**
*
* @param buflen
* @return
* @throws IOException
* @throws InterruptedException
*/
public int run(final int buflen) throws IOException, InterruptedException {
if (this.ofile != null) {
this.rc = run(this.cmd_v, this.ofile, this.ofile_append, buflen);
} else if (this.owriter != null) {
this.rc = run(this.cmd_v, this.owriter, this.ewriter, buflen);
} else {
this.rc = run(this.cmd_v, this.ostream, this.estream, buflen);
}
return this.rc;
}
public int run() throws IOException, InterruptedException {
return this.run(4096);
}
public File getOutputFile() {
return this.ofile;
}
public Writer getErrorWriter() {
return this.ewriter;
}
public Writer getOutputWriter() {
return this.owriter;
}
public StringBuffer getErrorBuffer() {
return ((StringWriter) this.ewriter).getBuffer();
}
public StringBuffer getOutputBuffer() {
return ((StringWriter) this.owriter).getBuffer();
}
/**
*
*/
public void appendErrorWriter() {
try {
this.owriter.write(this.getErrorBuffer().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public OutputStream getErrorStream() {
return this.estream;
}
public OutputStream getOutputStream() {
return this.ostream;
}
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append(this.cmd_v[0]);
for (int i = 1; i < this.cmd_v.length; ++i) {
buf.append(' ');
buf.append(this.cmd_v[i]);
}
buf.append(',');
buf.append(this.rc);
return buf.toString();
}
/**
*
* @param p
* @throws IOException
*/
public static void cleanup(final Process p) throws IOException {
p.getOutputStream().close();
p.getInputStream().close();
p.getErrorStream().close();
p.destroy();
}
/**
*
* @param p
* @param in
* @param out
* @param err
* @param buflen
* @return
*/
public static IOThread[] createIOThreads(final Process p, final InputStream in, final OutputStream out, final OutputStream err, final int buflen) {
return new IOThread[]{(in != null) ? new ByteIOThread(in, p.getOutputStream(), buflen) : null, (out != null) ? new ByteIOThread(p.getInputStream(), out, buflen) : null, (err != null) ? new ByteIOThread(p.getErrorStream(), err, buflen) : null};
}
public static IOThread[] createIOThreads(final Process p, final Reader in, final Writer out, final Writer err, final int buflen) {
return (buflen == 0) ? createLineIOThreads(p, in, out, err) : createCharIOThreads(p, in, out, err, buflen);
}
/**
*
* @param p
* @param in
* @param out
* @param err
* @param buflen
* @return
*/
public static IOThread[] createCharIOThreads(final Process p, final Reader in, final Writer out, final Writer err, final int buflen) {
final IOThread[] t;
t = new IOThread[]{(in != null) ? new CharIOThread(in, new OutputStreamWriter(p.getOutputStream()), buflen) : null, (out != null) ? new CharIOThread(new InputStreamReader(p.getInputStream()), out, buflen) : null, (err != null) ? new CharIOThread(new InputStreamReader(p.getErrorStream()), err, buflen) : null};
return t;
}
/**
*
* @param p
* @param in
* @param out
* @param err
* @return
*/
public static IOThread[] createLineIOThreads(final Process p, final Reader in, final Writer out, final Writer err) {
return new IOThread[]{(in != null) ? new LineIOThread(in, new OutputStreamWriter(p.getOutputStream())) : null, (out != null) ? new LineIOThread(new InputStreamReader(p.getInputStream()), out) : null, (err != null) ? new LineIOThread(new InputStreamReader(p.getErrorStream()), err) : null};
}
/**
*
* @param threads
* @throws IOException
* @throws InterruptedException
*/
public static void runIOThreads(final IOThread[] threads) throws IOException, InterruptedException {
for (IOThread thread : threads) {
if (thread != null) {
thread.start();
}
}
for (IOThread thread : threads) {
if (thread != null) {
thread.join();
}
}
for (IOThread thread : threads) {
if (thread != null) {
thread.rethrow();
}
}
}
/**
*
* @param cmd
* @param in
* @param out
* @param err
* @param buflen
* @return
* @throws IOException
* @throws InterruptedException
*/
public static int run(final String[] cmd, final InputStream in, final OutputStream out, final OutputStream err, final int buflen) throws IOException, InterruptedException {
Process p = null;
int rc = 1;
try {
p = ExternalCmd.m_runtime.exec(cmd);
final IOThread[] t = createIOThreads(p, in, out, err, buflen);
runIOThreads(t);
rc = p.waitFor();
} finally {
if (p != null) {
cleanup(p);
}
}
return rc;
}
/**
*
* @param cmd
* @param in
* @param out
* @param err
* @param buflen
* @return
* @throws IOException
* @throws InterruptedException
*/
public static int run(final String[] cmd, final Reader in, final Writer out, final Writer err, final int buflen) throws IOException, InterruptedException {
Process p = null;
int rc = 1;
try {
p = ExternalCmd.m_runtime.exec(cmd);
final IOThread[] t = createIOThreads(p, in, out, err, buflen);
runIOThreads(t);
rc = p.waitFor();
} finally {
if (p != null) {
cleanup(p);
}
}
return rc;
}
/**
*
* @param cmd
* @param out
* @param err
* @param buflen
* @return
* @throws IOException
* @throws InterruptedException
*/
public static int run(final String[] cmd, final OutputStream out, final OutputStream err, final int buflen) throws IOException, InterruptedException {
return run(cmd, null, out, err, buflen);
}
/**
*
* @param cmd
* @param out
* @param err
* @param buflen
* @return
* @throws IOException
* @throws InterruptedException
*/
public static int run(final String[] cmd, final Writer out, final Writer err, final int buflen) throws IOException, InterruptedException {
return run(cmd, null, out, err, buflen);
}
public static int run(final String[] cmd, final File file, final boolean append, final int buflen) throws IOException, InterruptedException {
BufferedOutputStream out = null;
int rc = 1;
try {
out = new BufferedOutputStream(new FileOutputStream(file.getPath(), append));
rc = run(cmd, null, out, out, buflen);
} finally {
if (out != null) {
out.close();
}
}
return rc;
}
static {
ExternalCmd.m_runtime = Runtime.getRuntime();
}
}
| {
"content_hash": "a1b095e893798c0496004acbfc0aa5c3",
"timestamp": "",
"source": "github",
"line_count": 362,
"max_line_length": 318,
"avg_line_length": 26.87845303867403,
"alnum_prop": 0.5542651593011305,
"repo_name": "benzewdu/PerformanceTracker",
"id": "540da7685a6a7842e72a8e72b63aa91e38e1758e",
"size": "10322",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/bzewdu/tools/perftrend/util/ExternalCmd.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11139"
},
{
"name": "Java",
"bytes": "128085"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Javadoc API documentation for Fresco 1.1.0." />
<link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" />
<title>
LocalVideoThumbnailProducer - Fresco 1.1.0 API
| Fresco 1.1.0
</title>
<link href="../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" />
<script src="../../../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../../../assets/doclava-developer-docs.js" type="text/javascript"></script>
<script src="../../../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
setToRoot("../../../../", "../../../../../assets/");
</script>
<script src="../../../../../assets/doclava-developer-reference.js" type="text/javascript"></script>
<script src="../../../../../assets/navtree_data.js" type="text/javascript"></script>
<script src="../../../../../assets/customizations.js" type="text/javascript"></script>
<noscript>
<style type="text/css">
html,body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
</head>
<body class="">
<div id="header">
<div id="headerLeft">
<span id="masthead-title"><a href="../../../../packages.html">Fresco 1.1.0</a></span>
</div>
<div id="headerRight">
<div id="search" >
<div id="searchForm">
<form accept-charset="utf-8" class="gsc-search-box"
onsubmit="return submit_search()">
<table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
<tr>
<td class="gsc-input">
<input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
title="search developer docs" name="q"
value="search developer docs"
onFocus="search_focus_changed(this, true)"
onBlur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../')"
onkeyup="return search_changed(event, false, '../../../../')" />
<div id="search_filtered_div" class="no-display">
<table id="search_filtered" cellspacing=0>
</table>
</div>
</td>
<!-- <td class="gsc-search-button">
<input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
</td>
<td class="gsc-clear-button">
<div title="clear results" class="gsc-clear-button"> </div>
</td> -->
</tr></tbody>
</table>
</form>
</div><!-- searchForm -->
</div><!-- search -->
</div>
</div><!-- header -->
<div class="g-section g-tpl-240" id="body-content">
<div class="g-unit g-first side-nav-resizable" id="side-nav">
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav">
<div id="index-links">
<a href="../../../../packages.html" >Packages</a> |
<a href="../../../../classes.html" >Classes</a>
</div>
<ul>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/soloader/package-summary.html">com.facebook.common.soloader</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/backends/volley/package-summary.html">com.facebook.drawee.backends.volley</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/wrapper/package-summary.html">com.facebook.fresco.animation.wrapper</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li>
<li class="selected api apilevel-">
<a href="../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li>
</ul><br/>
</div> <!-- end packages -->
</div> <!-- end resize-packages -->
<div id="classes-nav">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/Consumer.html">Consumer</a><T></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/JobScheduler.JobRunnable.html">JobScheduler.JobRunnable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/MediaVariationsIndex.html">MediaVariationsIndex</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/NetworkFetcher.html">NetworkFetcher</a><FETCH_STATE extends <a href="../../../../com/facebook/imagepipeline/producers/FetchState.html">FetchState</a>></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/NetworkFetcher.Callback.html">NetworkFetcher.Callback</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/Producer.html">Producer</a><T></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/ProducerContext.html">ProducerContext</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/ProducerContextCallbacks.html">ProducerContextCallbacks</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/ProducerListener.html">ProducerListener</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/ThumbnailProducer.html">ThumbnailProducer</a><T></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/AddImageTransformMetaDataProducer.html">AddImageTransformMetaDataProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/BaseConsumer.html">BaseConsumer</a><T></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/BaseNetworkFetcher.html">BaseNetworkFetcher</a><FETCH_STATE extends <a href="../../../../com/facebook/imagepipeline/producers/FetchState.html">FetchState</a>></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/BaseProducerContext.html">BaseProducerContext</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/BaseProducerContextCallbacks.html">BaseProducerContextCallbacks</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/BitmapMemoryCacheGetProducer.html">BitmapMemoryCacheGetProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/BitmapMemoryCacheKeyMultiplexProducer.html">BitmapMemoryCacheKeyMultiplexProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/BitmapMemoryCacheProducer.html">BitmapMemoryCacheProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/BranchOnSeparateImagesProducer.html">BranchOnSeparateImagesProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/DataFetchProducer.html">DataFetchProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/DecodeProducer.html">DecodeProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/DelegatingConsumer.html">DelegatingConsumer</a><I, O></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/DiskCacheReadProducer.html">DiskCacheReadProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/DiskCacheWriteProducer.html">DiskCacheWriteProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/DownsampleUtil.html">DownsampleUtil</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/EncodedCacheKeyMultiplexProducer.html">EncodedCacheKeyMultiplexProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/EncodedMemoryCacheProducer.html">EncodedMemoryCacheProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/FetchState.html">FetchState</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/HttpUrlConnectionNetworkFetcher.html">HttpUrlConnectionNetworkFetcher</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/JobScheduler.html">JobScheduler</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/LocalAssetFetchProducer.html">LocalAssetFetchProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/LocalContentUriFetchProducer.html">LocalContentUriFetchProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/LocalContentUriThumbnailFetchProducer.html">LocalContentUriThumbnailFetchProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/LocalExifThumbnailProducer.html">LocalExifThumbnailProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/LocalFetchProducer.html">LocalFetchProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/LocalFileFetchProducer.html">LocalFileFetchProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/LocalResourceFetchProducer.html">LocalResourceFetchProducer</a></li>
<li class="selected api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/LocalVideoThumbnailProducer.html">LocalVideoThumbnailProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/MediaVariationsFallbackProducer.html">MediaVariationsFallbackProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/MediaVariationsIndexDatabase.html">MediaVariationsIndexDatabase</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/MultiplexProducer.html">MultiplexProducer</a><K, T extends Closeable></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/NetworkFetchProducer.html">NetworkFetchProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/NoOpMediaVariationsIndex.html">NoOpMediaVariationsIndex</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/NullProducer.html">NullProducer</a><T></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/PostprocessedBitmapMemoryCacheProducer.html">PostprocessedBitmapMemoryCacheProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/PostprocessedBitmapMemoryCacheProducer.CachedPostprocessorConsumer.html">PostprocessedBitmapMemoryCacheProducer.CachedPostprocessorConsumer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/PostprocessorProducer.html">PostprocessorProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/RemoveImageTransformMetaDataProducer.html">RemoveImageTransformMetaDataProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/ResizeAndRotateProducer.html">ResizeAndRotateProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/SettableProducerContext.html">SettableProducerContext</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/StatefulProducerRunnable.html">StatefulProducerRunnable</a><T></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/SwallowResultProducer.html">SwallowResultProducer</a><T></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/ThreadHandoffProducer.html">ThreadHandoffProducer</a><T></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/ThreadHandoffProducerQueue.html">ThreadHandoffProducerQueue</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/ThrottlingProducer.html">ThrottlingProducer</a><T></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/ThumbnailBranchProducer.html">ThumbnailBranchProducer</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/ThumbnailSizeChecker.html">ThumbnailSizeChecker</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/producers/WebpTranscodeProducer.html">WebpTranscodeProducer</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none">
<div id="index-links">
<a href="../../../../packages.html" >Packages</a> |
<a href="../../../../classes.html" >Classes</a>
</div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
</div> <!-- end side-nav -->
<script>
if (!isMobile) {
//$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav");
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../");
} else {
addLoadEvent(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
}
//$("#swapper").css({borderBottom:"2px solid #aaa"});
} else {
swapNav(); // tree view should be used on mobile
}
</script>
<div class="g-unit" id="doc-content">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#constants">Constants</a>
| <a href="#pubctors">Ctors</a>
| <a href="#pubmethods">Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
class
<h1>LocalVideoThumbnailProducer</h1>
extends Object<br/>
implements
<a href="../../../../com/facebook/imagepipeline/producers/Producer.html">Producer</a><T>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell">java.lang.Object</td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.facebook.imagepipeline.producers.LocalVideoThumbnailProducer</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p>A producer that creates video thumbnails.
<p>At present, these thumbnails are created on the java heap rather than being pinned
purgeables. This is deemed okay as the thumbnails are only very small.
</p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="constants" class="jd-sumtable"><tr><th colspan="12">Constants</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">String</td>
<td class="jd-linkcol"><a href="../../../../com/facebook/imagepipeline/producers/LocalVideoThumbnailProducer.html#PRODUCER_NAME">PRODUCER_NAME</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/imagepipeline/producers/LocalVideoThumbnailProducer.html#LocalVideoThumbnailProducer(java.util.concurrent.Executor)">LocalVideoThumbnailProducer</a></span>(Executor executor)
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/imagepipeline/producers/LocalVideoThumbnailProducer.html#produceResults(com.facebook.imagepipeline.producers.Consumer<com.facebook.common.references.CloseableReference<com.facebook.imagepipeline.image.CloseableImage>>, com.facebook.imagepipeline.producers.ProducerContext)">produceResults</a></span>(<a href="../../../../com/facebook/imagepipeline/producers/Consumer.html">Consumer</a><<a href="../../../../com/facebook/common/references/CloseableReference.html">CloseableReference</a><<a href="../../../../com/facebook/imagepipeline/image/CloseableImage.html">CloseableImage</a>>> consumer, <a href="../../../../com/facebook/imagepipeline/producers/ProducerContext.html">ProducerContext</a> producerContext)
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
java.lang.Object
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Object
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">clone</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">equals</span>(Object arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">finalize</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
Class<?>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getClass</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">hashCode</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">notify</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">notifyAll</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
String
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">toString</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>(long arg0, int arg1)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>(long arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>()
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-com.facebook.imagepipeline.producers.Producer" class="jd-expando-trigger closed"
><img id="inherited-methods-com.facebook.imagepipeline.producers.Producer-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="../../../../com/facebook/imagepipeline/producers/Producer.html">com.facebook.imagepipeline.producers.Producer</a>
<div id="inherited-methods-com.facebook.imagepipeline.producers.Producer">
<div id="inherited-methods-com.facebook.imagepipeline.producers.Producer-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-com.facebook.imagepipeline.producers.Producer-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/imagepipeline/producers/Producer.html#produceResults(com.facebook.imagepipeline.producers.Consumer<T>, com.facebook.imagepipeline.producers.ProducerContext)">produceResults</a></span>(<a href="../../../../com/facebook/imagepipeline/producers/Consumer.html">Consumer</a><T> consumer, <a href="../../../../com/facebook/imagepipeline/producers/ProducerContext.html">ProducerContext</a> context)
<div class="jd-descrdiv">Start producing results for given context.</div>
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- ========= ENUM CONSTANTS DETAIL ======== -->
<h2>Constants</h2>
<a id="PRODUCER_NAME"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
final
String
</span>
PRODUCER_NAME
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
<div class="jd-tagdata">
<span class="jd-tagtitle">Constant Value: </span>
<span>
"VideoThumbnailProducer"
</span>
</div>
</div>
</div>
<!-- Fields -->
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<h2>Public Constructors</h2>
<a id="LocalVideoThumbnailProducer(java.util.concurrent.Executor)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
</span>
<span class="sympad">LocalVideoThumbnailProducer</span>
<span class="normal">(Executor executor)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<a id="produceResults(com.facebook.imagepipeline.producers.Consumer<com.facebook.common.references.CloseableReference<com.facebook.imagepipeline.image.CloseableImage>>, com.facebook.imagepipeline.producers.ProducerContext)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">produceResults</span>
<span class="normal">(<a href="../../../../com/facebook/imagepipeline/producers/Consumer.html">Consumer</a><<a href="../../../../com/facebook/common/references/CloseableReference.html">CloseableReference</a><<a href="../../../../com/facebook/imagepipeline/image/CloseableImage.html">CloseableImage</a>>> consumer, <a href="../../../../com/facebook/imagepipeline/producers/ProducerContext.html">ProducerContext</a> producerContext)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<a id="navbar_top"></a>
<div id="footer">
+Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>.
+</div> <!-- end footer - @generated -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script type="text/javascript">
init(); /* initialize doclava-developer-docs.js */
</script>
</body>
</html>
| {
"content_hash": "eaec48982b42b585013c02e71f1b27d4",
"timestamp": "",
"source": "github",
"line_count": 1076,
"max_line_length": 783,
"avg_line_length": 35.63104089219331,
"alnum_prop": 0.6027543754401523,
"repo_name": "desmond1121/fresco",
"id": "41448f7e9808eeb663e805273cfb5126801179e5",
"size": "38339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/javadoc/reference/com/facebook/imagepipeline/producers/LocalVideoThumbnailProducer.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "22418"
},
{
"name": "C++",
"bytes": "212041"
},
{
"name": "IDL",
"bytes": "1003"
},
{
"name": "Java",
"bytes": "2750756"
},
{
"name": "Makefile",
"bytes": "7247"
},
{
"name": "Prolog",
"bytes": "153"
},
{
"name": "Python",
"bytes": "10351"
},
{
"name": "Shell",
"bytes": "102"
}
],
"symlink_target": ""
} |
namespace _2.ConditionStatmentEx11OddNumber
{
using System;
using System.Collections.Generic;
using System.Linq;
public class OddNumber
{
public static void Main()
{
var n = Math.Abs(int.Parse(Console.ReadLine()));
while (n % 2 == 0)
{
Console.WriteLine("Please write an odd number.");
n = Math.Abs(int.Parse(Console.ReadLine()));
}
Console.WriteLine($"The number is: {n}");
}
}
}
| {
"content_hash": "c1b9a6aa210871d5ee046c4d341fed77",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 65,
"avg_line_length": 23.863636363636363,
"alnum_prop": 0.5219047619047619,
"repo_name": "dontito88/ProgrammFundamentalsSecondChance",
"id": "5ca77517233f15df8b1e7ccd3a2c73d43805be3f",
"size": "527",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SecondChance/2.ConditionStatmentEx11OddNumber/OddNumber.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "192614"
}
],
"symlink_target": ""
} |
package robots.epuck;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Observable;
import java.util.TooManyListenersException;
import java.util.Scanner;
import javax.swing.JOptionPane;
import model.Automat;
import view.MainFrame;
public class Communicator extends Observable implements SerialPortEventListener {
private CommPortIdentifier portIdentifier;
private SerialPort serialPort;
private InputStream inStream;
private OutputStream outStream;
private WriteThread writeThread;
private volatile boolean isConnected = false;
private final Object writeSignal = new Object();
private final static int eva = 100;
private final static int stringBuilderLength = 100;
private StringBuilder readBuffer = new StringBuilder(stringBuilderLength);
private int serialCounter = 0;
//private Scanner in;
private BufferedReader d;
public Communicator(String portName) {
if (MainFrame.DEBUG) {
System.out.println("New Communicator for: "+portName);
}
try {
portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
serialPort = (SerialPort) portIdentifier.open("Communicator", 2000);
inStream = serialPort.getInputStream();
//in = new Scanner( inStream );
d = new BufferedReader(new InputStreamReader(inStream));
outStream = serialPort.getOutputStream();
initSerialPort();
isConnected = true;
if (MainFrame.DEBUG) {
System.out.println("Communicator connected to: "+portName);
}
} catch (NoSuchPortException e) {
JOptionPane.showMessageDialog(MainFrame.mainFrame, "Der angegebene Port " + portName
+ " konnte nicht gefunden werden.", "Fehler beim Verbindungsaufbau", JOptionPane.WARNING_MESSAGE);
return;
} catch (PortInUseException e) {
JOptionPane.showMessageDialog(MainFrame.mainFrame, "<html>Der angegebene Port " + portName
+ " konnte nicht geöffnet werden.<br>" +
"Ist die Verbindung zum Roboter zuvor ungewollt<br>" +
"unterbrochen worden und verwendet kein anderes<br>" +
"Programm den angegebenen Port, kann dieses Problem<br>" +
"nur durch einen Neustart von ZUSMORO behoben werden!", "Fehler beim Verbindungsaufbau", JOptionPane.WARNING_MESSAGE);
return;
} catch (IOException e) {
JOptionPane.showMessageDialog(MainFrame.mainFrame, "Die E/A-Streams für Port " + portName
+ " konnten nicht geöffnet werden.", "Fehler beim Verbindungsaufbau", JOptionPane.WARNING_MESSAGE);
return;
} catch (TooManyListenersException e) {
e.printStackTrace();
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
// try {
// if (isConnected) {
// writeToStream("v");
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
}
private void initSerialPort() throws TooManyListenersException,
UnsupportedCommOperationException {
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort
.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
//serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.setDTR(true);
serialPort.setRTS(true);
//serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
}
public void serialEvent(SerialPortEvent event) {
//System.out.println("EVENT: " + event.getEventType());
switch (event.getEventType()) {
// case SerialPortEvent.BI:
// case SerialPortEvent.OE:
// case SerialPortEvent.FE:
// case SerialPortEvent.PE:
// case SerialPortEvent.CD:
// case SerialPortEvent.CTS:
// case SerialPortEvent.DSR:
// case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
//StringBuilder readBuffer = new StringBuilder(stringBuilderLength);
System.out.println("DATA_AVAILABLE: " + serialCounter);
int c;
try {
//System.out.println(in.read());
//System.out.println("ddddd: " + d.readLine());
String scannedInput = null;
while( (scannedInput = d.readLine()) != null){//solange wir noch nicht alle readlines abgearbeitet haben müssen wir weiter machen
//}
//scannedInput = d.readLine();
//if(scannedInput != null){
if(!scannedInput.equals("")){
System.out.println("scannedInput for " + serialCounter + ":" + scannedInput);
setChanged();
System.out.println("countObservers(): " + countObservers());
notifyObservers(scannedInput);
}else{
setChanged();
System.out.println("Void string..." + serialCounter);
notifyObservers(scannedInput);
}
//}else{
// System.out.println("Nothing to read..." + serialCounter);
//}
}
/*
while ((c = inStream.read()) > -1) {
if (c == 13 || c == 10) {
System.out.println("c"+ serialCounter + ": " + (byte) c);
}
if (c != 13 && c != 10) {
readBuffer.append((char) c);
System.out.print((byte) c);
} else if (c == 10) {
String scannedInput = readBuffer.toString();
byte[] ret = scannedInput.getBytes();
System.out.print("scannedInput " + serialCounter + ": ");
for(int j = 0;j < ret.length;j++){
System.out.print(ret[j]);
}
System.out.println("");
readBuffer = new StringBuilder(stringBuilderLength);
setChanged();
notifyObservers(scannedInput);
}
}*/
} catch (IOException e) {
// TODO hier etwas tun?
System.out.println(e.getMessage());
//setChanged();
//notifyObservers("ZERO");
}
serialCounter++;
break;
}
}
public void writeToStream(final String msg) throws IOException {
if (writeThread == null || !writeThread.isAlive()) {
writeThread = new WriteThread();
writeThread.start();
}
int queueSize = writeThread.writeMsg(msg);
if (MainFrame.DEBUG) {
System.out.println("Queue size: " + queueSize);
}
if (queueSize >= eva) {
writeThread.stopThread();
throw new IOException(
"<html>Fehler bei der Übertragung der Befehle,<br>evtl. ist die EVA-Frequenz zu hoch eingestellt");
}
}
public static ArrayList<String> getCOMPorts() {
String portName;
ArrayList<String> availablePorts = new ArrayList<String>();
for (int i = 1; i < 51; i++) {
try {
portName = "COM" + i;
CommPortIdentifier.getPortIdentifier(portName);
availablePorts.add(portName);
} catch (NoSuchPortException e) {
// dann halt nicht
}
}
return availablePorts;
}
public boolean isConnected() {
return isConnected;
}
public void disconnect() {
if (MainFrame.DEBUG) {
System.out.println("Communicator disconnecting...");
}
if (writeThread != null) {
if (MainFrame.DEBUG) {
System.out.println("stopping WriterThread...");
}
writeThread.stopThread();
if (MainFrame.DEBUG) {
System.out.println("interrupting WriterThread...");
}
writeThread.interrupt();
}
writeThread = null;
if (serialPort != null) {
if (MainFrame.DEBUG) {
System.out.println("closing Streams...");
}
try {
inStream.close();
outStream.close();
inStream = null;
outStream = null;
} catch (IOException e) {
e.printStackTrace();
if (MainFrame.DEBUG) {
System.out.println("Exception while closing Streams");
}
}
if (MainFrame.DEBUG) {
System.out.println("closing SerialPort...");
}
Thread closeThread = new Thread(new Runnable() {
public void run() {
SerialPort port = serialPort;
serialPort = null;
port.close();
}
});
closeThread.setDaemon(true);
closeThread.start();
if (MainFrame.DEBUG) {
System.out.println("SerialPort closed(?)...");
}
}
isConnected = false;
if (MainFrame.DEBUG) {
System.out.println("Communicator disconnected!");
}
}
private class WriteThread extends Thread {
private ArrayList<String> messages;
private volatile boolean stop;
public WriteThread() {
super("Communicator.WriteThread");
messages = new ArrayList<String>(eva);//20
stop = false;
setDaemon(true);
}
public int writeMsg(String msg) {
int size;
synchronized (messages) {
messages.add(msg);
size = messages.size();
}
synchronized (writeSignal) {
writeSignal.notify();
}
return size;
}
public void stopThread() {
stop = true;
if (MainFrame.DEBUG) {
System.out.println("Stop-Flag set!");
}
}
@Override
public void run() {
String msg;
stop = false;
while (!stop && !isInterrupted()) {
msg = null;
synchronized (messages) {
if (!messages.isEmpty()) {
msg = messages.get(0);
messages.remove(0);
}
}
if (msg != null) {
try {
if (MainFrame.DEBUG) {
System.out.println("Writing to Stream: "+msg);
System.out.print("Writing to Stream2: ");
byte[] ret = msg.getBytes();
for(int j = 0;j < ret.length;j++){
System.out.print(ret[j]);
}
System.out.println("");
}
//byte[] bytes = msg.getBytes();
//outStream.write((msg + (msg.endsWith("\r\n") ? "" : "\r\n")).getBytes());
outStream.write(msg.getBytes());
} catch (IOException e) {
Automat.runningAutomat.requestCancel("<html>Übermittlung zum Roboter fehlgeschlagen:<br>"
+ e.getMessage() + "</html>", true);
break;
}
} else {
try {
synchronized (writeSignal) {
writeSignal.wait(1000);
}
} catch (InterruptedException e) {
if (MainFrame.DEBUG) {
System.out.println("WriteThread interrupted!");
}
break;
}
}
}
if (MainFrame.DEBUG) {
System.out.println("WriteThread died!");
}
}
}
}
| {
"content_hash": "18b3e1fc009429c7e2a582f187dc7886",
"timestamp": "",
"source": "github",
"line_count": 341,
"max_line_length": 133,
"avg_line_length": 30.43108504398827,
"alnum_prop": 0.6439240628312615,
"repo_name": "iti-luebeck/ZUSMORO",
"id": "833197f5b3f06e2df465781553f8437d136bdbf3",
"size": "12032",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/robots/epuck/Communicator.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "380277"
},
{
"name": "Python",
"bytes": "2951"
}
],
"symlink_target": ""
} |
layout: post
title: "Undertow tuning"
excerpt: "specific tunning for the performance boost"
categories: devnote
tags: [undertow, server]
modified: 2016-10-23
comments: true
share: false
author: chungyu
---
Observer the usage of your server `htop`, if the CPU hasn't been fully utilized, you can...
```java
server = Undertow.builder()
.addHttpListener(80, "0.0.0.0")
.setHandler(path)
.setIoThreads(64)
.setWorkerThreads(100)
.setDirectBuffers(true)
.build();
```
> * Mainly from [Entering Undertow Web server](https://www.javacodegeeks.com/2014/01/entering-undertow-web-server.html)
> Other reference
* [reference 2](http://undertow.io/undertow-docs/undertow-docs-1.2.0/listeners.html)
* [reference 3](http://undertow.io/javadoc/1.2.x/io/undertow/Undertow.Builder.html#setDirectBuffers-boolean-)
# Buffer Caches
> * A Buffer is essentially a block of memory into which you can write data, which you can then later read again.
> * Buffer memory access is much faster than physical access.
# Task Keepalive
> * The Task keepalive (default 60) controls the number of seconds to wait for the next request from the same client on the same connection.
> * With Keep-Alives the browser gets to eliminate a full round trip for every request after the first, usually cutting full page load times in half.
# IO Threads
> * The number of Io threads corresponds to the number of Web server Threads available.
> * The Task Max Threads has control on the max number of concurrent requests.
# Buffer Pool
> * Undertow is based on the Java NIO API
> * In the NIO library, all data is handled with Buffers. When data is read, it is read directly into a buffer. When data is written, it is written into a buffer.
# Direct buffers
> * direct buffers are allocated outside the Java heap; therefore, once allocated, their memory address is fixed for the lifetime of the buffer.
> * Having a fixed memory address in turn causes that the kernel can safely access them directly and, hence, direct buffers can be used more efficiently in I/O operations
# Buffer size
> * Provided that direct buffers are being used, the default 16kb buffers are optimal if maximum performance is required
| {
"content_hash": "b04b60e7a0896abe08742ea434699f67",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 170,
"avg_line_length": 43.568627450980394,
"alnum_prop": 0.7488748874887489,
"repo_name": "chungyushao/chungyushao.github.io",
"id": "f7313d0acd343bc1b006601a0af24fb04840f7c0",
"size": "2226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/devnotes/2016-10-22-undertow-tuning.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "50701"
},
{
"name": "HTML",
"bytes": "18740"
},
{
"name": "JavaScript",
"bytes": "78211"
},
{
"name": "Ruby",
"bytes": "1549"
},
{
"name": "Shell",
"bytes": "25"
}
],
"symlink_target": ""
} |
import os
import re
from selenium import webdriver
from xvfbwrapper import Xvfb
from cabu.exceptions import DriverException
from cabu.utils.headers import Headers
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium import webdriver
try:
from urllib.parse import urlsplit
except ImportError: # pragma: no cover
from urlparse import urlsplit # flake8: noqa
def load_vdisplay(config):
"""Initialize a vdisplay (Xvfb subprocess instance).
Args:
config (dict): The configuration loaded previously in Cabu.
Returns:
vdisplay: An instance of Xvfb wrapper.
"""
vdisplay = None
if config['HEADLESS']:
vdisplay = Xvfb(
width=config['DRIVER_WINDOWS_WIDTH'],
height=config['DRIVER_WINDOWS_HEIGHT']
)
vdisplay.start()
return vdisplay
def unload_vdisplay(vdisplay):
"""Shutdown given Xvfb instance.
Args:
vdisplay (XvfbWrapper): The running virtual X server.
"""
vdisplay.stop()
def load_driver(config, vdisplay=None):
"""Initialize a weddriver selected in config with given config.
Args:
config (dict): The configuration loaded previously in Cabu.
Returns:
webdriver (selenium.webdriver): An instance of selenium webdriver or None.
"""
if config['DRIVER_NAME'] == 'Firefox':
driver = load_firefox(config)
elif config['DRIVER_NAME'] == 'Chrome':
driver = load_chrome(config)
elif config['DRIVER_NAME'] == 'PhantomJS':
driver = load_phantomjs(config)
elif not config.get('DRIVER_NAME'):
return None
else:
raise DriverException(vdisplay, 'Driver unrecognized.')
driver.set_page_load_timeout(config['DRIVER_PAGE_TIMEOUT'])
driver.set_window_size(config['DRIVER_WINDOWS_WIDTH'], config['DRIVER_WINDOWS_HEIGHT'])
return driver
def unload_driver(driver):
"""Shutdown given webdriver instance.
Args:
driver (selenium.webdriver): The running webdriver.
"""
driver.quit()
def load_firefox(config):
"""Start Firefox webdriver with the given configuration.
Args:
config (dict): The configuration loaded previously in Cabu.
Returns:
webdriver (selenium.webdriver): An instance of Firefox webdriver.
"""
binary = None
profile = webdriver.FirefoxProfile()
if os.environ.get('HTTPS_PROXY') or os.environ.get('HTTP_PROXY'):
proxy_address = os.environ.get('HTTPS_PROXY', os.environ.get('HTTP_PROXY'))
proxy_port = re.search('\:([0-9]+)$', proxy_address).group(1)
profile.set_preference('network.proxy.type', 1)
profile.set_preference(
'network.proxy.http',
proxy_address
)
profile.set_preference('network.proxy.http_port', proxy_port)
profile.update_preferences()
if 'HEADERS' in config and config['HEADERS']:
profile = Headers(config).set_headers(profile)
if config['DRIVER_BINARY_PATH']:
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
binary = FirefoxBinary(config['DRIVER_BINARY_PATH'])
return webdriver.Firefox(firefox_binary=binary, firefox_profile=profile)
def load_chrome(config):
"""Start Chrome webdriver with the given configuration.
Args:
config (dict): The configuration loaded previously in Cabu.
Returns:
webdriver (selenium.webdriver): An instance of Chrome webdriver.
"""
return webdriver.Chrome()
def load_phantomjs(config):
"""Start PhantomJS webdriver with the given configuration.
Args:
config (dict): The configuration loaded previously in Cabu.
Returns:
webdriver (selenium.webdriver): An instance of phantomJS webdriver.
"""
dcap = dict(DesiredCapabilities.PHANTOMJS)
service_args = [
'--ignore-ssl-errors=true',
'--ssl-protocol=any',
'--web-security=false'
]
if os.environ.get('HTTPS_PROXY') or os.environ.get('HTTP_PROXY'):
proxy_address = os.environ.get('HTTPS_PROXY', os.environ.get('HTTP_PROXY'))
proxy_ip = re.search('http\:\/\/(.*)$', proxy_address).group(1)
service_args.append('--proxy=%s' % proxy_ip)
service_args.append('--proxy-type=http')
if 'HEADERS' in config and config['HEADERS']:
dcap = Headers(config).set_headers(dcap)
return webdriver.PhantomJS(
desired_capabilities=dcap,
service_args=service_args,
service_log_path=os.path.devnull
)
| {
"content_hash": "913b0093c9169765f1f7a42e0aa6edf3",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 91,
"avg_line_length": 28.273291925465838,
"alnum_prop": 0.6603690685413005,
"repo_name": "thylong/cabu",
"id": "79f212ed18232d9a20e96553e02496b414e7481c",
"size": "4577",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cabu/drivers.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "43370"
}
],
"symlink_target": ""
} |
from unittest import TestCase
from projects.gui import project_selector
class ProjectSelectorBaseCases(TestCase):
def test__project_selector_can_be_initialized(self):
data = [
'one',
'two',
'three'
]
selector = project_selector.ProjectSelector(data, '', '', '')
self.assertEqual(data, selector.data)
self.assertEqual('', selector.keys)
self.assertEqual(0, selector.focus)
def test__focus_can_be_moved_down(self):
data = [
'one',
'two',
'three'
]
selector = project_selector.ProjectSelector(data, '', '', '')
self.assertEqual(0, selector.focus)
selector.down()
self.assertEqual(1, selector.focus)
def test__focus_has_lower_limit(self):
data = [
'one',
'two',
'three'
]
selector = project_selector.ProjectSelector(data, '', '', '')
selector.down()
selector.down()
self.assertEqual(2, selector.focus)
selector.down()
self.assertEqual(2, selector.focus)
def test__focus_can_be_moved_up(self):
data = [
'one',
'two',
'three'
]
selector = project_selector.ProjectSelector(data, '', '', '')
self.assertEqual(0, selector.focus)
selector.down()
selector.up()
self.assertEqual(0, selector.focus)
def test__focus_has_upper_limit(self):
data = [
'one',
'two',
'three'
]
selector = project_selector.ProjectSelector(data, '', '', '')
self.assertEqual(0, selector.focus)
selector.down()
selector.up()
self.assertEqual(0, selector.focus)
selector.up()
self.assertEqual(0, selector.focus)
def test__data_in_focus_will_be_returned_on_selection_from_the_filtered_list(self):
data = [
'a',
'b',
'c'
]
selector = project_selector.ProjectSelector(data, '', '', '')
selector.down()
expected = 'b'
result = selector.select()
self.assertEqual(expected, result)
def test__adding_key_is_only_possible_if_there_are_match(self):
data = [
'one',
'two',
'three'
]
selector = project_selector.ProjectSelector(data, '', '', '')
self.assertEqual('', selector.keys)
selector.add_key('a')
self.assertEqual('', selector.keys)
selector.add_key('o')
self.assertEqual('o', selector.keys)
selector.add_key('e')
self.assertEqual('oe', selector.keys)
selector.add_key('l')
self.assertEqual('oe', selector.keys)
def test__removing_key(self):
data = [
'one',
'two',
'three'
]
selector = project_selector.ProjectSelector(data, '', '', '')
selector.add_key('o')
selector.remove_key()
self.assertEqual('', selector.keys)
selector.remove_key()
self.assertEqual('', selector.keys)
| {
"content_hash": "c97335bc98aaddce91127e01806b32cb",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 87,
"avg_line_length": 29.045871559633028,
"alnum_prop": 0.5259001895135819,
"repo_name": "tiborsimon/projects",
"id": "a78dbe7401062d70ea6a2d41c355db7c519f335d",
"size": "3213",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/project_selector/test_project_selector.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "314013"
},
{
"name": "Shell",
"bytes": "1248"
}
],
"symlink_target": ""
} |
#if !LESSTHAN_NET35
using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using CodeJam.Arithmetic;
using CodeJam.Strings;
using NUnit.Framework;
using static NUnit.Framework.Assert;
#if LESSTHAN_NET40
using EnumTargetingHelpers = CodeJam.Targeting.EnumTargeting;
#else
using EnumTargetingHelpers = System.Enum;
#endif
namespace CodeJam
{
[TestFixture(Category = "EnumHelper")]
[SuppressMessage("ReSharper", "ArrangeRedundantParentheses")]
[SuppressMessage("ReSharper", "HeapView.BoxingAllocation")]
[SuppressMessage("ReSharper", "HeapView.DelegateAllocation")]
[SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")]
public class EnumHelperTests
{
#region Test helpers
[Flags]
private enum Flags : byte
{
Zero = 0x0,
A = 0x1,
B = 0x2,
C = 0x4,
D = 0x8,
// ReSharper disable once InconsistentNaming
CD = C | D
}
private const Flags Ab = Flags.A | Flags.B;
private const Flags Abc = Flags.A | Flags.B | Flags.C;
private const Flags Abcd = Flags.A | Flags.B | Flags.C | Flags.D;
private const Flags Bc = Flags.B | Flags.C;
private const Flags Bd = Flags.B | Flags.D;
private const Flags D = Flags.D;
private const Flags Zero = Flags.Zero;
private const Flags Undef = (Flags)0x10;
private const Flags AbU = Flags.A | Flags.B | Undef;
private enum NoFlags : byte
{
Zero = 0x0,
E = 0x1,
F = 0x2,
G = 0x4,
H = 0x8,
// ReSharper disable once InconsistentNaming
GH = G | H
}
// ReSharper disable BitwiseOperatorOnEnumWithoutFlags
private const NoFlags Ef = NoFlags.E | NoFlags.F;
private const NoFlags Efg = NoFlags.E | NoFlags.F | NoFlags.G;
private const NoFlags NoFlagsUndef = (NoFlags)0x10;
private const NoFlags EfU = NoFlags.E | NoFlags.F | NoFlagsUndef;
// ReSharper restore BitwiseOperatorOnEnumWithoutFlags
public enum NameDescEnum
{
[Display(Name = "Field 1", Description = "Field 1 Desc")]
Field1,
[Display]
Field2,
Field3
}
#endregion
[Test]
public void Test0001IsDefined()
{
Throws<ArgumentException>(() => Enum.IsDefined(typeof(int), 2));
IsTrue(EnumHelper.IsDefined(Flags.A));
IsTrue(EnumHelper.IsDefined(Flags.B));
IsTrue(EnumHelper.IsDefined(Flags.C));
IsTrue(EnumHelper.IsDefined(Flags.CD));
IsFalse(EnumHelper.IsDefined(Undef));
IsFalse(EnumHelper.IsDefined(Ab));
IsFalse(EnumHelper.IsDefined(Abc));
IsFalse(EnumHelper.IsDefined(AbU));
IsTrue(Enum.IsDefined(typeof(Flags), Flags.A));
IsTrue(Enum.IsDefined(typeof(Flags), Flags.B));
IsTrue(Enum.IsDefined(typeof(Flags), Flags.C));
IsTrue(Enum.IsDefined(typeof(Flags), Flags.CD));
IsFalse(Enum.IsDefined(typeof(Flags), Undef));
IsFalse(Enum.IsDefined(typeof(Flags), Ab));
IsFalse(Enum.IsDefined(typeof(Flags), Abc));
IsFalse(Enum.IsDefined(typeof(Flags), AbU));
IsTrue(EnumHelper.AreFlagsDefined(Flags.A));
IsTrue(EnumHelper.AreFlagsDefined(Flags.CD));
IsTrue(EnumHelper.AreFlagsDefined(Ab));
IsTrue(EnumHelper.AreFlagsDefined(Abc));
IsTrue(EnumHelper.AreFlagsDefined(Abcd));
IsFalse(EnumHelper.AreFlagsDefined(Undef));
IsFalse(EnumHelper.AreFlagsDefined(AbU));
IsTrue(EnumHelper.AreFlagsDefined(NoFlags.E));
IsTrue(EnumHelper.AreFlagsDefined(NoFlags.GH));
IsFalse(EnumHelper.AreFlagsDefined(Ef));
IsFalse(EnumHelper.AreFlagsDefined(Efg));
IsFalse(EnumHelper.AreFlagsDefined(NoFlagsUndef));
IsFalse(EnumHelper.AreFlagsDefined(EfU));
}
[TestCase("A", ExpectedResult = true)]
[TestCase("B", ExpectedResult = true)]
[TestCase("C", ExpectedResult = true)]
[TestCase("CD", ExpectedResult = true)]
[TestCase("Undef", ExpectedResult = false)]
public bool IsDefinedStr(string value) => EnumHelper.IsDefined<Flags>(value);
[Test]
public void Test0002FlagsVsNoFlags()
{
IsTrue(EnumHelper.IsFlagsEnum<Flags>());
IsFalse(EnumHelper.IsFlagsEnum<NoFlags>());
AreEqual(EnumHelper.GetFlagsMask<Flags>(), Abcd);
AreEqual(EnumHelper.GetFlagsMask<NoFlags>(), NoFlags.Zero);
}
[Test]
public void Test01Parse()
{
Flags result1;
Flags result2;
AreEqual(
EnumHelper.TryParse(nameof(Flags.A), out result1),
EnumTargetingHelpers.TryParse(nameof(Flags.A), out result2));
AreEqual(result1, result2);
AreEqual(result1, EnumHelper.TryParse<Flags>(nameof(Flags.A)));
AreEqual(
EnumHelper.TryParse(Undef.ToString(), out result1),
EnumTargetingHelpers.TryParse(Undef.ToString(), out result2));
AreEqual(result1, result2);
AreEqual(result1, EnumHelper.TryParse<Flags>(Undef.ToString()));
AreEqual(
EnumHelper.TryParse(nameof(Flags.CD), out result1),
EnumTargetingHelpers.TryParse(nameof(Flags.CD), out result2));
AreEqual(result1, result2);
AreEqual(
EnumHelper.TryParse(Abcd.ToString(), out result1),
EnumTargetingHelpers.TryParse(Abcd.ToString(), out result2));
AreEqual(result1, result2);
AreEqual(
EnumHelper.TryParse(AbU.ToString(), out result1),
EnumTargetingHelpers.TryParse(AbU.ToString(), out result2));
AreEqual(result1, result2);
AreEqual(
EnumHelper.TryParse("0", out result1),
EnumTargetingHelpers.TryParse("0", out result2));
AreEqual(result1, result2);
AreEqual(
EnumHelper.TryParse("1", out result1),
EnumTargetingHelpers.TryParse("1", out result2));
AreEqual(result1, result2);
}
[Test]
public void Test02GetName() => AreEqual("ReturnValue", EnumHelper.GetName(AttributeTargets.ReturnValue));
[Test]
public void Test03GetNames() =>
AreEqual(
"Assembly, Module, Class, Struct, Enum, Constructor, Method, Property, Field, Event, Interface, Parameter, " +
"Delegate, ReturnValue, GenericParameter, All",
EnumHelper.GetNames<AttributeTargets>().Join(", "));
[Test]
public void Test04GetValues() =>
AreEqual(
"Assembly, Module, Class, Struct, Enum, Constructor, Method, Property, Field, Event, Interface, Parameter, " +
"Delegate, ReturnValue, GenericParameter, All",
EnumHelper.GetValues<AttributeTargets>().Join(", "));
[Test]
public void Test05GetNameValues() =>
AreEqual(
"Assembly, Module, Class, Struct, Enum, Constructor, Method, Property, Field, Event, Interface, Parameter, " +
"Delegate, ReturnValue, GenericParameter, All",
EnumHelper.GetNameValues<AttributeTargets>().Select(kvp => kvp.Key).Join(", "));
[Test]
public static void Test0601IsFlagSet()
{
#if !LESSTHAN_NET45
IsTrue(Abc.HasFlag(Zero));
IsTrue(Abc.HasFlag(Bc));
IsTrue(Abc.HasFlag(Abc));
IsFalse(Abc.HasFlag(Abcd));
IsFalse(Abc.HasFlag(Bd));
IsFalse(Abc.HasFlag(D));
#endif
IsTrue(Abc.IsFlagSet(Zero));
IsTrue(Abc.IsFlagSet(Bc));
IsTrue(Abc.IsFlagSet(Abc));
IsFalse(Abc.IsFlagSet(Abcd));
IsFalse(Abc.IsFlagSet(Bd));
IsFalse(Abc.IsFlagSet(D));
IsFalse(Abc.IsAnyFlagUnset(Zero));
IsFalse(Abc.IsAnyFlagUnset(Bc));
IsFalse(Abc.IsAnyFlagUnset(Abc));
IsTrue(Abc.IsAnyFlagUnset(Abcd));
IsTrue(Abc.IsAnyFlagUnset(Bd));
IsTrue(Abc.IsAnyFlagUnset(D));
IsTrue(Abc.IsAnyFlagSet(Zero));
IsTrue(Abc.IsAnyFlagSet(Bc));
IsTrue(Abc.IsAnyFlagSet(Abc));
IsTrue(Abc.IsAnyFlagSet(Abcd));
IsTrue(Abc.IsAnyFlagSet(Bd));
IsFalse(Abc.IsAnyFlagSet(D));
IsFalse(Abc.IsFlagUnset(Zero));
IsFalse(Abc.IsFlagUnset(Bc));
IsFalse(Abc.IsFlagUnset(Abc));
IsFalse(Abc.IsFlagUnset(Abcd));
IsFalse(Abc.IsFlagUnset(Bd));
IsTrue(Abc.IsFlagUnset(D));
}
[Test]
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "LocalVariableHidesMember")]
public static void Test0602IsFlagSetOperators()
{
var isFlagSet = OperatorsFactory.IsFlagSetOperator<int>();
var isAnyFlagSet = OperatorsFactory.IsAnyFlagSetOperator<int>();
const int Abc = (int)EnumHelperTests.Abc;
const int Abcd = (int)EnumHelperTests.Abcd;
const int Bc = (int)EnumHelperTests.Bc;
const int Bd = (int)EnumHelperTests.Bd;
const int D = (int)EnumHelperTests.D;
const int Zero = (int)EnumHelperTests.Zero;
IsTrue(isFlagSet(Abc, Zero));
IsTrue(isFlagSet(Abc, Bc));
IsTrue(isFlagSet(Abc, Abc));
IsFalse(isFlagSet(Abc, Abcd));
IsFalse(isFlagSet(Abc, Bd));
IsFalse(isFlagSet(Abc, D));
IsTrue(isAnyFlagSet(Abc, Zero));
IsTrue(isAnyFlagSet(Abc, Bc));
IsTrue(isAnyFlagSet(Abc, Abc));
IsTrue(isAnyFlagSet(Abc, Abcd));
IsTrue(isAnyFlagSet(Abc, Bd));
IsFalse(isAnyFlagSet(Abc, D));
}
[Test]
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "LocalVariableHidesMember")]
public static void Test0603IsFlagSetInt()
{
bool IsFlagSet(int value, int flag) => (value & flag) == flag;
bool IsAnyFlagSet(int value, int flag) => (flag == 0) || ((value & flag) != 0);
const int Abc = (int)EnumHelperTests.Abc;
const int Abcd = (int)EnumHelperTests.Abcd;
const int Bc = (int)EnumHelperTests.Bc;
const int Bd = (int)EnumHelperTests.Bd;
const int D = (int)EnumHelperTests.D;
const int Zero = (int)EnumHelperTests.Zero;
IsTrue(IsFlagSet(Abc, Zero));
IsTrue(IsFlagSet(Abc, Bc));
IsTrue(IsFlagSet(Abc, Abc));
IsFalse(IsFlagSet(Abc, Abcd));
IsFalse(IsFlagSet(Abc, Bd));
IsFalse(IsFlagSet(Abc, D));
IsTrue(IsAnyFlagSet(Abc, Zero));
IsTrue(IsAnyFlagSet(Abc, Bc));
IsTrue(IsAnyFlagSet(Abc, Abc));
IsTrue(IsAnyFlagSet(Abc, Abcd));
IsTrue(IsAnyFlagSet(Abc, Bd));
IsFalse(IsAnyFlagSet(Abc, D));
}
[Test]
public static void Test07SetFlag()
{
AreEqual(Abc.SetFlag(Zero), Abc);
AreEqual(Abc.SetFlag(Bc), Abc);
AreEqual(Abc.SetFlag(Abc), Abc);
AreEqual(Abc.SetFlag(Abcd), Abcd);
AreEqual(Abc.SetFlag(Bd), Abcd);
AreEqual(Abc.SetFlag(D), Abcd);
}
[Test]
public static void Test08ClearFlag()
{
AreEqual(Abc.ClearFlag(Zero), Abc);
AreEqual(Abc.ClearFlag(Bc), Flags.A);
AreEqual(Abc.ClearFlag(Abc), Zero);
AreEqual(Abc.ClearFlag(Abcd), Zero);
AreEqual(Abc.ClearFlag(Bd), Flags.A | Flags.C);
AreEqual(Abc.ClearFlag(D), Abc);
}
[Test]
public static void Test09SetOrClearFlag()
{
AreEqual(Abc.SetFlag(Zero, true), Abc);
AreEqual(Abc.SetFlag(Bc, true), Abc);
AreEqual(Abc.SetFlag(Abc, true), Abc);
AreEqual(Abc.SetFlag(Abcd, true), Abcd);
AreEqual(Abc.SetFlag(Bd, true), Abcd);
AreEqual(Abc.SetFlag(D, true), Abcd);
AreEqual(Abc.SetFlag(Zero, false), Abc);
AreEqual(Abc.SetFlag(Bc, false), Flags.A);
AreEqual(Abc.SetFlag(Abc, false), Zero);
AreEqual(Abc.SetFlag(Abcd, false), Zero);
AreEqual(Abc.SetFlag(Bd, false), Flags.A | Flags.C);
AreEqual(Abc.SetFlag(D, false), Abc);
}
[TestCase(NameDescEnum.Field1, ExpectedResult = "Field 1")]
[TestCase(NameDescEnum.Field2, ExpectedResult = "Field2")]
[TestCase(NameDescEnum.Field3, ExpectedResult = "Field3")]
public string GetDisplayName(NameDescEnum value) => EnumHelper.GetDisplayName(value);
[TestCase(NameDescEnum.Field1, ExpectedResult = "Field 1 Desc")]
[TestCase(NameDescEnum.Field2, ExpectedResult = null)]
[TestCase(NameDescEnum.Field3, ExpectedResult = null)]
public string GetDescription(NameDescEnum value) => EnumHelper.GetDescription(value);
[TestCase(NameDescEnum.Field1, ExpectedResult = "Field 1 (Field 1 Desc)")]
[TestCase(NameDescEnum.Field2, ExpectedResult = "Field2")]
[TestCase(NameDescEnum.Field3, ExpectedResult = "Field3")]
public string GetDisplay(NameDescEnum value) => EnumHelper.GetEnumValue(value).ToString();
}
}
#endif | {
"content_hash": "40dc860a70310fe300825ca952a961be",
"timestamp": "",
"source": "github",
"line_count": 364,
"max_line_length": 114,
"avg_line_length": 31.486263736263737,
"alnum_prop": 0.707180874269261,
"repo_name": "NN---/CodeJam",
"id": "eb84943c1ee6c79f13ff53c6bfcbf77f72346afc",
"size": "11463",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CodeJam.Main.Tests/EnumHelperTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1402"
},
{
"name": "C#",
"bytes": "3895637"
},
{
"name": "PowerShell",
"bytes": "6413"
}
],
"symlink_target": ""
} |
<?php
/**
* Tag
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package skeleton
* @subpackage model
* @author Your name here
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class Tag extends BaseTag
{
}
| {
"content_hash": "5278d97a80c97f66a6f884d2cb4d8ad9",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 70,
"avg_line_length": 18.266666666666666,
"alnum_prop": 0.6423357664233577,
"repo_name": "bshaffer/Hadori-Demo",
"id": "e2c7f9706818fae8c308828584fb5ecf0bb8323e",
"size": "274",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/model/doctrine/Tag.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "21293"
},
{
"name": "PHP",
"bytes": "480659"
},
{
"name": "Shell",
"bytes": "25480"
}
],
"symlink_target": ""
} |
var express = require('../')
, request = require('./support/http')
, assert = require('assert');
describe('res', function(){
describe('.json(object)', function(){
it('should not support jsonp callbacks', function(done){
var app = express();
app.use(function(req, res){
res.json({ foo: 'bar' });
});
request(app)
.get('/?callback=foo')
.expect('{"foo":"bar"}', done);
})
describe('when given primitives', function(){
it('should respond with json', function(done){
var app = express();
app.use(function(req, res){
res.json(null);
});
request(app)
.get('/')
.end(function(err, res){
res.headers.should.have.property('content-type', 'application/json');
res.text.should.equal('null');
done();
})
})
})
describe('when given an array', function(){
it('should respond with json', function(done){
var app = express();
app.use(function(req, res){
res.json(['foo', 'bar', 'baz']);
});
request(app)
.get('/')
.end(function(err, res){
res.headers.should.have.property('content-type', 'application/json');
res.text.should.equal('["foo","bar","baz"]');
done();
})
})
})
describe('when given an object', function(){
it('should respond with json', function(done){
var app = express();
app.use(function(req, res){
res.json({ name: 'tobi' });
});
request(app)
.get('/')
.end(function(err, res){
res.headers.should.have.property('content-type', 'application/json');
res.text.should.equal('{"name":"tobi"}');
done();
})
})
})
describe('"json replacer" setting', function(){
it('should be passed to JSON.stringify()', function(done){
var app = express();
app.set('json replacer', function(key, val){
return '_' == key[0]
? undefined
: val;
});
app.use(function(req, res){
res.json({ name: 'tobi', _id: 12345 });
});
request(app)
.get('/')
.end(function(err, res){
res.text.should.equal('{"name":"tobi"}');
done();
});
})
})
describe('"json spaces" setting', function(){
it('should default to 2 in development', function(){
process.env.NODE_ENV = 'development';
var app = express();
app.get('json spaces').should.equal(2);
process.env.NODE_ENV = 'test';
})
it('should be undefined otherwise', function(){
var app = express();
assert(undefined === app.get('json spaces'));
})
it('should be passed to JSON.stringify()', function(done){
var app = express();
app.set('json spaces', 2);
app.use(function(req, res){
res.json({ name: 'tobi', age: 2 });
});
request(app)
.get('/')
.end(function(err, res){
res.text.should.equal('{\n "name": "tobi",\n "age": 2\n}');
done();
});
})
})
})
describe('.json(status, object)', function(){
it('should respond with json and set the .statusCode', function(done){
var app = express();
app.use(function(req, res){
res.json(201, { id: 1 });
});
request(app)
.get('/')
.end(function(err, res){
res.statusCode.should.equal(201);
res.headers.should.have.property('content-type', 'application/json');
res.text.should.equal('{"id":1}');
done();
})
})
})
describe('.json(object, status)', function(){
it('should respond with json and set the .statusCode for backwards compat', function(done){
var app = express();
app.use(function(req, res){
res.json({ id: 1 }, 201);
});
request(app)
.get('/')
.end(function(err, res){
res.statusCode.should.equal(201);
res.headers.should.have.property('content-type', 'application/json');
res.text.should.equal('{"id":1}');
done();
})
})
})
it('should not override previous Content-Types', function(done){
var app = express();
app.get('/', function(req, res){
res.type('application/vnd.example+json');
res.json({ hello: 'world' });
});
request(app)
.get('/')
.end(function(err, res){
res.statusCode.should.equal(200);
res.headers.should.have.property('content-type', 'application/vnd.example+json');
res.text.should.equal('{"hello":"world"}');
done();
})
})
})
| {
"content_hash": "954244bcb39b57103ee9117c9f98a8ed",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 95,
"avg_line_length": 25.885245901639344,
"alnum_prop": 0.5127717964956724,
"repo_name": "bevacqua/express",
"id": "da20a2c96c577c89e2f96aec94c059ce25cc730b",
"size": "4738",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/res.json.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package vgtest.testview.view;
import android.content.Context;
import android.widget.FrameLayout;
import android.widget.ScrollView;
//! 测试长幅绘图的滚动视图类
public class LargeView1 extends ScrollView {
public LargeView1(Context context) {
super(context);
this.createContentView(context);
}
private void createContentView(Context context) {
final StdGraphView1 view = new StdGraphView1(context);
final FrameLayout layout = new FrameLayout(context);
layout.addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, 2048));
this.addView(layout);
}
}
| {
"content_hash": "309636626b0133263e1721112bad15a0",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 80,
"avg_line_length": 28.59090909090909,
"alnum_prop": 0.6947535771065183,
"repo_name": "aw691190716/vgandroid-demo",
"id": "e38ee1b5da7ddc578051752ea018c8ea7881410f",
"size": "810",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/src/vgtest/testview/view/LargeView1.java",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "117977"
},
{
"name": "Shell",
"bytes": "1605"
}
],
"symlink_target": ""
} |
<?php
namespace Sylius\Behat\Context\Ui\Admin;
use Behat\Behat\Context\Context;
use Sylius\Behat\NotificationType;
use Sylius\Behat\Page\Admin\Crud\CreatePageInterface;
use Sylius\Behat\Page\Admin\Crud\IndexPageInterface;
use Sylius\Behat\Page\Admin\Crud\UpdatePageInterface;
use Sylius\Behat\Page\Admin\Product\CreateConfigurableProductPageInterface;
use Sylius\Behat\Page\Admin\Product\CreateSimpleProductPageInterface;
use Sylius\Behat\Page\Admin\Product\UpdateConfigurableProductPageInterface;
use Sylius\Behat\Page\Admin\Product\UpdateSimpleProductPageInterface;
use Sylius\Behat\Service\NotificationCheckerInterface;
use Sylius\Behat\Service\Resolver\CurrentProductPageResolverInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Behat\Service\SharedStorageInterface;
use Sylius\Component\Taxonomy\Model\TaxonInterface;
use Webmozart\Assert\Assert;
/**
* @author Kamil Kokot <kamil.kokot@lakion.com>
* @author Magdalena Banasiak <magdalena.banasiak@lakion.com>
* @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
*/
final class ManagingProductsContext implements Context
{
/**
* @var SharedStorageInterface
*/
private $sharedStorage;
/**x
* @var CreateSimpleProductPageInterface
*/
private $createSimpleProductPage;
/**
* @var CreateConfigurableProductPageInterface
*/
private $createConfigurableProductPage;
/**
* @var IndexPageInterface
*/
private $indexPage;
/**
* @var UpdateSimpleProductPageInterface
*/
private $updateSimpleProductPage;
/**
* @var UpdateConfigurableProductPageInterface
*/
private $updateConfigurableProductPage;
/**
* @var CurrentProductPageResolverInterface
*/
private $currentPageResolver;
/**
* @var NotificationCheckerInterface
*/
private $notificationChecker;
/**
* @param SharedStorageInterface $sharedStorage
* @param CreateSimpleProductPageInterface $createSimpleProductPage
* @param CreateConfigurableProductPageInterface $createConfigurableProductPage
* @param IndexPageInterface $indexPage
* @param UpdateSimpleProductPageInterface $updateSimpleProductPage
* @param UpdateConfigurableProductPageInterface $updateConfigurableProductPage
* @param CurrentProductPageResolverInterface $currentPageResolver
* @param NotificationCheckerInterface $notificationChecker
*/
public function __construct(
SharedStorageInterface $sharedStorage,
CreateSimpleProductPageInterface $createSimpleProductPage,
CreateConfigurableProductPageInterface $createConfigurableProductPage,
IndexPageInterface $indexPage,
UpdateSimpleProductPageInterface $updateSimpleProductPage,
UpdateConfigurableProductPageInterface $updateConfigurableProductPage,
CurrentProductPageResolverInterface $currentPageResolver,
NotificationCheckerInterface $notificationChecker
) {
$this->sharedStorage = $sharedStorage;
$this->createSimpleProductPage = $createSimpleProductPage;
$this->createConfigurableProductPage = $createConfigurableProductPage;
$this->indexPage = $indexPage;
$this->updateSimpleProductPage = $updateSimpleProductPage;
$this->updateConfigurableProductPage = $updateConfigurableProductPage;
$this->currentPageResolver = $currentPageResolver;
$this->notificationChecker = $notificationChecker;
}
/**
* @Given I want to create a new simple product
*/
public function iWantToCreateANewSimpleProduct()
{
$this->createSimpleProductPage->open();
}
/**
* @Given I want to create a new configurable product
*/
public function iWantToCreateANewConfigurableProduct()
{
$this->createConfigurableProductPage->open();
}
/**
* @When I specify its code as :code
* @When I do not specify its code
*/
public function iSpecifyItsCodeAs($code = null)
{
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->createSimpleProductPage,
$this->createConfigurableProductPage,
]);
$currentPage->specifyCode($code);
}
/**
* @When I name it :name in :language
*/
public function iNameItIn($name, $language)
{
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->createSimpleProductPage,
$this->createConfigurableProductPage,
]);
$currentPage->nameItIn($name, $language);
}
/**
* @When I rename it to :name in :language
*/
public function iRenameItToIn($name, $language)
{
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->updateSimpleProductPage,
$this->updateConfigurableProductPage,
], $this->sharedStorage->get('product'));
$currentPage->nameItIn($name, $language);
}
/**
* @When I add it
* @When I try to add it
*/
public function iAddIt()
{
/** @var CreatePageInterface $currentPage */
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->createSimpleProductPage,
$this->createConfigurableProductPage,
]);
Assert::isInstanceOf($currentPage, CreatePageInterface::class);
$currentPage->create();
}
/**
* @When I disable its inventory tracking
*/
public function iDisableItsTracking()
{
$this->updateSimpleProductPage->disableTracking();
}
/**
* @When I enable its inventory tracking
*/
public function iEnableItsTracking()
{
$this->updateSimpleProductPage->enableTracking();
}
/**
* @When /^I set its price to ("(?:€|£|\$)[^"]+")$/
*/
public function iSetItsPriceTo($price)
{
$this->createSimpleProductPage->specifyPrice($price);
}
/**
* @Given the product :productName should appear in the shop
* @Given the product :productName should be in the shop
* @Given this product should still be named :productName
*/
public function theProductShouldAppearInTheShop($productName)
{
$this->iWantToBrowseProducts();
Assert::true(
$this->indexPage->isSingleResourceOnPage(['name' => $productName]),
sprintf('The product with name %s has not been found.', $productName)
);
}
/**
* @When I want to browse products
*/
public function iWantToBrowseProducts()
{
$this->indexPage->open();
}
/**
* @Then I should see :numberOfProducts products in the list
*/
public function iShouldSeeProductsInTheList($numberOfProducts)
{
$foundRows = $this->indexPage->countItems();
Assert::eq(
$numberOfProducts,
$foundRows,
'%s rows with products should appear on page, %s rows has been found'
);
}
/**
* @When I delete the :product product
* @When I try to delete the :product product
*/
public function iDeleteProduct(ProductInterface $product)
{
$this->sharedStorage->set('product', $product);
$this->iWantToBrowseProducts();
$this->indexPage->deleteResourceOnPage(['name' => $product->getName()]);
}
/**
* @Then /^(this product) should not exist in the product catalog$/
*/
public function productShouldNotExist(ProductInterface $product)
{
$this->iWantToBrowseProducts();
Assert::false(
$this->indexPage->isSingleResourceOnPage(['code' => $product->getCode()]),
sprintf('Product with code %s exists but should not.', $product->getCode())
);
}
/**
* @Then I should be notified that this product is in use and cannot be deleted
*/
public function iShouldBeNotifiedOfFailure()
{
$this->notificationChecker->checkNotification(
"Cannot delete, the product is in use.",
NotificationType::failure()
);
}
/**
* @Then /^(this product) should still exist in the product catalog$/
*/
public function productShouldExistInTheProductCatalog(ProductInterface $product)
{
$this->theProductShouldAppearInTheShop($product->getName());
}
/**
* @When I want to modify the :product product
* @When /^I want to modify (this product)$/
*/
public function iWantToModifyAProduct(ProductInterface $product)
{
$this->sharedStorage->set('product', $product);
if ($product->isSimple()) {
$this->updateSimpleProductPage->open(['id' => $product->getId()]);
return;
}
$this->updateConfigurableProductPage->open(['id' => $product->getId()]);
}
/**
* @Then the code field should be disabled
*/
public function theCodeFieldShouldBeDisabled()
{
/** @var UpdatePageInterface $currentPage */
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->updateSimpleProductPage,
$this->updateConfigurableProductPage,
], $this->sharedStorage->get('product'));
Assert::true(
$currentPage->isCodeDisabled(),
'Code should be immutable, but it does not.'
);
}
/**
* @Then /^this product price should be "(?:€|£|\$)([^"]+)"$/
*/
public function thisProductPriceShouldBeEqualTo($price)
{
$this->assertElementValue('price', $price);
}
/**
* @Then this product name should be :name
*/
public function thisProductElementShouldBe($name)
{
$this->assertElementValue('name', $name);
}
/**
* @Then /^I should be notified that (code|name) is required$/
*/
public function iShouldBeNotifiedThatIsRequired($element)
{
$this->assertValidationMessage($element, sprintf('Please enter product %s.', $element));
}
/**
* @Then I should be notified that price is required
*/
public function iShouldBeNotifiedThatPriceIsRequired()
{
$this->assertValidationMessage('price', 'Please enter the price.');
}
/**
* @When I save my changes
* @When I try to save my changes
*/
public function iSaveMyChanges()
{
/** @var UpdatePageInterface $currentPage */
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->updateSimpleProductPage,
$this->updateConfigurableProductPage,
], $this->sharedStorage->get('product'));
Assert::isInstanceOf($currentPage, UpdatePageInterface::class);
$currentPage->saveChanges();
}
/**
* @When /^I change its price to "(?:€|£|\$)([^"]+)"$/
*/
public function iChangeItsPriceTo($price)
{
$this->updateSimpleProductPage->specifyPrice($price);
}
/**
* @Given I add the :optionName option to it
*/
public function iAddTheOptionToIt($optionName)
{
$this->createConfigurableProductPage->selectOption($optionName);
}
/**
* @When I set its :attribute attribute to :value
*/
public function iSetItsAttributeTo($attribute, $value)
{
$this->createSimpleProductPage->addAttribute($attribute, $value);
}
/**
* @When I remove its :attribute attribute
*/
public function iRemoveItsAttribute($attribute)
{
$this->createSimpleProductPage->removeAttribute($attribute);
}
/**
* @Then /^attribute "([^"]+)" of (product "[^"]+") should be "([^"]+)"$/
*/
public function itsAttributeShouldBe($attribute, ProductInterface $product, $value)
{
$this->updateSimpleProductPage->open(['id' => $product->getId()]);
Assert::same(
$value,
$this->updateSimpleProductPage->getAttributeValue($attribute),
sprintf('Attribute "%s" should have value "%s" but it does not.', $attribute, $value)
);
}
/**
* @Then /^(product "[^"]+") should not have a "([^"]+)" attribute$/
*/
public function productShouldNotHaveAttribute(ProductInterface $product, $attribute)
{
$this->updateSimpleProductPage->open(['id' => $product->getId()]);
Assert::false(
$this->updateSimpleProductPage->hasAttribute($attribute),
sprintf('Product "%s" should not have attribute "%s" but it does.', $product->getName(), $attribute)
);
}
/**
* @Given product with :element :value should not be added
*/
public function productWithNameShouldNotBeAdded($element, $value)
{
$this->iWantToBrowseProducts();
Assert::false(
$this->indexPage->isSingleResourceOnPage([$element => $value]),
sprintf('Product with %s %s was created, but it should not.', $element, $value)
);
}
/**
* @When I remove its name from :language translation
*/
public function iRemoveItsNameFromTranslation($language)
{
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->updateSimpleProductPage,
$this->updateConfigurableProductPage,
], $this->sharedStorage->get('product'));
$currentPage->nameItIn('', $language);
}
/**
* @Then /^this product should have (?:a|an) "([^"]+)" option$/
*/
public function thisProductShouldHaveOption($productOption)
{
$this->updateConfigurableProductPage->isProductOptionChosen($productOption);
}
/**
* @Then the option field should be disabled
*/
public function theOptionFieldShouldBeDisabled()
{
Assert::true(
$this->updateConfigurableProductPage->isCodeDisabled(),
'Option should be immutable, but it does not.'
);
}
/**
* @When /^I choose main (taxon "([^"]+)")$/
*/
public function iChooseMainTaxon(TaxonInterface $taxon)
{
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->updateSimpleProductPage,
$this->updateConfigurableProductPage,
], $this->sharedStorage->get('product'));
$currentPage->selectMainTaxon($taxon);
}
/**
* @Then /^(this product) main taxon should be "([^"]+)"$/
*/
public function thisProductMainTaxonShouldBe(ProductInterface $product, $taxonName)
{
/** @var UpdatePageInterface $currentPage */
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->updateSimpleProductPage,
$this->updateConfigurableProductPage,
], $this->sharedStorage->get('product'));
$currentPage->open(['id' => $product->getId()]);
Assert::true(
$this->updateConfigurableProductPage->isMainTaxonChosen($taxonName),
sprintf('The main taxon %s should be chosen, but it does not.', $taxonName)
);
}
/**
* @Then /^inventory of (this product) should not be tracked$/
*/
public function thisProductShouldNotBeTracked(ProductInterface $product)
{
$this->iWantToModifyAProduct($product);
Assert::false(
$this->updateSimpleProductPage->isTracked(),
'"%s" should not be tracked, but it is.'
);
}
/**
* @Then /^inventory of (this product) should be tracked$/
*/
public function thisProductShouldBeTracked(ProductInterface $product)
{
$this->iWantToModifyAProduct($product);
Assert::true(
$this->updateSimpleProductPage->isTracked(),
'"%s" should be tracked, but it is not.'
);
}
/**
* @param string $element
* @param string $value
*/
private function assertElementValue($element, $value)
{
/** @var UpdatePageInterface $currentPage */
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->updateSimpleProductPage,
$this->updateConfigurableProductPage,
], $this->sharedStorage->get('product'));
Assert::isInstanceOf($currentPage, UpdatePageInterface::class);
Assert::true(
$currentPage->hasResourceValues(
[$element => $value]
),
sprintf('Product should have %s with %s value.', $element, $value)
);
}
/**
* @param string $element
* @param string $message
*/
private function assertValidationMessage($element, $message)
{
$product = $this->sharedStorage->has('product') ? $this->sharedStorage->get('product') : null;
/** @var CreatePageInterface|UpdatePageInterface $currentPage */
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([
$this->createSimpleProductPage,
$this->createConfigurableProductPage,
$this->updateSimpleProductPage,
$this->updateConfigurableProductPage,
], $product);
Assert::same($currentPage->getValidationMessage($element), $message);
}
}
| {
"content_hash": "c42013d9f7a7d254f65f89d96e58ed6c",
"timestamp": "",
"source": "github",
"line_count": 562,
"max_line_length": 112,
"avg_line_length": 30.590747330960856,
"alnum_prop": 0.6319218241042345,
"repo_name": "Rvanlaak/Sylius",
"id": "cfd0a907922b135ba18dc7d2257eaa5f615ddc03",
"size": "17414",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/Sylius/Behat/Context/Ui/Admin/ManagingProductsContext.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "519"
},
{
"name": "Batchfile",
"bytes": "3643"
},
{
"name": "CSS",
"bytes": "77081"
},
{
"name": "Cucumber",
"bytes": "301177"
},
{
"name": "HTML",
"bytes": "481053"
},
{
"name": "JavaScript",
"bytes": "132932"
},
{
"name": "PHP",
"bytes": "4217617"
},
{
"name": "Puppet",
"bytes": "3165"
},
{
"name": "Ruby",
"bytes": "1210"
},
{
"name": "Shell",
"bytes": "5421"
}
],
"symlink_target": ""
} |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Range.h"
#include "swift/ABI/TypeIdentity.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Runtime/Portability.h"
#include "swift/Strings.h"
#include "Private.h"
#include <vector>
#if SWIFT_OBJC_INTEROP
#include <objc/runtime.h>
#endif
using namespace swift;
Demangle::NodePointer
swift::_buildDemanglingForContext(const ContextDescriptor *context,
llvm::ArrayRef<NodePointer> demangledGenerics,
Demangle::Demangler &Dem) {
unsigned usedDemangledGenerics = 0;
NodePointer node = nullptr;
// Walk up the context tree.
SmallVector<const ContextDescriptor *, 8> descriptorPath;
{
const ContextDescriptor *parent = context;
while (parent) {
descriptorPath.push_back(parent);
parent = parent->Parent;
}
}
auto getGenericArgsTypeListForContext =
[&](const ContextDescriptor *context) -> NodePointer {
if (demangledGenerics.empty())
return nullptr;
if (context->getKind() == ContextDescriptorKind::Anonymous)
return nullptr;
auto generics = context->getGenericContext();
if (!generics)
return nullptr;
auto numParams = generics->getGenericContextHeader().NumParams;
if (numParams <= usedDemangledGenerics)
return nullptr;
auto genericArgsList = Dem.createNode(Node::Kind::TypeList);
for (unsigned e = generics->getGenericContextHeader().NumParams;
usedDemangledGenerics < e;
++usedDemangledGenerics) {
genericArgsList->addChild(demangledGenerics[usedDemangledGenerics],
Dem);
}
return genericArgsList;
};
for (auto component : reversed(descriptorPath)) {
switch (auto kind = component->getKind()) {
case ContextDescriptorKind::Module: {
assert(node == nullptr && "module should be top level");
auto name = llvm::cast<ModuleContextDescriptor>(component)->Name.get();
node = Dem.createNode(Node::Kind::Module, name);
break;
}
case ContextDescriptorKind::Extension: {
auto extension = llvm::cast<ExtensionContextDescriptor>(component);
// Demangle the extension self type.
auto selfType = Dem.demangleType(extension->getMangledExtendedContext());
if (selfType->getKind() == Node::Kind::Type)
selfType = selfType->getChild(0);
// Substitute in the generic arguments.
auto genericArgsList = getGenericArgsTypeListForContext(component);
if (selfType->getKind() == Node::Kind::BoundGenericEnum
|| selfType->getKind() == Node::Kind::BoundGenericStructure
|| selfType->getKind() == Node::Kind::BoundGenericClass
|| selfType->getKind() == Node::Kind::BoundGenericOtherNominalType) {
if (genericArgsList) {
auto substSelfType = Dem.createNode(selfType->getKind());
substSelfType->addChild(selfType->getChild(0), Dem);
substSelfType->addChild(genericArgsList, Dem);
selfType = substSelfType;
} else {
// TODO: Use the unsubstituted type if we can't handle the
// substitutions yet.
selfType = selfType->getChild(0)->getChild(0);
}
}
auto extNode = Dem.createNode(Node::Kind::Extension);
extNode->addChild(node, Dem);
extNode->addChild(selfType, Dem);
// TODO: Turn the generic signature into a demangling as the third
// generic argument.
node = extNode;
break;
}
case ContextDescriptorKind::Protocol: {
auto protocol = llvm::cast<ProtocolDescriptor>(component);
auto name = protocol->Name.get();
auto protocolNode = Dem.createNode(Node::Kind::Protocol);
protocolNode->addChild(node, Dem);
auto nameNode = Dem.createNode(Node::Kind::Identifier, name);
protocolNode->addChild(nameNode, Dem);
node = protocolNode;
break;
}
default:
// Form a type context demangling for type contexts.
if (auto type = llvm::dyn_cast<TypeContextDescriptor>(component)) {
auto identity = ParsedTypeIdentity::parse(type);
Node::Kind nodeKind;
Node::Kind genericNodeKind;
switch (kind) {
case ContextDescriptorKind::Class:
nodeKind = Node::Kind::Class;
genericNodeKind = Node::Kind::BoundGenericClass;
break;
case ContextDescriptorKind::Struct:
nodeKind = Node::Kind::Structure;
genericNodeKind = Node::Kind::BoundGenericStructure;
break;
case ContextDescriptorKind::Enum:
nodeKind = Node::Kind::Enum;
genericNodeKind = Node::Kind::BoundGenericEnum;
break;
default:
// We don't know about this kind of type. Use an "other type" mangling
// for it.
nodeKind = Node::Kind::OtherNominalType;
genericNodeKind = Node::Kind::BoundGenericOtherNominalType;
break;
}
// Override the node kind if this is a Clang-imported type so we give it
// a stable mangling.
if (identity.isCTypedef()) {
nodeKind = Node::Kind::TypeAlias;
} else if (nodeKind != Node::Kind::Structure &&
_isCImportedTagType(type, identity)) {
nodeKind = Node::Kind::Structure;
}
auto typeNode = Dem.createNode(nodeKind);
typeNode->addChild(node, Dem);
auto nameNode = Dem.createNode(Node::Kind::Identifier,
identity.getABIName());
if (identity.isAnyRelatedEntity()) {
auto kindNode = Dem.createNode(Node::Kind::Identifier,
identity.getRelatedEntityName());
auto relatedName = Dem.createNode(Node::Kind::RelatedEntityDeclName);
relatedName->addChild(kindNode, Dem);
relatedName->addChild(nameNode, Dem);
nameNode = relatedName;
}
typeNode->addChild(nameNode, Dem);
node = typeNode;
// Apply generic arguments if the context is generic.
if (auto genericArgsList = getGenericArgsTypeListForContext(component)){
auto unspecializedType = Dem.createNode(Node::Kind::Type);
unspecializedType->addChild(node, Dem);
auto genericNode = Dem.createNode(genericNodeKind);
genericNode->addChild(unspecializedType, Dem);
genericNode->addChild(genericArgsList, Dem);
node = genericNode;
}
break;
}
// This runtime doesn't understand this context, or it's a context with
// no richer runtime information available about it (such as an anonymous
// context). Use an unstable mangling to represent the context by its
// pointer identity.
char addressBuf[sizeof(void*) * 2 + 1 + 1];
snprintf(addressBuf, sizeof(addressBuf), "$%" PRIxPTR, (uintptr_t)component);
auto anonNode = Dem.createNode(Node::Kind::AnonymousContext);
CharVector addressStr;
addressStr.append(addressBuf, Dem);
auto name = Dem.createNode(Node::Kind::Identifier, addressStr);
anonNode->addChild(name, Dem);
anonNode->addChild(node, Dem);
// Collect generic arguments if the context is generic.
auto genericArgsList = getGenericArgsTypeListForContext(component);
if (!genericArgsList)
genericArgsList = Dem.createNode(Node::Kind::TypeList);
anonNode->addChild(genericArgsList, Dem);
node = anonNode;
break;
}
}
// Wrap the final result in a top-level Type node.
auto top = Dem.createNode(Node::Kind::Type);
top->addChild(node, Dem);
return top;
}
// FIXME: This stuff should be merged with the existing logic in
// include/swift/Reflection/TypeRefBuilder.h as part of the rewrite
// to change stdlib reflection over to using remote mirrors.
Demangle::NodePointer
swift::_swift_buildDemanglingForMetadata(const Metadata *type,
Demangle::Demangler &Dem);
static Demangle::NodePointer
_buildDemanglerForBuiltinType(const Metadata *type, Demangle::Demangler &Dem) {
#define BUILTIN_TYPE(Symbol, Name) \
if (type == &METADATA_SYM(Symbol).base) \
return Dem.createNode(Node::Kind::BuiltinTypeName, Name);
#include "swift/Runtime/BuiltinTypes.def"
return nullptr;
}
/// Build a demangled type tree for a nominal type.
static Demangle::NodePointer
_buildDemanglingForNominalType(const Metadata *type, Demangle::Demangler &Dem) {
using namespace Demangle;
// Get the context descriptor from the type metadata.
const TypeContextDescriptor *description;
switch (type->getKind()) {
case MetadataKind::Class: {
auto classType = static_cast<const ClassMetadata *>(type);
#if SWIFT_OBJC_INTEROP
// Peek through artificial subclasses.
while (classType->isTypeMetadata() && classType->isArtificialSubclass())
classType = classType->Superclass;
#endif
description = classType->getDescription();
break;
}
case MetadataKind::Enum:
case MetadataKind::Optional: {
auto enumType = static_cast<const EnumMetadata *>(type);
description = enumType->Description;
break;
}
case MetadataKind::Struct: {
auto structType = static_cast<const StructMetadata *>(type);
description = structType->Description;
break;
}
case MetadataKind::ForeignClass: {
auto foreignType = static_cast<const ForeignClassMetadata *>(type);
description = foreignType->Description;
break;
}
default:
return nullptr;
}
// Gather the complete set of generic arguments that must be written to
// form this type.
SmallVector<const Metadata *, 8> allGenericArgs;
gatherWrittenGenericArgs(type, description, allGenericArgs, Dem);
// Demangle the generic arguments.
SmallVector<NodePointer, 8> demangledGenerics;
for (auto genericArg : allGenericArgs) {
// When there is no generic argument, put in a placeholder.
if (!genericArg) {
auto placeholder = Dem.createNode(Node::Kind::Tuple);
auto emptyList = Dem.createNode(Node::Kind::TypeList);
placeholder->addChild(emptyList, Dem);
auto type = Dem.createNode(Node::Kind::Type);
type->addChild(placeholder, Dem);
demangledGenerics.push_back(type);
continue;
}
// Demangle this argument.
auto genericArgDemangling =
_swift_buildDemanglingForMetadata(genericArg, Dem);
if (!genericArgDemangling)
return nullptr;
demangledGenerics.push_back(genericArgDemangling);
}
return _buildDemanglingForContext(description, demangledGenerics, Dem);
}
// Build a demangled type tree for a type.
//
// FIXME: This should use MetadataReader.h.
Demangle::NodePointer
swift::_swift_buildDemanglingForMetadata(const Metadata *type,
Demangle::Demangler &Dem) {
using namespace Demangle;
switch (type->getKind()) {
case MetadataKind::Class:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Struct:
case MetadataKind::ForeignClass:
return _buildDemanglingForNominalType(type, Dem);
case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
auto objcWrapper = static_cast<const ObjCClassWrapperMetadata *>(type);
const char *className = class_getName(objcWrapper->getObjCClassObject());
auto module = Dem.createNode(Node::Kind::Module, MANGLING_MODULE_OBJC);
auto node = Dem.createNode(Node::Kind::Class);
node->addChild(module, Dem);
node->addChild(Dem.createNode(Node::Kind::Identifier,
llvm::StringRef(className)), Dem);
return node;
#else
assert(false && "no ObjC interop");
return nullptr;
#endif
}
case MetadataKind::Existential: {
auto exis = static_cast<const ExistentialTypeMetadata *>(type);
auto protocols = exis->getProtocols();
auto type_list = Dem.createNode(Node::Kind::TypeList);
auto proto_list = Dem.createNode(Node::Kind::ProtocolList);
proto_list->addChild(type_list, Dem);
// The protocol descriptors should be pre-sorted since the compiler will
// only ever make a swift_getExistentialTypeMetadata invocation using
// its canonical ordering of protocols.
for (auto protocol : protocols) {
#if SWIFT_OBJC_INTEROP
if (protocol.isObjC()) {
// The protocol name is mangled as a type symbol, with the _Tt prefix.
StringRef ProtoName(protocol.getName());
NodePointer protocolNode = Dem.demangleSymbol(ProtoName);
// ObjC protocol names aren't mangled.
if (!protocolNode) {
auto module = Dem.createNode(Node::Kind::Module,
MANGLING_MODULE_OBJC);
auto node = Dem.createNode(Node::Kind::Protocol);
node->addChild(module, Dem);
node->addChild(Dem.createNode(Node::Kind::Identifier, ProtoName),
Dem);
auto typeNode = Dem.createNode(Node::Kind::Type);
typeNode->addChild(node, Dem);
type_list->addChild(typeNode, Dem);
continue;
}
// Dig out the protocol node.
// Global -> (Protocol|TypeMangling)
protocolNode = protocolNode->getChild(0);
if (protocolNode->getKind() == Node::Kind::TypeMangling) {
protocolNode = protocolNode->getChild(0); // TypeMangling -> Type
protocolNode = protocolNode->getChild(0); // Type -> ProtocolList
protocolNode = protocolNode->getChild(0); // ProtocolList -> TypeList
protocolNode = protocolNode->getChild(0); // TypeList -> Type
assert(protocolNode->getKind() == Node::Kind::Type);
assert(protocolNode->getChild(0)->getKind() == Node::Kind::Protocol);
} else {
assert(protocolNode->getKind() == Node::Kind::Protocol);
}
type_list->addChild(protocolNode, Dem);
continue;
}
#endif
auto protocolNode =
_buildDemanglingForContext(protocol.getSwiftProtocol(), { }, Dem);
if (!protocolNode)
return nullptr;
type_list->addChild(protocolNode, Dem);
}
if (auto superclass = exis->getSuperclassConstraint()) {
// If there is a superclass constraint, we mangle it specially.
auto result = Dem.createNode(Node::Kind::ProtocolListWithClass);
auto superclassNode = _swift_buildDemanglingForMetadata(superclass, Dem);
result->addChild(proto_list, Dem);
result->addChild(superclassNode, Dem);
return result;
}
if (exis->isClassBounded()) {
// Check if the class constraint is implied by any of our
// protocols.
bool requiresClassImplicit = false;
for (auto protocol : protocols) {
if (protocol.getClassConstraint() == ProtocolClassConstraint::Class)
requiresClassImplicit = true;
}
// If it was implied, we don't do anything special.
if (requiresClassImplicit)
return proto_list;
// If the existential type has an explicit AnyObject constraint,
// we must mangle it as such.
auto result = Dem.createNode(Node::Kind::ProtocolListWithAnyObject);
result->addChild(proto_list, Dem);
return result;
}
// Just a simple composition of protocols.
return proto_list;
}
case MetadataKind::ExistentialMetatype: {
auto metatype = static_cast<const ExistentialMetatypeMetadata *>(type);
auto instance = _swift_buildDemanglingForMetadata(metatype->InstanceType,
Dem);
auto node = Dem.createNode(Node::Kind::ExistentialMetatype);
node->addChild(instance, Dem);
return node;
}
case MetadataKind::Function: {
auto func = static_cast<const FunctionTypeMetadata *>(type);
Node::Kind kind;
switch (func->getConvention()) {
case FunctionMetadataConvention::Swift:
if (!func->isEscaping())
kind = Node::Kind::NoEscapeFunctionType;
else
kind = Node::Kind::FunctionType;
break;
case FunctionMetadataConvention::Block:
kind = Node::Kind::ObjCBlock;
break;
case FunctionMetadataConvention::CFunctionPointer:
kind = Node::Kind::CFunctionPointer;
break;
case FunctionMetadataConvention::Thin:
kind = Node::Kind::ThinFunctionType;
break;
}
SmallVector<std::pair<NodePointer, bool>, 8> inputs;
for (unsigned i = 0, e = func->getNumParameters(); i < e; ++i) {
auto param = func->getParameter(i);
auto flags = func->getParameterFlags(i);
auto input = _swift_buildDemanglingForMetadata(param, Dem);
auto wrapInput = [&](Node::Kind kind) {
auto parent = Dem.createNode(kind);
parent->addChild(input, Dem);
input = parent;
};
switch (flags.getValueOwnership()) {
case ValueOwnership::Default:
/* nothing */
break;
case ValueOwnership::InOut:
wrapInput(Node::Kind::InOut);
break;
case ValueOwnership::Shared:
wrapInput(Node::Kind::Shared);
break;
case ValueOwnership::Owned:
wrapInput(Node::Kind::Owned);
break;
}
inputs.push_back({input, flags.isVariadic()});
}
NodePointer totalInput = nullptr;
switch (inputs.size()) {
case 1: {
auto singleParam = inputs.front();
// If the sole unlabeled parameter has a non-tuple type, encode
// the parameter list as a single type.
if (!singleParam.second) {
auto singleType = singleParam.first;
if (singleType->getKind() == Node::Kind::Type)
singleType = singleType->getFirstChild();
if (singleType->getKind() != Node::Kind::Tuple) {
totalInput = singleParam.first;
break;
}
}
// Otherwise it requires a tuple wrapper.
LLVM_FALLTHROUGH;
}
// This covers both none and multiple parameters.
default:
auto tuple = Dem.createNode(Node::Kind::Tuple);
for (auto &input : inputs) {
NodePointer eltType;
bool isVariadic;
std::tie(eltType, isVariadic) = input;
// Tuple element := variadic-marker label? type
auto tupleElt = Dem.createNode(Node::Kind::TupleElement);
if (isVariadic)
tupleElt->addChild(Dem.createNode(Node::Kind::VariadicMarker), Dem);
if (eltType->getKind() == Node::Kind::Type) {
tupleElt->addChild(eltType, Dem);
} else {
auto type = Dem.createNode(Node::Kind::Type);
type->addChild(eltType, Dem);
tupleElt->addChild(type, Dem);
}
tuple->addChild(tupleElt, Dem);
}
totalInput = tuple;
break;
}
NodePointer parameters = Dem.createNode(Node::Kind::ArgumentTuple);
NodePointer paramType = Dem.createNode(Node::Kind::Type);
paramType->addChild(totalInput, Dem);
parameters->addChild(paramType, Dem);
NodePointer resultTy = _swift_buildDemanglingForMetadata(func->ResultType,
Dem);
NodePointer result = Dem.createNode(Node::Kind::ReturnType);
result->addChild(resultTy, Dem);
auto funcNode = Dem.createNode(kind);
if (func->throws())
funcNode->addChild(Dem.createNode(Node::Kind::ThrowsAnnotation), Dem);
funcNode->addChild(parameters, Dem);
funcNode->addChild(result, Dem);
return funcNode;
}
case MetadataKind::Metatype: {
auto metatype = static_cast<const MetatypeMetadata *>(type);
auto instance = _swift_buildDemanglingForMetadata(metatype->InstanceType,
Dem);
auto typeNode = Dem.createNode(Node::Kind::Type);
typeNode->addChild(instance, Dem);
auto node = Dem.createNode(Node::Kind::Metatype);
node->addChild(typeNode, Dem);
return node;
}
case MetadataKind::Tuple: {
auto tuple = static_cast<const TupleTypeMetadata *>(type);
const char *labels = tuple->Labels;
auto tupleNode = Dem.createNode(Node::Kind::Tuple);
for (unsigned i = 0, e = tuple->NumElements; i < e; ++i) {
auto elt = Dem.createNode(Node::Kind::TupleElement);
// Add a label child if applicable:
if (labels) {
// Look for the next space in the labels string.
if (const char *space = strchr(labels, ' ')) {
// If there is one, and the label isn't empty, add a label child.
if (labels != space) {
auto eltName =
Dem.createNode(Node::Kind::TupleElementName,
llvm::StringRef(labels, space - labels));
elt->addChild(eltName, Dem);
}
// Skip past the space.
labels = space + 1;
}
}
// Add the element type child.
auto eltType =
_swift_buildDemanglingForMetadata(tuple->getElement(i).Type, Dem);
if (eltType->getKind() == Node::Kind::Type) {
elt->addChild(eltType, Dem);
} else {
auto type = Dem.createNode(Node::Kind::Type);
type->addChild(eltType, Dem);
elt->addChild(type, Dem);
}
// Add the completed element to the tuple.
tupleNode->addChild(elt, Dem);
}
return tupleNode;
}
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
break;
case MetadataKind::Opaque:
default: {
if (auto builtinType = _buildDemanglerForBuiltinType(type, Dem))
return builtinType;
// FIXME: Some opaque types do have manglings, but we don't have enough info
// to figure them out.
break;
}
}
// Not a type.
return nullptr;
}
// NB: This function is not used directly in the Swift codebase, but is
// exported for Xcode support and is used by the sanitizers. Please coordinate
// before changing.
char *swift_demangle(const char *mangledName,
size_t mangledNameLength,
char *outputBuffer,
size_t *outputBufferSize,
uint32_t flags) {
if (flags != 0) {
swift::fatalError(0, "Only 'flags' value of '0' is currently supported.");
}
if (outputBuffer != nullptr && outputBufferSize == nullptr) {
swift::fatalError(0, "'outputBuffer' is passed but the size is 'nullptr'.");
}
// Check if we are dealing with Swift mangled name, otherwise, don't try
// to demangle and send indication to the user.
if (!Demangle::isSwiftSymbol(mangledName))
return nullptr; // Not a mangled name
// Demangle the name.
auto options = Demangle::DemangleOptions();
options.DisplayDebuggerGeneratedModule = false;
auto result =
Demangle::demangleSymbolAsString(mangledName,
mangledNameLength,
options);
// If the output buffer is not provided, malloc memory ourselves.
if (outputBuffer == nullptr || *outputBufferSize == 0) {
return strdup(result.c_str());
}
// Copy into the provided buffer.
_swift_strlcpy(outputBuffer, result.c_str(), *outputBufferSize);
// Indicate a failure if the result did not fit and was truncated
// by setting the required outputBufferSize.
if (*outputBufferSize < result.length() + 1) {
*outputBufferSize = result.length() + 1;
}
return outputBuffer;
}
| {
"content_hash": "3689833e2930a45e0b1e1e26d6983aa7",
"timestamp": "",
"source": "github",
"line_count": 679,
"max_line_length": 83,
"avg_line_length": 35.35346097201767,
"alnum_prop": 0.632701520516559,
"repo_name": "shahmishal/swift",
"id": "f5fc0152eaed2a17b48c9d0d1675cdd8ee1a4e05",
"size": "24005",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "stdlib/public/runtime/Demangle.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "12337"
},
{
"name": "C",
"bytes": "228905"
},
{
"name": "C++",
"bytes": "33424345"
},
{
"name": "CMake",
"bytes": "534257"
},
{
"name": "D",
"bytes": "1107"
},
{
"name": "DTrace",
"bytes": "2438"
},
{
"name": "Emacs Lisp",
"bytes": "57265"
},
{
"name": "LLVM",
"bytes": "70517"
},
{
"name": "MATLAB",
"bytes": "2576"
},
{
"name": "Makefile",
"bytes": "1841"
},
{
"name": "Objective-C",
"bytes": "420091"
},
{
"name": "Objective-C++",
"bytes": "248108"
},
{
"name": "Perl",
"bytes": "2211"
},
{
"name": "Python",
"bytes": "1564446"
},
{
"name": "Roff",
"bytes": "3495"
},
{
"name": "Ruby",
"bytes": "2091"
},
{
"name": "Shell",
"bytes": "229212"
},
{
"name": "Swift",
"bytes": "29078702"
},
{
"name": "Vim script",
"bytes": "16701"
},
{
"name": "sed",
"bytes": "1050"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ponytail Express</title>
<base href="/">
<link rel="apple-touch-icon" sizes="57x57" href="assets/ico/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="assets/ico/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="assets/ico/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="assets/ico/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="assets/ico/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="assets/ico/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="assets/ico/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="assets/ico/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="assets/ico/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="assets/ico/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="assets/ico/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="assets/ico/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="assets/ico/favicon-16x16.png">
<link rel="manifest" href="assets/ico/manifest.json">
<meta name="theme-color" content="#000000">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<qs-app>
<div style="padding: 20%;text-align:center;">
<div>Ponytail Express Loading...</div>
</div>
</qs-app>
</body>
</html> | {
"content_hash": "050f9f3c9407b78ec6a77990838e0ab4",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 95,
"avg_line_length": 46.588235294117645,
"alnum_prop": 0.6944444444444444,
"repo_name": "bdinsmor/pe2",
"id": "f24618fca47b27f3ce587bcc641015b53897eab2",
"size": "1584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7067"
},
{
"name": "HTML",
"bytes": "17938"
},
{
"name": "JavaScript",
"bytes": "2486"
},
{
"name": "Shell",
"bytes": "615"
},
{
"name": "TypeScript",
"bytes": "45985"
}
],
"symlink_target": ""
} |
<?php
class Dbsetting extends CI_Model {
public function __construct() {
$this->load->database();
}
//=====================================HEADER========================================================//
public function get_design_setup() {
$this->db->from('design_setup');
$query = $this->db->get();
return $query->result();
}
function update_design_header_setup($headerTitle, $headerLogo, $headerDescription, $headerBgColor) {
$data = Array(array('description' => $headerTitle), array('description' => $headerLogo), array('description' => $headerDescription), array('description' => $headerBgColor));
$i = 0;
foreach ($data as $value) {
$this->db->where('id', $i);
$this->db->update('design_setup', $value);
$i++;
}
}
function update_design_sidebar_setup($sideBarTitle, $sideBarDescription, $sideBarBgColor) {
$data = Array(array('description' => $sideBarTitle), array('description' => $sideBarDescription), array('description' => $sideBarBgColor));
$i = 4;
foreach ($data as $value) {
$this->db->where('id', $i);
$this->db->update('design_setup', $value);
$i++;
}
}
public function update_misc_setting($allowComment, $allowLike, $allowShare, $maximunPost, $maximumPage, $slideHeight, $slideWidth) {
$data = Array(array('description' => $allowComment), array('description' => $allowLike), array('description' => $allowShare), array('description' => $maximunPost), array('description' => $maximumPage), array('description' => $slideHeight), array('description' => $slideWidth));
$i = 0;
foreach ($data as $value) {
$this->db->where('id', $i);
$this->db->update('misc_setting', $value);
$i++;
}
}
public function get_misc_setting() {
$this->db->from('misc_setting');
$query = $this->db->get();
return $query->result();
}
function delete_favicone($id) {
$this->db->where('value', $id);
$this->db->update('meta_data', array('value' => " "));
}
function get_meta_data() {
$this->db->from('meta_data');
$query = $this->db->get();
return $query->result();
}
function update_meta_data($url, $title, $keyword, $description, $favicone) {
if ($favicone !== '' || $favicone !== NULL) {
$data = Array(array('value' => $url), array('value' => $title), array('value' => $keyword), array('value' => $description), array('value' => $favicone));
$i = 1;
foreach ($data as $value) {
$this->db->where('id', $i);
$this->db->update('meta_data', $value);
$i++;
}
} else {
$data = Array(array('value' => $url), array('value' => $title), array('value' => $keyword), array('value' => $description));
$i = 1;
foreach ($data as $value) {
$this->db->where('id', $i);
$this->db->update('meta_data', $value);
$i++;
}
}
}
public function update_navigation_url($prevUrl, $url)
{
$query=$this->db->query("UPDATE navigation
SET navigation_link = REPLACE(navigation_link, '$prevUrl', '$url')");
}
} | {
"content_hash": "5dd6953d3b2f4014cdb34dc0fe676dd3",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 285,
"avg_line_length": 32.96153846153846,
"alnum_prop": 0.5078763127187864,
"repo_name": "infotechnab/BnW",
"id": "d9b0ff359194b3406b919f333dcd113c9a1fec1a",
"size": "3428",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/Dbsetting.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "547"
},
{
"name": "CSS",
"bytes": "103105"
},
{
"name": "HTML",
"bytes": "5633"
},
{
"name": "JavaScript",
"bytes": "48467"
},
{
"name": "PHP",
"bytes": "2551635"
}
],
"symlink_target": ""
} |
./vendor/bin/phpunit --log-junit xunit-results.xml
| {
"content_hash": "e5e36f101e0af28cbe70059053b6d63e",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 50,
"avg_line_length": 51,
"alnum_prop": 0.7647058823529411,
"repo_name": "GoogleCloudPlatform/repo-automation-playground",
"id": "9da5af2ae43393e7fa8c35f6b72d4d7272bf3104",
"size": "51",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xunit-samples/php/run.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1246"
},
{
"name": "CSS",
"bytes": "753"
},
{
"name": "Dockerfile",
"bytes": "626"
},
{
"name": "Go",
"bytes": "1017"
},
{
"name": "HTML",
"bytes": "784"
},
{
"name": "Java",
"bytes": "1051"
},
{
"name": "JavaScript",
"bytes": "45361"
},
{
"name": "PHP",
"bytes": "205"
},
{
"name": "Python",
"bytes": "330226"
},
{
"name": "Ruby",
"bytes": "278"
},
{
"name": "Shell",
"bytes": "24283"
}
],
"symlink_target": ""
} |
layout: v2/docs_base
id: ui
title: Ionic 2 UI
header_title: Ionic 2 UI
header_sub_title: Ionic 2 Developer Preview
---
<div class="improve-docs">
<a href='https://github.com/driftyco/ionic-site/edit/ionic2/docs/v2/ui/index.md'>
Improve this doc
</a>
</div>
<h1 class="title">UI</h1>
TODO
| {
"content_hash": "fc5379b89b7c62506b8581e5e2ef5aeb",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 83,
"avg_line_length": 19.866666666666667,
"alnum_prop": 0.6912751677852349,
"repo_name": "saimandeper/ionic-site",
"id": "f5e78aad75626ee5b994ba6267273ec8bfb447e7",
"size": "302",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/v2/ui/index.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2120841"
},
{
"name": "HTML",
"bytes": "55113710"
},
{
"name": "JavaScript",
"bytes": "10300807"
},
{
"name": "Shell",
"bytes": "268"
}
],
"symlink_target": ""
} |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "Module.h"
#include "AnalogModule.h"
#include "DigitalModule.h"
//#include "SolenoidModule.h"
Module* Module::m_modules[kMaxModules] = {NULL};
/**
* Constructor.
*
* @param type The type of module represented.
* @param number The module index within the module type.
*/
Module::Module(nLoadOut::tModuleType type, uint8_t number)
: m_moduleType (type)
, m_moduleNumber (number)
{
m_modules[ToIndex(type, number)] = this;
}
/**
* Destructor.
*/
Module::~Module()
{
}
/**
* Static module singleton factory.
*
* @param type The type of module represented.
* @param number The module index within the module type.
*/
Module* Module::GetModule(nLoadOut::tModuleType type, uint8_t number)
{
if (m_modules[ToIndex(type, number)] == NULL)
{
switch(type)
{
case nLoadOut::kModuleType_Analog:
new AnalogModule(number);
break;
case nLoadOut::kModuleType_Digital:
new DigitalModule(number);
break;
/*
case nLoadOut::kModuleType_Solenoid:
new SolenoidModule(number);
break;
*/
default:
return NULL;
}
}
return m_modules[ToIndex(type, number)];
}
/**
* Create an index into the m_modules array based on type and number
*
* @param type The type of module represented.
* @param number The module index within the module type.
* @return The index into m_modules.
*/
uint8_t Module::ToIndex(nLoadOut::tModuleType type, uint8_t number)
{
if (number == 0 || number > kMaxModuleNumber) return 0;
if (type < nLoadOut::kModuleType_Analog || type > nLoadOut::kModuleType_Solenoid) return 0;
return (type * kMaxModuleNumber) + (number - 1);
}
| {
"content_hash": "1ff368eb5a2f5c94bb0c196e0321e4c3",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 92,
"avg_line_length": 27.13157894736842,
"alnum_prop": 0.6105722599418041,
"repo_name": "rbmj/wpilib",
"id": "5018ae58dfa4b3bf46972a79ba3e4c6b0ba98697",
"size": "2062",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Module.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "340908"
},
{
"name": "C++",
"bytes": "1744478"
},
{
"name": "Objective-C",
"bytes": "2535"
},
{
"name": "Shell",
"bytes": "8350"
}
],
"symlink_target": ""
} |
@interface ADReposViewCodeTableViewCell ()
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (weak, nonatomic) IBOutlet UIImageView *branchIcon;
@property (weak, nonatomic) IBOutlet UIButton *branchButton;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIButton *viewCodeButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *separator1Height;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *separator2Height;
@end
@implementation ADReposViewCodeTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
self.containerView.layer.borderColor = RGB(0x999999).CGColor;
self.containerView.layer.borderWidth = AD_1PX;
self.containerView.layer.cornerRadius = 3;
self.separator1Height.constant = AD_1PX;
self.separator2Height.constant = AD_1PX;
}
- (void)bindViewModel:(ADReposDetailViewModel *)viewModel {
[RACObserve(viewModel, reference)subscribeNext:^(OCTRef *reference) {
self.branchIcon.image = [UIImage ad_normalImageWithIdentifier:reference.ad_octiconIdentifier size:CGSizeMake(24, 24)];
NSString *title = [reference.name componentsSeparatedByString:@"/"].lastObject;
[self.branchButton setTitle:title forState:UIControlStateNormal];
}];
self.timeLabel.text = viewModel.dateUpdated;
UIImage *image = [UIImage ad_highlightImageWithIdentifier:@"FileDirectory" size:CGSizeMake(22, 22)];
[self.viewCodeButton setImage:image forState:UIControlStateNormal];
self.viewCodeButton.rac_command = viewModel.viewCodeCommand;
self.branchButton.rac_command = viewModel.changeBranchCommand;
}
@end
| {
"content_hash": "1f7e5dd0029d686749df811ade441422",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 126,
"avg_line_length": 39.95238095238095,
"alnum_prop": 0.7640047675804529,
"repo_name": "CrazyKids/Scarecrow",
"id": "5f1869a1a5eba187dc300da746ba68e70f99e3a9",
"size": "1998",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Scarecrow/Repos/View/ADReposViewCodeTableViewCell.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "346187"
},
{
"name": "Ruby",
"bytes": "357"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\Framework\Search\Request\Aggregation;
use Magento\Framework\Search\Request\BucketInterface;
/**
* Term Buckets
*/
class TermBucket implements BucketInterface
{
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $field;
/**
* @var array
*/
protected $metrics;
/**
* @param string $name
* @param string $field
* @param array $metrics
* @codeCoverageIgnore
*/
public function __construct($name, $field, array $metrics)
{
$this->name = $name;
$this->field = $field;
$this->metrics = $metrics;
}
/**
* {@inheritdoc}
*/
public function getType()
{
return BucketInterface::TYPE_TERM;
}
/**
* {@inheritdoc}
* @codeCoverageIgnore
*/
public function getName()
{
return $this->name;
}
/**
* {@inheritdoc}
* @codeCoverageIgnore
*/
public function getField()
{
return $this->field;
}
/**
* {@inheritdoc}
* @codeCoverageIgnore
*/
public function getMetrics()
{
return $this->metrics;
}
}
| {
"content_hash": "7a14d99150e81d59a2f0d3fad62cdeed",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 62,
"avg_line_length": 16.18918918918919,
"alnum_prop": 0.5258764607679466,
"repo_name": "enettolima/magento-training",
"id": "159da1c2be1168cfaee0e497a46b724c71722d57",
"size": "1296",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "magento2ce/lib/internal/Magento/Framework/Search/Request/Aggregation/TermBucket.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "22648"
},
{
"name": "CSS",
"bytes": "3382928"
},
{
"name": "HTML",
"bytes": "8749335"
},
{
"name": "JavaScript",
"bytes": "7355635"
},
{
"name": "PHP",
"bytes": "58607662"
},
{
"name": "Perl",
"bytes": "10258"
},
{
"name": "Shell",
"bytes": "41887"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
package net.minecraft.src;
import java.util.Random;
import net.minecraft.src.CreativeTabs;
public class BlockBoneOre extends Block
{
public BlockBoneOre(int par1)
{
super(par1, Material.rock);
this.setCreativeTab(CreativeTabs.tabBlock);
}
public int quantityDropped(Random r)
{
return 1;
}
public int idDropped(int par1, Random par2Random, int par3)
{
return mod_BoneOre.BlockBoneOre.blockID;
}
} | {
"content_hash": "88f260c0c1954192ed594afd3c543d93",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 59,
"avg_line_length": 20,
"alnum_prop": 0.6847826086956522,
"repo_name": "KinyoshiMods/Bone-Ore",
"id": "bbe342e2179ddfcc243b0b83f47e33164f873e25",
"size": "460",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BlockBoneOre.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [],
"symlink_target": ""
} |
[](https://github.com/reactphp/filesystem/actions)
[ReactPHP](https://reactphp.org/)'s filesystem component that enables non-blocking filesystem operations.
> **Development version:** This branch contains the code for the upcoming 0.2
> release which will be the way forward for this package.
>
> See [installation instructions](#install) for more details.
**Table of Contents**
* [Quickstart example](#quickstart-example)
* [Usage](#usage)
* [Factory](#factory)
* [create()](#create)
* [Filesystem implementations](#filesystem-implementations)
* [Uv](#uv)
* [AdapterInterface](#adapterinterface)
* [detect()](#detect)
* [directory()](#directory)
* [file()](#file)
* [NodeInterface](#nodeinterface)
* [path()](#path)
* [name()](#name)
* [stat()](#stat)
* [DirectoryInterface](#directoryinterface)
* [ls](#ls)
* [FileInterface](#fileinterface)
* [getContents()](#getcontents)
* [putContents()](#putcontents)
* [NotExistInterface](#notexistinterface)
* [createDirectory()](#createdirectory)
* [createFile()](#createfile)
* [Install](#install)
* [Tests](#tests)
* [License](#license)
## Quickstart example
Here is a program that lists everything in the current directory.
```php
use React\Filesystem\Factory;
use React\Filesystem\Node\DirectoryInterface;
use React\Filesystem\Node\NodeInterface;
Factory::create()->detect(__DIR__)->then(function (DirectoryInterface $directory) {
return $directory->ls();
})->then(static function ($nodes) {
foreach ($nodes as $node) {
assert($node instanceof NodeInterface);
echo $node->name(), ': ', get_class($node), PHP_EOL;
}
echo '----------------------------', PHP_EOL, 'Done listing directory', PHP_EOL;
}, function (Throwable $throwable) {
echo $throwable;
});
```
See also the [examples](examples).
## Usage
See [`Factory::create()`](#create).
### Factory
The `Factory` class exists as a convenient way to pick the best available
[filesystem implementation](#filesystem-implementations).
#### create()
The `create(): AdapterInterface` method can be used to create a new filesystem instance:
```php
$filesystem = \React\Filesystem\Factory::create();
```
This method always returns an instance implementing [`adapterinterface`](#adapterinterface),
the actual [Filesystem implementations](#filesystem-implementations) is an implementation detail.
This method can be called at any time. However, certain scheduling mechanisms are used that will make the event loop
busier with every new instance of a filesystem adapter. To prevent that it is preferred you create it once and inject
it where required.
### Filesystem implementations
In addition to the [`FilesystemInterface`](#filesysteminterface), there are a number of
filesystem implementations provided.
All the filesystems support these features:
* Stating a node
* Listing directory contents
* Reading/write from/to files
For most consumers of this package, the underlying filesystem implementation is
an implementation detail.
You should use the [`Factory`](#factory) to automatically create a new instance.
The factory will determine the most performant filesystem for your environment. Any extension based filesystem are
preferred before falling back to less performant filesystems. When no extensions are detected it will fall back to an
internal fallback filesystem that uses blocking system calls. As such it is highly recommended to install one of the
extensions that unlocks more performant filesystem operations.
Advanced! If you explicitly need a certain filesystem implementation, you can
manually instantiate one of the following classes.
Note that you may have to install the required PHP extensions for the respective
event loop implementation first or they will throw a `BadMethodCallException` on creation.
#### Uv
An `ext-uv` based filesystem.
This filesystem uses the [`uv` PECL extension](https://pecl.php.net/package/uv), that
provides an interface to `libuv` library.
This filesystem is known to work with PHP 7+.
### AdapterInterface
#### detect()
The `detect(string $path): PromiseInterface<NodeInterface>` is the preferred way to get an object representing a node on the filesystem.
When calling this method it will attempt to detect what kind of node the path is you've given it, and return an object
implementing [`NodeInterface`](#nodeinterface). If nothing exists at the given path, a [`NotExistInterface`](#notexistinterface) object will be
returned which you can use to create a file or directory.
#### directory()
The `directory(string $path): DirectoryInterface` creates an object representing a directory at the specified path.
Keep in mind that unlike the `detect` method the `directory` method cannot guarantee the path you pass is actually a
directory on the filesystem and may result in unexpected behavior.
#### file()
The `file(string $path): DirectoryInterface` creates an object representing a file at the specified path.
Keep in mind that unlike the `detect` method the `file` method cannot guarantee the path you pass is actually a
file on the filesystem and may result in unexpected behavior.
### NodeInterface
The `NodeInterface` is at the core of all other node interfaces such as `FileInterface` or `DirectoryInterface`. It
provides basic methods that are useful for all types of nodes.
#### path()
The `path(): string` method returns the path part of the node's location. So if the full path is `/path/to/file.ext` this method returns `/path/to/`.
#### name()
The `name(): string` method returns the name part of the node's location. So if the full path is `/path/to/file.ext` this method returns `file.ext`.
#### stat()
The `stat(): PromiseInterface<?Stat>` method stats the node and provides you with information such as its size, full path, create/update time.
### DirectoryInterface
#### ls
The `ls(): PromiseInterface<array<NodeInterface>>` method list all contents of the given directory and will return an
array with nodes in it. It will do it's best to detect which type a node is itself, and otherwise fallback
to `FilesystemInterface::detect(string $path): PromiseInterface<NodeInterface>`.
### FileInterface
The `*Contents` methods on this interface are designed to behave the same as PHP's `file_(get|put)_contents` functions
as possible. Resulting in a very familiar API to read/stream from files, or write/append to a file.
#### getContents
For reading from files `getContents(int $offset = 0 , ?int $maxlen = null): PromiseInterface<string>` provides two
arguments that control how much data it reads from the file. Without arguments, it will read everything:
```php
$file->getContents();
```
The offset and maximum length let you 'select' a chunk of the file to be read. The following will skip the first `2048`
bytes and then read up to `1024` bytes from the file. However, if the file only contains `512` bytes after the `2048`
offset it will only return those `512` bytes.
```php
$file->getContents(2048, 1024);
```
It is possible to tail files with, the following example uses a timer as trigger to check for updates:
```php
$offset = 0;
Loop::addPeriodicTimer(1, function (TimerInterface $timer) use ($file, &$offset, $loop): void {
$file->getContents($offset)->then(function (string $contents) use (&$offset, $timer, $loop): void {
echo $contents; // Echo's the content for example purposes
$offset += strlen($contents);
});
});
```
#### putContents
Writing to file's is `putContents(string $contents, int $flags = 0): PromiseInterface<int>` specialty. By default, when
passing it contents, it will truncate the file when it exists or create a new one and then fill it with the contents
given.
```php
$file->putContents('ReactPHP');
```
Appending files is also supported, by using the `\FILE_APPEND` constant the file is appended when it exists.
```php
$file->putContents(' is awesome!', \FILE_APPEND);
```
### NotExistInterface
Both creation methods will check if the parent directory exists and create it if it doesn't. Effectively making this
creation process recursively.
#### createDirectory
The following will create `lets/make/a/nested/directory` as a recursive directory structure.
```php
$filesystem->directory(
__DIR__ . 'lets' . DIRECTORY_SEPARATOR . 'make' . DIRECTORY_SEPARATOR . 'a' . DIRECTORY_SEPARATOR . 'nested' . DIRECTORY_SEPARATOR . 'directory'
)->createDirectory();
```
#### createFile
The following will create `with-a-file.txt` in `lets/make/a/nested/directory` and write `This is amazing!` into that file.
```php
use React\Filesystem\Node\FileInterface;
$filesystem->file(
__DIR__ . 'lets' . DIRECTORY_SEPARATOR . 'make' . DIRECTORY_SEPARATOR . 'a' . DIRECTORY_SEPARATOR . 'nested' . DIRECTORY_SEPARATOR . 'directory' . DIRECTORY_SEPARATOR . 'with-a-file.txt'
)->createFile()->then(function (FileInterface $file) {
return $file->putContents('This is amazing!')
});
```
## Install
The recommended way to install this library is [through Composer](https://getcomposer.org).
[New to Composer?](https://getcomposer.org/doc/00-intro.md)
Once released, this project will follow [SemVer](https://semver.org/).
At the moment, this will install the latest development version:
```bash
composer require react/filesystem:^0.2@dev
```
See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades.
This project aims to run on any platform and thus does not require any PHP
extensions and supports running on PHP 7.4 through current PHP 8+.
It's *highly recommended to use the latest supported PHP version* for this project.
Installing any of the event loop extensions is suggested, but entirely optional.
See also [event loop implementations](#loop-implementations) for more details.
## Tests
To run the test suite, you first need to clone this repo and then install all
dependencies [through Composer](https://getcomposer.org):
```bash
composer install
```
To run the test suite, go to the project root and run:
```bash
vendor/bin/phpunit
```
## License
MIT, see [LICENSE file](LICENSE).
| {
"content_hash": "515b65fbc9267d1c6f9cae649667e177",
"timestamp": "",
"source": "github",
"line_count": 287,
"max_line_length": 190,
"avg_line_length": 35.52613240418118,
"alnum_prop": 0.7375441349548842,
"repo_name": "reactphp/filesystem",
"id": "4093eeb8794f41816dee942946c4e6fbbf42da52",
"size": "10220",
"binary": false,
"copies": "1",
"ref": "refs/heads/0.2.x",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "43651"
},
{
"name": "Shell",
"bytes": "1348"
}
],
"symlink_target": ""
} |
the_beneficiary=each {_party}
=[G/Agt-Cooperate-CmA/Sec/Relate/Assign/Benefit/0.md] | {
"content_hash": "cce09c3e0fdd155936253719508ac4f6",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 53,
"avg_line_length": 28,
"alnum_prop": 0.7619047619047619,
"repo_name": "CommonAccord/Cmacc-Source",
"id": "cb7229b1648836892d0bdf4b2cdd2607dcbd0529",
"size": "84",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Doc/G/Agt-Cooperate-CmA/Sec/Relate/Assign/Benefit/-Mutual/0.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2498"
},
{
"name": "PHP",
"bytes": "1231"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CompareCloudware.Domain.Models
{
#region TagResult
public class TagResult
{
public virtual Tag Tag { get; set; }
public virtual CloudApplication CloudApplication { get; set; }
public virtual string TagTypeWhenTagTypeIsNull { get; set; }
public virtual int? VendorID { get; set; }
public virtual string VendorName { get; set; }
public virtual string ShopTagName { get; set; }
public virtual int? TagCategoryID { get; set; }
public virtual string TagCategoryName { get; set; }
public virtual int TagTypeID { get; set; }
public virtual int CloudApplicationCategoryID { get; set; }
public virtual string CloudApplicationCategoryName { get; set; }
public virtual string CloudApplicationCategoryTagName { get; set; }
public virtual string CloudApplicationShopTagName { get; set; }
}
#endregion
}
| {
"content_hash": "b69aca579ff2ec2e847d1fe7e7fc2231",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 75,
"avg_line_length": 37.51851851851852,
"alnum_prop": 0.6831194471865746,
"repo_name": "protechdm/CompareCloudware",
"id": "05cc7ba17c6c398fe605c94f0bce7e7bcd4d8c88",
"size": "1015",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CompareCloudware.Domain/Models/TagResult.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "224"
},
{
"name": "C#",
"bytes": "17009063"
},
{
"name": "CSS",
"bytes": "444980"
},
{
"name": "JavaScript",
"bytes": "655133"
},
{
"name": "Makefile",
"bytes": "1852"
},
{
"name": "PHP",
"bytes": "25856"
},
{
"name": "PowerShell",
"bytes": "107710"
},
{
"name": "Ruby",
"bytes": "4362"
},
{
"name": "XSLT",
"bytes": "10095"
}
],
"symlink_target": ""
} |
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.StringTokenizer;
/**
* @author Stefano Mazzocchi
*/
public class Loader {
static boolean verbose = false;
static final String REPOSITORIES = "loader.jar.repositories";
static final String VERBOSE = "loader.verbose";
static final String MAIN_CLASS = "loader.main.class";
static final String LOG = "loader.log";
class RepositoryClassLoader extends URLClassLoader {
BufferedWriter _log = null;
public RepositoryClassLoader(ClassLoader parent) {
this(parent,null);
}
public RepositoryClassLoader(ClassLoader parent, File logFile) {
super(new URL[0], parent);
if (logFile != null && logFile.canWrite()) {
try {
this._log = new BufferedWriter(new FileWriter(logFile));
} catch (IOException e) {
throw new RuntimeException("Error creating classloading log file: " + e.getMessage());
}
}
}
protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
try {
if (this._log != null) this._log.write(name + "\n");
} catch (IOException e) {
throw new RuntimeException("Error writing to the log file: " + e.getMessage());
}
return super.loadClass(name,resolve);
}
public void addRepository(File repository) {
if (verbose) System.out.println("Processing repository: " + repository);
if (repository.exists()) {
if (repository.isDirectory()) {
File[] jars = repository.listFiles();
try {
if (verbose) System.out.println("Adding folder: " + repository);
super.addURL(repository.toURL());
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e.toString());
}
for (int i = 0; i < jars.length; i++) {
if (jars[i].getAbsolutePath().endsWith(".jar")) {
addJar(jars[i]);
}
}
} else {
addJar(repository);
}
} else if (verbose) {
System.out.println("WARNING: repository " + repository + " does not exist");
}
}
private void addJar(File file) {
try {
URL url = file.toURL();
if (verbose) System.out.println("Adding jar: " + file);
super.addURL(url);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e.toString());
}
}
}
public static void main(String[] args) throws Exception {
new Loader().run(args);
}
void run(String[] args) throws Exception
{
String repositories = System.getProperty(REPOSITORIES);
if (repositories == null) {
System.out.println("Loader requires the '" + REPOSITORIES + "' property to be set");
System.exit(1);
}
String mainClass = System.getProperty(MAIN_CLASS);
if (mainClass == null) {
System.out.println("Loader requires the '" + MAIN_CLASS + "' property to be set");
System.exit(1);
}
String verboseProp = System.getProperty(VERBOSE);
verbose = verboseProp != null && "true".equals(verboseProp);
File log = null;
String logFile = System.getProperty(LOG);
if (logFile != null) {
log = new File(logFile);
}
if (verbose) System.out.println("-------------------- Loading --------------------");
RepositoryClassLoader classLoader = new RepositoryClassLoader(this.getClass().getClassLoader(), log);
StringTokenizer st = new StringTokenizer(repositories, File.pathSeparator);
while (st.hasMoreTokens()) {
classLoader.addRepository(new File(st.nextToken()));
}
Thread.currentThread().setContextClassLoader(classLoader);
if (verbose) System.out.println("-------------------- Executing -----------------");
if (verbose) System.out.println("Main Class: " + mainClass);
invokeMain(classLoader, mainClass, args);
}
void invokeMain(ClassLoader classloader, String classname, String[] args)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException
{
Class invokedClass = classloader.loadClass(classname);
Class[] methodParamTypes = new Class[1];
methodParamTypes[0] = args.getClass();
Method main = invokedClass.getDeclaredMethod("main", methodParamTypes);
Object[] methodParams = new Object[1];
methodParams[0] = args;
main.invoke(null, methodParams);
}
}
| {
"content_hash": "863b6828fe135322b9c00da28e01a2c1",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 109,
"avg_line_length": 34.966887417218544,
"alnum_prop": 0.5657196969696969,
"repo_name": "cul/marcmods2rdf",
"id": "729a72e2ec4aeb6dfbc12a37a79ba45ba605825c",
"size": "5900",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "tools/loader/src/Loader.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "24966"
},
{
"name": "Shell",
"bytes": "1489"
}
],
"symlink_target": ""
} |
cat >> ~/.bash_profile << EOF
export LIGHT_DIR=$(pwd)
alias lightdir='cd ${LIGHT_DIR}'
alias lightup='cd ${LIGHT_DIR} && vagrant up --provider vmware_fusion && vagrant ssh'
alias lightssh='cd ${LIGHT_DIR} && vagrant ssh'
EOF
source ~/.bash_profile
| {
"content_hash": "9f7dd76d3e46097d07b79cce8c08a9c7",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 85,
"avg_line_length": 27.77777777777778,
"alnum_prop": 0.684,
"repo_name": "framelab/lightbox",
"id": "7ccc9e2a3e53e4972940c9b6ec809de7cf843e2f",
"size": "262",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/osx-aliases.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "4930"
},
{
"name": "Shell",
"bytes": "8873"
}
],
"symlink_target": ""
} |
<?php
/**
* In this file you set up your send email details.
*
* @package cake.config
*/
/**
* Email configuration class.
* You can specify multiple configurations for production, development and testing.
*
* transport => The name of a supported transport; valid options are as follows:
* Mail - Send using PHP mail function
* Smtp - Send using SMTP
* Debug - Do not send the email, just return the result
*
* You can add custom transports (or override existing transports) by adding the
* appropriate file to app/Network/Email. Transports should be named 'YourTransport.php',
* where 'Your' is the name of the transport.
*
* from =>
* The origin email. See CakeEmail::from() about the valid values
*
*/
class EmailConfig {
public $default = array(
'transport' => 'Mail',
'from' => 'me@wvs.in',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $smtp = array(
'transport' => 'Smtp',
'from' => array('site@localhost' => 'My Site'),
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $fast = array(
'from' => 'you@wvs.in',
'sender' => 'you@wvs.in',
'to' => null,
'cc' => null,
'bcc' => null,
'replyTo' => null,
'readReceipt' => null,
'returnPath' => null,
'messageId' => true,
'subject' => null,
'message' => null,
'headers' => null,
'viewRender' => null,
'template' => false,
'layout' => false,
'viewVars' => null,
'attachments' => null,
'emailFormat' => null,
'transport' => 'Mail',
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => true,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
}
| {
"content_hash": "ce40f69ab33f51a7afb898ebdf478e26",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 90,
"avg_line_length": 23.632911392405063,
"alnum_prop": 0.5875736475629352,
"repo_name": "jumacro/JCRM",
"id": "7dfdeaaf7a3aa58af71f2186d362130e086fcb23",
"size": "2540",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Config/email.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "86234"
},
{
"name": "JavaScript",
"bytes": "2704789"
},
{
"name": "PHP",
"bytes": "8145492"
},
{
"name": "Shell",
"bytes": "2804"
}
],
"symlink_target": ""
} |
require 'OpenNebula'
##############################################################################
# This class represents a generic Cloud Server using the OpenNebula Cloud
# API (OCA). Any cloud implementation should derive from this class
##############################################################################
class CloudServer
##########################################################################
# Class Constants. Define the OpenNebula Error and HTTP codes mapping
##########################################################################
HTTP_ERROR_CODE = {
OpenNebula::Error::EAUTHENTICATION => 401,
OpenNebula::Error::EAUTHORIZATION => 403,
OpenNebula::Error::ENO_EXISTS => 404,
OpenNebula::Error::EACTION => 500,
OpenNebula::Error::EXML_RPC_API => 500,
OpenNebula::Error::EINTERNAL => 500,
OpenNebula::Error::ENOTDEFINED => 500
}
##########################################################################
# Public attributes
##########################################################################
attr_reader :config
# Initializes the Cloud server based on a config file
# config_file:: _String_ for the server. MUST include the following
# variables:
# AUTH
# VM_TYPE
# XMLRPC
def initialize(config, logger=nil)
# --- Load the Cloud Server configuration file ---
@config = config
@@logger = logger
end
def self.logger
return @@logger
end
def logger
return @@logger
end
#
# Prints the configuration of the server
#
def self.print_configuration(config)
puts "--------------------------------------"
puts " Server configuration "
puts "--------------------------------------"
pp config
STDOUT.flush
end
# Finds out if a port is available on ip
# ip:: _String_ IP address where the port to check is
# port:: _String_ port to find out whether is open
# [return] _Boolean_ Newly created image object
def self.is_port_open?(ip, port)
begin
Timeout::timeout(2) do
begin
s = TCPSocket.new(ip, port)
s.close
return true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
return false
end
end
rescue Timeout::Error
end
return false
end
end
module CloudLogger
require 'logger'
DEBUG_LEVEL = [
Logger::ERROR, # 0
Logger::WARN, # 1
Logger::INFO, # 2
Logger::DEBUG # 3
]
# Mon Feb 27 06:02:30 2012 [Clo] [E]: Error message example
MSG_FORMAT = %{%s [%s]: %s\n}
# Mon Feb 27 06:02:30 2012
DATE_FORMAT = "%a %b %d %H:%M:%S %Y"
# Patch logger class to be compatible with Rack::CommonLogger
class CloudLogger < Logger
def initialize(path)
super(path)
end
def write(msg)
info msg.chop
end
def add(severity, message = nil, progname = nil, &block)
rc = super(severity, message, progname, &block)
@logdev.dev.flush
rc
end
end
def enable_logging(path=nil, debug_level=3)
path ||= $stdout
logger = CloudLogger.new(path)
logger.level = DEBUG_LEVEL[debug_level]
logger.formatter = proc do |severity, datetime, progname, msg|
MSG_FORMAT % [
datetime.strftime(DATE_FORMAT),
severity[0..0],
msg ]
end
# Add the logger instance to the Sinatra settings
set :logger, logger
# The logging will be configured in Rack, not in Sinatra
disable :logging
# Use the logger instance in the Rack methods
use Rack::CommonLogger, logger
helpers do
def logger
settings.logger
end
end
end
end
| {
"content_hash": "2f865de75366d0b3f17572119e4488d6",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 78,
"avg_line_length": 28.53191489361702,
"alnum_prop": 0.48769574944071586,
"repo_name": "bcec/opennebula3.4.1",
"id": "904e072ec00f6374c97d32522b36a9e056ea3bb6",
"size": "5209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/cloud/common/CloudServer.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "721757"
},
{
"name": "C++",
"bytes": "1502569"
},
{
"name": "Java",
"bytes": "262511"
},
{
"name": "JavaScript",
"bytes": "906638"
},
{
"name": "Python",
"bytes": "2832"
},
{
"name": "Ruby",
"bytes": "1090866"
},
{
"name": "Shell",
"bytes": "154875"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>domain-theory: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">8.11.dev / domain-theory - dev</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
domain-theory
<small>
dev
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-02-20 10:20:10 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-02-20 10:20:10 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.11.dev Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.0 Official release 4.09.0
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "dev@clarus.me"
homepage: "https://github.com/coq-contribs/domain-theory"
license: "Proprietary"
build: [
["coq_makefile" "-f" "Make" "-o" "Makefile"]
[make "-j%{jobs}%"]
]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/DomainTheory"]
depends: [
"ocaml"
"coq" {= "dev"}
]
tags: [ "keyword:concrete domains" "category:Computer Science/Lambda Calculi" ]
authors: [ "Gilles Kahn <>" ]
synopsis: "Elements of Domain Theory."
description: """
Domain theory as devised by Scott and Plotkin and
following Kahn and Plotkin paper on Concrete Domains"""
flags: light-uninstall
url {
src: "git+https://github.com/coq-contribs/domain-theory.git#master"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-domain-theory.dev coq.8.11.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev).
The following dependencies couldn't be met:
- coq-domain-theory -> coq >= dev
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-domain-theory.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "a5dd282c6ad9e3138c77f47b8fa8de0b",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 157,
"avg_line_length": 40.23170731707317,
"alnum_prop": 0.5360715368293423,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "05aa33d19d0976a304f7bf6497088c1757c81ace",
"size": "6600",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.0-2.0.5/extra-dev/8.11.dev/domain-theory/dev.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
class TestFiniteStateMachine extends FiniteStateMachine
{
public function close()
{
}
protected function _close()
{
}
public function checkout()
{
}
public function process()
{
}
public function pend()
{
}
public function complete()
{
}
public function error()
{
}
public function void()
{
}
}
| {
"content_hash": "f42158f40553177096fc80210c28df67",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 55,
"avg_line_length": 11.222222222222221,
"alnum_prop": 0.5346534653465347,
"repo_name": "tourman/fsm",
"id": "b00a9d353ac09b6e666353a9845c9095b7162897",
"size": "404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/TestFiniteStateMachine.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "217375"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "2417ba0ab4ee438ca22f9b766b75bc91",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "5cf17d0675aae09e20cb47ae56e2f4558f7211b8",
"size": "189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Bacillariophyta/Bacillariophyceae/Bacillariales/Bacillariaceae/Hantzschia/Hantzschia pseudomarina/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
DPToastView
===========
(Yet another) Highly customizable toast view for iOS. This toast view supports simple strings or attributed strings, word wrap, notifications, and much more.
## Usage
Add the dependency to your `Podfile`:
```ruby
platform :ios
pod 'DPToastView'
...
```
Run `pod install` to install the dependencies.
Import the header file:
```objc
#import "DPToastView.h"
```
Make some toast!
```objc
// Show a simple toast.
DPToastView *toast = [DPToastView makeToast:@"I am just a string."];
[toast show];
```
or...
```objc
// Create an attributed string to display.
NSMutableParagraphStyle *parStyle = [[NSMutableParagraphStyle alloc] init];
[parStyle setAlignment:NSTextAlignmentCenter];
[parStyle setLineBreakMode:NSLineBreakByWordWrapping];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"I am an attributed toast that is centered and word wrapped."
attributes:@{
NSForegroundColorAttributeName : [UIColor yellowColor],
NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle),
NSFontAttributeName : [UIFont boldSystemFontOfSize:24.0],
NSParagraphStyleAttributeName : parStyle
}];
DPToastView *toast = [DPToastView makeToast:str];
[toast show];
```
Add some default styling with a category:
```objc
// Category on UIViewController...
@interface UIViewController (CustomDPToast)
- (id)makeRedToast:(NSString *)message gravity:(DPToastGravity)gravity duration:(NSTimeInterval)duration;
@end
@implementation UIViewController (CustomDPToast)
- (id)makeRedToast:(NSString *)message gravity:(DPToastGravity)gravity duration:(NSTimeInterval)duration {
DPToastView *toastView = [DPToastView makeToast:message gravity:gravity duration:duration];
// Style the toast...
[toastView setBackgroundColor:[[UIColor redColor] colorWithAlphaComponent:0.8]];
[toastView setFont:[UIFont boldSystemFontOfSize:20.0]];
return toastView;
}
@end
// and finally in your view controller...
DPToastView *toast = [self makeRedToast:@"I am a red toast" gravity:DPToastGravityCenter duration:DPToastDurationNormal];
[toast show];
```
## Requirements
`DPToastView` requires iOS 6.x or greater.
Requires ARC and auto-layout.
## License
Usage is provided under the [MIT License](http://http://opensource.org/licenses/mit-license.php). See LICENSE for the full details.
| {
"content_hash": "ab83d693968b9b68d576bbdaaab4d430",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 157,
"avg_line_length": 32.34146341463415,
"alnum_prop": 0.6730769230769231,
"repo_name": "ebaker355/DPToastView",
"id": "f783a58ad6865b985183784a025e21469a398011",
"size": "2652",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "28665"
},
{
"name": "Ruby",
"bytes": "506"
}
],
"symlink_target": ""
} |
/*
* BJAF - Beetle J2EE Application Framework
* 甲壳虫J2EE企业应用开发框架
* 版权所有2003-2015 余浩东 (www.beetlesoft.net)
*
* 这是一个免费开源的软件,您必须在
*<http://www.apache.org/licenses/LICENSE-2.0>
*协议下合法使用、修改或重新发布。
*
* 感谢您使用、推广本框架,若有建议或问题,欢迎您和我联系。
* 邮件: <yuhaodong@gmail.com/>.
*/
package com.beetle.framework.business.common.ejb;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import java.rmi.RemoteException;
import java.security.Principal;
public class SessionEJBImp implements SessionBean {
private static final long serialVersionUID = -19760224l;
private SessionContext sessionContext;
public SessionEJBImp() {
}
public void ejbCreate() throws CreateException {
// System.out.println("new:-->"+System.currentTimeMillis());
// this.principal = this.getSessionContext().getCallerPrincipal();
}
public Principal getPrincipal() {
Principal p = this.getSessionContext().getCallerPrincipal();
//System.out.println("------->>>z");
//System.out.println(p);
// System.out.println(p instanceof java.util.HashMap);
// System.out.println("------->>>");
boolean f = p instanceof java.io.Serializable;
if (!f) {
return null;//��ô�棿��
}
return p;
}
public void setSessionContext(SessionContext sessionContext)
throws EJBException, RemoteException {
this.sessionContext = sessionContext;
}
/**
* ��������ع�
*/
public void setRollbackOnly() {
try {
getSessionContext().setRollbackOnly();
} catch (final IllegalStateException exception) {
exception.printStackTrace();
}
}
/**
* ����SessionContext
*
* @return SessionContext
*/
public SessionContext getSessionContext() {
return sessionContext;
}
public void ejbRemove() throws EJBException, RemoteException {
}
public void ejbActivate() throws EJBException, RemoteException {
}
public void ejbPassivate() throws EJBException, RemoteException {
}
}
| {
"content_hash": "b10f89fe87c6d9a908962b90a0fbe755",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 68,
"avg_line_length": 24.73170731707317,
"alnum_prop": 0.6873767258382643,
"repo_name": "jbeetle/BJAF3.x",
"id": "3ea9d3d31f37b5008b22531c068b413f39ac9ca5",
"size": "2230",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/com/beetle/framework/business/common/ejb/SessionEJBImp.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1230833"
},
{
"name": "PLpgSQL",
"bytes": "1874"
},
{
"name": "SQLPL",
"bytes": "1318"
}
],
"symlink_target": ""
} |
<?php
namespace Documentor\Reflection;
/**
* @category Parsers
* @package Documentor
* @subpackage Reflection
* @author Julien Ballestracci <julien@nitronet.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://github.com/neiluj/Documentor
*/
class ReflectionMethod extends ReflectionFunction
{
const VIS_PUBLIC = 'public';
const VIS_PRIVATE = 'private';
const VIS_PROTECTED = 'protected';
protected $visibility = self::VIS_PUBLIC;
protected $abstract = false;
protected $static = false;
protected $final = false;
protected $declaringClass;
public function getVisibility()
{
return $this->visibility;
}
public function setVisibility($visibility)
{
$this->visibility = $visibility;
}
public function isAbstract()
{
return $this->abstract;
}
public function setAbstract($abstract)
{
$this->abstract = (bool)$abstract;
}
public function isStatic()
{
return $this->static;
}
public function setStatic($static)
{
$this->static = (bool)$static;
}
public function isFinal()
{
return $this->final;
}
public function setFinal($final)
{
$this->final = (bool)$final;
}
public function getParameters() {
if (!isset($this->parameters)) {
parent::getParameters();
foreach ($this->parameters as $param) {
$param->setDeclaringClass($this->getDeclaringClass());
}
}
return $this->parameters;
}
public function getDeclaringClass()
{
return $this->declaringClass;
}
public function setDeclaringClass(ReflectionClass $declaringClass)
{
$this->declaringClass = $declaringClass;
}
/**
*
* @return boolean
*/
public function isPublic()
{
return $this->visibility === self::VIS_PUBLIC;
}
/**
*
* @return boolean
*/
public function isProtected()
{
return $this->visibility === self::VIS_PROTECTED;
}
/**
*
* @return boolean
*/
public function isPrivate()
{
return $this->visibility === self::VIS_PRIVATE;
}
} | {
"content_hash": "3bcf2a804b833ad7644692d3c9a14ed6",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 78,
"avg_line_length": 19.863247863247864,
"alnum_prop": 0.5757314974182444,
"repo_name": "neiluJ/Documentor",
"id": "1fc959cd9f51de33334b46a406f1a562c6c9f9c3",
"size": "3689",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Reflection/ReflectionMethod.php",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "50460"
},
{
"name": "JavaScript",
"bytes": "2326"
},
{
"name": "PHP",
"bytes": "181957"
}
],
"symlink_target": ""
} |
package btree
// Return the mutated node along with a boolean that says whether a rebalance
// is required or not.
func (kn *knode) remove(store *Store, key Key, mv *MV) (
Node, bool, int64, int64) {
index, equal := kn.searchEqual(store, key)
mk, md := int64(-1), int64(-1)
if equal == false {
return kn, false, mk, md
}
copy(kn.ks[index:], kn.ks[index+1:])
copy(kn.ds[index:], kn.ds[index+1:])
kn.ks = kn.ks[:len(kn.ks)-1]
kn.ds = kn.ds[:len(kn.ds)-1]
kn.size = len(kn.ks)
copy(kn.vs[index:], kn.vs[index+1:])
kn.vs = kn.vs[:len(kn.ks)+1]
//Debug
if len(kn.vs) != len(kn.ks)+1 {
panic("Bomb")
}
// If first entry in the leaf node is always a separator key in
// intermediate node.
if index == 0 && kn.size > 0 {
mk, md = kn.ks[0], kn.ds[0]
}
if kn.size >= store.RebalanceThrs {
return kn, false, mk, md
}
return kn, true, mk, md
}
// Return the mutated node along with a boolean that says whether a rebalance
// is required or not.
func (in *inode) remove(store *Store, key Key, mv *MV) (
Node, bool, int64, int64) {
index, equal := in.searchEqual(store, key)
// Copy on write
stalechild := store.FetchMVCache(in.vs[index])
child := stalechild.copyOnWrite(store)
mv.stales = append(mv.stales, stalechild.getKnode().fpos)
mv.commits[child.getKnode().fpos] = child
// Recursive remove
child, rebalnc, mk, md := child.remove(store, key, mv)
if equal {
if mk < 0 || md < 0 {
panic("separator cannot be less than zero")
}
if index < 1 {
panic("cannot be less than 1")
}
in.ks[index-1], in.ds[index-1] = mk, md
}
in.vs[index] = child.getKnode().fpos
if rebalnc == false {
return in, false, mk, md
}
var node Node = in
// FIXME : In the below rebalance logic, we are fetching the left and right
// node and discarding it if they are of other type from child. Can this
// be avoided and optimized ?
// Try to rebalance from left, if there is a left node available.
if rebalnc && (index > 0) {
left := store.FetchMVCache(in.vs[index-1])
if canRebalance(child, left) {
node, index = in.rebalanceLeft(store, index, child, left, mv)
}
}
// Try to rebalance from right, if there is a right node available.
if rebalnc && (index >= 0) && (index+1 <= in.size) {
right := store.FetchMVCache(in.vs[index+1])
if canRebalance(child, right) {
node, index = in.rebalanceRight(store, index, child, right, mv)
}
}
// There is one corner case, where node is not `in` but `child` but in is
// in mv.commits and flushed into the disk, but actually orphaned.
if node.getKnode().size >= store.RebalanceThrs {
return node, false, mk, md
}
return node, true, mk, md
}
func (in *inode) rebalanceLeft(store *Store, index int, child Node, left Node, mv *MV) (
Node, int) {
count := left.balance(store, child)
mk, md := in.ks[index-1], in.ds[index-1]
if count == 0 { // We can merge with left child
_, stalenodes := left.mergeRight(store, child, mk, md)
mv.stales = append(mv.stales, stalenodes...)
if in.size == 1 { // This is where btree-level gets reduced. crazy eh!
mv.stales = append(mv.stales, in.fpos)
return child, -1
} else {
// The median aka seperator has to go
copy(in.ks[index-1:], in.ks[index:])
copy(in.ds[index-1:], in.ds[index:])
in.ks = in.ks[:len(in.ks)-1]
in.ds = in.ds[:len(in.ds)-1]
in.size = len(in.ks)
// left-child has to go
copy(in.vs[index-1:], in.vs[index:])
in.vs = in.vs[:len(in.ks)+1]
return in, (index - 1)
}
} else {
mv.stales = append(mv.stales, left.getKnode().fpos)
left := left.copyOnWrite(store)
mv.commits[left.getKnode().fpos] = left
in.ks[index-1], in.ds[index-1] = left.rotateRight(store, child, count, mk, md)
in.vs[index-1] = left.getKnode().fpos
return in, index
}
}
func (in *inode) rebalanceRight(store *Store, index int, child Node, right Node, mv *MV) (
Node, int) {
count := right.balance(store, child)
mk, md := in.ks[index], in.ds[index]
if count == 0 {
_, stalenodes := child.mergeLeft(store, right, mk, md)
mv.stales = append(mv.stales, stalenodes...)
if in.size == 1 { // There is where btree-level gets reduced. crazy eh!
mv.stales = append(mv.stales, in.fpos)
return child, -1
} else {
// The median aka separator has to go
copy(in.ks[index:], in.ks[index+1:])
copy(in.ds[index:], in.ds[index+1:])
in.ks = in.ks[:len(in.ks)-1]
in.ds = in.ds[:len(in.ds)-1]
in.size = len(in.ks)
// right child has to go
copy(in.vs[index+1:], in.vs[index+2:])
in.vs = in.vs[:len(in.ks)+1]
return in, index
}
} else {
mv.stales = append(mv.stales, right.getKnode().fpos)
right := right.copyOnWrite(store)
mv.commits[right.getKnode().fpos] = right
in.ks[index], in.ds[index] = child.rotateLeft(store, right, count, mk, md)
in.vs[index+1] = right.getKnode().fpos
return in, index
}
}
func (from *knode) balance(store *Store, to Node) int {
max := store.maxKeys()
size := from.size + to.getKnode().size
if float64(size) < (float64(max) * float64(0.6)) { // FIXME magic number ??
return 0
} else {
return (from.size - store.RebalanceThrs) / 2
}
}
// Merge `kn` into `other` Node, and return,
// - merged `other` node,
// - `kn` as stalenode
func (kn *knode) mergeRight(store *Store, othern Node, mk, md int64) (
Node, []int64) {
other := othern.(*knode)
max := store.maxKeys()
if kn.size+other.size >= max {
panic("We cannot merge knodes now. Combined size is greater")
}
other.ks = other.ks[:kn.size+other.size]
other.ds = other.ds[:kn.size+other.size]
copy(other.ks[kn.size:], other.ks[:other.size])
copy(other.ds[kn.size:], other.ds[:other.size])
copy(other.ks[:kn.size], kn.ks)
copy(other.ds[:kn.size], kn.ds)
other.vs = other.vs[:kn.size+other.size+1]
copy(other.vs[kn.size:], other.vs[:other.size+1])
copy(other.vs[:kn.size], kn.vs[:kn.size]) // Skip last value, which is zero
other.size = len(other.ks)
//Debug
if len(other.vs) != len(other.ks)+1 {
panic("Bomb")
}
store.wstore.countMergeRight += 1
return other, []int64{kn.fpos}
}
// rotate `count` entries from `left` node to child `n` node. Return the median
func (left *knode) rotateRight(store *Store, n Node, count int, mk, md int64) (
int64, int64) {
child := n.(*knode)
chlen, leftlen := len(child.ks), len(left.ks)
// Move last `count` keys from left -> child.
child.ks = child.ks[:chlen+count] // First expand
child.ds = child.ds[:chlen+count] // First expand
copy(child.ks[count:], child.ks[:chlen])
copy(child.ds[count:], child.ds[:chlen])
copy(child.ks[:count], left.ks[leftlen-count:])
copy(child.ds[:count], left.ds[leftlen-count:])
// Blindly shrink left keys
left.ks = left.ks[:leftlen-count]
left.ds = left.ds[:leftlen-count]
// Update size.
left.size, child.size = len(left.ks), len(child.ks)
// Move last count values from left -> child
child.vs = child.vs[:chlen+count+1] // First expand
copy(child.vs[count:], child.vs[:chlen+1])
copy(child.vs[:count], left.vs[leftlen-count:leftlen])
// Blinldy shrink left values and then append it with null pointer
left.vs = append(left.vs[:leftlen-count], 0)
//Debug
if (len(left.vs) != len(left.ks)+1) || (len(child.vs) != len(child.ks)+1) {
panic("Bomb")
}
// Return the median
store.wstore.countRotateRight += 1
return child.ks[0], child.ds[0]
}
// Merge `other` into `kn` Node, and return,
// - merged `kn` node,
// - `other` as stalenode
func (kn *knode) mergeLeft(store *Store, othern Node, mk, md int64) (
Node, []int64) {
other := othern.(*knode)
max := store.maxKeys()
if kn.size+other.size >= max {
panic("We cannot merge knodes now. Combined size is greater")
}
kn.ks = kn.ks[:kn.size+other.size]
kn.ds = kn.ds[:kn.size+other.size]
copy(kn.ks[kn.size:], other.ks[:other.size])
copy(kn.ds[kn.size:], other.ds[:other.size])
kn.vs = kn.vs[:kn.size+other.size+1]
copy(kn.vs[kn.size:], other.vs[:other.size+1])
kn.size = len(kn.ks)
//Debug
if len(kn.vs) != len(kn.ks)+1 {
panic("Bomb")
}
store.wstore.countMergeLeft += 1
return kn, []int64{other.fpos}
}
// rotate `count` entries from right `n` node to `child` node. Return median
func (child *knode) rotateLeft(store *Store, n Node, count int, mk, md int64) (
int64, int64) {
right := n.(*knode)
chlen := len(child.ks)
// Move first `count` keys from right -> child.
child.ks = child.ks[:chlen+count] // First expand
child.ds = child.ds[:chlen+count] // First expand
copy(child.ks[chlen:], right.ks[:count])
copy(child.ds[chlen:], right.ds[:count])
// Don't blindly shrink right keys
copy(right.ks, right.ks[count:])
copy(right.ds, right.ds[count:])
right.ks = right.ks[:len(right.ks)-count]
right.ds = right.ds[:len(right.ds)-count]
// Update size.
right.size, child.size = len(right.ks), len(child.ks)
// Move last count values from right -> child
child.vs = child.vs[:chlen+count+1] // First expand
copy(child.vs[chlen:], right.vs[:count])
child.vs[chlen+count] = 0
// Don't blinldy shrink right values
copy(right.vs, right.vs[count:])
right.vs = right.vs[:len(right.vs)-count]
//Debug
if len(child.vs) != len(child.ks)+1 {
panic("Bomb")
}
// Return the median
store.wstore.countRotateLeft += 1
return right.ks[0], right.ds[0]
}
// Merge `in` into `other` Node, and return,
// - merged `other` node,
// - `in` as stalenode
func (in *inode) mergeRight(store *Store, othern Node, mk, md int64) (
Node, []int64) {
other := othern.(*inode)
max := store.maxKeys()
if (in.size + other.size + 1) >= max {
panic("We cannot merge inodes now. Combined size is greater")
}
other.ks = other.ks[:in.size+other.size+1]
other.ds = other.ds[:in.size+other.size+1]
copy(other.ks[in.size+1:], other.ks[:other.size])
copy(other.ds[in.size+1:], other.ds[:other.size])
copy(other.ks[:in.size], in.ks)
copy(other.ds[:in.size], in.ds)
other.ks[in.size], other.ds[in.size] = mk, md
other.vs = other.vs[:in.size+other.size+2]
copy(other.vs[in.size+1:], other.vs)
copy(other.vs[:in.size+1], in.vs)
other.size = len(other.ks)
store.wstore.countMergeRight += 1
return other, []int64{in.fpos}
}
// rotate `count` entries from `left` node to child `n` node. Return the median
func (left *inode) rotateRight(store *Store, n Node, count int, mk, md int64) (
int64, int64) {
child := n.(*inode)
left.ks = append(left.ks, mk)
left.ds = append(left.ds, md)
chlen, leftlen := len(child.ks), len(left.ks)
// Move last `count` keys from left -> child.
child.ks = child.ks[:chlen+count] // First expand
child.ds = child.ds[:chlen+count] // First expand
copy(child.ks[count:], child.ks[:chlen])
copy(child.ds[count:], child.ds[:chlen])
copy(child.ks[:count], left.ks[leftlen-count:])
copy(child.ds[:count], left.ds[leftlen-count:])
// Blindly shrink left keys
left.ks = left.ks[:leftlen-count]
left.ds = left.ds[:leftlen-count]
// Update size.
left.size, child.size = len(left.ks), len(child.ks)
// Move last count values from left -> child
child.vs = child.vs[:chlen+count+1] // First expand
copy(child.vs[count:], child.vs[:chlen+1])
copy(child.vs[:count], left.vs[len(left.vs)-count:])
left.vs = left.vs[:len(left.vs)-count]
// Pop out median
mk, md = left.ks[left.size-1], left.ds[left.size-1]
left.ks = left.ks[:left.size-1]
left.ds = left.ds[:left.size-1]
left.size = len(left.ks)
// Return the median
store.wstore.countRotateRight += 1
return mk, md
}
// Merge `other` into `in` Node, and return,
// - merged `in` node,
// - `other` as stalenode
func (in *inode) mergeLeft(store *Store, othern Node, mk, md int64) (
Node, []int64) {
other := othern.(*inode)
max := store.maxKeys()
if (in.size + other.size + 1) >= max {
panic("We cannot merge inodes now. Combined size is greater")
}
in.ks = in.ks[:in.size+other.size+1]
in.ds = in.ds[:in.size+other.size+1]
copy(in.ks[in.size+1:], other.ks[:other.size])
copy(in.ds[in.size+1:], other.ds[:other.size])
in.ks[in.size], in.ds[in.size] = mk, md
in.vs = in.vs[:in.size+other.size+2]
copy(in.vs[in.size+1:], other.vs[:other.size+1])
in.size = len(in.ks)
store.wstore.countMergeLeft += 1
return in, []int64{other.fpos}
}
// rotate `count` entries from right `n` node to `child` node. Return median
func (child *inode) rotateLeft(store *Store, n Node, count int, mk, md int64) (
int64, int64) {
right := n.(*inode)
child.ks = append(child.ks, mk)
child.ds = append(child.ds, md)
chlen := len(child.ks)
rlen := len(right.ks)
// Move first `count` keys from right -> child.
child.ks = child.ks[:chlen+count] // First expand
child.ds = child.ds[:chlen+count] // First expand
copy(child.ks[chlen:], right.ks[:count])
copy(child.ds[chlen:], right.ds[:count])
// Don't blindly shrink right keys
copy(right.ks, right.ks[count:])
copy(right.ds, right.ds[count:])
right.ks = right.ks[:rlen-count]
right.ds = right.ds[:rlen-count]
// Update size.
right.size, child.size = len(right.ks), len(child.ks)
// Move last count values from right -> child
child.vs = child.vs[:chlen+count] // First expand
copy(child.vs[chlen:], right.vs[:count])
// Don't blinldy shrink right values
copy(right.vs, right.vs[count:])
right.vs = right.vs[:rlen-count+1]
// Pop out median
mk, md = child.ks[child.size-1], child.ds[child.size-1]
child.ks = child.ks[:child.size-1]
child.ds = child.ds[:child.size-1]
child.size = len(child.ks)
// Return the median
store.wstore.countRotateLeft += 1
return mk, md
}
func canRebalance(n Node, m Node) bool {
var rc bool
if _, ok := n.(*knode); ok {
if _, ok = m.(*knode); ok {
rc = true
}
} else {
if _, ok = m.(*inode); ok {
rc = true
}
}
return rc
}
| {
"content_hash": "c6dc81ddf18fc149912153205687a2df",
"timestamp": "",
"source": "github",
"line_count": 456,
"max_line_length": 90,
"avg_line_length": 29.767543859649123,
"alnum_prop": 0.6490349196994254,
"repo_name": "prataprc/gobtree",
"id": "9a29935d52dbc134deb77da61daa73aa7b2f9ae2",
"size": "14162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "remove.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "122026"
}
],
"symlink_target": ""
} |
This is the repository for Data Structure assignments of a BUPT team.
Current developer:
Tianrui Niu the mechanism designer, artist
Contact: heranort@163.com
Han Liu the algorithm implementor, database manager
Contact: liuhan132@foxmail.com
Mo Ying the GUI designer, vital developer
Contact: 1456415911@qq.com
## Current development process
2016-3-3
Our project has been launched! Thanks to all of us!
2016-3-5
First developers' meeting, decision of language, utilities, facilities and organization!
2016-3-6
Second developers’ meeting, finished requirement analysis, pushing the development into general design progress.
2016-3-7
Decision of using Python 2.7 has been changed to using Python 3.4. Keeping sharp & new is far better than staying outdated.
2016-3-10
The original design of transmitter module.
2016-3-20
Finished data designing, Including three means of transportation, 10 cities and hundreds of direct paths.
2016-3-21
Introducing mailer, the main machanism for module communication.
More in the code!
2016-3-21
Mailer upgraded to version 0.3, the first ready-to-use version of mailer mechanism.
2016-3-23
Finished designation of all modules.
2016-3-28
Upgrading database managing module. The interface to sql server.
2016-3-29
Finished the first ready—to-use transmitter module, including MASS (Modularized Abstract Socket Server), version 0.23
2016-4-7
Added core algorithm of minimal-cost.
2016-4-9
Added core module. It serves as the main interface to the whole software. The Map-Walker is now usable!
2016-5-23
Added Python List-\>C++ Vector parser, serve as a translator between client and server.
2016-5-23
Added departure time of each station, marks as a new era.
2016-5-24
Updated the database module.
2016-5-24
Updated minimal cost guiding algorithm.
2016-5-24
Updated minimal time guiding algorithm.
2016-5-25
Implemented tracer, the simulator.
2016-5-25
Renewed core interface. Slashed the flash screen problem.
## License
We use MIT License.
Each distribution of this software must contain a copy of a LICENSE file.
See that file for detail. If you haven't received that copy, contact the developers above.
| {
"content_hash": "576e55fe6db2b23d828d61a02d4c74ed",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 123,
"avg_line_length": 26.414634146341463,
"alnum_prop": 0.7903970452446907,
"repo_name": "niwtr/map-walker",
"id": "23b644eaefecb4a1a14140c9691f4882f820cb59",
"size": "2259",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "1402"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe Compare do
include RepoHelpers
let(:project) { create(:project, :public, :repository) }
let(:commit) { project.commit }
let(:start_commit) { sample_image_commit }
let(:head_commit) { sample_commit }
let(:raw_compare) { Gitlab::Git::Compare.new(project.repository.raw_repository, start_commit.id, head_commit.id) }
subject { described_class.new(raw_compare, project) }
describe '#start_commit' do
it 'returns raw compare base commit' do
expect(subject.start_commit.id).to eq(start_commit.id)
end
it 'returns nil if compare base commit is nil' do
expect(raw_compare).to receive(:base).and_return(nil)
expect(subject.start_commit).to eq(nil)
end
end
describe '#commit' do
it 'returns raw compare head commit' do
expect(subject.commit.id).to eq(head_commit.id)
end
it 'returns nil if compare head commit is nil' do
expect(raw_compare).to receive(:head).and_return(nil)
expect(subject.commit).to eq(nil)
end
end
describe '#base_commit_sha' do
it 'returns @base_sha if it is present' do
expect(project).not_to receive(:merge_base_commit)
sha = double
service = described_class.new(raw_compare, project, base_sha: sha)
expect(service.base_commit_sha).to eq(sha)
end
it 'fetches merge base SHA from repo when @base_sha is nil' do
expect(project).to receive(:merge_base_commit)
.with(start_commit.id, head_commit.id)
.once
.and_call_original
expect(subject.base_commit_sha)
.to eq(project.repository.merge_base(start_commit.id, head_commit.id))
end
it 'is memoized on first call' do
expect(project).to receive(:merge_base_commit)
.with(start_commit.id, head_commit.id)
.once
.and_call_original
3.times { subject.base_commit_sha }
end
it 'returns nil if there is no start_commit' do
expect(subject).to receive(:start_commit).and_return(nil)
expect(subject.base_commit_sha).to eq(nil)
end
it 'returns nil if there is no head commit' do
expect(subject).to receive(:head_commit).and_return(nil)
expect(subject.base_commit_sha).to eq(nil)
end
end
describe '#diff_refs' do
it 'uses base_commit_sha sha as base_sha' do
expect(subject.diff_refs.base_sha).to eq(subject.base_commit_sha)
end
it 'uses start_commit sha as start_sha' do
expect(subject.diff_refs.start_sha).to eq(start_commit.id)
end
it 'uses commit sha as head sha' do
expect(subject.diff_refs.head_sha).to eq(head_commit.id)
end
end
describe '#modified_paths' do
context 'changes are present' do
let(:raw_compare) do
Gitlab::Git::Compare.new(
project.repository.raw_repository, 'before-create-delete-modify-move', 'after-create-delete-modify-move'
)
end
it 'returns affected file paths, without duplication' do
expect(subject.modified_paths).to contain_exactly(*%w{
foo/for_move.txt
foo/bar/for_move.txt
foo/for_create.txt
foo/for_delete.txt
foo/for_edit.txt
})
end
end
context 'changes are absent' do
let(:start_commit) { sample_commit }
let(:head_commit) { sample_commit }
it 'returns empty array' do
expect(subject.modified_paths).to eq([])
end
end
end
end
| {
"content_hash": "57e7fd609d1eeb6d031ea5271a48e34b",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 116,
"avg_line_length": 27.774193548387096,
"alnum_prop": 0.6472125435540069,
"repo_name": "dreampet/gitlab",
"id": "0bc3ee014e6b4e1731925ebd131bbd02f12ab709",
"size": "3444",
"binary": false,
"copies": "2",
"ref": "refs/heads/11-7-stable-zh",
"path": "spec/models/compare_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "675415"
},
{
"name": "Clojure",
"bytes": "79"
},
{
"name": "Dockerfile",
"bytes": "1907"
},
{
"name": "HTML",
"bytes": "1329381"
},
{
"name": "JavaScript",
"bytes": "4251148"
},
{
"name": "Ruby",
"bytes": "19538796"
},
{
"name": "Shell",
"bytes": "44183"
},
{
"name": "Vue",
"bytes": "1051808"
}
],
"symlink_target": ""
} |
Jayson is a [JSON-RPC 2.0][jsonrpc-spec] compliant server and client written in JavaScript for [node.js][node.js] that aims to be as simple as possible to use.
[jsonrpc-spec]: http://jsonrpc.org/spec.html
[jsonrpc1-spec]: http://json-rpc.org/wiki/specification
[node.js]: http://nodejs.org/
[travis]: https://travis-ci.org/tedeh/jayson
[travis-img]: https://travis-ci.org/tedeh/jayson.png?branch=master
**Build status:** [![Build Status][travis-img]][travis]
## Table of contents
- [Features](#features)
- [Example](#example)
- [Installation](#installation)
- [Changelog](#changelog)
- [Requirements](#requirements)
- [Class Documentation](#class-documentation)
- [Running tests](#running-tests)
- [Usage](#usage)
- [Client](#client)
- [Interface description](#client-interface-description)
- [Notifications](#notifications)
- [Batches](#batches)
- [Callback syntactic sugar](#client-callback-syntactic-sugar)
- [Events](#client-events)
- [Server](#server)
- [Interface description](#server-interface-description)
- [Using many interfaces at the same time](#using-many-server-interfaces-at-the-same-time)
- [Using the server as a relay](#using-the-server-as-a-relay)
- [Method routing](#method-routing)
- [Events](#server-events)
- [Errors](#server-errors)
- [Revivers and replacers](#revivers-and-replacers)
- [Named parameters](#named-parameters)
- [Contributing](#contributing)
## Features
* Servers that can listen to several interfaces at the same time
* Supports both HTTP and TCP client and server connections
* Server-side method - [Method routing]
* jQuery client
* Relaying of requests to other servers
* JSON reviving and replacing for transparent serialization of complex objects
* CLI client
* Fully tested to comply with the [official JSON-RPC 2.0 specification][jsonrpc-spec]
* Also supports [JSON-RPC 1.0][jsonrpc1-spec]
## Example
A basic JSON-RPC 2.0 server via HTTP:
Server in `examples/simple_example/server.js`:
```javascript
var jayson = require(__dirname + '/../..');
// create a server
var server = jayson.server({
add: function(a, b, callback) {
callback(null, a + b);
}
});
// Bind a http interface to the server and let it listen to localhost:3000
server.http().listen(3000);
```
Client in `examples/simple_example/client.js` invoking `add` on the above server:
```javascript
var jayson = require(__dirname + '/../..');
// create a client
var client = jayson.client.http({
port: 3000,
hostname: 'localhost'
});
// invoke "add"
client.request('add', [1, 1], function(err, error, response) {
if(err) throw err;
console.log(response); // 2!
});
```
## Installation
Install the latest version of _jayson_ from [npm](https://github.com/isaacs/npm) by executing `npm install jayson` in your shell. Do a global install with `npm install --global jayson` if you want the `jayson` client CLI in your PATH.
## Changelog
- *1.1.0*
- More http server events
- Remove fork server and client
- Add server routing
- *1.0.11*
Add support for a HTTPS client
- *1.0.10*
Bugfixes
- *1.0.9*
Add support for TCP servers and clients
### CLI client
There is a CLI client in `bin/jayson.js` and it should be available as `jayson` in your shell if you installed the package with the `--global` switch. Run `jayson --help` to see how it works.
## Requirements
Jayson does not have any special dependencies that cannot be resolved with a simple `npm install`. It has been tested with the following node.js versions:
- node.js v0.8.x
- node.js v0.10.x
## Class documentation
In addition to this document, a comprehensive class documentation made with [jsdoc][jsdoc-spec] is available at [jayson.tedeh.net](http://jayson.tedeh.net).
[jsdoc-spec]: http://usejsdoc.org/
## Running tests
- Change directory to the repository root
- Install the testing framework
([mocha](https://github.com/visionmedia/mocha) together with
[should](https://github.com/visionmedia/should.js)) by executing `npm install
--dev`
- Run the tests with `make test` or `npm test`
## Usage
### Client
The client is available as the `Client` or `client` property of `require('jayson')`.
#### Client interface description
* `Client` Base class for interfacing with a server.
* `Client.tcp` TCP interface.
* `Client.http` HTTP interface.
* `Client.https` HTTPS interface.
* `Client.jquery` Wrapper around `jQuery.ajax`.
Every client supports these options:
* `reviver` -> Function to use as a JSON reviver
* `replacer` -> Function to use as a JSON replacer
* `generator` -> Function to generate request ids with. If omitted, Jayson will just generate a "random" number that is [RFC4122][rfc_4122_spec] compliant and looks similar to this: `3d4be346-b5bb-4e28-bc4a-0b721d4f9ef9`
* `version` -> Can be either `1` or `2` depending on which specification should be followed in communicating with the server. Defaults to `2` for [JSON-RPC 2.0][jsonrpc-spec]
[rfc_4122_spec]: http://www.ietf.org/rfc/rfc4122.txt
##### Client.http
Uses the same options as [http.request][nodejs_docs_http_request] in addition to these options:
* `encoding` -> String that determines the encoding to use and defaults to utf8
It is possible to pass a string URL as the first argument. The URL will be run through [url.parse][nodejs_docs_url_parse]. Example:
```javascript
var jayson = require(__dirname + '/../..');
var client = jayson.client.http('http://localhost:3000');
// client.options is now the result of url.parse
```
[nodejs_docs_http_request]: http://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback
[nodejs_docs_url_parse]: http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost
##### Client.https
Uses the same options as [https.request][nodejs_docs_https_request] in addition _to the same options as `Client.http`_. This means it is also possible
to pass a string URL as the first argument and have it interpreted by [url.parse][nodejs_docs_url_parse].
[nodejs_docs_https_request]: http://nodejs.org/api/all.html#all_https_request_options_callback
##### Client.tcp
Uses the same options as the base class.
##### Client.jquery
The jQuery Client is stand-alone from the other classes and should preferably be compiled with `make compile` which outputs different flavors into the `build` directory. Supports inclusion via AMD. Uses the same options as [jQuery.ajax][jquery_docs_ajax] and exposes itself as $.jayson with the same arguments as `Client.prototype.request`.
[jquery_docs_ajax]: http://api.jquery.com/jQuery.ajax/
#### Notifications
Notification requests are for cases where the reply from the server is not important and should be ignored. This is accomplished by setting the `id` property of a request object to `null`.
Client in `examples/notifications/client.js` doing a notification request:
```javascript
var jayson = require(__dirname + '/../..');
var client = jayson.client.http({
host: 'localhost',
port: 3000
});
// the third parameter is set to "null" to indicate a notification
client.request('ping', [], null, function(err) {
if(err) throw err;
// request was received successfully
});
```
A server in `examples/notifications/server.js`:
```javascript
var jayson = require(__dirname + '/../..');
var server = jayson.server({
ping: function(callback) {
// do something
callback();
}
});
server.http().listen(3000);
```
##### Notes
* Any value that the server returns will be discarded when doing a notification request.
* Omitting the third argument `null` to `Client.prototype.request` does not generate a notification request. This argument has to be set explicitly to `null` for this to happen.
* Network errors and the like will still reach the callback. When the callback is invoked (with or without error) one can be certain that the server has received the request.
* See the [Official JSON-RPC 2.0 Specification][jsonrpc-spec] for additional information on how Jayson handles notifications that are erroneous.
#### Batches
A batch request is an array of individual requests that are sent to the server as one. Doing a batch request is very simple in Jayson and consists of constructing an `Array` of individual requests (created by not passing a callback to `Client.prototype.request`) that is then itself passed to `Client.prototype.request`.
Client example in `examples/batch_request/client.js`:
```javascript
var jayson = require(__dirname + '/../..');
var client = jayson.client.http({
host: 'localhost',
port: 3000
});
var batch = [
client.request('does_not_exist', [10, 5]),
client.request('add', [1, 1]),
client.request('add', [0, 0], null) // a notification
];
// callback takes two arguments (first type of callback)
client.request(batch, function(err, responses) {
if(err) throw err;
// responses is an array of errors and successes together
console.log('responses', responses);
});
// callback takes three arguments (second type of callback)
client.request(batch, function(err, errors, successes) {
if(err) throw err;
// errors is an array of the requests that errored
console.log('errors', errors);
// successes is an array of requests that succeded
console.log('successes', successes);
});
```
Server example in `examples/batch_request/server.js`:
```javascript
var jayson = require(__dirname + '/../..');
var server = jayson.server({
add: function(a, b, callback) {
callback(null, a + b);
}
});
server.http().listen(3000);
```
##### Notes
* See the [Official JSON-RPC 2.0 Specification][jsonrpc-spec] for additional information on how Jayson handles different types of batches, mainly with regards to notifications, request errors and so forth.
* There is no guarantee that the results will be in the same order as request Array `request`. To find the right result, compare the ID from the request with the ID in the result yourself.
#### Client callback syntactic sugar
When the length (number of arguments) of a client callback function is either 2 or 3 it receives slightly different values when invoked.
* 2 arguments: first argument is an error or `null`, second argument is the response object as returned (containing _either_ a `result` or a `error` property) or `null` for notifications.
* 3 arguments: first argument is an error or null, second argument is a JSON-RPC `error` property or `null` (if success), third argument is a JSON-RPC `result` property or `null` (if error).
When doing a batch request with a 3-length callback, the second argument will be an array of requests with a `error` property and the third argument will be an array of requests with a `result` property.
#### Client events
A client will emit the following events (in addition to any special ones emitted by a specific interface):
* `request` Emitted when a client is just about to dispatch a request. First argument is the request object.
* `response` Emitted when a client has just received a reponse. First argument is the request object, second argument is the response as received.
### Server
The server classes are available as the `Server` or `server` property of `require('jayson')`.
The server also sports several interfaces that can be accessed as properties of an instance of `Server`.
#### Server interface description
* `Server` - Base interface for a server that supports receiving JSON-RPC 2.0 requests.
* `Server.tcp` - TCP server that inherits from [net.Server][nodejs_doc_net_server].
* `Server.http` - HTTP server that inherits from [http.Server][nodejs_doc_http_server].
* `Server.https` - HTTPS server that inherits from [https.Server][nodejs_doc_https_server].
* `Server.middleware` - Method that returns a [Connect][connect]/[Express][express] compatible middleware function.
[nodejs_doc_net_server]: http://nodejs.org/docs/latest/api/net.html#net_class_net_server
[nodejs_doc_http_server]: http://nodejs.org/docs/latest/api/http.html#http_class_http_server
[nodejs_doc_https_server]: http://nodejs.org/docs/latest/api/https.html#https_class_https_server
[connect]: http://www.senchalabs.org/connect/
[express]: http://expressjs.com/
Every server supports these options:
* `reviver` -> Function to use as a JSON reviver
* `replacer` -> Function to use as a JSON replacer
* `router` -> Function to find which method to use for a request. See the chapter on [method routing](#method-routing).
* `version` -> Can be either `1` or `2` depending on which specification clients are expected to follow. Defaults to `2` for [JSON-RPC 2.0][jsonrpc-spec]
##### Server.tcp
Uses the same options as the base class. Inherits from [net.Server][nodejs_doc_net_server].
##### Server.http
Uses the same options as the base class. Inherits from [http.Server][nodejs_doc_http_server].
###### Events
The HTTP server will emit the following events:
* `http request` Emitted when the server has just created a HTTP request. First argument is an instance of `http.ClientRequest`
* `http response` Emitted when the server has received an HTTP response. First argument is an instance of `http.IncomingMessage` and second argument an instance of `http.ClientRequest`.
* `http error` Emitted when the underlying stream emits `error`. First argument is the error.
##### Server.https
Uses the same options as the base class. Inherits from [https.Server][nodejs_doc_https_server] and `jayson.Server.http`. For information on how to configure certificates, [see the documentation on https.Server][nodejs_doc_https_server].
##### Server.middleware
Uses the same options as the base class. Returns a function that is compatible with [Connect][connect] or [Express][express]. Will expect the request to be `req.body`, meaning that the request body must be parsed (typically using `connect.bodyParser`) before the middleware is invoked.
Middleware example in `examples/middleware/server.js`:
```javascript
var jayson = require(__dirname + '/../..');
var connect = require('connect');
var app = connect();
var server = jayson.server({
add: function(a, b, callback) {
callback(null, a + b);
}
});
// parse request body before the jayson middleware
app.use(connect.bodyParser());
app.use(server.middleware());
app.listen(3000);
````
#### Using many server interfaces at the same time
A Jayson server can use many interfaces at the same time.
Server in `examples/many_interfaces/server.js` that listens to both `http` and a `https` requests:
```javascript
var jayson = require(__dirname + '/../..');
var server = jayson.server({
add: function(a, b, callback) {
return callback(null, a + b);
}
});
// "http" will be an instance of require('http').Server
var http = server.http();
// "https" will be an instance of require('https').Server
var https = server.https({
//cert: require('fs').readFileSync('cert.pem'),
//key require('fs').readFileSync('key.pem')
});
http.listen(80, function() {
console.log('Listening on *:80')
});
https.listen(443, function() {
console.log('Listening on *:443')
});
```
#### Using the server as a relay
Passing an instance of a client as a method to the server makes the server relay incoming requests to wherever the client is pointing to. This might be used to delegate computationally expensive functions into a separate server or to abstract a cluster of servers behind a common interface.
Public server in `examples/relay/server_public.js` listening on `*:3000`:
```javascript
var jayson = require(__dirname + '/../..');
// create a server where "add" will relay a localhost-only server
var server = jayson.server({
add: jayson.client.http({
hostname: 'localhost',
port: 3001
})
});
// let the server listen to *:3000
server.http().listen(3000, function() {
console.log('Listening on *:3000');
});
```
Private server in `examples/relay/server_private.js` listening on localhost:3001:
```javascript
var jayson = require(__dirname + '/../..');
var server = jayson.server({
add: function(a, b, callback) {
callback(null, a + b);
}
});
// let the private server listen to localhost:3001
server.http().listen(3001, '127.0.0.1', function() {
console.log('Listening on 127.0.0.1:3001');
});
```
Every request to `add` on the public server will now relay the request to the private server. See the client example in `examples/relay/client.js`.
#### Method routing
Passing a property named `router` in the server options will enable you to write your own logic for routing requests to specific functions.
Server with custom routing logic in `examples/method_routing/server.js`:
```javascript
var jayson = require(__dirname + '/../..');
var format = require('util').format;
var methods = {
add: function(a, b, callback) {
callback(null, a + b);
}
};
var server = jayson.server(methods, {
router: function(method) {
// regular by-name routing first
if(typeof(this._methods[method]) === 'function') return this._methods[method];
if(method === 'add_2') return this._methods.add.bind(this, 2);
}
});
```
Client in `examples/method_routing/client.js` invoking `add_2` on the above server:
```javascript
var jayson = require(__dirname + '/../..');
// create a client
var client = jayson.client.http({
port: 3000,
hostname: 'localhost'
});
// invoke "add_2"
client.request('add_2', [3], function(err, error, response) {
if(err) throw err;
console.log(response); // 5!
});
```
An example of nested routes where each property is separated by a dot (you do not need to use the router option for this):
```javascript
var _ = require('underscore');
var jayson = require(__dirname + '/../..');
var methods = {
foo: {
bar: function(callback) {
callback(null, 'ping pong');
}
},
math: {
add: function(a, b, callback) {
callback(null, a + b);
}
}
};
// this reduction produces an object like this: {'foo.bar': [Function], 'math.add': [Function]}
var map = _.reduce(methods, collapse('', '.'), {});
var server = jayson.server(map);
function collapse(stem, sep) {
return function(map, value, key) {
var prop = stem ? stem + sep + key : key;
if(_.isFunction(value)) map[prop] = value;
else if(_.isObject(value)) map = _.reduce(value, collapse(prop, sep), map);
return map;
}
}
```
##### Notes
* If `router` does not return anything, the reserver will respond with a `Method Not Found` error.
* The `Server.prototype` methods `method`, `methods`, `removeMethod` and `hasMethod` will not use the `router` method, but will operate on the internal `Server.prototype._methods` map.
#### Server events
In addition to events that are specific to certain interfaces, all servers will emit the following events:
* `request` Emitted when the server receives an interpretable (non-batch) request. First argument is the request object.
* `response` Emitted when the server is returning a response. First argument is the request object, the second is the response object.
* `batch` Emitted when the server receives a batch request. First argument is an array of requests. Will emit `request` for each interpretable request in the batch.
#### Server Errors
If you should like to return an error from an method request to indicate a failure, remember that the [JSON-RPC 2.0][jsonrpc-spec] specification requires the error to be an `Object` with a `code (Integer/Number)` to be regarded as valid. You can also provide a `message (String)` and a `data (Object)` with additional information. Example:
```javascript
var jayson = require(__dirname + '/../..');
var server = jayson.server({
i_cant_find_anything: function(id, callback) {
var error = {code: 404, message: 'Cannot find ' + id};
callback(error); // will return the error object as given
},
i_cant_return_a_valid_error: function(callback) {
callback({message: 'I forgot to enter a code'}); // will return a pre-defined "Internal Error"
}
});
```
##### Predefined Errors
It is also possible to cause a method to return one of the predefined [JSON-RPC 2.0 error codes][jsonrpc-spec#error_object] using the server helper function `Server.prototype.error` inside of a server method. Example:
[jsonrpc-spec#error_object]: http://jsonrpc.org/spec.html#error_object
```javascript
var jayson = require(__dirname + '/../..');
var server = jayson.server({
invalid_params: function(id, callback) {
var error = this.error(-32602); // returns an error with the default properties set
callback(error);
}
});
```
You can even override the default messages:
```javascript
var jayson = require(__dirname + '/../..');
var server = jayson.server({
error_giver_of_doom: function(callback) {
callback(true) // invalid error format, which causes an Internal Error to be returned instead
}
});
// Override the default message
server.errorMessages[Server.errors.INTERNAL_ERROR] = 'I has a sad. I cant do anything right';
```
### Revivers and Replacers
JSON lacks support for representing types other than the simple ones defined in the [JSON specification][jsonrpc-spec]. Fortunately the JSON methods in JavaScript (`JSON.parse` and `JSON.stringify`) provide options for custom serialization/deserialization routines. Jayson allows you to pass your own routines as options to both clients and servers.
Simple example transferring the state of an object between a client and a server:
Shared code between the server and the client in `examples/reviving_and_replacing/shared.js`:
```javascript
var Counter = exports.Counter = function(value) {
this.count = value || 0;
};
Counter.prototype.increment = function() {
this.count += 1;
};
exports.replacer = function(key, value) {
if(value instanceof Counter) {
return {$class: 'counter', $props: {count: value.count}};
}
return value;
};
exports.reviver = function(key, value) {
if(value && value.$class === 'counter') {
var obj = new Counter;
for(var prop in value.$props) obj[prop] = value.$props[prop];
return obj;
}
return value;
};
```
Server in `examples/reviving_and_replacing/server.js`:
```javascript
var jayson = require(__dirname + '/../..');
var shared = require('./shared');
// Set the reviver/replacer options
var options = {
reviver: shared.reviver,
replacer: shared.replacer
};
// create a server
var server = jayson.server({
increment: function(counter, callback) {
counter.increment();
callback(null, counter);
}
}, options);
// let the server listen to for http connections on localhost:3000
server.http().listen(3000);
```
A client in `examples/reviving_and_replacing/client.js` invoking "increment" on the server:
```javascript
var jayson = require(__dirname + '/../..');
var shared = require('./shared');
// create a client with the shared reviver and replacer
var client = jayson.client.http({
port: 3000,
hostname: 'localhost',
reviver: shared.reviver,
replacer: shared.replacer
});
// create the object
var instance = new shared.Counter(2);
// invoke "increment"
client.request('increment', [instance], function(err, error, result) {
if(err) throw err;
console.log(result instanceof shared.Counter); // true
console.log(result.count); // 3!
console.log(instance === result); // false - it won't be the same object, naturally
});
```
#### Notes
* Instead of using a replacer, it is possible to define a `toJSON` method for any JavaScript object. Unfortunately there is no corresponding method for reviving objects (that would not work, obviously), so the _reviver_ always has to be set up manually.
### Named parameters
It is possible to specify named parameters when doing a client request by passing an Object instead of an Array.
Client example in `examples/named_parameters/client.js`:
```javascript
var jayson = require(__dirname + '/../../');
var client = jayson.client.http({
host: 'localhost',
port: 3000
});
client.request('add', {b: 1, a: 2}, function(err, error, response) {
if(err) throw err;
console.log(response); // 3!
});
```
Server example in `examples/named_parameters/server.js`:
```javascript
var jayson = require(__dirname + '/../..');
var server = jayson.server({
add: function(a, b, callback) {
callback(null, a + b);
}
});
server.http().listen(3000);
```
#### Notes
* If requesting methods on a Jayson server, arguments left out will be `undefined`
* Too many arguments or arguments with invalid names will be ignored
* It is assumed that the last argument to a server method is the callback and it will not be filled with something else
### Contributing
Highlighting [issues](https://github.com/tedeh/jayson/issues) or submitting pull
requests on [Github](https://github.com/tedeh/jayson) is most welcome.
| {
"content_hash": "5bd2a27f4ec8bca90dba540ac1202b73",
"timestamp": "",
"source": "github",
"line_count": 719,
"max_line_length": 349,
"avg_line_length": 34.280945757997216,
"alnum_prop": 0.7159201557935735,
"repo_name": "mtoma/zonemaster",
"id": "74b4f3a7f2c75a5d428f49dcfb134432b5c0d4b5",
"size": "24658",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Zonemaster-GUI/Zonemaster_node.js/node_modules/jayson/README.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "14961"
},
{
"name": "JavaScript",
"bytes": "220729"
},
{
"name": "Perl",
"bytes": "644725"
},
{
"name": "Shell",
"bytes": "365"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-character: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.2~camlp4 / mathcomp-character - 1.12.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-character
<small>
1.12.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-14 05:12:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-14 05:12:06 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads base
base-unix base
camlp4 4.02+7 Camlp4 is a system for writing extensible parsers for programming languages
conf-findutils 1 Virtual package relying on findutils
conf-which 1 Virtual package relying on which
coq 8.5.2~camlp4 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
ocamlbuild 0 Build system distributed with the OCaml compiler since OCaml 3.10.0
# opam file:
opam-version: "2.0"
maintainer: "Mathematical Components <mathcomp-dev@sympa.inria.fr>"
homepage: "https://math-comp.github.io/"
bug-reports: "https://github.com/math-comp/math-comp/issues"
dev-repo: "git+https://github.com/math-comp/math-comp.git"
license: "CECILL-B"
build: [ make "-C" "mathcomp/character" "-j" "%{jobs}%" "COQEXTRAFLAGS+=-native-compiler yes" {coq-native:installed & coq:version < "8.13~" } ]
install: [ make "-C" "mathcomp/character" "install" ]
depends: [ "coq-mathcomp-field" { = version } ]
tags: [ "keyword:algebra" "keyword:character" "keyword:small scale reflection" "keyword:mathematical components" "keyword:odd order theorem" "logpath:mathcomp.character" ]
authors: [ "Jeremy Avigad <>" "Andrea Asperti <>" "Stephane Le Roux <>" "Yves Bertot <>" "Laurence Rideau <>" "Enrico Tassi <>" "Ioana Pasca <>" "Georges Gonthier <>" "Sidi Ould Biha <>" "Cyril Cohen <>" "Francois Garillot <>" "Alexey Solovyev <>" "Russell O'Connor <>" "Laurent Théry <>" "Assia Mahboubi <>" ]
synopsis: "Mathematical Components Library on character theory"
description:"""
This library contains definitions and theorems about group
representations, characters and class functions.
"""
url {
src: "https://github.com/math-comp/math-comp/archive/mathcomp-1.12.0.tar.gz"
checksum: "sha256=a57b79a280e7e8527bf0d8710c1f65cde00032746b52b87be1ab12e6213c9783"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-mathcomp-character.1.12.0 coq.8.5.2~camlp4</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.2~camlp4).
The following dependencies couldn't be met:
- coq-mathcomp-character -> coq-mathcomp-field = 1.12.0 -> coq-mathcomp-solvable = 1.12.0 -> coq-mathcomp-algebra = 1.12.0 -> coq-mathcomp-fingroup = 1.12.0 -> coq-mathcomp-ssreflect = 1.12.0 -> coq >= 8.10 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-character.1.12.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "decd6178565a15f8585897df30fa0637",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 554,
"avg_line_length": 49.93827160493827,
"alnum_prop": 0.5705809641532756,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "7ccab9b498d01dceb4eedfa925a8f33258ee26c2",
"size": "8116",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.5.2~camlp4/mathcomp-character/1.12.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
# Cronner [](https://travis-ci.org/stekycz/Cronner)
- [Description](#description)
- [Usage](#usage)
- [Annotations](#annotations)
- [Author](#author)
- [License](#license)
## Description
Simple tool which helps with maintenance of cron tasks.
It requires **PHP >= 5.3.3** and **Nette Framework >= 2.0.0**.
## Usage
It is very simple to use it because configuration is only in method annotations. Example class with tasks follows.
```php
class CronTasks {
/**
* @cronner-task E-mail sending
* @cronner-period 1 day
* @cronner-days working days
* @cronner-time 23:30 - 05:00
*/
public function sendEmails() {
// Code which sends all your e-mails
}
/**
* @cronner-task Important data replication
* @cronner-period 3 hours
*/
public function replicateImportantData() {
// Replication code
}
}
```
It is recommend to use compiler extension.
```neon
extension:
cronner: stekycz\Cronner\DI\CronnerExtension
```
It does not require any configuration however your own implementation of timestamp storage could be better
then the default storage. Your storage must be defined as a service in `config.neon` and Cronner will find it.
However you can specify service manually if it is not autowireable.
```neon
cronner:
timestampStorage: @myCoolTimestampStorage
```
Or you can change the directory for default storage.
```neon
cronner:
timestampStorage: stekycz\Cronner\TimestampStorage\FileStorage(%wwwDir%/../temp/cronner)
```
It is also possible to define `maxExecutionTime` for Cronner so you do not have make it by you own code
(and probably for all your requests). Option `criticalSectionTempDir` can be change however the directory
must be writable for php process. It is used to run each task only once at time.
At the end you would need to specify your task objects. It would be some service with high probability.
You can add tag `cronner.tasks` to all services with Cronner tasks and those services will be bind
automatically. However you can still add new task objects by your own using `addTasks` method.
Then you can use it very easily in `Presenter`
```php
class CronPresenter extends \Nette\Application\UI\Presenter {
/**
* @var \stekycz\Cronner\Cronner
* @inject
*/
public $cronner;
public function actionCron() {
$this->cronner->run();
}
}
```
or in `Command` from [Kdyby/Console](https://github.com/Kdyby/Console).
Service configuration is also possible but it **should not** be used using new versions of Nette because extension
usage is recommended and preferable way. However you will still need to call `run` method somewhere in your
`Presenter` or console `Command`.
```neon
services:
cronner: stekycz\Cronner\Cronner(stekycz\Cronner\TimestampStorage\FileStorage(%wwwDir%/../temp/cronner))
setup:
- addTasks(new CronTasks())
```
## Annotations
### @cronner-task
This annotations is **required** for all public methods which should be used as a task.
Its value is used as a name of task. If the value is missing the name is build from class name
and method name.
If this annotation is single (for Cronner) in task method comment then the task is run
every time when Cronner runs.
**Note:** Magic methods cannot be used as task (`__construct`, `__sleep`, etc.).
#### Example
```php
/**
* @cronner-task Fetches all public data from all registered social networks
*/
```
### @cronner-period
Not required but recommended annotation which specifies period of task execution.
The period is minimal time between two executions of the task. It's value can be
anything what is acceptable for `strtotime()` function. The only restriction is usability
with "+" sign before the time because it is added by Cronner automatically. So `first day of this month`
is not acceptable however `1 month` is acceptable.
**Attention!** The value of this annotation must not contain any sign (+ or -).
#### Example
```php
/**
* @cronner-period 1 day
*/
```
### @cronner-days
Allows run the task only on specified days. Possible values are abbreviations of week day names.
It means `Mon`, `Tue`, `Wed`, `Thu`, `Fri`, `Sat` and `Sun`. There are two shortcuts for easier usage:
`working days` (`Mon`, `Tue`, `Wed`, `Thu`, `Fri`) and `weekend` (`Sat` and `Sun`) which are internally
expanded to specific days. Multiple values must be separated by comma (`Mon, Wed, Fri`) or can be specified by range `Mon-Thu`.
#### Example
```php
/**
* @cronner-days working days, Sun
*/
```
### @cronner-time
Specifies day time range (or ranges) in which the task can be run. It can be range or a specific minute.
It uses 24 hour time model. Multiple values must be separated by comma.
The time can be defined over midnight as it is in following example.
**Note:** There is tolerance time of 5 seconds to run task as soon as possible if previous run have had slower
start from any reason.
#### Example
```php
/**
* @cronner-time 11:00, 23:30 - 05:00
*/
```
## Author
My name is Martin Štekl. Feel free to contact me on [e-mail](mailto:martin.stekl@gmail.com)
or follow me on [Twitter](https://twitter.com/stekycz).
## License
Copyright (c) 2013 Martin Štekl <martin.stekl@gmail.com>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
| {
"content_hash": "ac3b4429010813b8c803489c62d52cab",
"timestamp": "",
"source": "github",
"line_count": 201,
"max_line_length": 127,
"avg_line_length": 31.577114427860696,
"alnum_prop": 0.7304238222782417,
"repo_name": "AntikCz/Cronner",
"id": "f2a45bef92fb306491fc63710c3cbafbc6598c33",
"size": "6349",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2517"
},
{
"name": "PHP",
"bytes": "69768"
}
],
"symlink_target": ""
} |
package blue.lapis.pore.impl.entity;
import blue.lapis.pore.converter.wrapper.WrapperConverter;
import org.bukkit.entity.EntityType;
import org.spongepowered.api.entity.living.monster.Creeper;
public class PoreCreeper extends PoreMonster implements org.bukkit.entity.Creeper {
public static PoreCreeper of(Creeper handle) {
return WrapperConverter.of(PoreCreeper.class, handle);
}
protected PoreCreeper(Creeper handle) {
super(handle);
}
@Override
public Creeper getHandle() {
return (Creeper) super.getHandle();
}
@Override
public EntityType getType() {
return EntityType.CREEPER;
}
@Override
public boolean isPowered() {
return getHandle().isPowered();
}
@Override
public void setPowered(boolean value) {
getHandle().setPowered(value);
}
}
| {
"content_hash": "559c6a492240f5c14a11edfc009b912f",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 83,
"avg_line_length": 22.736842105263158,
"alnum_prop": 0.6851851851851852,
"repo_name": "phase/Pore",
"id": "9b31db2c42deac63efd87f9808afe0305cc502c5",
"size": "2040",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/blue/lapis/pore/impl/entity/PoreCreeper.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Diff",
"bytes": "20966"
},
{
"name": "Java",
"bytes": "1184235"
},
{
"name": "Shell",
"bytes": "7220"
}
],
"symlink_target": ""
} |
package frequentflyer.com.services;
import frequentflyer.com.domain.RotationDto;
import frequentflyer.com.entities.Combination;
import frequentflyer.com.services.exceptions.NvtServiceException;
import java.util.List;
/**
* Created by sasaradovanovic on 10/10/17.
*/
public interface RotationService {
/**
*
* Remove all rotations from a combination
*
* @param combination
*/
void removeAllRotationsForCombination(Combination combination);
/**
*
* Create new rotations
*
* @param origin - IATA code of orgin airport
* @param destination - destination code of destination airport
* @param frequency - Frequency string, i.e. '1/3/7'
* @param localDepartureTime - HH:mm string
* @param flightLength - Total flight length in minutes
* @param combinationId - ID combination
* @throws NvtServiceException
*/
void createNewRotation(String origin, String destination, String frequency,
String localDepartureTime, int flightLength, long combinationId) throws NvtServiceException;
/**
*
* Retrieve all rotations from a combination
*
* @param combinationId - ID of combination
* @return List of {@link RotationDto} objects
*/
List<RotationDto> getAllRotationsForCombination(long combinationId);
/**
*
* Remove certain rotation
*
* @param id - rotationId
*/
void removeRotation(long id);
}
| {
"content_hash": "f70f99b5cb7d8b93f029851e79b6f068",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 119,
"avg_line_length": 26.945454545454545,
"alnum_prop": 0.6734143049932524,
"repo_name": "sasa-radovanovic/ff-network-visualization-tool",
"id": "b29ffecdac9c92a33ddaa1025186a6c5581549be",
"size": "1482",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nvt-backend/src/main/java/frequentflyer/com/services/RotationService.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5489"
},
{
"name": "HTML",
"bytes": "830"
},
{
"name": "Java",
"bytes": "75437"
},
{
"name": "JavaScript",
"bytes": "18932"
},
{
"name": "Roff",
"bytes": "10556849"
},
{
"name": "Shell",
"bytes": "7891"
},
{
"name": "Vue",
"bytes": "121508"
}
],
"symlink_target": ""
} |
'use strict';
/*
* If a string’s ratio of alphanumeric characters to total characters is less than 50%, the string is garbage
*/
module.exports = function alphanumeric(word) {
var totalLength = word.length;
var alphanumericLength = word.replace(/[^0-9A-Z]/gi, "").length;
if(totalLength !== 1 && alphanumericLength / totalLength < 0.5) {
return false;
}
return true;
}; | {
"content_hash": "61fddc37103714bff71ba29fd4043245",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 109,
"avg_line_length": 25.933333333333334,
"alnum_prop": 0.6838046272493573,
"repo_name": "Amoki/rmgarbage",
"id": "eb56dcca43949d450774ebf383b64c0fd8832050",
"size": "391",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/checkers/alphanumeric.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5844"
}
],
"symlink_target": ""
} |
<?php
namespace Doctrine\ODM\MongoDB\Mapping\Annotations;
/**
* @Annotation
* @deprecated This class will be removed in ODM 2.0
*/
final class Timestamp extends AbstractField
{
public $type = 'timestamp';
}
| {
"content_hash": "5478a62a83bffdade4a32b446bd1c012",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 52,
"avg_line_length": 16.692307692307693,
"alnum_prop": 0.7142857142857143,
"repo_name": "waldihuber/mongodb-odm",
"id": "3ef480cfe3dc443e085c682fbcb40f891fa2b3bd",
"size": "1198",
"binary": false,
"copies": "3",
"ref": "refs/heads/patch-1",
"path": "lib/Doctrine/ODM/MongoDB/Mapping/Annotations/Timestamp.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "1930261"
}
],
"symlink_target": ""
} |
'''OpenGL extension NV.parameter_buffer_object
This module customises the behaviour of the
OpenGL.raw.GL.NV.parameter_buffer_object to provide a more
Python-friendly API
Overview (from the spec)
This extension, in conjunction with NV_gpu_program4, provides a new type
of program parameter than can be used as a constant during vertex,
fragment, or geometry program execution. Each program target has a set of
parameter buffer binding points to which buffer objects can be attached.
A vertex, fragment, or geometry program can read data from the attached
buffer objects using a binding of the form "program.buffer[a][b]". This
binding reads data from the buffer object attached to binding point <a>.
The buffer object attached is treated either as an array of 32-bit words
or an array of four-component vectors, and the binding above reads the
array element numbered <b>.
The use of buffer objects allows applications to change large blocks of
program parameters at once, simply by binding a new buffer object. It
also provides a number of new ways to load parameter values, including
readback from the frame buffer (EXT_pixel_buffer_object), transform
feedback (NV_transform_feedback), buffer object loading functions such as
MapBuffer and BufferData, as well as dedicated parameter buffer update
functions provided by this extension.
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/NV/parameter_buffer_object.txt
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions, wrapper
from OpenGL.GL import glget
import ctypes
from OpenGL.raw.GL.NV.parameter_buffer_object import *
### END AUTOGENERATED SECTION | {
"content_hash": "e4b756f902968dbe71c09fde9bf83731",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 75,
"avg_line_length": 46.513513513513516,
"alnum_prop": 0.7960488088320744,
"repo_name": "frederica07/Dragon_Programming_Process",
"id": "e7ed60bb803260a9ed4d741256f902535c3c0364",
"size": "1721",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "PyOpenGL-3.0.2/OpenGL/GL/NV/parameter_buffer_object.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Makefile",
"bytes": "1548"
},
{
"name": "Python",
"bytes": "2558317"
}
],
"symlink_target": ""
} |
package sqlite
import (
"database/sql"
_ "github.com/mattn/go-sqlite3" // required database driver
)
// schema copied from https://github.com/mfn/osmlib-sqlite
// Connection - Connection
type Connection struct {
db *sql.DB
Stmt *Statements
}
// GetDB - expose the underlying db object
func (c *Connection) GetDB() *sql.DB {
return c.db
}
// Open - open connection and set up
func (c *Connection) Open(path string) {
db, err := sql.Open("sqlite3", path)
if err != nil {
panic(err)
}
c.db = db
c.tables()
c.prepare()
// https://github.com/mattn/go-sqlite3/issues/274
db.SetMaxOpenConns(1)
// start transaction
_, err = c.db.Exec("BEGIN TRANSACTION")
if err != nil {
panic(err)
}
}
// Close - close connection and clean up
func (c *Connection) Close() {
defer c.Stmt.Close()
defer c.db.Close()
// commit transaction
_, err := c.db.Exec("END TRANSACTION")
if err != nil {
panic(err)
}
}
// created tables
func (c *Connection) tables() {
_, err := c.db.Exec(`
PRAGMA main.foreign_keys=OFF;
PRAGMA main.page_size=4096;
PRAGMA main.cache_size=-2000;
PRAGMA main.synchronous=OFF;
PRAGMA main.journal_mode=OFF;
PRAGMA main.temp_store=MEMORY;
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS nodes (
id INTEGER NOT NULL PRIMARY KEY,
lon REAL NOT NULL,
lat REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS node_tags (
ref INTEGER NOT NULL,
key TEXT,
value TEXT,
UNIQUE( ref, key ) ON CONFLICT REPLACE
);
CREATE TABLE IF NOT EXISTS ways (
id INTEGER NOT NULL PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS way_tags (
ref INTEGER NOT NULL,
key TEXT,
value TEXT,
UNIQUE( ref, key ) ON CONFLICT REPLACE
);
CREATE TABLE IF NOT EXISTS way_nodes (
way INTEGER NOT NULL,
num INTEGER NOT NULL,
node INTEGER NOT NULL,
UNIQUE( way, num ) ON CONFLICT REPLACE
);
CREATE TABLE IF NOT EXISTS relations (
id INTEGER NOT NULL PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS relation_tags (
ref INTEGER NOT NULL,
key TEXT,
value TEXT,
UNIQUE( ref, key ) ON CONFLICT REPLACE
);
CREATE TABLE IF NOT EXISTS members (
relation INTEGER NOT NULL,
type TEXT,
ref INTEGER NOT NULL,
role TEXT
);
COMMIT TRANSACTION;`)
if err != nil {
panic(err)
}
}
// created prepared statement
func (c *Connection) prepare() {
node, err := c.db.Prepare("INSERT OR REPLACE INTO nodes (id, lon, lat) VALUES (:id, :lon, :lat)")
if err != nil {
panic(err)
}
nodeTags, err := c.db.Prepare("INSERT OR REPLACE INTO node_tags (ref, key, value) VALUES (:ref, :key, :value)")
if err != nil {
panic(err)
}
way, err := c.db.Prepare("INSERT OR REPLACE INTO ways (id) VALUES (:id)")
if err != nil {
panic(err)
}
wayTags, err := c.db.Prepare("INSERT OR REPLACE INTO way_tags (ref, key, value) VALUES (:ref, :key, :value)")
if err != nil {
panic(err)
}
wayNodes, err := c.db.Prepare("INSERT OR REPLACE INTO way_nodes (way, num, node) VALUES (:way, :num, :node)")
if err != nil {
panic(err)
}
relation, err := c.db.Prepare("INSERT OR REPLACE INTO relations (id) VALUES (:id)")
if err != nil {
panic(err)
}
relationTags, err := c.db.Prepare("INSERT OR REPLACE INTO relation_tags (ref, key, value) VALUES (:ref, :key, :value)")
if err != nil {
panic(err)
}
member, err := c.db.Prepare("INSERT OR REPLACE INTO members (relation, type, ref, role) VALUES (:relation, :type, :ref, :role)")
if err != nil {
panic(err)
}
c.Stmt = &Statements{
Node: node,
NodeTags: nodeTags,
Way: way,
WayTags: wayTags,
WayNodes: wayNodes,
Relation: relation,
RelationTags: relationTags,
Member: member,
}
}
| {
"content_hash": "18f95d4984518da93ba1b647e5e35088",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 129,
"avg_line_length": 22.339285714285715,
"alnum_prop": 0.6333599786837197,
"repo_name": "missinglink/pbf",
"id": "cc30e6c1a341896878fc0984fb6f912c61c2a0e8",
"size": "3753",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sqlite/connection.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "320"
},
{
"name": "Go",
"bytes": "134898"
},
{
"name": "Shell",
"bytes": "4140"
}
],
"symlink_target": ""
} |
package akka.libprocess.serde
import java.io.{ ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream }
import scala.util.Try
class RawMessageSerDe extends MessageSerDe {
override def deserialize(message: TransportMessage): Try[AnyRef] = Try {
val bs = new ByteArrayInputStream(message.data)
val is = new ObjectInputStream(bs)
is.readObject()
}
override def serialize(obj: AnyRef): Try[TransportMessage] = Try {
val bs = new ByteArrayOutputStream()
val os = new ObjectOutputStream(bs)
os.writeObject(obj)
val res = bs.toByteArray
os.close()
TransportMessage(obj.getClass.getCanonicalName, res)
}
}
| {
"content_hash": "4a1581caf33ec5dbf4981a35900f605f",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 101,
"avg_line_length": 29.347826086956523,
"alnum_prop": 0.7437037037037038,
"repo_name": "drexin/akka-libprocess",
"id": "ca1f8f1aa0479ec236883e495312345457e89935",
"size": "675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/scala/akka/libprocess/serde/RawMessageSerDe.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<!-- I used Google's Material Design Lite here (getmdl.io)-->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.blue-orange.min.css" />
<script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<style>
.demo-card-square.mdl-card {
width: 320px;
height: 320px;
}
.demo-card-square > .mdl-card__title {
color: #fff;
background:
bottom right 15% no-repeat #46B6AC;
}
</style>
<div class="demo-card-square mdl-card mdl-shadow--2dp">
<div class="mdl-card__title mdl-card--expand">
<h2 class="mdl-card__title-text">Work In Progress</h2>
</div>
<div class="mdl-card__supporting-text">
This website is a work in progress!
</div>
<div class="mdl-card__actions mdl-card--border">
<a data-g-event="section:cta:badge" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--white" href="https://github.com/Racer500/Hub/">Check it out in GitHub!</a>
</a>
</div>
</div>
</body>
</html>
| {
"content_hash": "b0a4c05dd96d1ee80ddb1505f464791b",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 197,
"avg_line_length": 34.35294117647059,
"alnum_prop": 0.6789383561643836,
"repo_name": "Racer500/Hub",
"id": "bae7c3350f4457ae99f26cc97b5a41d0cf1d8693",
"size": "1168",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1168"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_77) on Mon May 23 19:36:19 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Class org.tartarus.snowball.ext.ItalianStemmer (Lucene 6.0.1 API)</title>
<meta name="date" content="2016-05-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.tartarus.snowball.ext.ItalianStemmer (Lucene 6.0.1 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/tartarus/snowball/ext/ItalianStemmer.html" title="class in org.tartarus.snowball.ext">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/tartarus/snowball/ext/class-use/ItalianStemmer.html" target="_top">Frames</a></li>
<li><a href="ItalianStemmer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.tartarus.snowball.ext.ItalianStemmer" class="title">Uses of Class<br>org.tartarus.snowball.ext.ItalianStemmer</h2>
</div>
<div class="classUseContainer">No usage of org.tartarus.snowball.ext.ItalianStemmer</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/tartarus/snowball/ext/ItalianStemmer.html" title="class in org.tartarus.snowball.ext">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/tartarus/snowball/ext/class-use/ItalianStemmer.html" target="_top">Frames</a></li>
<li><a href="ItalianStemmer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2016 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| {
"content_hash": "0d02d88cdb7884754300ace1bdb61b45",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 143,
"avg_line_length": 35.92142857142857,
"alnum_prop": 0.5971366076754822,
"repo_name": "YorkUIRLab/irlab",
"id": "e45e86987494091bc5cd486963f0c66ae9aa29e8",
"size": "5029",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/lucene-6.0.1/docs/analyzers-common/org/tartarus/snowball/ext/class-use/ItalianStemmer.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "433499"
},
{
"name": "Gnuplot",
"bytes": "2444"
},
{
"name": "HTML",
"bytes": "95820812"
},
{
"name": "Java",
"bytes": "303195"
},
{
"name": "JavaScript",
"bytes": "33538"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_31) on Wed Dec 17 20:48:22 PST 2014 -->
<title>compact2 - java.nio.file.attribute (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="java.nio.file.attribute package">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../compact2-summary.html" target="classFrame">compact2</a> - <a href="../../../../java/nio/file/attribute/compact2-package-summary.html" target="classFrame">java.nio.file.attribute</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="AclFileAttributeView.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">AclFileAttributeView</span></a></li>
<li><a href="AttributeView.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">AttributeView</span></a></li>
<li><a href="BasicFileAttributes.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">BasicFileAttributes</span></a></li>
<li><a href="BasicFileAttributeView.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">BasicFileAttributeView</span></a></li>
<li><a href="DosFileAttributes.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">DosFileAttributes</span></a></li>
<li><a href="DosFileAttributeView.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">DosFileAttributeView</span></a></li>
<li><a href="FileAttribute.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">FileAttribute</span></a></li>
<li><a href="FileAttributeView.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">FileAttributeView</span></a></li>
<li><a href="FileOwnerAttributeView.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">FileOwnerAttributeView</span></a></li>
<li><a href="FileStoreAttributeView.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">FileStoreAttributeView</span></a></li>
<li><a href="GroupPrincipal.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">GroupPrincipal</span></a></li>
<li><a href="PosixFileAttributes.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">PosixFileAttributes</span></a></li>
<li><a href="PosixFileAttributeView.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">PosixFileAttributeView</span></a></li>
<li><a href="UserDefinedFileAttributeView.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">UserDefinedFileAttributeView</span></a></li>
<li><a href="UserPrincipal.html" title="interface in java.nio.file.attribute" target="classFrame"><span class="interfaceName">UserPrincipal</span></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="AclEntry.html" title="class in java.nio.file.attribute" target="classFrame">AclEntry</a></li>
<li><a href="AclEntry.Builder.html" title="class in java.nio.file.attribute" target="classFrame">AclEntry.Builder</a></li>
<li><a href="FileTime.html" title="class in java.nio.file.attribute" target="classFrame">FileTime</a></li>
<li><a href="PosixFilePermissions.html" title="class in java.nio.file.attribute" target="classFrame">PosixFilePermissions</a></li>
<li><a href="UserPrincipalLookupService.html" title="class in java.nio.file.attribute" target="classFrame">UserPrincipalLookupService</a></li>
</ul>
<h2 title="Enums">Enums</h2>
<ul title="Enums">
<li><a href="AclEntryFlag.html" title="enum in java.nio.file.attribute" target="classFrame">AclEntryFlag</a></li>
<li><a href="AclEntryPermission.html" title="enum in java.nio.file.attribute" target="classFrame">AclEntryPermission</a></li>
<li><a href="AclEntryType.html" title="enum in java.nio.file.attribute" target="classFrame">AclEntryType</a></li>
<li><a href="PosixFilePermission.html" title="enum in java.nio.file.attribute" target="classFrame">PosixFilePermission</a></li>
</ul>
<h2 title="Exceptions">Exceptions</h2>
<ul title="Exceptions">
<li><a href="UserPrincipalNotFoundException.html" title="class in java.nio.file.attribute" target="classFrame">UserPrincipalNotFoundException</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "a591c87e98cabd4a6992e9db1e2c3e29",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 223,
"avg_line_length": 89.81481481481481,
"alnum_prop": 0.7455670103092783,
"repo_name": "fbiville/annotation-processing-ftw",
"id": "a2c4d57d9b4bac2ea294283533e01d73e7582c74",
"size": "4850",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/java/jdk8/java/nio/file/attribute/compact2-package-frame.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "191178"
},
{
"name": "HTML",
"bytes": "63904"
},
{
"name": "Java",
"bytes": "107042"
},
{
"name": "JavaScript",
"bytes": "246677"
}
],
"symlink_target": ""
} |
//
// Copyright 2018 SenX S.A.S.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package io.warp10.continuum.gts;
import io.warp10.continuum.gts.GeoTimeSerie.TYPE;
import io.warp10.continuum.store.Constants;
import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptStackFunction;
import io.warp10.script.WarpScriptException;
import io.warp10.script.WarpScriptStack;
import java.util.ArrayList;
import java.util.List;
import edu.emory.mathcs.jtransforms.fft.DoubleFFT_1D;
/**
* Computes a FFT of a numeric GTS
*
* Code implements Cooley-Tuckey radix-2, inspired by the following:
* @see http://introcs.cs.princeton.edu/java/97data/FFT.java.html
*/
public class FFT {
public static class Builder extends NamedWarpScriptFunction implements WarpScriptStackFunction {
private final boolean complex;
public Builder(String name, boolean complex) {
super(name);
this.complex = complex;
}
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
Object top = stack.pop();
if (top instanceof GeoTimeSerie) {
stack.push(fft((GeoTimeSerie) top, this.complex));
} else if (top instanceof List) {
List<List<Object>> series = new ArrayList<List<Object>>();
for (Object o: (List<Object>) top) {
if (! (o instanceof GeoTimeSerie)) {
stack.push(top);
throw new WarpScriptException("FFT can only operate on Geo Time Series instances.");
}
series.add(fft((GeoTimeSerie) o, this.complex));
}
stack.push(series);
} else {
stack.push(top);
throw new WarpScriptException("FFT can only operate on Geo Time Series instances.");
}
return stack;
}
}
public static List<Object> fft(GeoTimeSerie gts, boolean complex) throws WarpScriptException {
List<Object> fft = new ArrayList<Object>();
//
// FFT can only be applied to numeric and bucketized GTS instances
//
if (TYPE.LONG != gts.type && TYPE.DOUBLE != gts.type) {
throw new WarpScriptException("FFT can only be applied to numeric Geo Time Series.");
}
if (!GTSHelper.isBucketized(gts)) {
throw new WarpScriptException("FFT can only be applied to bucketized Geo Time Series.");
}
//
// It is still possible to create a GTS with values at ticks not at bucket boundaries or with duplicate ticks.
// This will be checked inline
//
//
// Sort the GTS
//
GTSHelper.sort(gts);
//
// Allocate two arrays for the real and imaginary parts of the FFT coefficients
// and one for the initial values
//
double[] x = new double[gts.values * 2];
long bucketboundary = gts.lastbucket % gts.bucketspan;
long lasttick = Long.MAX_VALUE;
for (int i = 0; i < gts.values; i++) {
// Check that the tick is a bucket boundary
if (gts.ticks[i] % gts.bucketspan != bucketboundary) {
throw new WarpScriptException("Found a tick not on a bucket boundary.");
}
// Check for duplicate ticks
if (lasttick == gts.ticks[i]) {
throw new WarpScriptException("Found duplicate tick.");
}
if (Long.MAX_VALUE != lasttick && gts.ticks[i] - lasttick != gts.bucketspan) {
throw new WarpScriptException("Found a displaced tick, should have been 'bucketspan' away from previous.");
}
lasttick = gts.ticks[i];
x[i*2] = ((Number) GTSHelper.valueAtIndex(gts, i)).doubleValue();
}
DoubleFFT_1D dfft = new DoubleFFT_1D(x.length / 2);
dfft.complexForward(x);
GeoTimeSerie amplitudeGTS = null;
GeoTimeSerie phaseGTS = null;
GeoTimeSerie reGTS = null;
GeoTimeSerie imGTS = null;
if (complex) {
reGTS = new GeoTimeSerie(gts.values);
reGTS.setName(gts.getName());
reGTS.setLabels(gts.getLabels());
imGTS = new GeoTimeSerie(gts.values);
imGTS.setName(gts.getName());
imGTS.setLabels(gts.getLabels());
fft.add(reGTS);
fft.add(imGTS);
} else {
amplitudeGTS = new GeoTimeSerie(gts.values);
amplitudeGTS.setName(gts.getName());
amplitudeGTS.setLabels(gts.getLabels());
phaseGTS = new GeoTimeSerie(gts.values);
phaseGTS.setName(gts.getName());
phaseGTS.setLabels(gts.getLabels());
fft.add(amplitudeGTS);
fft.add(phaseGTS);
}
int n = gts.values;
for (int k = 0; k < gts.values; k++) {
if (complex) {
GTSHelper.setValue(reGTS, k, x[2*k]);
GTSHelper.setValue(imGTS, k, x[2*k+1]);
} else {
double amp = Math.sqrt(x[2*k] * x[2*k] + x[2*k+1] * x[2*k+1]);
double phase = Math.atan2(x[2*k+1], x[2*k]);
// Pseudo timestamp is the period associated with coefficient k,
// i.e. Tk = n/k * bucketspan
// 0 == k ? gts.bucketspan : (n * gts.bucketspan / k)
GTSHelper.setValue(amplitudeGTS, k, amp);
GTSHelper.setValue(phaseGTS, k, phase);
}
}
fft.add(((double) Constants.TIME_UNITS_PER_S) / (n * gts.bucketspan));
return fft;
}
}
| {
"content_hash": "384c1b7c34f2dd7853247c5a8df781b4",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 115,
"avg_line_length": 32.52247191011236,
"alnum_prop": 0.6291242010709968,
"repo_name": "hbs/warp10-platform",
"id": "bfd7722cf11069408d50f0439ad1cb955cef14ea",
"size": "5789",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "warp10/src/main/java/io/warp10/continuum/gts/FFT.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5465364"
},
{
"name": "JavaScript",
"bytes": "959"
},
{
"name": "Python",
"bytes": "22264"
},
{
"name": "Shell",
"bytes": "30391"
},
{
"name": "Thrift",
"bytes": "19972"
}
],
"symlink_target": ""
} |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Errors | </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
<script src="../assets/js/modernizr.js"></script>
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title"></a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-private" checked />
<label class="tsd-widget" for="tsd-filter-private">Private</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="../modules/edge.html">Edge</a>
</li>
<li>
<a href="../modules/edge.fileuploader.html">FileUploader</a>
</li>
<li>
<a href="edge.fileuploader.errors.html">Errors</a>
</li>
</ul>
<h1>Class Errors</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-not-exported">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported"><a href="edge.fileuploader.errors.html#static-directory_upload" class="tsd-kind-icon">DIRECTORY_<wbr>UPLOAD</a></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported"><a href="edge.fileuploader.errors.html#static-server_invalid_response" class="tsd-kind-icon">SERVER_<wbr>INVALID_<wbr>RESPONSE</a></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported"><a href="edge.fileuploader.errors.html#static-user_error" class="tsd-kind-icon">USER_<wbr>ERROR</a></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported"><a href="edge.fileuploader.errors.html#static-wrong_file_type" class="tsd-kind-icon">WRONG_<wbr>FILE_<wbr>TYPE</a></li>
</ul>
</section>
</div>
</section>
</section> <section class="tsd-panel-group tsd-member-group tsd-is-not-exported">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported">
<a name="static-directory_upload" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagstatic">static</span> DIRECTORY_<wbr>UPLOAD</h3>
<div class="tsd-signature tsd-kind-icon">DIRECTORY_<wbr>UPLOAD<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">Object</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:91</li>
</ul>
</aside>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-property tsd-is-not-exported">
<a name="directory_upload.directory_upload_errorcode" class="tsd-anchor"></a>
<h3>DIRECTORY_<wbr>UPLOAD.error<wbr>Code</h3>
<div class="tsd-signature tsd-kind-icon">DIRECTORY_<wbr>UPLOAD.error<wbr>Code<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">number</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:91</li>
</ul>
</aside>
</section> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-property tsd-is-not-exported">
<a name="directory_upload.directory_upload_localkey" class="tsd-anchor"></a>
<h3>DIRECTORY_<wbr>UPLOAD.local<wbr>Key</h3>
<div class="tsd-signature tsd-kind-icon">DIRECTORY_<wbr>UPLOAD.local<wbr>Key<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:91</li>
</ul>
</aside>
</section></section> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported">
<a name="static-server_invalid_response" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagstatic">static</span> SERVER_<wbr>INVALID_<wbr>RESPONSE</h3>
<div class="tsd-signature tsd-kind-icon">SERVER_<wbr>INVALID_<wbr>RESPONSE<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">Object</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:93</li>
</ul>
</aside>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-property tsd-is-not-exported">
<a name="server_invalid_response.server_invalid_response_errorcode" class="tsd-anchor"></a>
<h3>SERVER_<wbr>INVALID_<wbr>RESPONSE.error<wbr>Code</h3>
<div class="tsd-signature tsd-kind-icon">SERVER_<wbr>INVALID_<wbr>RESPONSE.error<wbr>Code<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">number</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:93</li>
</ul>
</aside>
</section> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-property tsd-is-not-exported">
<a name="server_invalid_response.server_invalid_response_localkey" class="tsd-anchor"></a>
<h3>SERVER_<wbr>INVALID_<wbr>RESPONSE.local<wbr>Key</h3>
<div class="tsd-signature tsd-kind-icon">SERVER_<wbr>INVALID_<wbr>RESPONSE.local<wbr>Key<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:93</li>
</ul>
</aside>
</section></section> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported">
<a name="static-user_error" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagstatic">static</span> USER_<wbr>ERROR</h3>
<div class="tsd-signature tsd-kind-icon">USER_<wbr>ERROR<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">Object</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:92</li>
</ul>
</aside>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-property tsd-is-not-exported">
<a name="user_error.user_error_errorcode" class="tsd-anchor"></a>
<h3>USER_<wbr>ERROR.error<wbr>Code</h3>
<div class="tsd-signature tsd-kind-icon">USER_<wbr>ERROR.error<wbr>Code<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">number</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:92</li>
</ul>
</aside>
</section> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-property tsd-is-not-exported">
<a name="user_error.user_error_localkey" class="tsd-anchor"></a>
<h3>USER_<wbr>ERROR.local<wbr>Key</h3>
<div class="tsd-signature tsd-kind-icon">USER_<wbr>ERROR.local<wbr>Key<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:92</li>
</ul>
</aside>
</section></section> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported">
<a name="static-wrong_file_type" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagstatic">static</span> WRONG_<wbr>FILE_<wbr>TYPE</h3>
<div class="tsd-signature tsd-kind-icon">WRONG_<wbr>FILE_<wbr>TYPE<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">Object</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:90</li>
</ul>
</aside>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-property tsd-is-not-exported">
<a name="wrong_file_type.wrong_file_type_errorcode" class="tsd-anchor"></a>
<h3>WRONG_<wbr>FILE_<wbr>TYPE.error<wbr>Code</h3>
<div class="tsd-signature tsd-kind-icon">WRONG_<wbr>FILE_<wbr>TYPE.error<wbr>Code<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">number</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:90</li>
</ul>
</aside>
</section> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-property tsd-is-not-exported">
<a name="wrong_file_type.wrong_file_type_localkey" class="tsd-anchor"></a>
<h3>WRONG_<wbr>FILE_<wbr>TYPE.local<wbr>Key</h3>
<div class="tsd-signature tsd-kind-icon">WRONG_<wbr>FILE_<wbr>TYPE.local<wbr>Key<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in ts/EdgeFileUploader.ts:90</li>
</ul>
</aside>
</section></section></section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
<li class=" tsd-kind-container">
<a href="../modules/edge.html">Edge</a>
</li>
<li class="current tsd-kind-container tsd-parent-kind-container">
<a href="../modules/edge.fileuploader.html">Edge.<wbr>File<wbr>Uploader</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
<li class=" tsd-kind-interface tsd-parent-kind-container">
<a href="../interfaces/edge.fileuploader.ifileautouploadconfig.html" class="tsd-kind-icon">IFile<wbr>Auto<wbr>Upload<wbr>Config</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-container">
<a href="../interfaces/edge.fileuploader.ifileuploaderconfig.html" class="tsd-kind-icon">IFile<wbr>Uploader<wbr>Config</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-container">
<a href="../interfaces/edge.fileuploader.ifileuploaderprocessors.html" class="tsd-kind-icon">IFile<wbr>Uploader<wbr>Processors</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-container">
<a href="../interfaces/edge.fileuploader.iparcelinputcontainer.html" class="tsd-kind-icon">IParcel<wbr>Input<wbr>Container</a>
</li>
</ul>
<ul class="current">
<li class="current tsd-kind-class tsd-parent-kind-container tsd-is-not-exported">
<a href="edge.fileuploader.errors.html" class="tsd-kind-icon">Errors</a>
<ul>
<li class=" tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported">
<a href="edge.fileuploader.errors.html#static-directory_upload" class="tsd-kind-icon">DIRECTORY_<wbr>UPLOAD</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported">
<a href="edge.fileuploader.errors.html#static-server_invalid_response" class="tsd-kind-icon">SERVER_<wbr>INVALID_<wbr>RESPONSE</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported">
<a href="edge.fileuploader.errors.html#static-user_error" class="tsd-kind-icon">USER_<wbr>ERROR</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-class tsd-is-static tsd-is-not-exported">
<a href="edge.fileuploader.errors.html#static-wrong_file_type" class="tsd-kind-icon">WRONG_<wbr>FILE_<wbr>TYPE</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
<li class=" tsd-kind-class tsd-parent-kind-container tsd-is-not-exported">
<a href="edge.fileuploader.fileaction.html" class="tsd-kind-icon">File<wbr>Action</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-container">
<a href="edge.fileuploader.fileparcel.html" class="tsd-kind-icon">File<wbr>Parcel</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-container tsd-is-not-exported">
<a href="edge.fileuploader.helper.html" class="tsd-kind-icon">Helper</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-container">
<a href="edge.fileuploader.localization.html" class="tsd-kind-icon">Localization</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-container">
<a href="edge.fileuploader.uploadmanager.html" class="tsd-kind-icon">Upload<wbr>Manager</a>
</li>
<li class=" tsd-kind-variable tsd-parent-kind-container">
<a href="../modules/edge.fileuploader.html#create" class="tsd-kind-icon">create</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-container"><span class="tsd-kind-icon">Container, dynamic module</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-construct-signature"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-call-signature"><span class="tsd-kind-icon">Function, call signature, accessor</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-construct-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Member, accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-construct-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Member, accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li> </li>
<li class="tsd-kind-construct-signature tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited member</span></li>
</ul>
<ul class="tsd-legend">
<li> </li>
<li class="tsd-kind-construct-signature tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private member</span></li>
</ul>
<ul class="tsd-legend">
<li> </li>
<li> </li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static member</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.io" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html> | {
"content_hash": "9d8566398f3a4e847c3aeb3183c9b9fd",
"timestamp": "",
"source": "github",
"line_count": 329,
"max_line_length": 229,
"avg_line_length": 55.32522796352583,
"alnum_prop": 0.6556971761344907,
"repo_name": "activenode/EdgeJS",
"id": "645fb9f807ca64b4b34d02ce5d470dcc6d23ffd5",
"size": "18204",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/doc/classes/edge.fileuploader.errors.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "55882"
},
{
"name": "HTML",
"bytes": "504229"
},
{
"name": "JavaScript",
"bytes": "54663"
},
{
"name": "TypeScript",
"bytes": "58244"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<link rel="stylesheet" href="../resources/default.css"></style>
<body style="height:2000px">
<div style="top: 700px; left: 100px" class="absolute green"></div>
</body>
<script>
window.scrollTo(100, 500);
</script>
| {
"content_hash": "d48096649b579b4b551bcb370b6d4c1f",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 68,
"avg_line_length": 29,
"alnum_prop": 0.6853448275862069,
"repo_name": "ric2b/Vivaldi-browser",
"id": "ee0721bad5a278e3b55db7505b1e98df5fb0bb05",
"size": "232",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "chromium/third_party/blink/web_tests/paint/invalidation/scroll/fixed-and-absolute-position-scrolled-expected.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php namespace Arcanesoft\Backups\Providers;
use Arcanedev\Support\Providers\CommandServiceProvider as ServiceProvider;
use Arcanesoft\Backups\Console\InstallCommand;
use Arcanesoft\Backups\Console\PublishCommand;
/**
* Class CommandServiceProvider
*
* @package Arcanesoft\Backups\Providers
* @author ARCANEDEV <arcanedev.maroc@gmail.com>
*/
class CommandServiceProvider extends ServiceProvider
{
/* -----------------------------------------------------------------
| Properties
| -----------------------------------------------------------------
*/
/**
* The commands to be registered.
*
* @var array
*/
protected $commands = [
InstallCommand::class,
PublishCommand::class,
];
}
| {
"content_hash": "95d15c9bbb7d659e2eb4b12482b70306",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 74,
"avg_line_length": 26.344827586206897,
"alnum_prop": 0.5641361256544503,
"repo_name": "ARCANESOFT/Backups",
"id": "4e8e73c055e360e260f76b623925f743e57ec406",
"size": "764",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Providers/CommandServiceProvider.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "17910"
},
{
"name": "PHP",
"bytes": "29792"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `PF_ATMPVC` constant in crate `libc`.">
<meta name="keywords" content="rust, rustlang, rust-lang, PF_ATMPVC">
<title>libc::PF_ATMPVC - Rust</title>
<link rel="stylesheet" type="text/css" href="../normalize.css">
<link rel="stylesheet" type="text/css" href="../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../main.css">
<link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc constant">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a>
<p class='location'><a href='index.html'>libc</a></p><script>window.sidebarCurrent = {name: 'PF_ATMPVC', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content">
<h1 class='fqn'><span class='in-band'>Constant <a href='index.html'>libc</a>::<wbr><a class="constant" href=''>PF_ATMPVC</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a class='srclink' href='../src/libc/unix/notbsd/mod.rs.html#504' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const PF_ATMPVC: <a class="type" href="../libc/type.c_int.html" title="type libc::c_int">c_int</a><code> = </code><code>AF_ATMPVC</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../";
window.currentCrate = "libc";
</script>
<script src="../jquery.js"></script>
<script src="../main.js"></script>
<script defer src="../search-index.js"></script>
</body>
</html> | {
"content_hash": "51c1fc084618862ea0da34e87cc667e1",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 197,
"avg_line_length": 38.04424778761062,
"alnum_prop": 0.5096534077692486,
"repo_name": "nitro-devs/nitro-game-engine",
"id": "e8f0fc28123efa366593d6ca05a17ff5a9292e6f",
"size": "4309",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/libc/constant.PF_ATMPVC.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CMake",
"bytes": "1032"
},
{
"name": "Rust",
"bytes": "59380"
}
],
"symlink_target": ""
} |
package br.org.am.biblioteca.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.org.am.biblioteca.dao.GrupoDAO;
import br.org.am.biblioteca.model.Grupo;
@Service
@Transactional
class GrupoServiceImpl implements GrupoService {
private GrupoDAO grupoDAO;
@Autowired
public void setGrupoDAO(GrupoDAO grupoDAO) {
this.grupoDAO = grupoDAO;
}
public Grupo findByNome(String nome) {
return grupoDAO.findByNome(nome);
}
}
| {
"content_hash": "f1b782c19ad687fc74ac9cb667778259",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 64,
"avg_line_length": 26.17391304347826,
"alnum_prop": 0.7691029900332226,
"repo_name": "eltonsrc/biblioteca",
"id": "e36e5e06ae11dd1792d243cff0d72fa7d2958026",
"size": "602",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "biblioteca-webservice/src/main/java/br/org/am/biblioteca/service/GrupoServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "140"
},
{
"name": "HTML",
"bytes": "13640"
},
{
"name": "Java",
"bytes": "53449"
},
{
"name": "JavaScript",
"bytes": "483967"
}
],
"symlink_target": ""
} |
class coDCEL;
/// Returns an arbitrary half edge of the resulting face or coUint32(-1) if no joining took place
coUint32 coAbsorbNextRadialFace(coDCEL& dcel, coUint32 edgeIdx);
| {
"content_hash": "d179982d8be00fa969db7f2c70b25740",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 97,
"avg_line_length": 44.5,
"alnum_prop": 0.7921348314606742,
"repo_name": "smogpill/core",
"id": "174f71ea00c1b8f0cbdfea8cf14ebddb293d7ef9",
"size": "353",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/math/topology/dcel/dissolve/coAbsorbFace_f.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1950195"
},
{
"name": "C++",
"bytes": "3500164"
},
{
"name": "GLSL",
"bytes": "1451"
},
{
"name": "Lua",
"bytes": "9569"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "d696bb645185a77ad8f06a58f6035e9d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "401e91a8b7b0c8b4a6f5419caf60e5e73a8a51a3",
"size": "185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Elaphandra macrolepis/ Syn. Aspilia macrolepis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace App\Http\Controllers;
use Auth;
use App\Repositories\GameRepository;
use App\Criteria\VisibleGameCriterion;
use App\Criteria\GameHasTagRequestCriterion;
use App\Http\Requests\StoreGameRequest;
use App\Http\Requests\UpdateGameRequest;
use App\Entities\Game;
class GameController extends Controller
{
/**
* The Game Repository.
*
* @var GameRepository
*/
protected $games;
/**
* The name of the presenter to use for summary representation.
*
* @var string
*/
protected $summaryPresenter = 'App\Presenters\GameSummaryPresenter';
/**
* Instantiate a new GameController.
*
* @param GameRepository $gameRepo
*
* @return void
*/
public function __construct(GameRepository $gameRepo)
{
$this->games = $gameRepo;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(VisibleGameCriterion $visibleCriterion, GameHasTagRequestCriterion $hasTagCriterion)
{
$this->games->setPresenter($this->summaryPresenter);
$this->games->pushCriteria($visibleCriterion);
$this->games->pushCriteria($hasTagCriterion);
return $this->games->paginate();
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response
*/
public function store(StoreGameRequest $request)
{
$this->authorize('store', Game::class);
return $this->games->create(array_merge($request->json('data'), ['owner_id' => Auth::user()->id]));
}
/**
* Display the specified resource.
*
* @param int $id
*
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$game = $this->games->skipPresenter()->find($id);
if ($game->public < 1) {
$this->authorize($game);
}
return $game->presenter();
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
*
* @return \Illuminate\Http\Response
*/
public function update(UpdateGameRequest $request, $id)
{
$game = $this->games->skipPresenter()->find($id);
if ($game->public < 3) {
$this->authorize($game);
}
$data = $request->json('data');
unset($data['owner_id']);
return $this->games->skipPresenter(false)->update($data, $id);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
*
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$game = $this->games->skipPresenter()->find($id);
if ($game->public < 3) {
$this->authorize($game);
}
if ($this->games->delete($id)) {
return response('', 204);
}
return response('', 500);
}
}
| {
"content_hash": "cda36b9d3c5ce4b854000ec13ed4c2e6",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 110,
"avg_line_length": 24.150793650793652,
"alnum_prop": 0.5747617482747289,
"repo_name": "jupiter24/web-chess",
"id": "894df216edfe19eda9df6b38d1a459dba351a7a7",
"size": "3043",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/Http/Controllers/GameController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "356"
},
{
"name": "CSS",
"bytes": "2036"
},
{
"name": "HTML",
"bytes": "2362"
},
{
"name": "JavaScript",
"bytes": "2568"
},
{
"name": "PHP",
"bytes": "334615"
},
{
"name": "TypeScript",
"bytes": "15029"
}
],
"symlink_target": ""
} |
=head1 NAME
ProteinTreeAdaptor - DESCRIPTION of Object
=head1 SYNOPSIS
=head1 DESCRIPTION
=head1 CONTACT
Contact Jessica Severin on implemetation/design detail: jessica@ebi.ac.uk
Contact Ewan Birney on EnsEMBL in general: birney@sanger.ac.uk
=head1 APPENDIX
The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _
=cut
package Bio::EnsEMBL::Compara::DBSQL::ProteinTreeAdaptor;
use strict;
use Bio::EnsEMBL::Compara::ProteinTree;
use Bio::EnsEMBL::Compara::AlignedMember;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Compara::DBSQL::NestedSetAdaptor;
use Bio::EnsEMBL::Compara::DBSQL::MemberAdaptor;
our @ISA = qw(Bio::EnsEMBL::Compara::DBSQL::NestedSetAdaptor);
###########################
# FETCH methods
###########################
=head2 fetch_all
Arg[1] : [optional] int clusterset_id (def. 1)
Example : $all_trees = $proteintree_adaptor->fetch_all(1);
Description: Fetches from the database all the protein trees
Returntype : arrayref of Bio::EnsEMBL::Compara::NestedSet
Exceptions :
Caller :
=cut
sub fetch_all {
my ($self, $clusterset_id) = @_;
$clusterset_id = 1 if ! defined $clusterset_id;
my $table = $self->tables->[0]->[1];
my $constraint = "WHERE ${table}.node_id = ${table}.root_id and ${table}.clusterset_id = ${clusterset_id}";
my $nodes = $self->_generic_fetch($constraint);
return $nodes;
}
=head2 fetch_by_Member_root_id
Arg[1] : Bio::EnsEMBL::Compara::Member
Arg[2] : [optional] int clusterset_id (def. 1)
Example : $protein_tree = $proteintree_adaptor->fetch_by_Member_root_id($member);
Description: Fetches from the database the protein_tree that contains the
member. If you give it a clusterset id of 0 this will cause
the search span across all known clustersets.
Returntype : Bio::EnsEMBL::Compara::ProteinTree
Exceptions :
Caller :
=cut
sub fetch_by_Member_root_id {
my ($self, $member, $clusterset_id) = @_;
$clusterset_id = 1 if ! defined $clusterset_id;
my $root_id = $self->gene_member_id_is_in_tree($member->gene_member_id || $member->member_id);
return undef unless (defined $root_id);
my $aligned_member = $self->fetch_AlignedMember_by_member_id_root_id
(
$member->get_canonical_peptide_Member->member_id,
$clusterset_id);
return undef unless (defined $aligned_member);
my $node = $aligned_member->subroot;
return undef unless (defined $node);
my $protein_tree = $self->fetch_node_by_node_id($node->node_id);
return $protein_tree;
}
=head2 fetch_by_stable_id
Arg[1] : string $protein_tree_stable_id
Example : $protein_tree = $proteintree_adaptor->fetch_by_stable_id("ENSGT00590000083078");
Description: Fetches from the database the protein_tree for that stable ID
Returntype : Bio::EnsEMBL::Compara::ProteinTree
Exceptions : returns undef if $stable_id is not found.
Caller :
=cut
sub fetch_by_stable_id {
my ($self, $stable_id) = @_;
my $root_id = $self->db->get_ProteinTreeStableIdAdaptor->fetch_node_id_by_stable_id($stable_id);
return undef unless (defined $root_id);
my $protein_tree = $self->fetch_node_by_node_id($root_id);
return $protein_tree;
}
=head2 fetch_by_gene_Member_root_id
=cut
sub fetch_by_gene_Member_root_id {
my ($self, $member, $clusterset_id) = @_;
$clusterset_id = 1 if ! defined $clusterset_id;
my $root_id = $self->gene_member_id_is_in_tree($member->member_id);
return undef unless (defined $root_id);
my $protein_tree = $self->fetch_node_by_node_id($root_id);
return $protein_tree;
}
=head2 fetch_AlignedMember_by_member_id_root_id
Arg[1] : int member_id of a peptide member (longest translation)
Arg[2] : [optional] int clusterset_id (def. 0)
Example :
my $aligned_member = $proteintree_adaptor->
fetch_AlignedMember_by_member_id_root_id
(
$member->get_canonical_peptide_Member->member_id
);
Description: Fetches from the database the protein_tree that contains the member_id
Returntype : Bio::EnsEMBL::Compara::AlignedMember
Exceptions :
Caller :
=cut
sub fetch_AlignedMember_by_member_id_root_id {
my ($self, $member_id, $clusterset_id) = @_;
my $constraint = "WHERE tm.member_id = $member_id and m.member_id = $member_id";
$constraint .= " AND t.clusterset_id = $clusterset_id" if($clusterset_id and $clusterset_id>0);
my $final_clause = "order by tm.node_id desc";
$self->final_clause($final_clause);
my ($node) = @{$self->_generic_fetch($constraint)};
return $node;
}
# This is experimental -- use at your own risk
sub fetch_first_shared_ancestor_indexed {
my $self = shift;
my $node1 = shift;
my $node2 = shift;
my $root_id1 = $node1->_root_id; # This depends on the new root_id field in the schema
my $root_id2 = $node2->_root_id;
return undef unless ($root_id1 eq $root_id2);
my $left_node_id1 = $node1->left_index;
my $left_node_id2 = $node2->left_index;
my $right_node_id1 = $node1->right_index;
my $right_node_id2 = $node2->right_index;
my $min_left;
$min_left = $left_node_id1 if ($left_node_id1 < $left_node_id2);
$min_left = $left_node_id2 if ($left_node_id2 < $left_node_id1);
my $max_right;
$max_right = $right_node_id1 if ($right_node_id1 > $right_node_id2);
$max_right = $right_node_id2 if ($right_node_id2 > $right_node_id1);
my $constraint = "WHERE t.root_id=$root_id1 AND left_index < $min_left";
$constraint .= " AND right_index > $max_right";
$constraint .= " ORDER BY (right_index-left_index) LIMIT 1";
my $ancestor = $self->_generic_fetch($constraint)->[0];
return $ancestor;
}
=head2 fetch_AlignedMember_by_member_id_mlssID
Arg[1] : int member_id of a peptide member (longest translation)
Arg[2] : [optional] int clusterset_id (def. 0)
Example :
my $aligned_member = $proteintree_adaptor->
fetch_AlignedMember_by_member_id_mlssID
(
$member->get_canonical_peptide_Member->member_id, $mlssID
);
Description: Fetches from the database the protein_tree that contains the member_id
Returntype : Bio::EnsEMBL::Compara::AlignedMember
Exceptions :
Caller :
=cut
sub fetch_AlignedMember_by_member_id_mlssID {
my ($self, $member_id, $mlss_id) = @_;
my $constraint = "WHERE tm.member_id = $member_id and m.member_id = $member_id";
$constraint .= " AND tm.method_link_species_set_id = $mlss_id" if($mlss_id and $mlss_id>0);
my ($node) = @{$self->_generic_fetch($constraint)};
return $node;
}
sub gene_member_id_is_in_tree {
my ($self, $member_id) = @_;
my $sth = $self->prepare("SELECT ptm1.root_id FROM member m1, protein_tree_member ptm1 WHERE ptm1.member_id=m1.member_id AND m1.gene_member_id=? LIMIT 1");
$sth->execute($member_id);
my($root_id) = $sth->fetchrow_array;
if (defined($root_id)) {
return $root_id;
} else {
return undef;
}
}
sub fetch_all_AlignedMembers_by_root_id {
my ($self, $root_id) = @_;
my $constraint = "WHERE tm.root_id = $root_id";
my $nodes = $self->_generic_fetch($constraint);
return $nodes;
}
###########################
# STORE methods
###########################
sub store {
my ($self, $node) = @_;
unless($node->isa('Bio::EnsEMBL::Compara::NestedSet')) {
throw("set arg must be a [Bio::EnsEMBL::Compara::NestedSet] not a $node");
}
$self->store_node($node);
# recursively do all the children
my $children = $node->children;
foreach my $child_node (@$children) {
$child_node->clusterset_id($node->clusterset_id) unless (defined($child_node->clusterset_id));
$self->store($child_node);
}
return $node->node_id;
}
sub delete_tag {
my $self = shift;
my $node_id = shift;
my $tag = shift;
my $sql = "DELETE from protein_tree_tag where node_id=$node_id and tag=\"$tag\"";
#print("$sql\n");
$self->dbc->do($sql);
}
sub store_node {
my ($self, $node) = @_;
unless($node->isa('Bio::EnsEMBL::Compara::NestedSet')) {
throw("set arg must be a [Bio::EnsEMBL::Compara::NestedSet] not a $node");
}
if($node->adaptor and
$node->adaptor->isa('Bio::EnsEMBL::Compara::DBSQL::NestedSetAdaptor') and
$node->adaptor eq $self)
{
#already stored so just update
return $self->update_node($node);
}
my $parent_id = 0; my $root_id = 0; my $clusterset_id = undef;
if($node->parent) {
$parent_id = $node->parent->node_id;
if (ref($node->node_id)) {
# We got here because we haven't stored this node and so it
# doesn't have a node_id, returning a hashref (node object) for node_id
# instead of an integer
$root_id = $node->root->node_id;
} else {
$root_id = $node->subroot->node_id;
}
}
$clusterset_id = $node->clusterset_id || 1;
#printf("inserting parent_id = %d, root_id = %d\n", $parent_id, $root_id);
my $sth = $self->prepare("INSERT INTO protein_tree_node
(parent_id,
root_id,
clusterset_id,
left_index,
right_index,
distance_to_parent) VALUES (?,?,?,?,?,?)");
$sth->execute($parent_id, $root_id, $clusterset_id, $node->left_index, $node->right_index, $node->distance_to_parent);
$node->node_id( $sth->{'mysql_insertid'} );
#printf(" new node_id %d\n", $node->node_id);
$node->adaptor($self);
$sth->finish;
if($node->isa('Bio::EnsEMBL::Compara::AlignedMember')) {
$sth = $self->prepare("INSERT ignore INTO protein_tree_member
(node_id,
root_id,
member_id,
method_link_species_set_id,
cigar_line) VALUES (?,?,?,?,?)");
$sth->execute($node->node_id, $root_id, $node->member_id, $node->method_link_species_set_id, $node->cigar_line);
$sth->finish;
}
return $node->node_id;
}
sub update_node {
my ($self, $node) = @_;
unless($node->isa('Bio::EnsEMBL::Compara::NestedSet')) {
throw("set arg must be a [Bio::EnsEMBL::Compara::NestedSet] not a $node");
}
my $parent_id = 0; my $root_id = 0; my $clusterset_id = undef;
if($node->parent) {
$parent_id = $node->parent->node_id;
if (ref($node->node_id)) {
# We got here because we haven't stored this node and so it
# doesn't have a node_id, returning a hashref (node object) for node_id
# instead of an integer
$root_id = $node->root->node_id;
} else {
$root_id = $node->subroot->node_id;
}
$clusterset_id = $node->clusterset_id || 1;
}
my $sth = $self->prepare("UPDATE protein_tree_node SET
parent_id=?,
root_id=?,
left_index=?,
right_index=?,
distance_to_parent=?
WHERE node_id=?");
$sth->execute($parent_id, $root_id, $node->left_index, $node->right_index,
$node->distance_to_parent, $node->node_id);
$node->adaptor($self);
$sth->finish;
if($node->isa('Bio::EnsEMBL::Compara::AlignedMember')) {
my $sql = "UPDATE protein_tree_member SET ".
"cigar_line='". $node->cigar_line . "'";
$sql .= ", cigar_start=" . $node->cigar_start if($node->cigar_start);
$sql .= ", cigar_end=" . $node->cigar_end if($node->cigar_end);
$sql .= ", root_id=" . $root_id;
$sql .= ", method_link_species_set_id=" . $node->method_link_species_set_id if($node->method_link_species_set_id);
$sql .= " WHERE node_id=". $node->node_id;
$self->dbc->do($sql);
}
}
sub merge_nodes {
my ($self, $node1, $node2) = @_;
unless($node1->isa('Bio::EnsEMBL::Compara::NestedSet')) {
throw("set arg must be a [Bio::EnsEMBL::Compara::NestedSet] not a $node1");
}
# printf("MERGE children from parent %d => %d\n", $node2->node_id, $node1->node_id);
my $sth = $self->prepare("UPDATE protein_tree_node SET
parent_id=?
WHERE parent_id=?");
$sth->execute($node1->node_id, $node2->node_id);
$sth->finish;
$sth = $self->prepare("DELETE from protein_tree_node WHERE node_id=?");
$sth->execute($node2->node_id);
$sth->finish;
}
sub delete_flattened_leaf {
my $self = shift;
my $node = shift;
my $node_id = $node->node_id;
#print("delete node $node_id\n");
# $self->dbc->do("UPDATE protein_tree_node dn, protein_tree_node n SET ".
# "n.parent_id = dn.parent_id WHERE n.parent_id=dn.node_id AND dn.node_id=$node_id");
$self->dbc->do("DELETE from protein_tree_node WHERE node_id = $node_id");
$self->dbc->do("DELETE from protein_tree_tag WHERE node_id = $node_id");
$self->dbc->do("DELETE from protein_tree_member WHERE node_id = $node_id");
}
sub delete_node {
my $self = shift;
my $node = shift;
my $node_id = $node->node_id;
#print("delete node $node_id\n");
$self->dbc->do("UPDATE protein_tree_node dn, protein_tree_node n SET ".
"n.parent_id = dn.parent_id WHERE n.parent_id=dn.node_id AND dn.node_id=$node_id");
$self->dbc->do("DELETE from protein_tree_node WHERE node_id = $node_id");
$self->dbc->do("DELETE from protein_tree_tag WHERE node_id = $node_id");
$self->dbc->do("DELETE from protein_tree_member WHERE node_id = $node_id");
}
sub delete_nodes_not_in_tree
{
my $self = shift;
my $tree = shift;
unless($tree->isa('Bio::EnsEMBL::Compara::NestedSet')) {
throw("set arg must be a [Bio::EnsEMBL::Compara::NestedSet] not a $tree");
}
#print("delete_nodes_not_present under ", $tree->node_id, "\n");
my $dbtree = $self->fetch_node_by_node_id($tree->node_id);
my @all_db_nodes = $dbtree->get_all_subnodes;
foreach my $dbnode (@all_db_nodes) {
next if($tree->find_node_by_node_id($dbnode->node_id));
$self->delete_node($dbnode);
}
$dbtree->release_tree;
}
sub delete_node_and_under {
my $self = shift;
my $node = shift;
my @all_subnodes = $node->get_all_subnodes;
foreach my $subnode (@all_subnodes) {
my $subnode_id = $subnode->node_id;
$self->dbc->do("DELETE from protein_tree_node WHERE node_id = $subnode_id");
$self->dbc->do("DELETE from protein_tree_tag WHERE node_id = $subnode_id");
$self->dbc->do("DELETE from protein_tree_member WHERE node_id = $subnode_id");
}
my $node_id = $node->node_id;
$self->dbc->do("DELETE from protein_tree_node WHERE node_id = $node_id");
$self->dbc->do("DELETE from protein_tree_tag WHERE node_id = $node_id");
$self->dbc->do("DELETE from protein_tree_member WHERE node_id = $node_id");
}
sub store_supertree_node_and_under {
my $self = shift;
my $node = shift;
$self->dbc->do("CREATE TABLE IF NOT EXISTS super_protein_tree_node like protein_tree_node");
$self->dbc->do("CREATE TABLE IF NOT EXISTS super_protein_tree_member like protein_tree_member");
$self->dbc->do("CREATE TABLE IF NOT EXISTS super_protein_tree_tag like protein_tree_tag");
my @all_subnodes = $node->get_all_subnodes;
foreach my $subnode (@all_subnodes) {
my $subnode_id = $subnode->node_id;
$self->dbc->do("INSERT IGNORE into super_protein_tree_node SELECT * from protein_tree_node WHERE node_id = $subnode_id");
$self->dbc->do("INSERT IGNORE into super_protein_tree_member SELECT * from protein_tree_member WHERE node_id = $subnode_id");
$self->dbc->do("INSERT IGNORE into super_protein_tree_tag SELECT * from protein_tree_tag WHERE node_id = $subnode_id");
}
my $node_id = $node->node_id;
$self->dbc->do("INSERT IGNORE into super_protein_tree_node SELECT * from protein_tree_node WHERE node_id = $node_id");
$self->dbc->do("INSERT IGNORE into super_protein_tree_member SELECT * from protein_tree_member WHERE node_id = $node_id");
$self->dbc->do("INSERT IGNORE into super_protein_tree_tag SELECT * from protein_tree_tag WHERE node_id = $node_id");
}
# Fetch data from stable_id table -- similar in concept to fetching sequence from member
sub _fetch_stable_id_by_node_id {
my ($self, $node_id) = @_;
return $self->db->get_ProteinTreeStableIdAdaptor->fetch_by_node_id($node_id);
}
###################################
#
# tagging
#
###################################
sub _load_tagvalues {
my $self = shift;
my $node = shift;
unless($node->isa('Bio::EnsEMBL::Compara::NestedSet')) {
throw("set arg must be a [Bio::EnsEMBL::Compara::NestedSet] not a $node");
}
my $sth = $self->prepare("SELECT tag,value from protein_tree_tag where node_id=?");
$sth->execute($node->node_id);
while (my ($tag, $value) = $sth->fetchrow_array()) {
$node->add_tag($tag,$value);
}
$sth->finish;
}
sub _store_tagvalue {
my $self = shift;
my $node_id = shift;
my $tag = shift;
my $value = shift;
$value="" unless(defined($value));
my $sth = $self->prepare("INSERT ignore into protein_tree_tag (node_id,tag) values (?, ?)");
$sth->execute($node_id, $tag);
#my $sql = "INSERT ignore into protein_tree_tag (node_id,tag) values ($node_id,\"$tag\")";
#print("$sql\n");
#$self->dbc->do($sql);
$sth = $self->prepare("UPDATE protein_tree_tag set value=? where node_id=? and tag=?");
$sth->execute($value, $node_id, $tag);
#$sql = "UPDATE protein_tree_tag set value=\"$value\" where node_id=$node_id and tag=\"$tag\"";
#print("$sql\n");
#$self->dbc->do($sql);
}
##################################
#
# subclass override methods
#
##################################
sub columns {
my $self = shift;
return ['t.node_id',
't.parent_id',
't.root_id',
't.clusterset_id',
't.left_index',
't.right_index',
't.distance_to_parent',
'tm.cigar_line',
'tm.cigar_start',
'tm.cigar_end',
'tm.method_link_species_set_id',
@{Bio::EnsEMBL::Compara::DBSQL::MemberAdaptor->columns()}
];
}
sub tables {
my $self = shift;
return [['protein_tree_node', 't']];
}
sub left_join_clause {
return "left join protein_tree_member tm on t.node_id = tm.node_id left join member m on tm.member_id = m.member_id";
}
sub default_where_clause {
return "";
}
sub create_instance_from_rowhash {
my $self = shift;
my $rowhash = shift;
my $node;
if($rowhash->{'member_id'}) {
$node = new Bio::EnsEMBL::Compara::AlignedMember;
} else {
$node = new Bio::EnsEMBL::Compara::ProteinTree;
}
$self->init_instance_from_rowhash($node, $rowhash);
return $node;
}
sub _objs_from_sth {
my ($self, $sth) = @_;
my $node_list = [];
while(my $rowhash = $sth->fetchrow_hashref) {
my $node = $self->create_instance_from_rowhash($rowhash);
push @$node_list, $node;
}
return $node_list;
}
sub init_instance_from_rowhash {
my $self = shift;
my $node = shift;
my $rowhash = shift;
#SUPER is NestedSetAdaptor
$self->SUPER::init_instance_from_rowhash($node, $rowhash);
if($rowhash->{'member_id'}) {
Bio::EnsEMBL::Compara::DBSQL::MemberAdaptor->init_instance_from_rowhash($node, $rowhash);
$node->cigar_line($rowhash->{'cigar_line'});
$node->method_link_species_set_id($rowhash->{method_link_species_set_id});
# cigar_start and cigar_end does not need to be set.
# $node->cigar_start($rowhash->{'cigar_start'});
# $node->cigar_end($rowhash->{'cigar_end'});
}
# print(" create node : ", $node, " : "); $node->print_node;
$node->adaptor($self);
return $node;
}
##########################################################
#
# explicit method forwarding to MemberAdaptor
#
##########################################################
sub _fetch_sequence_by_id {
my $self = shift;
return $self->db->get_MemberAdaptor->_fetch_sequence_by_id(@_);
}
sub fetch_gene_for_peptide_member_id {
my $self = shift;
return $self->db->get_MemberAdaptor->fetch_gene_for_peptide_member_id(@_);
}
sub fetch_peptides_for_gene_member_id {
my $self = shift;
return $self->db->get_MemberAdaptor->fetch_peptides_for_gene_member_id(@_);
}
sub fetch_longest_peptide_member_for_gene_member_id {
my $self = shift;
return $self->db->get_MemberAdaptor->fetch_longest_peptide_member_for_gene_member_id(@_);
}
1;
| {
"content_hash": "91e06c406e085872f0a491f5bb93162c",
"timestamp": "",
"source": "github",
"line_count": 664,
"max_line_length": 157,
"avg_line_length": 30.724397590361445,
"alnum_prop": 0.6089407381991079,
"repo_name": "adamsardar/perl-libs-custom",
"id": "efd98eb5f1f2474071acd1d22e095e9a28e21e01",
"size": "20401",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EnsemblAPI/ensembl-compara/modules/Bio/EnsEMBL/Compara/DBSQL/ProteinTreeAdaptor.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "23699"
},
{
"name": "C++",
"bytes": "262813"
},
{
"name": "Java",
"bytes": "11912"
},
{
"name": "Perl",
"bytes": "16848036"
},
{
"name": "Prolog",
"bytes": "31116"
},
{
"name": "Shell",
"bytes": "111607"
},
{
"name": "Tcl",
"bytes": "2051"
},
{
"name": "XSLT",
"bytes": "84130"
}
],
"symlink_target": ""
} |
"use strict";
const ROUND_DURATION = 10000;
const WAIT_DURATION = 2000;
const TRIVIA_FILE = "data/trivia.json";
const TriviaManager = require("../trivia-manager");
exports.game = "trivia";
exports.aliases = ["triv"];
const Trivia = new TriviaManager(TRIVIA_FILE);
class TriviaGame extends Rooms.botGame {
constructor(room, scorecap) {
super(room);
this.scorecap = Math.abs(parseInt(scorecap) || 5);
this.gameId = "trivia";
this.gameName = "Trivia";
this.answers = [];
this.question = null;
this.answered = false;
this.round = 0;
this.onInit();
}
onInit() {
if (Trivia.isEmpty()) {
this.sendRoom("There are no trivia questions loaded. Game automatically ended.");
return this.onEnd();
}
this.sendRoom(`A new game of Trivia is starting! Use \`\`${this.room.commandCharacter[0]}join\`\` to join the game. First to ${this.scorecap} points win!`);
this.onInitRound();
}
onInitRound() {
let entry = Trivia.getQuestion();
this.question = entry.question;
this.answers = entry.answers;
this.round++;
this.answered = false;
clearTimeout(this.timer);
this.sendRoom(`Round ${this.round} | ${this.question}`);
this.timer = setTimeout(() => {
this.sendRoom(`Time's up! The correct answer${(this.answers.length > 1 ? "s are" : " is")}: ${this.answers.join(", ")}`);
this.timer = setTimeout(() => this.onInitRound(), WAIT_DURATION);
}, ROUND_DURATION);
}
onGuess(user, target) {
target = toId(target);
if (!this.answers.map(p => toId(p)).includes(target) || this.answered) return;
clearTimeout(this.timer);
this.answered = true;
if (!(user.userid in this.users)) {
this.users[user.userid] = new Rooms.botGamePlayer(user);
this.users[user.userid].points = 0;
this.userList.push(user.userid);
}
let player = this.users[user.userid];
player.points++;
this.sendRoom(`${user.name} got the right answer and has ${player.points} points!${this.answers.length > 1 ? ` Possible Answers: ${this.answers.join(", ")}` : ""}`);
if (this.scorecap <= player.points) {
this.onEnd(player);
} else {
this.timer = setTimeout(() => this.onInitRound(), WAIT_DURATION);
}
}
onEnd(winner) {
if (winner) {
this.sendRoom(`Congratulations to ${winner.name} for winning the game of Trivia!`);
Leaderboard.onWin("trivia", this.room, winner.userid, this.scorecap);
}
this.destroy();
}
getScoreBoard() {
return "Points: " + Object.keys(this.users).sort().map((u) => {
return this.users[u].name + " (" + this.users[u].points + ")";
}).join(", ");
}
}
exports.commands = {
trivia: function (target, room, user) {
if (!room || !this.can("games")) return false;
if (room.game) return this.send("There is already a game going on in this room! (" + room.game.gameName + ")");
room.game = new TriviaGame(room, target);
},
triviarepost: function (target, room, user) {
if (!room || !this.can("games") || !room.game || room.game.gameId !== "statspread") return false;
this.send(`Round ${room.game.round} | ${room.game.question}`);
},
triviaskip: function (target, room, user) {
if (!room || !this.can("games") || !room.game || room.game.gameId !== "trivia") return false;
this.send(`The correct answer${(room.game.answers.length > 1 ? "s are" : " is")}: ${room.game.answers.join(", ")}`);
room.game.onInitRound();
},
addtrivia: function (target, room, user) {
if (!user.hasBotRank("+")) return false;
let [question, answers] = target.split("|").map(p => p.trim());
if (!question || !answers) return this.send("Invalid question/answer pair.");
answers = answers.split(",").map(p => p.trim());
if (answers.some(a => !toId(a))) return this.send("All answers must have alphanumeric characters.");
if (Trivia.findQuestion(question)) return this.send("The question already exists.");
Trivia.addQuestion(question, answers).write();
this.send("Added!");
},
deletetrivia: function (target, room, user) {
if (!user.hasBotRank("%")) return false;
if (!Trivia.findQuestion(target)) return this.send("The question does not exist.");
Trivia.removeQuestion(target).write();
this.send("Deleted.");
},
trivialist: function (target, room, user) {
if (!user.hasBotRank("~")) return false;
let questions = Trivia.allQuestions();
Tools.uploadToHastebin(questions.map(q => `Question: ${q.question}\nAnswer(s): ${q.answers.join(", ")}`).join("\n\n"),
link => user.sendTo(`${questions.length} questions - ${link}`));
},
} | {
"content_hash": "937f80ba5fbdb251423e784080e8d9ea",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 173,
"avg_line_length": 35.53061224489796,
"alnum_prop": 0.556193758376412,
"repo_name": "sparkychildcharlie/Foxiebot-kit",
"id": "fdc068b16437483ca19623dd97c903e423918519",
"size": "5223",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chat-plugins/trivia.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "457594"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class PullRequest
{
public PullRequest() { }
public PullRequest(int number)
{
Number = number;
}
public PullRequest(long id, Uri url, Uri htmlUrl, Uri diffUrl, Uri patchUrl, Uri issueUrl, Uri statusesUrl, int number, ItemState state, string title, string body, DateTimeOffset createdAt, DateTimeOffset updatedAt, DateTimeOffset? closedAt, DateTimeOffset? mergedAt, GitReference head, GitReference @base, User user, User assignee, IReadOnlyList<User> assignees, bool? mergeable, User mergedBy, int comments, int commits, int additions, int deletions, int changedFiles, Milestone milestone, bool locked)
{
Id = id;
Url = url;
HtmlUrl = htmlUrl;
DiffUrl = diffUrl;
PatchUrl = patchUrl;
IssueUrl = issueUrl;
StatusesUrl = statusesUrl;
Number = number;
State = state;
Title = title;
Body = body;
CreatedAt = createdAt;
UpdatedAt = updatedAt;
ClosedAt = closedAt;
MergedAt = mergedAt;
Head = head;
Base = @base;
User = user;
Assignee = assignee;
Assignees = assignees;
Mergeable = mergeable;
MergedBy = mergedBy;
Comments = comments;
Commits = commits;
Additions = additions;
Deletions = deletions;
ChangedFiles = changedFiles;
Milestone = milestone;
Locked = locked;
}
/// <summary>
/// The internal Id for this pull request (not the pull request number)
/// </summary>
public long Id { get; protected set; }
/// <summary>
/// The URL for this pull request.
/// </summary>
public Uri Url { get; protected set; }
/// <summary>
/// The URL for the pull request page.
/// </summary>
public Uri HtmlUrl { get; protected set; }
/// <summary>
/// The URL for the pull request's diff (.diff) file.
/// </summary>
public Uri DiffUrl { get; protected set; }
/// <summary>
/// The URL for the pull request's patch (.patch) file.
/// </summary>
public Uri PatchUrl { get; protected set; }
/// <summary>
/// The URL for the specific pull request issue.
/// </summary>
public Uri IssueUrl { get; protected set; }
/// <summary>
/// The URL for the pull request statuses.
/// </summary>
public Uri StatusesUrl { get; protected set; }
/// <summary>
/// The pull request number.
/// </summary>
public int Number { get; protected set; }
/// <summary>
/// Whether the pull request is open or closed. The default is <see cref="ItemState.Open"/>.
/// </summary>
public ItemState State { get; protected set; }
/// <summary>
/// Title of the pull request.
/// </summary>
public string Title { get; protected set; }
/// <summary>
/// The body (content) contained within the pull request.
/// </summary>
public string Body { get; protected set; }
/// <summary>
/// When the pull request was created.
/// </summary>
public DateTimeOffset CreatedAt { get; protected set; }
/// <summary>
/// When the pull request was last updated.
/// </summary>
public DateTimeOffset UpdatedAt { get; protected set; }
/// <summary>
/// When the pull request was closed.
/// </summary>
public DateTimeOffset? ClosedAt { get; protected set; }
/// <summary>
/// When the pull request was merged.
/// </summary>
public DateTimeOffset? MergedAt { get; protected set; }
/// <summary>
/// The HEAD reference for the pull request.
/// </summary>
public GitReference Head { get; protected set; }
/// <summary>
/// The BASE reference for the pull request.
/// </summary>
public GitReference Base { get; protected set; }
/// <summary>
/// The user who created the pull request.
/// </summary>
public User User { get; protected set; }
/// <summary>
/// The user who is assigned the pull request.
/// </summary>
public User Assignee { get; protected set; }
/// <summary>
///The multiple users this pull request is assigned to.
/// </summary>
public IReadOnlyList<User> Assignees { get; protected set; }
/// <summary>
/// The milestone, if any, that this pull request is assigned to.
/// </summary>
public Milestone Milestone { get; protected set; }
/// <summary>
/// Whether or not the pull request has been merged.
/// </summary>
public bool Merged
{
get { return MergedAt.HasValue; }
}
/// <summary>
/// Whether or not the pull request can be merged.
/// </summary>
public bool? Mergeable { get; protected set; }
/// <summary>
/// The user who merged the pull request.
/// </summary>
public User MergedBy { get; protected set; }
/// <summary>
/// Total number of comments contained in the pull request.
/// </summary>
public int Comments { get; protected set; }
/// <summary>
/// Total number of commits contained in the pull request.
/// </summary>
public int Commits { get; protected set; }
/// <summary>
/// Total number of additions contained in the pull request.
/// </summary>
public int Additions { get; protected set; }
/// <summary>
/// Total number of deletions contained in the pull request.
/// </summary>
public int Deletions { get; protected set; }
/// <summary>
/// Total number of files changed in the pull request.
/// </summary>
public int ChangedFiles { get; protected set; }
/// <summary>
/// If the issue is locked or not
/// </summary>
public bool Locked { get; protected set; }
internal string DebuggerDisplay
{
get { return string.Format(CultureInfo.InvariantCulture, "Number: {0} State: {1}", Number, State); }
}
}
}
| {
"content_hash": "b063e251dd4c5554cfc47a110e4cd4eb",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 512,
"avg_line_length": 32.27272727272727,
"alnum_prop": 0.5463306152705708,
"repo_name": "rlugojr/octokit.net",
"id": "5644a0b3eb14419b6edc6ad5fae32d00c0986cb9",
"size": "6747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Octokit/Models/Response/PullRequest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1562"
},
{
"name": "C#",
"bytes": "6183435"
},
{
"name": "F#",
"bytes": "11906"
},
{
"name": "PowerShell",
"bytes": "6444"
},
{
"name": "Shell",
"bytes": "1831"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
#include("/common/header.html")
${css}
</head>
${body}
<script src="${url('/resources/js/jquery-2.1.1.js')}"></script>
<script src="${url('/resources/js/bootstrap.min.js')}"></script>
${js}
</html>
| {
"content_hash": "82915d84e997041405818afc6dc7de93",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 64,
"avg_line_length": 20.90909090909091,
"alnum_prop": 0.6173913043478261,
"repo_name": "uchoice/uchoice-ucenter",
"id": "61bd4fe554ea71deaa371681c0f8e12f3d9e5101",
"size": "230",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "uchoice-ucenter-ui/src/main/resources/templates/common/base.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "495141"
},
{
"name": "HTML",
"bytes": "31772"
},
{
"name": "Java",
"bytes": "58638"
},
{
"name": "JavaScript",
"bytes": "2415030"
}
],
"symlink_target": ""
} |
We study how to use own user management in activiti for a while. So let me start to introduce how we implement it.
We take an example for the 'Openstack Keystone User Management', and of course, we can use any user management modules of third party to instead the 'Keystone'
According to the Big Man --- Nadav Azaria --- whose article is [《Activiti Authentication And Identity Management Tutorial》](http://developer4life.blogspot.com/2012/02/activiti-authentication-and-identity.html) in 2012, We start to newest customization.
This article is built on the shoulder of 'activiti-webapp-rest2' module in activiti source code.
Because Activiti has provided for us such entrance which has been used by the 'activiti ldap' module.
But one question is how the customized classed can be identified by the activiti engine, and how to register them.
Obviously, **'SessionFactory'** has provided us such interface.
>First of all, we must build the class **OwnUserManagerFactory & OwnGroupManagerFactory** which must be implemented the **SessionFactory**. The class mentioned in them will be displayed later.
```java
public class OwnUserManagerFactory implements SessionFactory {
private KeystoneConnection keystoneConnection;
public OwnUserManagerFactory (KeystoneConnection keystoneConnection) {
this.keystoneConnection = keystoneConnection;
}
public Class<?> getSessionType() {
return UserIdentityManager.class;
}
public Session openSession() {
return new OwnUserManager(this.getKeystoneConnection());
}
public KeystoneConnection getKeystoneConnection() {
return keystoneConnection;
}
public void setKeystoneConnection(KeystoneConnection keystoneConnection) {
this.keystoneConnection = keystoneConnection;
}
}
```
```java
public class OwnGroupMagagerFactory implements SessionFactory {
private KeystoneConnection keystoneConnection;
public OwnGroupMagagerFactory(KeystoneConnection keystoneConnection) {
this.keystoneConnection = keystoneConnection;
}
@Override
public Class<?> getSessionType() {
return GroupIdentityManager.class;
}
@Override
public Session openSession() {
return new OwnGroupManager(this.getKeystoneConnection());
}
public KeystoneConnection getKeystoneConnection() {
return keystoneConnection;
}
public void setKeystoneConnection(KeystoneConnection keystoneConnection) {
this.keystoneConnection = keystoneConnection;
}
}
```
>Then, We must define the class **OwnUserManager & OwnGroupManager** which extend the class --- **UserEntityManager**. And we have to implement our own query logic in **在findUserByQueryCriteria中**. Any communication with other user management of third party can be used.
```java
import org.activiti.engine.ActivitiException;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.Page;
import org.activiti.engine.impl.UserQueryImpl;
import org.activiti.engine.impl.persistence.entity.UserEntityManager;
public class OwnUserManager extends UserEntityManager {
private KeystoneConnection keystoneConnection;
public OwnUserManager(KeystoneConnection keystoneConnection) {
this.keystoneConnection = keystoneConnection;
}
@Override
public User createNewUser(String userId) {
return super.createNewUser(userId);
// throw new ActivitiException("User manager doesn't support creating a newe user");
}
@Override
public void insertUser(User user) {
super.insertUser(user);
// throw new ActivitiException("User manager doesn't support inserting a newe user");
}
@Override
public void updateUser(User updatedUser) {
super.updateUser(updatedUser);
// throw new ActivitiException("User manager doesn't support updating a newe user");
}
@Override
public User findUserById(String userId) {
return super.findUserById(userId);
// throw new ActivitiException("User manager doesn't support finding an user by id");
}
@Override
public void deleteUser(String userId) {
throw new ActivitiException("User manager doesn't support deleting a newe user");
}
@Override
public List<User> findUserByQueryCriteria(UserQueryImpl query, Page page) {
System.out.println(
"start to findUserByQueryCriteria.....................!!!!!!_----------------------------------------------------");
// use your own method or third party method...
return super.findUserByQueryCriteria(query, page);
}
@Override
public List<User> findUsersByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
System.out.println(
"start to findUsersByNativeQuery.....................!!!!!!_----------------------------------------------------");
// use your own method or third party method...
return super.findUsersByNativeQuery(parameterMap, firstResult, maxResults);
}
@Override
public long findUserCountByQueryCriteria(UserQueryImpl query) {
return super.findUserCountByQueryCriteria(query);
// return findUserByQueryCriteria(query, null).size();
}
@Override
public Boolean checkPassword(String userId, String password) {
// now return true, means that ignoring the password verification
return true;
}
}
```
>>The method --- checkPassword --- returns true, means to skip the user verification
```java
public class OwnGroupManager extends GroupEntityManager {
private KeystoneConnection keystoneConnection;
public OwnGroupManager(KeystoneConnection keystoneConnection) {
this.keystoneConnection = keystoneConnection;
}
@Override
public void insertGroup(Group group) {
throw new ActivitiException("My group manager doesn't support inserting a new group");
}
@Override
public void updateGroup(Group updatedGroup) {
throw new ActivitiException("My group manager doesn't support updating a new group");
}
@Override
public void deleteGroup(String groupId) {
throw new ActivitiException("My group manager doesn't support deleting a new group");
}
@Override
public List<Group> findGroupByQueryCriteria(GroupQueryImpl query, Page page) {
// sometimes to implement how to query the Group
// return super.findGroupByQueryCriteria(query, page);
List<Group> groups = new ArrayList<Group>();
GroupEntity ge = new GroupEntity();
ge.setId("admin");
ge.setRevision(1);
ge.setName("Administrators");
ge.setType("security-role");
groups.add(ge);
return groups;
}
@Override
public long findGroupCountByQueryCriteria(GroupQueryImpl query) {
// TODO Auto-generated method stub
return super.findGroupCountByQueryCriteria(query);
}
@Override
public List<Group> findGroupsByUser(String userId) {
throw new ActivitiException("My group manager doesn't support finding a group");
}
}
```
>In the **findGroupByQueryCriteria || findUserByQueryCriteria** function, we can implement our real logic.
>Furthermore, build the 'KeystoneConnection', of course, it can be any other user configuration POJO.
```java
public class KeystoneConnection {
private String protocal;
private String address;
private String port;
public KeystoneConnection() {
}
public KeystoneConnection(String protocal, String address, String port) {
this.protocal = protocal;
this.address = address;
this.port = port;
}
public String getKeystoneUrl(String url) {
return this.protocal + "://" + this.address + ":" + this.port + url;
}
// getter and setter
}
```
>At last, we must tell the activiti engine, how to identify the two Factory class we have defined in the first step. Of course, it is the process of registration. So we extend the class **ActivitiEngineConfiguration** in the 'activiti-webapp-rest2' module.
Or it will also nicely configure them in spring configuration xml.
```java
@Configuration
public class ActivitiEngineConfiguration
```
```java
@Bean(name = "processEngineConfiguration")
public ProcessEngineConfigurationImpl processEngineConfiguration() {
SpringProcessEngineConfiguration processEngineConfiguration = new SpringProcessEngineConfiguration();
// add following configuration
// load the custom manager session factory
List<SessionFactory> customSessionFactories = new ArrayList<SessionFactory>();
customSessionFactories.add(new OwnUserManagerFactory(keystoneConnection()));
customSessionFactories.add(new OwnGroupMagagerFactory(keystoneConnection()));
processEngineConfiguration.setCustomSessionFactories(customSessionFactories);
return processEngineConfiguration;
}
```
**Conclusion:**
**The reason is very simple, the 'SessionFactory' in the Activiti Engine maintains a specific data structure below**
```java
HashMap<SessionType, Session>
```
**So the two sub-SessionFactory classes we registered will cover the old ones which are loaded when the activiti engine started**
**And then, it is definitely that the engine will read our own management Factory every time.**
| {
"content_hash": "b1a5abdfa236d02116b1aa0bd69acc3f",
"timestamp": "",
"source": "github",
"line_count": 269,
"max_line_length": 270,
"avg_line_length": 32.57992565055762,
"alnum_prop": 0.7635782747603834,
"repo_name": "xiabin1235910/Activiti-Article",
"id": "42220b9251a2857bc27151fcfadb94acc1499306",
"size": "8835",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "use-customized-usermangement-in-activiti.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
* @test SpreadNullArg
* @bug 7141637
* @summary verifies that the MethodHandle spread adapter can gracefully handle null arguments.
* @run main SpreadNullArg
* @author volker.simonis@gmail.com
*/
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class SpreadNullArg {
public static void main(String args[]) {
MethodType mt_ref_arg = MethodType.methodType(int.class, Integer.class);
MethodHandle mh_spreadInvoker = MethodHandles.spreadInvoker(mt_ref_arg, 0);
MethodHandle mh_spread_target;
int result = 42;
try {
mh_spread_target =
MethodHandles.lookup().findStatic(SpreadNullArg.class, "target_spread_arg", mt_ref_arg);
result = (int) mh_spreadInvoker.invokeExact(mh_spread_target, (Object[]) null);
throw new Error("Expected IllegalArgumentException was not thrown");
} catch (IllegalArgumentException e) {
System.out.println("Expected exception : " + e);
} catch (Throwable e) {
throw new Error(e);
}
if (result != 42) {
throw new Error("result [" + result
+ "] != 42 : Expected IllegalArgumentException was not thrown?");
}
}
public static int target_spread_arg(Integer i1) {
return i1.intValue();
}
}
| {
"content_hash": "41f72af30ae30446022ae97c467ad69b",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 96,
"avg_line_length": 28.866666666666667,
"alnum_prop": 0.6859122401847575,
"repo_name": "rokn/Count_Words_2015",
"id": "195e106d542f61f92fb0ced08306dfefa8a5275b",
"size": "2323",
"binary": false,
"copies": "56",
"ref": "refs/heads/master",
"path": "testing/openjdk2/hotspot/test/compiler/7141637/SpreadNullArg.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "61802"
},
{
"name": "Ruby",
"bytes": "18888605"
}
],
"symlink_target": ""
} |
""" Distribution setup for ‘python-daemon’ library. """
from __future__ import (absolute_import, unicode_literals)
import sys
import os
import os.path
import pydoc
import distutils.util
from setuptools import (setup, find_packages)
import version
fromlist_expects_type = str
if sys.version_info < (3, 0):
fromlist_expects_type = bytes
main_module_name = 'daemon'
main_module_fromlist = list(map(fromlist_expects_type, [
'_metadata']))
main_module = __import__(
main_module_name,
level=0, fromlist=main_module_fromlist)
metadata = main_module._metadata
(synopsis, long_description) = pydoc.splitdoc(pydoc.getdoc(main_module))
version_info = metadata.get_distribution_version_info()
version_string = version_info['version']
(maintainer_name, maintainer_email) = metadata.parse_person_field(
version_info['maintainer'])
setup(
name=metadata.distribution_name,
version=version_string,
packages=find_packages(exclude=["test"]),
cmdclass={
"write_version_info": version.WriteVersionInfoCommand,
"egg_info": version.EggInfoCommand,
},
# Setuptools metadata.
maintainer=maintainer_name,
maintainer_email=maintainer_email,
zip_safe=False,
setup_requires=[
"docutils",
],
test_suite="unittest2.collector",
tests_require=[
"unittest2 >=0.5.1",
"testtools",
"testscenarios >=0.4",
"mock >=1.3",
"docutils",
],
install_requires=[
"setuptools",
"docutils",
"lockfile >=0.10",
],
# PyPI metadata.
author=metadata.author_name,
author_email=metadata.author_email,
description=synopsis,
license=metadata.license,
keywords="daemon fork unix".split(),
url=metadata.url,
long_description=long_description,
classifiers=[
# Reference: http://pypi.python.org/pypi?%3Aaction=list_classifiers
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: Apache Software License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
# Local variables:
# coding: utf-8
# mode: python
# End:
# vim: fileencoding=utf-8 filetype=python :
| {
"content_hash": "201fc7f4a414ceecf6ef6ab07ea7e828",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 79,
"avg_line_length": 26.835051546391753,
"alnum_prop": 0.5985401459854015,
"repo_name": "eaufavor/python-daemon",
"id": "6edb8abe9b6af4bfa298fc0e43802d300e939391",
"size": "3134",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "260659"
}
],
"symlink_target": ""
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/test_util.h>
#include <google/protobuf/test_util2.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_mset.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
#include <google/protobuf/stubs/stl_util.h>
// Must be included last.
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
namespace internal {
namespace {
using TestUtil::EqualsToSerialized;
// This test closely mirrors net/proto2/compiler/cpp/internal/unittest.cc
// except that it uses extensions rather than regular fields.
TEST(ExtensionSetTest, Defaults) {
// Check that all default values are set correctly in the initial message.
unittest::TestAllExtensions message;
TestUtil::ExpectExtensionsClear(message);
// Messages should return pointers to default instances until first use.
// (This is not checked by ExpectClear() since it is not actually true after
// the fields have been set and then cleared.)
EXPECT_EQ(&unittest::OptionalGroup_extension::default_instance(),
&message.GetExtension(unittest::optionalgroup_extension));
EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(),
&message.GetExtension(unittest::optional_nested_message_extension));
EXPECT_EQ(
&unittest::ForeignMessage::default_instance(),
&message.GetExtension(unittest::optional_foreign_message_extension));
EXPECT_EQ(&unittest_import::ImportMessage::default_instance(),
&message.GetExtension(unittest::optional_import_message_extension));
}
TEST(ExtensionSetTest, Accessors) {
// Set every field to a unique value then go back and check all those
// values.
unittest::TestAllExtensions message;
TestUtil::SetAllExtensions(&message);
TestUtil::ExpectAllExtensionsSet(message);
TestUtil::ModifyRepeatedExtensions(&message);
TestUtil::ExpectRepeatedExtensionsModified(message);
}
TEST(ExtensionSetTest, Clear) {
// Set every field to a unique value, clear the message, then check that
// it is cleared.
unittest::TestAllExtensions message;
TestUtil::SetAllExtensions(&message);
message.Clear();
TestUtil::ExpectExtensionsClear(message);
// Unlike with the defaults test, we do NOT expect that requesting embedded
// messages will return a pointer to the default instance. Instead, they
// should return the objects that were created when mutable_blah() was
// called.
EXPECT_NE(&unittest::OptionalGroup_extension::default_instance(),
&message.GetExtension(unittest::optionalgroup_extension));
EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(),
&message.GetExtension(unittest::optional_nested_message_extension));
EXPECT_NE(
&unittest::ForeignMessage::default_instance(),
&message.GetExtension(unittest::optional_foreign_message_extension));
EXPECT_NE(&unittest_import::ImportMessage::default_instance(),
&message.GetExtension(unittest::optional_import_message_extension));
// Make sure setting stuff again after clearing works. (This takes slightly
// different code paths since the objects are reused.)
TestUtil::SetAllExtensions(&message);
TestUtil::ExpectAllExtensionsSet(message);
}
TEST(ExtensionSetTest, ClearOneField) {
// Set every field to a unique value, then clear one value and insure that
// only that one value is cleared.
unittest::TestAllExtensions message;
TestUtil::SetAllExtensions(&message);
int64 original_value =
message.GetExtension(unittest::optional_int64_extension);
// Clear the field and make sure it shows up as cleared.
message.ClearExtension(unittest::optional_int64_extension);
EXPECT_FALSE(message.HasExtension(unittest::optional_int64_extension));
EXPECT_EQ(0, message.GetExtension(unittest::optional_int64_extension));
// Other adjacent fields should not be cleared.
EXPECT_TRUE(message.HasExtension(unittest::optional_int32_extension));
EXPECT_TRUE(message.HasExtension(unittest::optional_uint32_extension));
// Make sure if we set it again, then all fields are set.
message.SetExtension(unittest::optional_int64_extension, original_value);
TestUtil::ExpectAllExtensionsSet(message);
}
TEST(ExtensionSetTest, SetAllocatedExtension) {
unittest::TestAllExtensions message;
EXPECT_FALSE(
message.HasExtension(unittest::optional_foreign_message_extension));
// Add a extension using SetAllocatedExtension
unittest::ForeignMessage* foreign_message = new unittest::ForeignMessage();
message.SetAllocatedExtension(unittest::optional_foreign_message_extension,
foreign_message);
EXPECT_TRUE(
message.HasExtension(unittest::optional_foreign_message_extension));
EXPECT_EQ(foreign_message, message.MutableExtension(
unittest::optional_foreign_message_extension));
EXPECT_EQ(foreign_message, &message.GetExtension(
unittest::optional_foreign_message_extension));
// SetAllocatedExtension should delete the previously existing extension.
// (We reply on unittest to check memory leaks for this case)
message.SetAllocatedExtension(unittest::optional_foreign_message_extension,
new unittest::ForeignMessage());
// SetAllocatedExtension with nullptr is equivalent to ClearExtenion.
message.SetAllocatedExtension(unittest::optional_foreign_message_extension,
nullptr);
EXPECT_FALSE(
message.HasExtension(unittest::optional_foreign_message_extension));
}
TEST(ExtensionSetTest, ReleaseExtension) {
proto2_wireformat_unittest::TestMessageSet message;
EXPECT_FALSE(message.HasExtension(
unittest::TestMessageSetExtension1::message_set_extension));
// Add a extension using SetAllocatedExtension
unittest::TestMessageSetExtension1* extension =
new unittest::TestMessageSetExtension1();
message.SetAllocatedExtension(
unittest::TestMessageSetExtension1::message_set_extension, extension);
EXPECT_TRUE(message.HasExtension(
unittest::TestMessageSetExtension1::message_set_extension));
// Release the extension using ReleaseExtension
unittest::TestMessageSetExtension1* released_extension =
message.ReleaseExtension(
unittest::TestMessageSetExtension1::message_set_extension);
EXPECT_EQ(extension, released_extension);
EXPECT_FALSE(message.HasExtension(
unittest::TestMessageSetExtension1::message_set_extension));
// ReleaseExtension will return the underlying object even after
// ClearExtension is called.
message.SetAllocatedExtension(
unittest::TestMessageSetExtension1::message_set_extension,
released_extension);
message.ClearExtension(
unittest::TestMessageSetExtension1::message_set_extension);
released_extension = message.ReleaseExtension(
unittest::TestMessageSetExtension1::message_set_extension);
EXPECT_TRUE(released_extension != nullptr);
delete released_extension;
}
TEST(ExtensionSetTest, ArenaUnsafeArenaSetAllocatedAndRelease) {
Arena arena;
unittest::TestAllExtensions* message =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
unittest::ForeignMessage extension;
message->UnsafeArenaSetAllocatedExtension(
unittest::optional_foreign_message_extension, &extension);
// No copy when set.
unittest::ForeignMessage* mutable_extension =
message->MutableExtension(unittest::optional_foreign_message_extension);
EXPECT_EQ(&extension, mutable_extension);
// No copy when unsafe released.
unittest::ForeignMessage* released_extension =
message->UnsafeArenaReleaseExtension(
unittest::optional_foreign_message_extension);
EXPECT_EQ(&extension, released_extension);
EXPECT_FALSE(
message->HasExtension(unittest::optional_foreign_message_extension));
// Set the ownership back and let the destructors run. It should not take
// ownership, so this should not crash.
message->UnsafeArenaSetAllocatedExtension(
unittest::optional_foreign_message_extension, &extension);
}
TEST(ExtensionSetTest, UnsafeArenaSetAllocatedAndRelease) {
unittest::TestAllExtensions message;
unittest::ForeignMessage* extension = new unittest::ForeignMessage();
message.UnsafeArenaSetAllocatedExtension(
unittest::optional_foreign_message_extension, extension);
// No copy when set.
unittest::ForeignMessage* mutable_extension =
message.MutableExtension(unittest::optional_foreign_message_extension);
EXPECT_EQ(extension, mutable_extension);
// No copy when unsafe released.
unittest::ForeignMessage* released_extension =
message.UnsafeArenaReleaseExtension(
unittest::optional_foreign_message_extension);
EXPECT_EQ(extension, released_extension);
EXPECT_FALSE(
message.HasExtension(unittest::optional_foreign_message_extension));
// Set the ownership back and let the destructors run. It should take
// ownership, so this should not leak.
message.UnsafeArenaSetAllocatedExtension(
unittest::optional_foreign_message_extension, extension);
}
TEST(ExtensionSetTest, ArenaUnsafeArenaReleaseOfHeapAlloc) {
Arena arena;
unittest::TestAllExtensions* message =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
unittest::ForeignMessage* extension = new unittest::ForeignMessage;
message->SetAllocatedExtension(unittest::optional_foreign_message_extension,
extension);
// The arena should maintain ownership of the heap allocated proto because we
// used UnsafeArenaReleaseExtension. The leak checker will ensure this.
unittest::ForeignMessage* released_extension =
message->UnsafeArenaReleaseExtension(
unittest::optional_foreign_message_extension);
EXPECT_EQ(extension, released_extension);
EXPECT_FALSE(
message->HasExtension(unittest::optional_foreign_message_extension));
}
TEST(ExtensionSetTest, CopyFrom) {
unittest::TestAllExtensions message1, message2;
TestUtil::SetAllExtensions(&message1);
message2.CopyFrom(message1);
TestUtil::ExpectAllExtensionsSet(message2);
message2.CopyFrom(message1); // exercise copy when fields already exist
TestUtil::ExpectAllExtensionsSet(message2);
}
TEST(ExtensionSetTest, CopyFromPacked) {
unittest::TestPackedExtensions message1, message2;
TestUtil::SetPackedExtensions(&message1);
message2.CopyFrom(message1);
TestUtil::ExpectPackedExtensionsSet(message2);
message2.CopyFrom(message1); // exercise copy when fields already exist
TestUtil::ExpectPackedExtensionsSet(message2);
}
TEST(ExtensionSetTest, CopyFromUpcasted) {
unittest::TestAllExtensions message1, message2;
const Message& upcasted_message = message1;
TestUtil::SetAllExtensions(&message1);
message2.CopyFrom(upcasted_message);
TestUtil::ExpectAllExtensionsSet(message2);
// exercise copy when fields already exist
message2.CopyFrom(upcasted_message);
TestUtil::ExpectAllExtensionsSet(message2);
}
TEST(ExtensionSetTest, SwapWithEmpty) {
unittest::TestAllExtensions message1, message2;
TestUtil::SetAllExtensions(&message1);
TestUtil::ExpectAllExtensionsSet(message1);
TestUtil::ExpectExtensionsClear(message2);
message1.Swap(&message2);
TestUtil::ExpectAllExtensionsSet(message2);
TestUtil::ExpectExtensionsClear(message1);
}
TEST(ExtensionSetTest, SwapWithSelf) {
unittest::TestAllExtensions message;
TestUtil::SetAllExtensions(&message);
TestUtil::ExpectAllExtensionsSet(message);
message.Swap(&message);
TestUtil::ExpectAllExtensionsSet(message);
}
TEST(ExtensionSetTest, SwapExtension) {
unittest::TestAllExtensions message1;
unittest::TestAllExtensions message2;
TestUtil::SetAllExtensions(&message1);
std::vector<const FieldDescriptor*> fields;
// Swap empty fields.
const Reflection* reflection = message1.GetReflection();
reflection->SwapFields(&message1, &message2, fields);
TestUtil::ExpectAllExtensionsSet(message1);
TestUtil::ExpectExtensionsClear(message2);
// Swap two extensions.
fields.push_back(reflection->FindKnownExtensionByNumber(12));
fields.push_back(reflection->FindKnownExtensionByNumber(25));
reflection->SwapFields(&message1, &message2, fields);
EXPECT_TRUE(message1.HasExtension(unittest::optional_int32_extension));
EXPECT_FALSE(message1.HasExtension(unittest::optional_double_extension));
EXPECT_FALSE(message1.HasExtension(unittest::optional_cord_extension));
EXPECT_FALSE(message2.HasExtension(unittest::optional_int32_extension));
EXPECT_TRUE(message2.HasExtension(unittest::optional_double_extension));
EXPECT_TRUE(message2.HasExtension(unittest::optional_cord_extension));
}
TEST(ExtensionSetTest, SwapExtensionWithEmpty) {
unittest::TestAllExtensions message1;
unittest::TestAllExtensions message2;
unittest::TestAllExtensions message3;
TestUtil::SetAllExtensions(&message3);
const Reflection* reflection = message3.GetReflection();
std::vector<const FieldDescriptor*> fields;
reflection->ListFields(message3, &fields);
reflection->SwapFields(&message1, &message2, fields);
TestUtil::ExpectExtensionsClear(message1);
TestUtil::ExpectExtensionsClear(message2);
}
TEST(ExtensionSetTest, SwapExtensionBothFull) {
unittest::TestAllExtensions message1;
unittest::TestAllExtensions message2;
TestUtil::SetAllExtensions(&message1);
TestUtil::SetAllExtensions(&message2);
const Reflection* reflection = message1.GetReflection();
std::vector<const FieldDescriptor*> fields;
reflection->ListFields(message1, &fields);
reflection->SwapFields(&message1, &message2, fields);
TestUtil::ExpectAllExtensionsSet(message1);
TestUtil::ExpectAllExtensionsSet(message2);
}
TEST(ExtensionSetTest, ArenaSetAllExtension) {
Arena arena1;
unittest::TestAllExtensions* message1 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
TestUtil::SetAllExtensions(message1);
TestUtil::ExpectAllExtensionsSet(*message1);
}
TEST(ExtensionSetTest, ArenaCopyConstructor) {
Arena arena1;
unittest::TestAllExtensions* message1 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
TestUtil::SetAllExtensions(message1);
unittest::TestAllExtensions message2(*message1);
arena1.Reset();
TestUtil::ExpectAllExtensionsSet(message2);
}
TEST(ExtensionSetTest, ArenaMergeFrom) {
Arena arena1;
unittest::TestAllExtensions* message1 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
TestUtil::SetAllExtensions(message1);
unittest::TestAllExtensions message2;
message2.MergeFrom(*message1);
arena1.Reset();
TestUtil::ExpectAllExtensionsSet(message2);
}
TEST(ExtensionSetTest, ArenaSetAllocatedMessageAndRelease) {
Arena arena;
unittest::TestAllExtensions* message =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
EXPECT_FALSE(
message->HasExtension(unittest::optional_foreign_message_extension));
// Add a extension using SetAllocatedExtension
unittest::ForeignMessage* foreign_message = new unittest::ForeignMessage();
message->SetAllocatedExtension(unittest::optional_foreign_message_extension,
foreign_message);
// foreign_message is now owned by the arena.
EXPECT_EQ(foreign_message, message->MutableExtension(
unittest::optional_foreign_message_extension));
// Underlying message is copied, and returned.
unittest::ForeignMessage* released_message =
message->ReleaseExtension(unittest::optional_foreign_message_extension);
delete released_message;
EXPECT_FALSE(
message->HasExtension(unittest::optional_foreign_message_extension));
}
TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) {
Arena arena1;
std::unique_ptr<Arena> arena2(new Arena());
unittest::TestAllExtensions* message1 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
unittest::TestAllExtensions* message2 =
Arena::CreateMessage<unittest::TestAllExtensions>(arena2.get());
TestUtil::SetAllExtensions(message1);
TestUtil::SetAllExtensions(message2);
message1->SetExtension(unittest::optional_int32_extension, 1);
message2->SetExtension(unittest::optional_int32_extension, 2);
message1->Swap(message2);
EXPECT_EQ(2, message1->GetExtension(unittest::optional_int32_extension));
EXPECT_EQ(1, message2->GetExtension(unittest::optional_int32_extension));
// Re-set the original values so ExpectAllExtensionsSet is happy.
message1->SetExtension(unittest::optional_int32_extension, 101);
message2->SetExtension(unittest::optional_int32_extension, 101);
TestUtil::ExpectAllExtensionsSet(*message1);
TestUtil::ExpectAllExtensionsSet(*message2);
arena2.reset(nullptr);
TestUtil::ExpectAllExtensionsSet(*message1);
// Test corner cases, when one is empty and other is not.
Arena arena3, arena4;
unittest::TestAllExtensions* message3 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena3);
unittest::TestAllExtensions* message4 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena4);
TestUtil::SetAllExtensions(message3);
message3->Swap(message4);
arena3.Reset();
TestUtil::ExpectAllExtensionsSet(*message4);
}
TEST(ExtensionSetTest, SwapFieldsOfExtensionBothFullWithArena) {
Arena arena1;
Arena* arena2 = new Arena();
unittest::TestAllExtensions* message1 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
unittest::TestAllExtensions* message2 =
Arena::CreateMessage<unittest::TestAllExtensions>(arena2);
TestUtil::SetAllExtensions(message1);
TestUtil::SetAllExtensions(message2);
const Reflection* reflection = message1->GetReflection();
std::vector<const FieldDescriptor*> fields;
reflection->ListFields(*message1, &fields);
reflection->SwapFields(message1, message2, fields);
TestUtil::ExpectAllExtensionsSet(*message1);
TestUtil::ExpectAllExtensionsSet(*message2);
delete arena2;
TestUtil::ExpectAllExtensionsSet(*message1);
}
TEST(ExtensionSetTest, SwapExtensionWithSelf) {
unittest::TestAllExtensions message1;
TestUtil::SetAllExtensions(&message1);
std::vector<const FieldDescriptor*> fields;
const Reflection* reflection = message1.GetReflection();
reflection->ListFields(message1, &fields);
reflection->SwapFields(&message1, &message1, fields);
TestUtil::ExpectAllExtensionsSet(message1);
}
TEST(ExtensionSetTest, SerializationToArray) {
// Serialize as TestAllExtensions and parse as TestAllTypes to insure wire
// compatibility of extensions.
//
// This checks serialization to a flat array by explicitly reserving space in
// the string and calling the generated message's
// SerializeWithCachedSizesToArray.
unittest::TestAllExtensions source;
unittest::TestAllTypes destination;
TestUtil::SetAllExtensions(&source);
size_t size = source.ByteSizeLong();
std::string data;
data.resize(size);
uint8* target = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = source.SerializeWithCachedSizesToArray(target);
EXPECT_EQ(size, end - target);
EXPECT_TRUE(destination.ParseFromString(data));
TestUtil::ExpectAllFieldsSet(destination);
}
TEST(ExtensionSetTest, SerializationToStream) {
// Serialize as TestAllExtensions and parse as TestAllTypes to insure wire
// compatibility of extensions.
//
// This checks serialization to an output stream by creating an array output
// stream that can only buffer 1 byte at a time - this prevents the message
// from ever jumping to the fast path, ensuring that serialization happens via
// the CodedOutputStream.
unittest::TestAllExtensions source;
unittest::TestAllTypes destination;
TestUtil::SetAllExtensions(&source);
size_t size = source.ByteSizeLong();
std::string data;
data.resize(size);
{
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
source.SerializeWithCachedSizes(&output_stream);
ASSERT_FALSE(output_stream.HadError());
}
EXPECT_TRUE(destination.ParseFromString(data));
TestUtil::ExpectAllFieldsSet(destination);
}
TEST(ExtensionSetTest, PackedSerializationToArray) {
// Serialize as TestPackedExtensions and parse as TestPackedTypes to insure
// wire compatibility of extensions.
//
// This checks serialization to a flat array by explicitly reserving space in
// the string and calling the generated message's
// SerializeWithCachedSizesToArray.
unittest::TestPackedExtensions source;
unittest::TestPackedTypes destination;
TestUtil::SetPackedExtensions(&source);
size_t size = source.ByteSizeLong();
std::string data;
data.resize(size);
uint8* target = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = source.SerializeWithCachedSizesToArray(target);
EXPECT_EQ(size, end - target);
EXPECT_TRUE(destination.ParseFromString(data));
TestUtil::ExpectPackedFieldsSet(destination);
}
TEST(ExtensionSetTest, PackedSerializationToStream) {
// Serialize as TestPackedExtensions and parse as TestPackedTypes to insure
// wire compatibility of extensions.
//
// This checks serialization to an output stream by creating an array output
// stream that can only buffer 1 byte at a time - this prevents the message
// from ever jumping to the fast path, ensuring that serialization happens via
// the CodedOutputStream.
unittest::TestPackedExtensions source;
unittest::TestPackedTypes destination;
TestUtil::SetPackedExtensions(&source);
size_t size = source.ByteSizeLong();
std::string data;
data.resize(size);
{
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
source.SerializeWithCachedSizes(&output_stream);
ASSERT_FALSE(output_stream.HadError());
}
EXPECT_TRUE(destination.ParseFromString(data));
TestUtil::ExpectPackedFieldsSet(destination);
}
TEST(ExtensionSetTest, NestedExtensionGroup) {
// Serialize as TestGroup and parse as TestGroupExtension.
unittest::TestGroup source;
unittest::TestGroupExtension destination;
std::string data;
source.mutable_optionalgroup()->set_a(117);
source.set_optional_foreign_enum(unittest::FOREIGN_BAZ);
source.SerializeToString(&data);
EXPECT_TRUE(destination.ParseFromString(data));
EXPECT_TRUE(
destination
.GetExtension(unittest::TestNestedExtension::optionalgroup_extension)
.has_a());
EXPECT_EQ(117, destination
.GetExtension(
unittest::TestNestedExtension::optionalgroup_extension)
.a());
EXPECT_TRUE(destination.HasExtension(
unittest::TestNestedExtension::optional_foreign_enum_extension));
EXPECT_EQ(
unittest::FOREIGN_BAZ,
destination.GetExtension(
unittest::TestNestedExtension::optional_foreign_enum_extension));
}
TEST(ExtensionSetTest, Parsing) {
// Serialize as TestAllTypes and parse as TestAllExtensions.
unittest::TestAllTypes source;
unittest::TestAllExtensions destination;
std::string data;
TestUtil::SetAllFields(&source);
source.SerializeToString(&data);
EXPECT_TRUE(destination.ParseFromString(data));
TestUtil::SetOneofFields(&destination);
TestUtil::ExpectAllExtensionsSet(destination);
}
TEST(ExtensionSetTest, PackedParsing) {
// Serialize as TestPackedTypes and parse as TestPackedExtensions.
unittest::TestPackedTypes source;
unittest::TestPackedExtensions destination;
std::string data;
TestUtil::SetPackedFields(&source);
source.SerializeToString(&data);
EXPECT_TRUE(destination.ParseFromString(data));
TestUtil::ExpectPackedExtensionsSet(destination);
}
TEST(ExtensionSetTest, PackedToUnpackedParsing) {
unittest::TestPackedTypes source;
unittest::TestUnpackedExtensions destination;
std::string data;
TestUtil::SetPackedFields(&source);
source.SerializeToString(&data);
EXPECT_TRUE(destination.ParseFromString(data));
TestUtil::ExpectUnpackedExtensionsSet(destination);
// Reserialize
unittest::TestUnpackedTypes unpacked;
TestUtil::SetUnpackedFields(&unpacked);
// Serialized proto has to be the same size and parsed to the same message.
EXPECT_EQ(unpacked.SerializeAsString().size(),
destination.SerializeAsString().size());
EXPECT_TRUE(EqualsToSerialized(unpacked, destination.SerializeAsString()));
// Make sure we can add extensions.
destination.AddExtension(unittest::unpacked_int32_extension, 1);
destination.AddExtension(unittest::unpacked_enum_extension,
protobuf_unittest::FOREIGN_BAR);
}
TEST(ExtensionSetTest, UnpackedToPackedParsing) {
unittest::TestUnpackedTypes source;
unittest::TestPackedExtensions destination;
std::string data;
TestUtil::SetUnpackedFields(&source);
source.SerializeToString(&data);
EXPECT_TRUE(destination.ParseFromString(data));
TestUtil::ExpectPackedExtensionsSet(destination);
// Reserialize
unittest::TestPackedTypes packed;
TestUtil::SetPackedFields(&packed);
// Serialized proto has to be the same size and parsed to the same message.
EXPECT_EQ(packed.SerializeAsString().size(),
destination.SerializeAsString().size());
EXPECT_TRUE(EqualsToSerialized(packed, destination.SerializeAsString()));
// Make sure we can add extensions.
destination.AddExtension(unittest::packed_int32_extension, 1);
destination.AddExtension(unittest::packed_enum_extension,
protobuf_unittest::FOREIGN_BAR);
}
TEST(ExtensionSetTest, IsInitialized) {
// Test that IsInitialized() returns false if required fields in nested
// extensions are missing.
unittest::TestAllExtensions message;
EXPECT_TRUE(message.IsInitialized());
message.MutableExtension(unittest::TestRequired::single);
EXPECT_FALSE(message.IsInitialized());
message.MutableExtension(unittest::TestRequired::single)->set_a(1);
EXPECT_FALSE(message.IsInitialized());
message.MutableExtension(unittest::TestRequired::single)->set_b(2);
EXPECT_FALSE(message.IsInitialized());
message.MutableExtension(unittest::TestRequired::single)->set_c(3);
EXPECT_TRUE(message.IsInitialized());
message.AddExtension(unittest::TestRequired::multi);
EXPECT_FALSE(message.IsInitialized());
message.MutableExtension(unittest::TestRequired::multi, 0)->set_a(1);
EXPECT_FALSE(message.IsInitialized());
message.MutableExtension(unittest::TestRequired::multi, 0)->set_b(2);
EXPECT_FALSE(message.IsInitialized());
message.MutableExtension(unittest::TestRequired::multi, 0)->set_c(3);
EXPECT_TRUE(message.IsInitialized());
}
TEST(ExtensionSetTest, MutableString) {
// Test the mutable string accessors.
unittest::TestAllExtensions message;
message.MutableExtension(unittest::optional_string_extension)->assign("foo");
EXPECT_TRUE(message.HasExtension(unittest::optional_string_extension));
EXPECT_EQ("foo", message.GetExtension(unittest::optional_string_extension));
message.AddExtension(unittest::repeated_string_extension)->assign("bar");
ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_string_extension));
EXPECT_EQ("bar",
message.GetExtension(unittest::repeated_string_extension, 0));
}
TEST(ExtensionSetTest, SpaceUsedExcludingSelf) {
// Scalar primitive extensions should increase the extension set size by a
// minimum of the size of the primitive type.
#define TEST_SCALAR_EXTENSIONS_SPACE_USED(type, value) \
do { \
unittest::TestAllExtensions message; \
const int base_size = message.SpaceUsedLong(); \
message.SetExtension(unittest::optional_##type##_extension, value); \
int min_expected_size = \
base_size + \
sizeof(message.GetExtension(unittest::optional_##type##_extension)); \
EXPECT_LE(min_expected_size, message.SpaceUsedLong()); \
} while (0)
TEST_SCALAR_EXTENSIONS_SPACE_USED(int32, 101);
TEST_SCALAR_EXTENSIONS_SPACE_USED(int64, 102);
TEST_SCALAR_EXTENSIONS_SPACE_USED(uint32, 103);
TEST_SCALAR_EXTENSIONS_SPACE_USED(uint64, 104);
TEST_SCALAR_EXTENSIONS_SPACE_USED(sint32, 105);
TEST_SCALAR_EXTENSIONS_SPACE_USED(sint64, 106);
TEST_SCALAR_EXTENSIONS_SPACE_USED(fixed32, 107);
TEST_SCALAR_EXTENSIONS_SPACE_USED(fixed64, 108);
TEST_SCALAR_EXTENSIONS_SPACE_USED(sfixed32, 109);
TEST_SCALAR_EXTENSIONS_SPACE_USED(sfixed64, 110);
TEST_SCALAR_EXTENSIONS_SPACE_USED(float, 111);
TEST_SCALAR_EXTENSIONS_SPACE_USED(double, 112);
TEST_SCALAR_EXTENSIONS_SPACE_USED(bool, true);
#undef TEST_SCALAR_EXTENSIONS_SPACE_USED
{
unittest::TestAllExtensions message;
const int base_size = message.SpaceUsedLong();
message.SetExtension(unittest::optional_nested_enum_extension,
unittest::TestAllTypes::FOO);
int min_expected_size =
base_size +
sizeof(message.GetExtension(unittest::optional_nested_enum_extension));
EXPECT_LE(min_expected_size, message.SpaceUsedLong());
}
{
// Strings may cause extra allocations depending on their length; ensure
// that gets included as well.
unittest::TestAllExtensions message;
const int base_size = message.SpaceUsedLong();
const std::string s(
"this is a fairly large string that will cause some "
"allocation in order to store it in the extension");
message.SetExtension(unittest::optional_string_extension, s);
int min_expected_size = base_size + s.length();
EXPECT_LE(min_expected_size, message.SpaceUsedLong());
}
{
// Messages also have additional allocation that need to be counted.
unittest::TestAllExtensions message;
const int base_size = message.SpaceUsedLong();
unittest::ForeignMessage foreign;
foreign.set_c(42);
message.MutableExtension(unittest::optional_foreign_message_extension)
->CopyFrom(foreign);
int min_expected_size = base_size + foreign.SpaceUsedLong();
EXPECT_LE(min_expected_size, message.SpaceUsedLong());
}
// Repeated primitive extensions will increase space used by at least a
// RepeatedField<T>, and will cause additional allocations when the array
// gets too big for the initial space.
// This macro:
// - Adds a value to the repeated extension, then clears it, establishing
// the base size.
// - Adds a small number of values, testing that it doesn't increase the
// SpaceUsedLong()
// - Adds a large number of values (requiring allocation in the repeated
// field), and ensures that that allocation is included in SpaceUsedLong()
#define TEST_REPEATED_EXTENSIONS_SPACE_USED(type, cpptype, value) \
do { \
unittest::TestAllExtensions message; \
const size_t base_size = message.SpaceUsedLong(); \
size_t min_expected_size = sizeof(RepeatedField<cpptype>) + base_size; \
message.AddExtension(unittest::repeated_##type##_extension, value); \
message.ClearExtension(unittest::repeated_##type##_extension); \
const size_t empty_repeated_field_size = message.SpaceUsedLong(); \
EXPECT_LE(min_expected_size, empty_repeated_field_size) << #type; \
message.AddExtension(unittest::repeated_##type##_extension, value); \
message.AddExtension(unittest::repeated_##type##_extension, value); \
EXPECT_EQ(empty_repeated_field_size, message.SpaceUsedLong()) << #type; \
message.ClearExtension(unittest::repeated_##type##_extension); \
const size_t old_capacity = \
message.GetRepeatedExtension(unittest::repeated_##type##_extension) \
.Capacity(); \
EXPECT_GE(old_capacity, kRepeatedFieldLowerClampLimit); \
for (int i = 0; i < 16; ++i) { \
message.AddExtension(unittest::repeated_##type##_extension, value); \
} \
int expected_size = \
sizeof(cpptype) * \
(message \
.GetRepeatedExtension(unittest::repeated_##type##_extension) \
.Capacity() - \
old_capacity) + \
empty_repeated_field_size; \
EXPECT_LE(expected_size, message.SpaceUsedLong()) << #type; \
} while (0)
TEST_REPEATED_EXTENSIONS_SPACE_USED(int32, int32, 101);
TEST_REPEATED_EXTENSIONS_SPACE_USED(int64, int64, 102);
TEST_REPEATED_EXTENSIONS_SPACE_USED(uint32, uint32, 103);
TEST_REPEATED_EXTENSIONS_SPACE_USED(uint64, uint64, 104);
TEST_REPEATED_EXTENSIONS_SPACE_USED(sint32, int32, 105);
TEST_REPEATED_EXTENSIONS_SPACE_USED(sint64, int64, 106);
TEST_REPEATED_EXTENSIONS_SPACE_USED(fixed32, uint32, 107);
TEST_REPEATED_EXTENSIONS_SPACE_USED(fixed64, uint64, 108);
TEST_REPEATED_EXTENSIONS_SPACE_USED(sfixed32, int32, 109);
TEST_REPEATED_EXTENSIONS_SPACE_USED(sfixed64, int64, 110);
TEST_REPEATED_EXTENSIONS_SPACE_USED(float, float, 111);
TEST_REPEATED_EXTENSIONS_SPACE_USED(double, double, 112);
TEST_REPEATED_EXTENSIONS_SPACE_USED(bool, bool, true);
TEST_REPEATED_EXTENSIONS_SPACE_USED(nested_enum, int,
unittest::TestAllTypes::FOO);
#undef TEST_REPEATED_EXTENSIONS_SPACE_USED
// Repeated strings
{
unittest::TestAllExtensions message;
const size_t base_size = message.SpaceUsedLong();
size_t min_expected_size =
sizeof(RepeatedPtrField<std::string>) + base_size;
const std::string value(256, 'x');
// Once items are allocated, they may stick around even when cleared so
// without the hardcore memory management accessors there isn't a notion of
// the empty repeated field memory usage as there is with primitive types.
for (int i = 0; i < 16; ++i) {
message.AddExtension(unittest::repeated_string_extension, value);
}
min_expected_size +=
(sizeof(value) + value.size()) * (16 - kRepeatedFieldLowerClampLimit);
EXPECT_LE(min_expected_size, message.SpaceUsedLong());
}
// Repeated messages
{
unittest::TestAllExtensions message;
const size_t base_size = message.SpaceUsedLong();
size_t min_expected_size =
sizeof(RepeatedPtrField<unittest::ForeignMessage>) + base_size;
unittest::ForeignMessage prototype;
prototype.set_c(2);
for (int i = 0; i < 16; ++i) {
message.AddExtension(unittest::repeated_foreign_message_extension)
->CopyFrom(prototype);
}
min_expected_size +=
(16 - kRepeatedFieldLowerClampLimit) * prototype.SpaceUsedLong();
EXPECT_LE(min_expected_size, message.SpaceUsedLong());
}
}
// N.B.: We do not test range-based for here because we remain C++03 compatible.
template <typename T, typename M, typename ID>
inline T SumAllExtensions(const M& message, ID extension, T zero) {
T sum = zero;
typename RepeatedField<T>::const_iterator iter =
message.GetRepeatedExtension(extension).begin();
typename RepeatedField<T>::const_iterator end =
message.GetRepeatedExtension(extension).end();
for (; iter != end; ++iter) {
sum += *iter;
}
return sum;
}
template <typename T, typename M, typename ID>
inline void IncAllExtensions(M* message, ID extension, T val) {
typename RepeatedField<T>::iterator iter =
message->MutableRepeatedExtension(extension)->begin();
typename RepeatedField<T>::iterator end =
message->MutableRepeatedExtension(extension)->end();
for (; iter != end; ++iter) {
*iter += val;
}
}
TEST(ExtensionSetTest, RepeatedFields) {
unittest::TestAllExtensions message;
// Test empty repeated-field case (b/12926163)
ASSERT_EQ(
0,
message.GetRepeatedExtension(unittest::repeated_int32_extension).size());
ASSERT_EQ(
0, message.GetRepeatedExtension(unittest::repeated_nested_enum_extension)
.size());
ASSERT_EQ(
0,
message.GetRepeatedExtension(unittest::repeated_string_extension).size());
ASSERT_EQ(
0,
message.GetRepeatedExtension(unittest::repeated_nested_message_extension)
.size());
unittest::TestAllTypes::NestedMessage nested_message;
nested_message.set_bb(42);
unittest::TestAllTypes::NestedEnum nested_enum =
unittest::TestAllTypes::NestedEnum_MIN;
for (int i = 0; i < 10; ++i) {
message.AddExtension(unittest::repeated_int32_extension, 1);
message.AddExtension(unittest::repeated_int64_extension, 2);
message.AddExtension(unittest::repeated_uint32_extension, 3);
message.AddExtension(unittest::repeated_uint64_extension, 4);
message.AddExtension(unittest::repeated_sint32_extension, 5);
message.AddExtension(unittest::repeated_sint64_extension, 6);
message.AddExtension(unittest::repeated_fixed32_extension, 7);
message.AddExtension(unittest::repeated_fixed64_extension, 8);
message.AddExtension(unittest::repeated_sfixed32_extension, 7);
message.AddExtension(unittest::repeated_sfixed64_extension, 8);
message.AddExtension(unittest::repeated_float_extension, 9.0);
message.AddExtension(unittest::repeated_double_extension, 10.0);
message.AddExtension(unittest::repeated_bool_extension, true);
message.AddExtension(unittest::repeated_nested_enum_extension, nested_enum);
message.AddExtension(unittest::repeated_string_extension,
std::string("test"));
message.AddExtension(unittest::repeated_bytes_extension,
std::string("test\xFF"));
message.AddExtension(unittest::repeated_nested_message_extension)
->CopyFrom(nested_message);
message.AddExtension(unittest::repeated_nested_enum_extension, nested_enum);
}
ASSERT_EQ(10, SumAllExtensions<int32>(message,
unittest::repeated_int32_extension, 0));
IncAllExtensions<int32>(&message, unittest::repeated_int32_extension, 1);
ASSERT_EQ(20, SumAllExtensions<int32>(message,
unittest::repeated_int32_extension, 0));
ASSERT_EQ(20, SumAllExtensions<int64>(message,
unittest::repeated_int64_extension, 0));
IncAllExtensions<int64>(&message, unittest::repeated_int64_extension, 1);
ASSERT_EQ(30, SumAllExtensions<int64>(message,
unittest::repeated_int64_extension, 0));
ASSERT_EQ(30, SumAllExtensions<uint32>(
message, unittest::repeated_uint32_extension, 0));
IncAllExtensions<uint32>(&message, unittest::repeated_uint32_extension, 1);
ASSERT_EQ(40, SumAllExtensions<uint32>(
message, unittest::repeated_uint32_extension, 0));
ASSERT_EQ(40, SumAllExtensions<uint64>(
message, unittest::repeated_uint64_extension, 0));
IncAllExtensions<uint64>(&message, unittest::repeated_uint64_extension, 1);
ASSERT_EQ(50, SumAllExtensions<uint64>(
message, unittest::repeated_uint64_extension, 0));
ASSERT_EQ(50, SumAllExtensions<int32>(
message, unittest::repeated_sint32_extension, 0));
IncAllExtensions<int32>(&message, unittest::repeated_sint32_extension, 1);
ASSERT_EQ(60, SumAllExtensions<int32>(
message, unittest::repeated_sint32_extension, 0));
ASSERT_EQ(60, SumAllExtensions<int64>(
message, unittest::repeated_sint64_extension, 0));
IncAllExtensions<int64>(&message, unittest::repeated_sint64_extension, 1);
ASSERT_EQ(70, SumAllExtensions<int64>(
message, unittest::repeated_sint64_extension, 0));
ASSERT_EQ(70, SumAllExtensions<uint32>(
message, unittest::repeated_fixed32_extension, 0));
IncAllExtensions<uint32>(&message, unittest::repeated_fixed32_extension, 1);
ASSERT_EQ(80, SumAllExtensions<uint32>(
message, unittest::repeated_fixed32_extension, 0));
ASSERT_EQ(80, SumAllExtensions<uint64>(
message, unittest::repeated_fixed64_extension, 0));
IncAllExtensions<uint64>(&message, unittest::repeated_fixed64_extension, 1);
ASSERT_EQ(90, SumAllExtensions<uint64>(
message, unittest::repeated_fixed64_extension, 0));
// Usually, floating-point arithmetic cannot be trusted to be exact, so it is
// a Bad Idea to assert equality in a test like this. However, we're dealing
// with integers with a small number of significant mantissa bits, so we
// should actually have exact precision here.
ASSERT_EQ(90, SumAllExtensions<float>(message,
unittest::repeated_float_extension, 0));
IncAllExtensions<float>(&message, unittest::repeated_float_extension, 1);
ASSERT_EQ(100, SumAllExtensions<float>(
message, unittest::repeated_float_extension, 0));
ASSERT_EQ(100, SumAllExtensions<double>(
message, unittest::repeated_double_extension, 0));
IncAllExtensions<double>(&message, unittest::repeated_double_extension, 1);
ASSERT_EQ(110, SumAllExtensions<double>(
message, unittest::repeated_double_extension, 0));
RepeatedPtrField<std::string>::iterator string_iter;
RepeatedPtrField<std::string>::iterator string_end;
for (string_iter =
message
.MutableRepeatedExtension(unittest::repeated_string_extension)
->begin(),
string_end =
message
.MutableRepeatedExtension(unittest::repeated_string_extension)
->end();
string_iter != string_end; ++string_iter) {
*string_iter += "test";
}
RepeatedPtrField<std::string>::const_iterator string_const_iter;
RepeatedPtrField<std::string>::const_iterator string_const_end;
for (string_const_iter =
message.GetRepeatedExtension(unittest::repeated_string_extension)
.begin(),
string_const_end =
message.GetRepeatedExtension(unittest::repeated_string_extension)
.end();
string_iter != string_end; ++string_iter) {
ASSERT_TRUE(*string_iter == "testtest");
}
RepeatedField<unittest::TestAllTypes_NestedEnum>::iterator enum_iter;
RepeatedField<unittest::TestAllTypes_NestedEnum>::iterator enum_end;
for (enum_iter = message
.MutableRepeatedExtension(
unittest::repeated_nested_enum_extension)
->begin(),
enum_end = message
.MutableRepeatedExtension(
unittest::repeated_nested_enum_extension)
->end();
enum_iter != enum_end; ++enum_iter) {
*enum_iter = unittest::TestAllTypes::NestedEnum_MAX;
}
RepeatedField<unittest::TestAllTypes_NestedEnum>::const_iterator
enum_const_iter;
RepeatedField<unittest::TestAllTypes_NestedEnum>::const_iterator
enum_const_end;
for (enum_const_iter =
message
.GetRepeatedExtension(unittest::repeated_nested_enum_extension)
.begin(),
enum_const_end =
message
.GetRepeatedExtension(unittest::repeated_nested_enum_extension)
.end();
enum_const_iter != enum_const_end; ++enum_const_iter) {
ASSERT_EQ(*enum_const_iter, unittest::TestAllTypes::NestedEnum_MAX);
}
RepeatedPtrField<unittest::TestAllTypes_NestedMessage>::iterator msg_iter;
RepeatedPtrField<unittest::TestAllTypes_NestedMessage>::iterator msg_end;
for (msg_iter = message
.MutableRepeatedExtension(
unittest::repeated_nested_message_extension)
->begin(),
msg_end = message
.MutableRepeatedExtension(
unittest::repeated_nested_message_extension)
->end();
msg_iter != msg_end; ++msg_iter) {
msg_iter->set_bb(1234);
}
RepeatedPtrField<unittest::TestAllTypes_NestedMessage>::const_iterator
msg_const_iter;
RepeatedPtrField<unittest::TestAllTypes_NestedMessage>::const_iterator
msg_const_end;
for (msg_const_iter = message
.GetRepeatedExtension(
unittest::repeated_nested_message_extension)
.begin(),
msg_const_end = message
.GetRepeatedExtension(
unittest::repeated_nested_message_extension)
.end();
msg_const_iter != msg_const_end; ++msg_const_iter) {
ASSERT_EQ(msg_const_iter->bb(), 1234);
}
// Test one primitive field.
for (auto& x :
*message.MutableRepeatedExtension(unittest::repeated_int32_extension)) {
x = 4321;
}
for (const auto& x :
message.GetRepeatedExtension(unittest::repeated_int32_extension)) {
ASSERT_EQ(x, 4321);
}
// Test one string field.
for (auto& x :
*message.MutableRepeatedExtension(unittest::repeated_string_extension)) {
x = "test_range_based_for";
}
for (const auto& x :
message.GetRepeatedExtension(unittest::repeated_string_extension)) {
ASSERT_TRUE(x == "test_range_based_for");
}
// Test one message field.
for (auto& x : *message.MutableRepeatedExtension(
unittest::repeated_nested_message_extension)) {
x.set_bb(4321);
}
for (const auto& x : *message.MutableRepeatedExtension(
unittest::repeated_nested_message_extension)) {
ASSERT_EQ(x.bb(), 4321);
}
}
// From b/12926163
TEST(ExtensionSetTest, AbsentExtension) {
unittest::TestAllExtensions message;
message.MutableRepeatedExtension(unittest::repeated_nested_message_extension)
->Add()
->set_bb(123);
ASSERT_EQ(1,
message.ExtensionSize(unittest::repeated_nested_message_extension));
EXPECT_EQ(123,
message.GetExtension(unittest::repeated_nested_message_extension, 0)
.bb());
}
#ifdef PROTOBUF_HAS_DEATH_TEST
TEST(ExtensionSetTest, InvalidEnumDeath) {
unittest::TestAllExtensions message;
EXPECT_DEBUG_DEATH(
message.SetExtension(unittest::optional_foreign_enum_extension,
static_cast<unittest::ForeignEnum>(53)),
"IsValid");
}
#endif // PROTOBUF_HAS_DEATH_TEST
TEST(ExtensionSetTest, DynamicExtensions) {
// Test adding a dynamic extension to a compiled-in message object.
FileDescriptorProto dynamic_proto;
dynamic_proto.set_name("dynamic_extensions_test.proto");
dynamic_proto.add_dependency(
unittest::TestAllExtensions::descriptor()->file()->name());
dynamic_proto.set_package("dynamic_extensions");
// Copy the fields and nested types from TestDynamicExtensions into our new
// proto, converting the fields into extensions.
const Descriptor* template_descriptor =
unittest::TestDynamicExtensions::descriptor();
DescriptorProto template_descriptor_proto;
template_descriptor->CopyTo(&template_descriptor_proto);
dynamic_proto.mutable_message_type()->MergeFrom(
template_descriptor_proto.nested_type());
dynamic_proto.mutable_enum_type()->MergeFrom(
template_descriptor_proto.enum_type());
dynamic_proto.mutable_extension()->MergeFrom(
template_descriptor_proto.field());
// For each extension that we added...
for (int i = 0; i < dynamic_proto.extension_size(); i++) {
// Set its extendee to TestAllExtensions.
FieldDescriptorProto* extension = dynamic_proto.mutable_extension(i);
extension->set_extendee(
unittest::TestAllExtensions::descriptor()->full_name());
// If the field refers to one of the types nested in TestDynamicExtensions,
// make it refer to the type in our dynamic proto instead.
std::string prefix = "." + template_descriptor->full_name() + ".";
if (extension->has_type_name()) {
std::string* type_name = extension->mutable_type_name();
if (HasPrefixString(*type_name, prefix)) {
type_name->replace(0, prefix.size(), ".dynamic_extensions.");
}
}
}
// Now build the file, using the generated pool as an underlay.
DescriptorPool dynamic_pool(DescriptorPool::generated_pool());
const FileDescriptor* file = dynamic_pool.BuildFile(dynamic_proto);
ASSERT_TRUE(file != nullptr);
DynamicMessageFactory dynamic_factory(&dynamic_pool);
dynamic_factory.SetDelegateToGeneratedFactory(true);
// Construct a message that we can parse with the extensions we defined.
// Since the extensions were based off of the fields of TestDynamicExtensions,
// we can use that message to create this test message.
std::string data;
unittest::TestDynamicExtensions dynamic_extension;
{
unittest::TestDynamicExtensions message;
message.set_scalar_extension(123);
message.set_enum_extension(unittest::FOREIGN_BAR);
message.set_dynamic_enum_extension(
unittest::TestDynamicExtensions::DYNAMIC_BAZ);
message.mutable_message_extension()->set_c(456);
message.mutable_dynamic_message_extension()->set_dynamic_field(789);
message.add_repeated_extension("foo");
message.add_repeated_extension("bar");
message.add_packed_extension(12);
message.add_packed_extension(-34);
message.add_packed_extension(56);
message.add_packed_extension(-78);
// Also add some unknown fields.
// An unknown enum value (for a known field).
message.mutable_unknown_fields()->AddVarint(
unittest::TestDynamicExtensions::kDynamicEnumExtensionFieldNumber,
12345);
// A regular unknown field.
message.mutable_unknown_fields()->AddLengthDelimited(54321, "unknown");
message.SerializeToString(&data);
dynamic_extension = message;
}
// Now we can parse this using our dynamic extension definitions...
unittest::TestAllExtensions message;
{
io::ArrayInputStream raw_input(data.data(), data.size());
io::CodedInputStream input(&raw_input);
input.SetExtensionRegistry(&dynamic_pool, &dynamic_factory);
ASSERT_TRUE(message.ParseFromCodedStream(&input));
ASSERT_TRUE(input.ConsumedEntireMessage());
}
// Can we print it?
EXPECT_EQ(
"[dynamic_extensions.scalar_extension]: 123\n"
"[dynamic_extensions.enum_extension]: FOREIGN_BAR\n"
"[dynamic_extensions.dynamic_enum_extension]: DYNAMIC_BAZ\n"
"[dynamic_extensions.message_extension] {\n"
" c: 456\n"
"}\n"
"[dynamic_extensions.dynamic_message_extension] {\n"
" dynamic_field: 789\n"
"}\n"
"[dynamic_extensions.repeated_extension]: \"foo\"\n"
"[dynamic_extensions.repeated_extension]: \"bar\"\n"
"[dynamic_extensions.packed_extension]: 12\n"
"[dynamic_extensions.packed_extension]: -34\n"
"[dynamic_extensions.packed_extension]: 56\n"
"[dynamic_extensions.packed_extension]: -78\n"
"2002: 12345\n"
"54321: \"unknown\"\n",
message.DebugString());
// Can we serialize it?
EXPECT_TRUE(
EqualsToSerialized(dynamic_extension, message.SerializeAsString()));
// What if we parse using the reflection-based parser?
{
unittest::TestAllExtensions message2;
io::ArrayInputStream raw_input(data.data(), data.size());
io::CodedInputStream input(&raw_input);
input.SetExtensionRegistry(&dynamic_pool, &dynamic_factory);
ASSERT_TRUE(WireFormat::ParseAndMergePartial(&input, &message2));
ASSERT_TRUE(input.ConsumedEntireMessage());
EXPECT_EQ(message.DebugString(), message2.DebugString());
}
// Are the embedded generated types actually using the generated objects?
{
const FieldDescriptor* message_extension =
file->FindExtensionByName("message_extension");
ASSERT_TRUE(message_extension != nullptr);
const Message& sub_message =
message.GetReflection()->GetMessage(message, message_extension);
const unittest::ForeignMessage* typed_sub_message =
#if PROTOBUF_RTTI
dynamic_cast<const unittest::ForeignMessage*>(&sub_message);
#else
static_cast<const unittest::ForeignMessage*>(&sub_message);
#endif
ASSERT_TRUE(typed_sub_message != nullptr);
EXPECT_EQ(456, typed_sub_message->c());
}
// What does GetMessage() return for the embedded dynamic type if it isn't
// present?
{
const FieldDescriptor* dynamic_message_extension =
file->FindExtensionByName("dynamic_message_extension");
ASSERT_TRUE(dynamic_message_extension != nullptr);
const Message& parent = unittest::TestAllExtensions::default_instance();
const Message& sub_message = parent.GetReflection()->GetMessage(
parent, dynamic_message_extension, &dynamic_factory);
const Message* prototype =
dynamic_factory.GetPrototype(dynamic_message_extension->message_type());
EXPECT_EQ(prototype, &sub_message);
}
}
TEST(ExtensionSetTest, BoolExtension) {
unittest::TestAllExtensions msg;
uint8 wire_bytes[2] = {13 * 8, 42 /* out of bounds payload for bool */};
EXPECT_TRUE(msg.ParseFromArray(wire_bytes, 2));
EXPECT_TRUE(msg.GetExtension(protobuf_unittest::optional_bool_extension));
}
TEST(ExtensionSetTest, ConstInit) {
PROTOBUF_CONSTINIT static ExtensionSet set{};
EXPECT_EQ(set.NumExtensions(), 0);
}
} // namespace
} // namespace internal
} // namespace protobuf
} // namespace google
| {
"content_hash": "9f57e6c9f3eb84634df8da1b214dce9f",
"timestamp": "",
"source": "github",
"line_count": 1338,
"max_line_length": 92,
"avg_line_length": 42.0186846038864,
"alnum_prop": 0.7091478273243095,
"repo_name": "google/protobuf",
"id": "debdd6670c522782d1ca545a16df1442a499113c",
"size": "56221",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "src/google/protobuf/extension_set_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "2465"
},
{
"name": "C",
"bytes": "1715931"
},
{
"name": "C#",
"bytes": "2741284"
},
{
"name": "C++",
"bytes": "9392605"
},
{
"name": "CMake",
"bytes": "67942"
},
{
"name": "Dockerfile",
"bytes": "15452"
},
{
"name": "Emacs Lisp",
"bytes": "7898"
},
{
"name": "Go",
"bytes": "3348"
},
{
"name": "Java",
"bytes": "3728111"
},
{
"name": "JavaScript",
"bytes": "842875"
},
{
"name": "M4",
"bytes": "61074"
},
{
"name": "Makefile",
"bytes": "200091"
},
{
"name": "Objective-C",
"bytes": "2865986"
},
{
"name": "Objective-C++",
"bytes": "2897"
},
{
"name": "PAWN",
"bytes": "341"
},
{
"name": "PHP",
"bytes": "869597"
},
{
"name": "Python",
"bytes": "1381859"
},
{
"name": "Ruby",
"bytes": "165154"
},
{
"name": "Shell",
"bytes": "125403"
},
{
"name": "Swift",
"bytes": "20112"
},
{
"name": "Vim script",
"bytes": "3759"
}
],
"symlink_target": ""
} |
Apiary
=======
[](https://raw.githubusercontent.com/robojackets/apiary/master/LICENSE) [](https://concourse.sandbox.aws.robojackets.net/teams/information-technology/pipelines/apiary)
Apiary is a tool for managing the membership and operations of RoboJackets, a student organization at Georgia Tech.
## Motivation
This project grew out of frustration with the limitations imposed by Georgia Tech's student organization management system, OrgSync. We found that while it may be an excellent tool for managing small groups, it does not scale very well. To that end, we've tried to design an application that can better support our student organization at its current size, and grow and develop along with our group.
This project has been tailored to support the specific workflow of RoboJackets and is not currently built in a manner that would be easily adaptable to another organization. The decision to limit the scope of this project was made in light of the extensive approvals process to access the amount of student data we currently store. We believe it is unlikely that another org will be able and willing to navigate that process.
## Getting Help
- For development of Apiary, [open a Github issue](https://github.com/RoboJackets/apiary/issues/new) or ask in [#apiary](https://robojackets.slack.com/app_redirect?channel=apiary) on Slack
- For production support of MyRoboJackets, ask in [#it-helpdesk](https://robojackets.slack.com/app_redirect?channel=it-helpdesk) on Slack
## Getting Started with Local Development - Docker
---
While this repository itself is open-source, we use several **confidential and proprietary** components which are packed into Docker images produced by this process. Images should **never** be pushed to a public registry.
---
Install Docker and Docker Compose.
Clone the repository, then run
```sh
export DOCKER_BUILDKIT=1
docker build --pull --target backend-uncompressed --network host --secret id=composer_auth,src=auth.json . --tag robojackets/apiary
docker compose up
```
You will need to provide an `auth.json` file that has credentials for downloading Laravel Nova. Ask in Slack and we can provide this file to you.
## Getting Started with Local Development - Hard Way
If you've never worked with [Laravel](https://laravel.com) before, we recommend watching [the Laravel from Scratch webcast series](https://laracasts.com/series/laravel-from-scratch-2017) to get you up to speed quickly.
Apiary is written entirely in languages that can be run from any operating system; however, support is only provided for Linux environments. All instructions below assume that the user is running on a modern, Debian-based Linux distribution.
For an easier setup, you may wish to use [Laravel Homestead](https://laravel.com/docs/5.6/homestead).
Homestead is a pre-packaged [Vagrant](https://www.vagrantup.com/) box maintained by the Laravel creators designed for Laravel development. It takes care of most of the server configuration so that you can get up and running quickly. **If you opt to use Homestead, all steps listed below should be performed inside the Vagrant box, rather than on the host machine.**
Laravel Mix is used to compile browser assets. Currently, we're concatenating and minifying all of our JS and CSS. This step is also where we compile our SCSS into CSS. In your local dev environment, you should run `npm run dev` the first time you clone the repo and any time the assets change. Laravel Mix is a simple wrapper around webpack, which you really don't need to know about at this point. However, the fact that we use Webpack as a module bundler means that the process to reference JavaScript and CSS is a little bit different. It also means that if you add new CSS or JS files into the project, you need to reference them in [`webpack.mix.js`](webpack.mix.js) to be compiled. See [the relevant Laravel documentation](https://laravel.com/docs/5.4/mix#running-mix) for more details.
Most of the backend code lives under [`app/Http`](/app/Http), with templates under [`resources/views`](/resources/views) and [`resources/js`](/resources/js), but you're encouraged to browse through the project tree to get a better feel of where different components live. The `php artisan` command can generate new classes for you in the correct locations automatically - run it with no parameters to see all the options.
### Install dependencies
This is a pretty conventional Laravel project, so we recommend following [the official guide](https://laravel.com/docs/5.6#installation) to get your workspace set up. At minimum, you will need PHP 7.1.3+, [`composer`](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx), `npm`, and a MySQL 5.7+ compatible database available on your machine.
*If you're using Homestead, this section is taken care of for you out of the box.*
You can install most of the required php extensions with:
```
$ sudo apt install php php-common php-cli php-mysql php-mbstring php-json php-opcache php-xml php-bcmath php-curl php-gd php-zip php-ldap php-uuid
```
On certain Linux flavors, you may need to manually install the PHP `sodium` extension, which is used by Laravel Passport's
dependencies. Sodium is likely not included on RHEL and has to be manually built and enabled. For RHEL 8, [this third-party](https://gist.github.com/davidalger/c19a53ed293291ec2e93b5227f9e0a2d#file-install-php-sodium-on-el8-sh)
script (reproduced below in case the Gist disappears, but use at your own risk) has worked to enable the `sodium` extension:
```bash
yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm \
&& yum install -y php-cli libsodium \
&& yum install -y php-pear php-devel libsodium-devel make \
&& pecl channel-update pecl.php.net \
&& pecl install libsodium \
&& yum remove -y php-pear php-devel libsodium-devel make \
&& echo 'extension=sodium.so' > /etc/php.d/20-sodium.ini \
&& php -i | grep sodium
```
For the resume book functionality, you'll also need to install `exiftool` and Ghostscript:
```
$ sudo apt install exiftool ghostscript
```
### Install Redis
Apiary uses Redis for queueing jobs, with Laravel Horizon used to manage them. You should be able to just install Redis and the corresponding PHP extension. Once you get Apiary configured below, you can run `php artisan horizon` to process jobs.
### Install Apiary
Clone the repository onto your local machine:
```
$ git clone https://github.com/RoboJackets/apiary.git
```
If you a member of RoboJackets, reach out in [#apiary](https://robojackets.slack.com/app_redirect?channel=apiary) on Slack and ask for a copy of a mostly configured `.env` file.
Copy the example environment file to configure Apiary for local development:
```
$ cp .env.example .env
```
For a basic development environment, you'll need to modify the following settings:
| Key | Value |
|------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| APP_URL | Set to the hostname of your local dev environment, ex. `apiary.test`. |
| DB_* | Set appropriately for your database. |
| MAIL_* | Mailgun is the suggested mail driver, but you can easily configure Mailtrap or a local mail server referencing the [Laravel documentation](https://laravel.com/docs/5.4/mail). |
| CAS_HOSTNAME | FQDN of the CAS server to use, ex. login.gatech.edu |
| CAS_REAL_HOSTS | Should match CAS_HOSTNAME |
| CAS_LOGOUT_URL | CAS logout URL, ex. https://login.gatech.edu/cas/logout |
| CAS_MASQUERADE | If set, bypasses the CAS authentication flow and authenticates as the specified username. |
| CAS_MASQUERADE_gtGTID | GTID number for the masquerading user (90xxxxxxx) |
| CAS_MASQUERADE_email_primary | Primary email address for the masquerading user |
| CAS_MASQUERADE_givenName | Given Name (First Name) for the masquerading user |
| CAS_MASQUERADE_sn | SN (Second/Last Name) for the masquerading user
| PASSPORT_PERSONAL_ACCESS_CLIENT_ID | Client ID from running `php artisan passport:client --personal` used to generate OAuth2 Personal Access Tokens |
| PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET | Client secret from running `php artisan passport:client --personal` used to generate OAuth2 Personal Access Tokens |
#### Installing dependencies
```
$ composer install && npm install
```
Please note that we are using [Laravel Nova](https://nova.laravel.com/) for some admin pages. You will be prompted for credentials when running Composer if an update to Nova is required. Get in touch with us in [#apiary](https://robojackets.slack.com/app_redirect?channel=apiary) when this happens.
You will need to run these commands again in the future if there are any changes to required packages.
### Before Your First Run
Generate an application key (run this only once for initial setup.)
```
$ php artisan key:generate
```
Run database migrations to set up tables (run this for initial setup and when any new migrations are added later.)
```
$ php artisan migrate
```
Setup Laravel Passport:
```
$ php artisan passport:keys
```
*(Optional - Required to create Personal Access Tokens)* Create OAuth2 Personal Access Client: Add the client ID and
secret created to the `PASSPORT_PERSONAL_ACCESS_CLIENT_ID` and `PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET` environment
variables.
```
$ php artisan passport:client --personal
```
Seed the database tables with base content (run this only once for initial setup.)
```
$ php artisan db:seed
```
Generate static assets (run this every time Vue or JS files are edited.)
```
$ npm run dev
```
### Starting the Local Development Server
You can use `php`'s built in development web server to easily test your application without needing to configure a production-ready web server, such as `nginx` or `apache`. To start this server:
```
$ php artisan serve
```
This is not necessary if you are using Homestead - you should use the configured hostname from `Homestead.yaml` instead, ex. `apiary.test`.
## Tips for Development
### `npm run watch`
Automatically rebuilds your front-end assets whenever the files change on disk. It's the same as running `npm run dev`. Some platforms will need `npm run watch-poll` to see changes to files, rather than just `watch`.
### `php artisan tinker`
Tinker allows you to interact with Apiary on the command line including the Eloquent ORM, jobs, events, and more. A good introduction to Tinker can be found [here](https://scotch.io/tutorials/tinker-with-the-data-in-your-laravel-apps-with-php-artisan-tinker).
### `composer run test`
Use this command to run unit/feature tests locally. You shouldn't need to modify `.env.testing`. If you add migrations,
there's no need to dump the schema again; the migrations will be run as part of the tests. (It's possible to squash the
migrations again if the tests take too long, but simply dumping the schema is insufficient.)
If you try to run PHPUnit directly, you may get various "file not found" errors since the `composer run test` command
runs extra steps before the tests are run.
## Moving to Production
### `.env`
There are a few additional changes needed to `.env` when moving to production.
| Key | Value |
|------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| APP_NAME | MyRoboJackets (or other as you see fit) |
| APP_ENV | production |
| APP_DEBUG | false |
| APP_LOG_LEVEL | info (or other as you see fit) |
| APP_URL | DNS hostname for production environment |
| GA_UA | Google Analytics identifier, if desired |
| SQUARE_* | Square API credentials (Get these from the Square Developer Dashboard)
### Horizon Configuration
Review the Laravel documentation on deploying Horizon to a production environment.
Also be sure to set up a cron job to run scheduled tasks - Horizon uses this to keep track of statistics.
# Security reporting
Any security issues with the Apiary code or any RoboJackets-managed Apiary deployment (*.robojackets.org) should be reported to [apiary@robojackets.org](mailto:apiary@robojackets.org). This will notify our development and operations teams and you should receive a response within 8 business hours Eastern Time.
| {
"content_hash": "4ae94dbd29cc383226880f097a434c18",
"timestamp": "",
"source": "github",
"line_count": 221,
"max_line_length": 793,
"avg_line_length": 69.04524886877829,
"alnum_prop": 0.6137361557113834,
"repo_name": "RoboJackets/apiary",
"id": "4f3a92f1c971952e9295785567d6a4db3753905e",
"size": "15259",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Blade",
"bytes": "53723"
},
{
"name": "Dockerfile",
"bytes": "3796"
},
{
"name": "HCL",
"bytes": "9233"
},
{
"name": "PHP",
"bytes": "1046730"
},
{
"name": "Shell",
"bytes": "4581"
},
{
"name": "Smarty",
"bytes": "1366"
},
{
"name": "Vue",
"bytes": "111904"
}
],
"symlink_target": ""
} |
require 'closer'
begin
require 'cucumber/rails'
puts 'cucumber-rails loaded.'
rescue LoadError => e
end
DatabaseCleaner.strategy = :truncation
require_relative 'hooks/fixtures'
require 'daddy/cucumber'
| {
"content_hash": "644a0206f8a4a9203ef3f8d53d1a848f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 38,
"avg_line_length": 16.153846153846153,
"alnum_prop": 0.7666666666666667,
"repo_name": "ichylinux/daddy",
"id": "fee9b396f595beb532d57b1f6cd1c9e301ca9bae",
"size": "210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/daddy/cucumber/rails.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "43"
},
{
"name": "Dockerfile",
"bytes": "3614"
},
{
"name": "HTML",
"bytes": "48942"
},
{
"name": "JavaScript",
"bytes": "2944"
},
{
"name": "Ruby",
"bytes": "68086"
},
{
"name": "SCSS",
"bytes": "306"
},
{
"name": "Shell",
"bytes": "6617"
}
],
"symlink_target": ""
} |
import './commands'
// Alternatively you can use CommonJS syntax:
import '@cypress/code-coverage/support'
| {
"content_hash": "5894b9c7bead72a9d4e28bac7a380024",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 45,
"avg_line_length": 26.75,
"alnum_prop": 0.7663551401869159,
"repo_name": "thednp/bootstrap.native",
"id": "e02780e1f923bf4146089b6d36c9eceee551154e",
"size": "710",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cypress/support/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "45029"
},
{
"name": "JavaScript",
"bytes": "285236"
},
{
"name": "TypeScript",
"bytes": "976"
}
],
"symlink_target": ""
} |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: Google/Ads/GoogleAds/Util/FieldMasks/Proto/tester.proto
namespace Google\Ads\GoogleAds\Util\FieldMasks\Proto;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* The non-optional sub-message field for Resource.
*
* Generated from protobuf message <code>google.ads.googleads.util.fieldmasks.proto.DynamicSetting</code>
*/
class DynamicSetting extends \Google\Protobuf\Internal\Message
{
/**
* Generated from protobuf field <code>string domain_name = 1;</code>
*/
protected $domain_name = '';
/**
* Generated from protobuf field <code>bool use_supplied_urls_only = 2;</code>
*/
protected $use_supplied_urls_only = null;
/**
* Generated from protobuf field <code>.google.ads.googleads.util.fieldmasks.proto.TrackingSetting tracking_setting = 3;</code>
*/
protected $tracking_setting = null;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $domain_name
* @type bool $use_supplied_urls_only
* @type \Google\Ads\GoogleAds\Util\FieldMasks\Proto\TrackingSetting $tracking_setting
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Ads\GoogleAds\Util\FieldMasks\Proto\Tester::initOnce();
parent::__construct($data);
}
/**
* Generated from protobuf field <code>string domain_name = 1;</code>
* @return string
*/
public function getDomainName()
{
return $this->domain_name;
}
/**
* Generated from protobuf field <code>string domain_name = 1;</code>
* @param string $var
* @return $this
*/
public function setDomainName($var)
{
GPBUtil::checkString($var, True);
$this->domain_name = $var;
return $this;
}
/**
* Generated from protobuf field <code>bool use_supplied_urls_only = 2;</code>
* @return bool
*/
public function getUseSuppliedUrlsOnly()
{
return isset($this->use_supplied_urls_only) ? $this->use_supplied_urls_only : false;
}
public function hasUseSuppliedUrlsOnly()
{
return isset($this->use_supplied_urls_only);
}
public function clearUseSuppliedUrlsOnly()
{
unset($this->use_supplied_urls_only);
}
/**
* Generated from protobuf field <code>bool use_supplied_urls_only = 2;</code>
* @param bool $var
* @return $this
*/
public function setUseSuppliedUrlsOnly($var)
{
GPBUtil::checkBool($var);
$this->use_supplied_urls_only = $var;
return $this;
}
/**
* Generated from protobuf field <code>.google.ads.googleads.util.fieldmasks.proto.TrackingSetting tracking_setting = 3;</code>
* @return \Google\Ads\GoogleAds\Util\FieldMasks\Proto\TrackingSetting
*/
public function getTrackingSetting()
{
return isset($this->tracking_setting) ? $this->tracking_setting : null;
}
public function hasTrackingSetting()
{
return isset($this->tracking_setting);
}
public function clearTrackingSetting()
{
unset($this->tracking_setting);
}
/**
* Generated from protobuf field <code>.google.ads.googleads.util.fieldmasks.proto.TrackingSetting tracking_setting = 3;</code>
* @param \Google\Ads\GoogleAds\Util\FieldMasks\Proto\TrackingSetting $var
* @return $this
*/
public function setTrackingSetting($var)
{
GPBUtil::checkMessage($var, \Google\Ads\GoogleAds\Util\FieldMasks\Proto\TrackingSetting::class);
$this->tracking_setting = $var;
return $this;
}
}
| {
"content_hash": "f16e94447e7f698c1da38c8de6001e1f",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 131,
"avg_line_length": 28.455223880597014,
"alnum_prop": 0.6409651193286127,
"repo_name": "googleads/google-ads-php",
"id": "3971ca530201325d420b719207ed8703aa12a0ce",
"size": "3813",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tests/Google/Ads/GoogleAds/Util/FieldMasks/Proto/DynamicSetting.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "899"
},
{
"name": "PHP",
"bytes": "9952711"
},
{
"name": "Shell",
"bytes": "338"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharpSharp
{
/// <summary>
/// Provides additional methods to help working with strings.
/// </summary>
public static class StringSharp
{
#region Casing methods
/// <summary>
/// Returns a copy of this <c>System.String</c> converted to camel case.
/// The first word of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized.
/// </summary>
/// <param name="theString">The string.</param>
/// <returns>A <c>System.String</c> in camelCase.</returns>
public static string ToCamelCase(this string theString)
{
string camelCaseVersion = "";
int index = 0;
foreach (string segment in theString.SplitWords())
{
bool isFirstSegment = index == 0;
if (isFirstSegment)
{
camelCaseVersion += segment.ToLowerInvariant();
}
else
{
camelCaseVersion += segment.Capitalize();
}
index++;
}
return camelCaseVersion;
}
/// <summary>
/// Returns a copy of this <c>System.String</c> converted to pascal case.
/// The first letter of each concatenated word are capitalized.
/// </summary>
/// <param name="theString">The string.</param>
/// <returns>A <c>System.String</c> in PascalCase.</returns>
public static string ToPascalCase(this string theString)
{
string pascalCaseVersion = "";
foreach (string segment in theString.SplitWords())
{
pascalCaseVersion += segment.Capitalize();
}
return pascalCaseVersion;
}
/// <summary>
/// Returns a copy of this <c>System.String</c> converted to title case.
/// The first letter of each word are capitalized and all the words are separated by a space.
/// </summary>
/// <param name="theString">The string.</param>
/// <returns>A <c>System.String</c> in Title Case.</returns>
public static string ToTitleCase(this string theString)
{
string titleCaseVersion = "";
foreach (string segment in theString.SplitWords())
{
titleCaseVersion += segment.Capitalize() + " ";
}
// Remove the trailing space
if (titleCaseVersion.Length > 0)
{
titleCaseVersion = titleCaseVersion.Substring(0, titleCaseVersion.Length - 1);
}
return titleCaseVersion;
}
/// <summary>
/// Returns a copy of this <c>System.String</c> converted to plain english.
/// All the words are in lowercase and are separated by a space.
/// </summary>
/// <param name="theString">The string.</param>
/// <returns>A <c>System.String</c> in plain english.</returns>
public static string ToPlainEnglish(this string theString)
{
return theString.ToPlainEnglish(false);
}
/// <summary>
/// Returns a copy of this <c>System.String</c> converted to plain english.
/// All the words are in lowercase and are separated by a space. The first word
/// will be capitalized if requested.
/// </summary>
/// <param name="theString">The string.</param>
/// <param name="capitalizeFirstWord">if set to <c>true</c> capitalizes the first word.</param>
/// <returns>A <c>System.String</c> in Plain english.</returns>
public static string ToPlainEnglish(this string theString, bool capitalizeFirstWord)
{
string plainEnglishVersion = "";
int index = 0;
foreach (string word in theString.SplitWords())
{
bool isFirstWord = index == 0;
plainEnglishVersion += (isFirstWord && capitalizeFirstWord ? word.Capitalize() : word) + " ";
index++;
}
// Remove the trailing space
if (plainEnglishVersion.Length > 0)
{
plainEnglishVersion = plainEnglishVersion.Substring(0, plainEnglishVersion.Length - 1);
}
return plainEnglishVersion;
}
/// <summary>
/// Returns a copy of this <c>System.String</c> with the
/// first letter in uppercase.
/// </summary>
/// <param name="theString">The string.</param>
/// <returns>A <c>System.String</c> with the first letter in uppercase.</returns>
public static string Capitalize(this string theString)
{
if (String.IsNullOrEmpty(theString))
{
throw new ArgumentException("Can't capitalize an empty string.");
}
bool hasMoreThanOneCharacter = theString.Length > 1;
return char.ToUpperInvariant(theString[0]) + (hasMoreThanOneCharacter ? theString.Substring(1) : "");
}
/// <summary>
/// Returns a string array that contains the words in the string delimited by a space or a group
/// of capital letters (such as an acronym).
/// </summary>
/// <param name="theString">The string.</param>
/// <returns>An array of <c>System.String</c> in lowercase.</returns>
public static string[] SplitWords(this string theString)
{
// Add a space before every word (a word starts by a capital letter or at the first letter after a space)
// A group of uppercase characters will be considered a word because it probably is an acronym
// ex: VariableName -> Variable Name, IPAddress -> IP Address
bool lastCharWasUpper = false;
for (int index = 0; index < theString.Length; index++)
{
bool charIsUpper = char.IsUpper(theString, index);
bool nextCharIsLower = index != theString.Length - 1 ? char.IsLower(theString, index + 1) : false;
if (charIsUpper && (!lastCharWasUpper || nextCharIsLower))
{
// Insert a space before the char (and update the index to stay on the char)
theString = theString.Insert(index, " ");
index++;
}
lastCharWasUpper = charIsUpper;
}
// Split the string into words
string[] segments = theString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
// Lowercase each word (except words that are all uppercase, which are most probably acronyms)
for (int index = 0; index < segments.Length; index++)
{
bool isAllUppercase = segments[index] == segments[index].ToUpperInvariant();
if (!isAllUppercase)
{
segments[index] = segments[index].ToLowerInvariant();
}
}
return segments;
}
/// <summary>
/// Splits the lines.
/// </summary>
/// <param name="theString">The string.</param>
/// <returns></returns>
public static string[] SplitLines(this string theString)
{
return theString.SplitLines(StringSplitOptions.None);
}
/// <summary>
/// Splits the lines.
/// </summary>
/// <param name="theString">The string.</param>
/// <param name="options">The options.</param>
/// <returns></returns>
public static string[] SplitLines(this string theString, StringSplitOptions options)
{
return theString.Split(new string[] { "\r\n", "\n", "\r" }, options);
}
#endregion // Casing methods
#region Cardinality methods
/// <summary>
/// Singularizes the string.
/// </summary>
/// <param name="theString">The string.</param>
/// <returns></returns>
public static string Singularize(this string theString)
{
return System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(System.Threading.Thread.CurrentThread.CurrentUICulture).Singularize(theString);
}
/// <summary>
/// Pluralizes the string.
/// </summary>
/// <param name="theString">The string.</param>
/// <returns></returns>
public static string Pluralize(this string theString)
{
return System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(System.Threading.Thread.CurrentThread.CurrentUICulture).Pluralize(theString);
}
#endregion // Cardinality methods
#region Conversion methods
/// <summary>
/// Fluent interface for <c>int.Parse(value)</c>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The integer representation of the value.</returns>
public static int ToInt(this string value)
{
return int.Parse(value);
}
/// <summary>
/// Fluent interface for <c>long.Parse(value)</c>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The longeger representation of the value.</returns>
public static long ToLong(this string value)
{
return long.Parse(value);
}
/// <summary>
/// Fluent interface for <c>BooleanSharp.Parse(value)</c>.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <exception cref="System.FormatException">The value is not an accepted string.</exception>
/// <returns>true if value is accepted true string; otherwise, false.</returns>
public static bool ToBool(this string value)
{
return value.ToBool(false);
}
/// <summary>
/// Converts the value using either <c>BooleanSharp.Parse(value)</c> or
/// <c>bool.Parse(value)</c> depending on the value of <c>useStandardBooleanParser</c>.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="useStandardBooleanParser">if set to <c>true</c> use the standard boolean parser (<c>bool.Parse(value)</c>).</param>
/// <returns>
/// true if value is an accepted true string; otherwise, false.
/// </returns>
/// <exception cref="System.FormatException">The value is not an accepted string.</exception>
public static bool ToBool(this string value, bool useStandardBooleanParser)
{
if (useStandardBooleanParser)
{
return bool.Parse(value);
}
else
{
return BooleanSharp.Parse(value);
}
}
/// <summary>
/// Converts the string representation of the name or numeric value of one or
/// more enumerated constants to an equivalent enumerated object.
/// </summary>
/// <typeparam name="TEnum">The type of the enum.</typeparam>
/// <param name="value">The value.</param>
/// <returns>
/// An object of type TEnum whose value is represented by value.
/// </returns>
/// <exception cref="System.ArgumentException">
/// TEnum is not an System.Enum.
/// -or-
/// value is either an empty string ("") or only contains white space.
/// -or-
/// value is a name, but not one of the named constants defined for the enumeration.
/// </exception>
/// <exception cref="System.OverflowException">
/// value is outside the range of the underlying type of TEnum.
/// </exception>
public static TEnum ToEnum<TEnum>(this string value)
where TEnum : struct
{
return (TEnum)Enum.Parse(typeof(TEnum), value, true);
}
#endregion // Conversion methods
}
}
| {
"content_hash": "c692d5537ef08e2d401e7845d435bbc3",
"timestamp": "",
"source": "github",
"line_count": 319,
"max_line_length": 181,
"avg_line_length": 39.41379310344828,
"alnum_prop": 0.5507038892865664,
"repo_name": "mbillard/csharpsharp",
"id": "e5faae6b4f402e4a0feed2e1e445a925521a2ba3",
"size": "12575",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CSharpSharp/StringSharp.cs",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "88485"
}
],
"symlink_target": ""
} |
import { moduleFor, test } from 'ember-qunit';
moduleFor('controller:submit', 'Unit | Controller | submit', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
needs: ['validator:presence', 'validator:length', 'validator:format'],
});
// Replace this with your real tests.
test('it exists', function(assert) {
let controller = this.subject();
assert.ok(controller);
});
| {
"content_hash": "e313e899bb99662ceba6be641eca9f11",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 74,
"avg_line_length": 32.53846153846154,
"alnum_prop": 0.6855791962174941,
"repo_name": "hmoco/ember-preprints",
"id": "8a9e53fcda94ce932b7e8351739c6e43744e3fda",
"size": "423",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/unit/controllers/submit-test.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "19773"
},
{
"name": "HTML",
"bytes": "62395"
},
{
"name": "JavaScript",
"bytes": "113252"
}
],
"symlink_target": ""
} |
@interface SomeUnitTest : BaseTestCase
@end
@implementation SomeUnitTest
-(void)setUp {
[super setUp];
// Set-up code here.
}
-(void)tearDown {
// Tear-down code here.
[super tearDown];
}
-(void)testExample {
id mockFoo = [OCMockObject mockForClass:[NSString class]];
[[[mockFoo stub] andReturn:@"foo"] lowercaseString];
expect([mockFoo lowercaseString]).toEqual(@"foo");
}
@end
| {
"content_hash": "be6bc90ef4b47458c4c0f02d02b62b3a",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 62,
"avg_line_length": 17.583333333333332,
"alnum_prop": 0.6516587677725119,
"repo_name": "twobitlabs/iOSXcodeStarterProject",
"id": "2f5a809d2500415ae334a61b9b7a1f5b38f32b36",
"size": "489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tests/Unit Tests/SomeUnitTest.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "70"
},
{
"name": "Objective-C",
"bytes": "26283"
},
{
"name": "Shell",
"bytes": "2747"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.