code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2017 Bitergia # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA. # # Authors: # Santiago Dueñas <sduenas@bitergia.com> # import argparse import hashlib import importlib import json import logging import os import pkgutil import sys from datetime import datetime as dt from grimoirelab.toolkit.introspect import find_signature_parameters from grimoirelab.toolkit.datetime import str_to_datetime from .archive import Archive, ArchiveManager from .errors import ArchiveError from ._version import __version__ logger = logging.getLogger(__name__) ARCHIVES_DEFAULT_PATH = '~/.perceval/archives/' class Backend: """Abstract class for backends. Base class to fetch data from a repository. This repository will be named as 'origin'. During the initialization, an `Archive` object can be provided for archiving raw data from the repositories. Derivated classes have to implement `fetch_items`, `has_archiving` and `has_resuming` methods. Otherwise, `NotImplementedError` exception will be raised. Metadata decorator can be used together with fetch methods but requires the implementation of `metadata_id`, `metadata_updated_on` and `metadata_category` static methods. The fetched items can be tagged using the `tag` parameter. It will be useful to trace data. When it is set to `None` or to an empty string, the tag will be the same that the `origin` attribute. To track which version of the backend was used during the fetching process, this class provides a `version` attribute that each backend may override. :param origin: identifier of the repository :param tag: tag items using this label :param archive: archive to store/retrieve data :raises ValueError: raised when `archive` is not an instance of `Archive` class """ version = '0.6.0' def __init__(self, origin, tag=None, archive=None): self._origin = origin self.tag = tag if tag else origin self.archive = archive or None @property def origin(self): return self._origin @property def archive(self): return self._archive @archive.setter def archive(self, obj): if obj and not isinstance(obj, Archive): msg = "obj is not an instance of Archive. %s object given" \ % (str(type(obj))) raise ValueError(msg) self._archive = obj def fetch_items(self, **kwargs): raise NotImplementedError def fetch(self, category, **kwargs): """Fetch items from the repository. The method retrieves items from a repository. :param category: the category of the items fetched :param kwargs: a list of other parameters (e.g., from_date, offset, etc. specific for each backend) :returns: a generator of items """ if self.archive: self.archive.init_metadata(self.origin, self.__class__.__name__, self.version, category, kwargs) self.client = self._init_client() for item in self.fetch_items(**kwargs): yield self.metadata(item) def fetch_from_archive(self): """Fetch the questions from an archive. It returns the items stored within an archive. If this method is called but no archive was provided, the method will raise a `ArchiveError` exception. :returns: a generator of items :raises ArchiveError: raised when an error occurs accessing an archive """ if not self.archive: raise ArchiveError(cause="archive instance was not provided") self.client = self._init_client(from_archive=True) for item in self.fetch_items(**self.archive.backend_params): yield self.metadata(item) def metadata(self, item): """Add metadata to an item. It adds metadata to a given item such as how and when it was fetched. The contents from the original item will be stored under the 'data' keyword. :param item: an item fetched by a backend """ item = { 'backend_name': self.__class__.__name__, 'backend_version': self.version, 'perceval_version': __version__, 'timestamp': dt.utcnow().timestamp(), 'origin': self.origin, 'uuid': uuid(self.origin, self.metadata_id(item)), 'updated_on': self.metadata_updated_on(item), 'category': self.metadata_category(item), 'tag': self.tag, 'data': item, } return item @classmethod def has_archiving(cls): raise NotImplementedError @classmethod def has_resuming(cls): raise NotImplementedError @staticmethod def metadata_id(item): raise NotImplementedError @staticmethod def metadata_updated_on(item): raise NotImplementedError @staticmethod def metadata_category(item): raise NotImplementedError def _init_client(self, from_archive=False): raise NotImplementedError class BackendCommandArgumentParser: """Manage and parse backend command arguments. This class defines and parses a set of arguments common to backends commands. Some parameters like archive or the different types of authentication can be set during the initialization of the instance. :param from_date: set from_date argument :param to_date: set to_date argument :param offset: set offset argument :param basic_auth: set basic authentication arguments :param token_auth: set token/key authentication arguments :param archive: set archiving arguments :param aliases: define aliases for parsed arguments :raises AttributeArror: when both `from_date` and `offset` are set to `True` """ def __init__(self, from_date=False, to_date=False, offset=False, basic_auth=False, token_auth=False, archive=False, aliases=None): self._from_date = from_date self._to_date = to_date self._archive = archive self.aliases = aliases or {} self.parser = argparse.ArgumentParser() group = self.parser.add_argument_group('general arguments') group.add_argument('--category', dest='category', help="type of the items to fetch") group.add_argument('--tag', dest='tag', help="tag the items generated during the fetching process") if (from_date or to_date) and offset: raise AttributeError("date and offset parameters are incompatible") if from_date: group.add_argument('--from-date', dest='from_date', default='1970-01-01', help="fetch items updated since this date") if to_date: group.add_argument('--to-date', dest='to_date', help="fetch items updated before this date") if offset: group.add_argument('--offset', dest='offset', type=int, default=0, help="offset to start fetching items") if basic_auth or token_auth: self._set_auth_arguments(basic_auth=basic_auth, token_auth=token_auth) if archive: self._set_archive_arguments() self._set_output_arguments() def parse(self, *args): """Parse a list of arguments. Parse argument strings needed to run a backend command. The result will be a `argparse.Namespace` object populated with the values obtained after the validation of the parameters. :param args: argument strings :result: an object with the parsed values """ parsed_args = self.parser.parse_args(args) if self._from_date: parsed_args.from_date = str_to_datetime(parsed_args.from_date) if self._to_date and parsed_args.to_date: parsed_args.to_date = str_to_datetime(parsed_args.to_date) if self._archive and parsed_args.archived_since: parsed_args.archived_since = str_to_datetime(parsed_args.archived_since) if self._archive and parsed_args.fetch_archive and parsed_args.no_archive: raise AttributeError("fetch-archive and no-archive arguments are not compatible") if self._archive and parsed_args.fetch_archive and not parsed_args.category: raise AttributeError("fetch-archive needs a category to work with") # Set aliases for alias, arg in self.aliases.items(): if (alias not in parsed_args) and (arg in parsed_args): value = getattr(parsed_args, arg, None) setattr(parsed_args, alias, value) return parsed_args def _set_auth_arguments(self, basic_auth=True, token_auth=False): """Activate authentication arguments parsing""" group = self.parser.add_argument_group('authentication arguments') if basic_auth: group.add_argument('-u', '--backend-user', dest='user', help="backend user") group.add_argument('-p', '--backend-password', dest='password', help="backend password") if token_auth: group.add_argument('-t', '--api-token', dest='api_token', help="backend authentication token / API key") def _set_archive_arguments(self): """Activate archive arguments parsing""" group = self.parser.add_argument_group('archive arguments') group.add_argument('--archive-path', dest='archive_path', default=None, help="directory path to the archives") group.add_argument('--no-archive', dest='no_archive', action='store_true', help="do not archive data") group.add_argument('--fetch-archive', dest='fetch_archive', action='store_true', help="fetch data from the archives") group.add_argument('--archived-since', dest='archived_since', default='1970-01-01', help="retrieve items archived since the given date") def _set_output_arguments(self): """Activate output arguments parsing""" group = self.parser.add_argument_group('output arguments') group.add_argument('-o', '--output', type=argparse.FileType('w'), dest='outfile', default=sys.stdout, help="output file") class BackendCommand: """Abstract class to run backends from the command line. When the class is initialized, it parses the given arguments using the defined argument parser on `setump_cmd_parser` method. Those arguments will be stored in the attribute `parsed_args`. The arguments will be used to inizialize and run the `Backend` object assigned to this command. The backend used to run the command is stored under `BACKEND` class attributed. Any class derived from this and must set its own `Backend` class. Moreover, the method `setup_cmd_parser` must be implemented to exectute the backend. """ BACKEND = None def __init__(self, *args): parser = self.setup_cmd_parser() self.parsed_args = parser.parse(*args) self.archive_manager = None self._pre_init() self._initialize_archive() self._post_init() self.outfile = self.parsed_args.outfile def run(self): """Fetch and write items. This method runs the backend to fetch the items from the given origin. Items are converted to JSON objects and written to the defined output. If `fetch-archive` parameter was given as an argument during the inizialization of the instance, the items will be retrieved using the archive manager. """ backend_args = vars(self.parsed_args) if self.archive_manager and self.parsed_args.fetch_archive: items = fetch_from_archive(self.BACKEND, backend_args, self.archive_manager, self.parsed_args.category, self.parsed_args.archived_since) else: items = fetch(self.BACKEND, backend_args, manager=self.archive_manager) try: for item in items: obj = json.dumps(item, indent=4, sort_keys=True) self.outfile.write(obj) self.outfile.write('\n') except IOError as e: raise RuntimeError(str(e)) except Exception as e: raise RuntimeError(str(e)) def _pre_init(self): """Override to execute before backend is initialized.""" pass def _post_init(self): """Override to execute after backend is initialized.""" pass def _initialize_archive(self): """Initialize archive based on the parsed parameters""" if 'archive_path' not in self.parsed_args: manager = None elif self.parsed_args.no_archive: manager = None else: if not self.parsed_args.archive_path: archive_path = os.path.expanduser(ARCHIVES_DEFAULT_PATH) else: archive_path = self.parsed_args.archive_path manager = ArchiveManager(archive_path) self.archive_manager = manager @staticmethod def setup_cmd_parser(): raise NotImplementedError def uuid(*args): """Generate a UUID based on the given parameters. The UUID will be the SHA1 of the concatenation of the values from the list. The separator bewteedn these values is ':'. Each value must be a non-empty string, otherwise, the function will raise an exception. :param *args: list of arguments used to generate the UUID :returns: a universal unique identifier :raises ValueError: when anyone of the values is not a string, is empty or `None`. """ def check_value(v): if not isinstance(v, str): raise ValueError("%s value is not a string instance" % str(v)) elif not v: raise ValueError("value cannot be None or empty") else: return v s = ':'.join(map(check_value, args)) sha1 = hashlib.sha1(s.encode('utf-8', errors='surrogateescape')) uuid_sha1 = sha1.hexdigest() return uuid_sha1 def fetch(backend_class, backend_args, manager=None): """Fetch items using the given backend. Generator to get items using the given backend class. When an archive manager is given, this function will store the fetched items in an `Archive`. If an exception is raised, this archive will be removed to avoid corrupted archives. The parameters needed to initialize the `backend` class and get the items are given using `backend_args` dict parameter. :param backend_class: backend class to fetch items :param backend_args: dict of arguments needed to fetch the items :param manager: archive manager needed to store the items :returns: a generator of items """ init_args = find_signature_parameters(backend_class.__init__, backend_args) archive = manager.create_archive() if manager else None init_args['archive'] = archive backend = backend_class(**init_args) fetch_args = find_signature_parameters(backend.fetch, backend_args) items = backend.fetch(**fetch_args) try: for item in items: yield item except Exception as e: if manager: archive_path = archive.archive_path manager.remove_archive(archive_path) raise e def fetch_from_archive(backend_class, backend_args, manager, category, archived_after): """Fetch items from an archive manager. Generator to get the items of a category (previously fetched by the given backend class) from an archive manager. Only those items archived after the given date will be returned. The parameters needed to initialize `backend` and get the items are given using `backend_args` dict parameter. :param backend_class: backend class to retrive items :param backend_args: dict of arguments needed to retrieve the items :param manager: archive manager where the items will be retrieved :param category: category of the items to retrieve :param archived_after: return items archived after this date :returns: a generator of archived items """ init_args = find_signature_parameters(backend_class.__init__, backend_args) backend = backend_class(**init_args) filepaths = manager.search(backend.origin, backend.__class__.__name__, category, archived_after) for filepath in filepaths: backend.archive = Archive(filepath) items = backend.fetch_from_archive() try: for item in items: yield item except ArchiveError as e: logger.warning("Ignoring %s archive due to: %s", filepath, str(e)) def find_backends(top_package): """Find available backends. Look for the Perceval backends and commands under `top_package` and its sub-packages. When `top_package` defines a namespace, backends under that same namespace will be found too. :param top_package: package storing backends :returns: a tuple with two dicts: one with `Backend` classes and one with `BackendCommand` classes """ candidates = pkgutil.walk_packages(top_package.__path__, prefix=top_package.__name__ + '.') modules = [name for _, name, is_pkg in candidates if not is_pkg] return _import_backends(modules) def _import_backends(modules): for module in modules: importlib.import_module(module) bkls = _find_classes(Backend, modules) ckls = _find_classes(BackendCommand, modules) backends = {name: kls for name, kls in bkls} commands = {name: klass for name, klass in ckls} return backends, commands def _find_classes(parent, modules): parents = parent.__subclasses__() while parents: kls = parents.pop() m = kls.__module__ if m not in modules: continue name = m.split('.')[-1] parents.extend(kls.__subclasses__()) yield name, kls
sduenas/perceval
perceval/backend.py
Python
gpl-3.0
19,497
package com.earth2me.essentials; import net.ess3.api.IEssentials; import net.ess3.api.IUser; import org.bukkit.Location; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import java.util.UUID; import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; public class AsyncTimedTeleport implements Runnable { private static final double MOVE_CONSTANT = 0.3; private final IUser teleportOwner; private final IEssentials ess; private final AsyncTeleport teleport; private final UUID timer_teleportee; private final long timer_started; // time this task was initiated private final long timer_delay; // how long to delay the teleportPlayer private final CompletableFuture<Boolean> parentFuture; // note that I initially stored a clone of the location for reference, but... // when comparing locations, I got incorrect mismatches (rounding errors, looked like) // so, the X/Y/Z values are stored instead and rounded off private final long timer_initX; private final long timer_initY; private final long timer_initZ; private final ITarget timer_teleportTarget; private final boolean timer_respawn; private final boolean timer_canMove; private final Trade timer_chargeFor; private final TeleportCause timer_cause; private int timer_task; private double timer_health; AsyncTimedTeleport(final IUser user, final IEssentials ess, final AsyncTeleport teleport, final long delay, final IUser teleportUser, final ITarget target, final Trade chargeFor, final TeleportCause cause, final boolean respawn) { this(user, ess, teleport, delay, null, teleportUser, target, chargeFor, cause, respawn); } AsyncTimedTeleport(final IUser user, final IEssentials ess, final AsyncTeleport teleport, final long delay, final CompletableFuture<Boolean> future, final IUser teleportUser, final ITarget target, final Trade chargeFor, final TeleportCause cause, final boolean respawn) { this.teleportOwner = user; this.ess = ess; this.teleport = teleport; this.timer_started = System.currentTimeMillis(); this.timer_delay = delay; this.timer_health = teleportUser.getBase().getHealth(); this.timer_initX = Math.round(teleportUser.getBase().getLocation().getX() * MOVE_CONSTANT); this.timer_initY = Math.round(teleportUser.getBase().getLocation().getY() * MOVE_CONSTANT); this.timer_initZ = Math.round(teleportUser.getBase().getLocation().getZ() * MOVE_CONSTANT); this.timer_teleportee = teleportUser.getBase().getUniqueId(); this.timer_teleportTarget = target; this.timer_chargeFor = chargeFor; this.timer_cause = cause; this.timer_respawn = respawn; this.timer_canMove = user.isAuthorized("essentials.teleport.timer.move"); timer_task = ess.runTaskTimerAsynchronously(this, 20, 20).getTaskId(); if (future != null) { this.parentFuture = future; return; } final CompletableFuture<Boolean> cFuture = new CompletableFuture<>(); cFuture.exceptionally(e -> { ess.showError(teleportOwner.getSource(), e, "\\ teleport"); return false; }); this.parentFuture = cFuture; } @Override public void run() { if (teleportOwner == null || !teleportOwner.getBase().isOnline() || teleportOwner.getBase().getLocation() == null) { cancelTimer(false); return; } final IUser teleportUser = ess.getUser(this.timer_teleportee); if (teleportUser == null || !teleportUser.getBase().isOnline()) { cancelTimer(false); return; } final Location currLocation = teleportUser.getBase().getLocation(); if (currLocation == null) { cancelTimer(false); return; } if (!timer_canMove && (Math.round(currLocation.getX() * MOVE_CONSTANT) != timer_initX || Math.round(currLocation.getY() * MOVE_CONSTANT) != timer_initY || Math.round(currLocation.getZ() * MOVE_CONSTANT) != timer_initZ || teleportUser.getBase().getHealth() < timer_health)) { // user moved, cancelTimer teleportPlayer cancelTimer(true); return; } class DelayedTeleportTask implements Runnable { @Override public void run() { timer_health = teleportUser.getBase().getHealth(); // in case user healed, then later gets injured final long now = System.currentTimeMillis(); if (now > timer_started + timer_delay) { try { teleport.cooldown(false); } catch (final Throwable ex) { teleportOwner.sendMessage(tl("cooldownWithMessage", ex.getMessage())); if (teleportOwner != teleportUser) { teleportUser.sendMessage(tl("cooldownWithMessage", ex.getMessage())); } } try { cancelTimer(false); teleportUser.sendMessage(tl("teleportationCommencing")); if (timer_chargeFor != null) { timer_chargeFor.isAffordableFor(teleportOwner); } if (timer_respawn) { teleport.respawnNow(teleportUser, timer_cause, parentFuture); } else { teleport.nowAsync(teleportUser, timer_teleportTarget, timer_cause, parentFuture); } parentFuture.thenAccept(success -> { if (timer_chargeFor != null) { try { timer_chargeFor.charge(teleportOwner); } catch (final ChargeException ex) { ess.showError(teleportOwner.getSource(), ex, "\\ teleport"); } } }); } catch (final Exception ex) { ess.showError(teleportOwner.getSource(), ex, "\\ teleport"); } } } } ess.scheduleSyncDelayedTask(new DelayedTeleportTask()); } //If we need to cancelTimer a pending teleportPlayer call this method void cancelTimer(final boolean notifyUser) { if (timer_task == -1) { return; } try { ess.getServer().getScheduler().cancelTask(timer_task); if (notifyUser) { teleportOwner.sendMessage(tl("pendingTeleportCancelled")); if (timer_teleportee != null && !timer_teleportee.equals(teleportOwner.getBase().getUniqueId())) { ess.getUser(timer_teleportee).sendMessage(tl("pendingTeleportCancelled")); } } } finally { timer_task = -1; } } }
drtshock/Essentials
Essentials/src/main/java/com/earth2me/essentials/AsyncTimedTeleport.java
Java
gpl-3.0
7,164
#!/usr/bin/env python from __future__ import print_function from glob import glob from tempfile import NamedTemporaryFile import sys from alibuild_helpers.log import debug, error, info from os import remove from alibuild_helpers.utilities import format from alibuild_helpers.cmd import execute from alibuild_helpers.utilities import detectArch from alibuild_helpers.utilities import parseRecipe, getRecipeReader def deps(recipesDir, topPackage, outFile, buildRequires, transitiveRed, disable): dot = {} keys = [ "requires" ] if buildRequires: keys.append("build_requires") for p in glob("%s/*.sh" % recipesDir): debug(format("Reading file %(filename)s", filename=p)) try: err, recipe, _ = parseRecipe(getRecipeReader(p)) name = recipe["package"] if name in disable: debug("Ignoring %s, disabled explicitly" % name) continue except Exception as e: error(format("Error reading recipe %(filename)s: %(type)s: %(msg)s", filename=p, type=type(e).__name__, msg=str(e))) sys.exit(1) dot[name] = dot.get(name, []) for k in keys: for d in recipe.get(k, []): d = d.split(":")[0] d in disable or dot[name].append(d) selected = None if topPackage != "all": if not topPackage in dot: error(format("Package %(topPackage)s does not exist", topPackage=topPackage)) return False selected = [ topPackage ] olen = 0 while len(selected) != olen: olen = len(selected) selected += [ x for s in selected if s in dot for x in dot[s] if not x in selected ] selected.sort() result = "digraph {\n" for p,deps in list(dot.items()): if selected and not p in selected: continue result += " \"%s\";\n" % p for d in deps: result += " \"%s\" -> \"%s\";\n" % (p,d) result += "}\n" with NamedTemporaryFile(delete=False) as fp: fp.write(result) try: if transitiveRed: execute(format("tred %(dotFile)s > %(dotFile)s.0 && mv %(dotFile)s.0 %(dotFile)s", dotFile=fp.name)) execute(["dot", fp.name, "-Tpdf", "-o", outFile]) except Exception as e: error(format("Error generating dependencies with dot: %(type)s: %(msg)s", type=type(e).__name__, msg=str(e))) else: info(format("Dependencies graph generated: %(outFile)s", outFile=outFile)) remove(fp.name) return True def depsArgsParser(parser): parser.add_argument("topPackage") parser.add_argument("-a", "--architecture", help="force architecture", dest="architecture", default=detectArch()) parser.add_argument("--dist", dest="distDir", default="alidist", help="Recipes directory") parser.add_argument("--output-file", "-o", dest="outFile", default="dist.pdf", help="Output file (PDF format)") parser.add_argument("--debug", "-d", dest="debug", action="store_true", default=False, help="Debug output") parser.add_argument("--build-requires", "-b", dest="buildRequires", action="store_true", default=False, help="Debug output") parser.add_argument("--neat", dest="neat", action="store_true", default=False, help="Neat graph with transitive reduction") parser.add_argument("--disable", dest="disable", default=[], help="List of packages to ignore") return parser
dberzano/alibuild
alibuild_helpers/deps.py
Python
gpl-3.0
3,451
QUnit.test( "TestDate", function( assert ) { var converter = new DataTypeConverter(); var value = "CAF 92"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.TEXT, "Text /" + value + "/ correctly recognized."); var value = "2023-04"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "2016-03-07"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "02600"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.TEXT, "Text /" + value + "/ correctly recognized."); var value = "0"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.NUMBER, "Text /" + value + "/ correctly recognized."); var value = "02/03/2016 18:57"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "02/03/2016"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "2016-03-07T11:26:17+00:00"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "92077-02"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.TEXT, "Text /" + value + "/ correctly recognized."); var value = "1936.27"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.NUMBER, "Text /" + value + "/ correctly recognized."); var value = "50/50/2016"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.TEXT, "Text /" + value + "/ correctly recognized."); var value = "02/13/2016"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "12/26/2016"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "1/1/2016"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "01/1/2016"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "01/1/250"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "520/12/1"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "520/12"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.DATETIME, "Text /" + value + "/ correctly recognized."); var value = "520/50"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.TEXT, "Text /" + value + "/ correctly recognized."); /*var value = "1936,27"; var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.NUMBER, "Text /" + value + "/ correctly recognized.");*/ }); QUnit.test("TestIsPercentage", function (assert) { var converter = new DataTypeConverter(); var value = "5%"; var isperc = DataTypesUtils.FilterPercentage(value); assert.ok(isperc, value + " recognized."); var dt = converter.inferDataTypeOfValue(value); assert.equal(dt.type, DataTypeConverter.TYPES.NUMBER, "Text /" + value + "/ correctly recognized."); assert.equal(dt.subtype, DataTypeConverter.TYPES.PERCENTAGE, "Text /" + value + "/ correctly recognized."); var value = "5 %"; var isperc = DataTypesUtils.FilterPercentage(value); assert.ok(isperc, value + " recognized."); assert.equal(dt.type, DataTypeConverter.TYPES.NUMBER, "Text /" + value + "/ correctly recognized."); assert.equal(dt.subtype, DataTypeConverter.TYPES.PERCENTAGE, "Text /" + value + "/ correctly recognized."); var value = "%5%"; var isperc = DataTypesUtils.FilterPercentage(value); assert.equal(isperc, null, value + " recognized."); var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.TEXT, "Text /" + value + "/ correctly recognized."); var value = "%"; var isperc = DataTypesUtils.FilterPercentage(value); assert.equal(isperc, null, value + " recognized."); var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.TEXT, "Text /" + value + "/ correctly recognized."); var value = "%5"; var isperc = DataTypesUtils.FilterPercentage(value); assert.equal(isperc, null, value + " recognized."); var dt = converter.inferDataTypeOfValue(value); assert.equal(dt, DataTypeConverter.TYPES.TEXT, "Text /" + value + "/ correctly recognized."); }); QUnit.test("TestIsNumber", function(assert) { var converter = new DataTypeConverter(); var value = "1936"; var isnumber = DataTypesUtils.FilterNumber(value); assert.ok(isnumber, value + " recognized."); var dt = converter.inferDataSubTypeOfValue(value); assert.equal(dt, DataTypeConverter.SUBTYPES.NUMINTEGER, "Text /" + value + "/ correctly recognized."); var value = "1936.27"; var isnumber = DataTypesUtils.FilterNumber(value); assert.ok(isnumber, value + " recognized."); var dt = converter.inferDataSubTypeOfValue(value); assert.equal(dt, DataTypeConverter.SUBTYPES.NUMREAL, "Text /" + value + "/ correctly recognized."); var value = "-1936.27"; var isnumber = DataTypesUtils.FilterNumber(value); assert.ok(isnumber, value + " recognized."); var dt = converter.inferDataSubTypeOfValue(value); assert.equal(dt, DataTypeConverter.SUBTYPES.NUMREAL, "Text /" + value + "/ correctly recognized."); var value = "+1936.27"; var isnumber = DataTypesUtils.FilterNumber(value); assert.ok(isnumber, value + " recognized."); var dt = converter.inferDataSubTypeOfValue(value); assert.equal(dt, DataTypeConverter.SUBTYPES.NUMREAL, "Text /" + value + "/ correctly recognized."); var value = "1936,27"; var isnumber = DataTypesUtils.FilterNumber(value); assert.ok(isnumber, value + " recognized."); var dt = converter.inferDataSubTypeOfValue(value); assert.equal(dt, DataTypeConverter.SUBTYPES.NUMREAL, "Text /" + value + "/ correctly recognized."); var value = "-1936,27"; var isnumber = DataTypesUtils.FilterNumber(value); assert.ok(isnumber, value + " recognized."); var dt = converter.inferDataSubTypeOfValue(value); assert.equal(dt, DataTypeConverter.SUBTYPES.NUMREAL, "Text /" + value + "/ correctly recognized."); var value = "+1936,27"; var isnumber = DataTypesUtils.FilterNumber(value); assert.ok(isnumber, value + " recognized."); var dt = converter.inferDataSubTypeOfValue(value); assert.equal(dt, DataTypeConverter.SUBTYPES.NUMREAL, "Text /" + value + "/ correctly recognized."); var value = "1.936.27"; var isnumber = DataTypesUtils.FilterNumber(value); assert.notOk(isnumber, value + " recognized."); var value = "1,936,27"; var isnumber = DataTypesUtils.FilterNumber(value); assert.notOk(isnumber, value + " recognized."); var value = "1.936,27"; var isnumber = DataTypesUtils.FilterNumber(value); assert.notOk(isnumber, value + " recognized."); var value = "1,936.27"; var isnumber = DataTypesUtils.FilterNumber(value); assert.notOk(isnumber, value + " recognized."); var value = "1936."; var isnumber = DataTypesUtils.FilterNumber(value); assert.notOk(isnumber, value + " recognized."); var value = "1936,"; var isnumber = DataTypesUtils.FilterNumber(value); assert.notOk(isnumber, value + " recognized."); var value = "1936,07"; var isnumber = DataTypesUtils.FilterNumber(value); assert.ok(isnumber, value + " recognized."); var dt = converter.inferDataSubTypeOfValue(value); assert.equal(dt, DataTypeConverter.SUBTYPES.NUMREAL, "Text /" + value + "/ correctly recognized."); });
donpir/JSDataChecker
tests/TestCase01_InferDataTypeOnSingleValue/DataTypeSingleValueTestCase.js
JavaScript
gpl-3.0
8,748
#include <iostream> #include <vector> #include <cmath> #include <fstream> #include "utils.h" using namespace std; using namespace Eigen; double euclidean_dist(Point2d p, Point2d q) { return sqrt((q.x-p.x)*(q.x-p.x) + (q.y-p.y)*(q.y-p.y)); } double angle_two_points(Point2d p, Point2d q) { double theta; double dot, pnorm, qnorm; dot = p.x * q.x + p.y * q.y; pnorm = sqrt(p.x * p.x + p.y * p.y); qnorm = sqrt(q.x * q.x + q.y * q.y); theta = acos(dot/(pnorm*qnorm)); return theta * 180.0 / PI; } double min_function(double p, double q){ if(p <= q) { return p; } else return q; } double max_function(double p, double q){ if(p >= q) { return p; } else return q; } bool read_points(string fname, vector<Point> &points){ ifstream input(fname.c_str()); int x, y, size = 0, i; if(!input){ cerr << "The file could not be opened! (Utils)" << endl; return false; } while(input >> x >> y){ size++; } points.resize(size); input.clear(); input.seekg(0, ios::beg); for(i = 0; i < size; ++i){ input >> points[i].x >> points[i].y; } return true; } pair<Matrix3d, Vector3d> kalman_filter(Vector3d pos_cam, Vector2d v_w, Vector3d last_pos , double dt, Matrix3d last_P){ double v = 1.14 * v_w[0], w = 1.14 * v_w[1], ds = v * dt, dw = w * dt; double b = 0.055; //Distância entre eixos do carrinho 'CHECK' double dsr = ds + (b*dw)/2, dsl = ds - (b*dw)/2; double kr = 9, kl = 9; Vector3d prediction, pos_predicted, pos_current; Matrix2d covar; Matrix3d P = last_P, C, R, I, fp, P_predicted, K; MatrixXd fdrl(3, 2), inv; pair<Matrix3d, Vector3d> res; C = MatrixXd::Identity(3,3); I = MatrixXd::Identity(3,3); R << 0,0 ,0 , 0 ,0,0 , 0 ,0 ,6.14071137584 ; //6.14071137584 estava no lugar do 6 a matrix R 9.23765359168e-07 7.93803166352e-07 //Kalman Extended prediction << ds*cos((last_pos(2,0)+dw/2)*PI/180), ds*sin((last_pos(2,0)+dw/2)*PI/180), dw; pos_predicted = last_pos + prediction; covar << kr*abs(dsr),0 , 0 ,kl*abs(dsl); fp << 1, 0, -ds*sin((last_pos(2,0)+dw/2)*PI/180), 0, 1, ds*cos((last_pos(2,0)+dw/2)*PI/180) , 0, 0, 1 ; fdrl << (1/2)*cos((last_pos(2,0)+dw/2)*PI/180)-ds/(2*b)*sin((last_pos(2,0)+dw/2)*PI/180), (1/2)*cos((last_pos(2,0)+dw/2)*PI/180)+ds/(2*b)*sin((last_pos(2,0)+dw/2)*PI/180), (1/2)*sin((last_pos(2,0)+dw/2)*PI/180)+ds/(2*b)*cos((last_pos(2,0)+dw/2)*PI/180), (1/2)*sin((last_pos(2,0)+dw/2)*PI/180)-ds/(2*b)*cos((last_pos(2,0)+dw/2)*PI/180), 1/b , -1/b ; P_predicted = (fp * P * fp.transpose()) + (fdrl * covar * fdrl.transpose()); inv = C * P_predicted * C.transpose() + R; K = P_predicted * C.transpose() * inv.inverse(); pos_current = pos_predicted + K * (pos_cam - C * pos_predicted); P = (I - K * C) * P_predicted; res.first = P; res.second = pos_current; return res; } vector<int> hsv2rgb(vector<int> in) { double hh, p, q, t, ff; long i; vector<int> out(3); if(in[1] <= 0.0) { // < is bogus, just shuts up warnings out[0] = in[2]; out[1] = in[2]; out[2] = in[2]; return out; } hh = in[0]; if(hh >= 360.0) hh = 0.0; hh /= 60.0; i = (long)hh; ff = hh - i; p = in[2] * (1.0 - in[1]); q = in[2] * (1.0 - (in[1] * ff)); t = in[2] * (1.0 - (in[1] * (1.0 - ff))); switch(i) { case 0: out[0] = in[2]; out[1] = t; out[2] = p; break; case 1: out[0] = q; out[1] = in[2]; out[2] = p; break; case 2: out[0] = p; out[1] = in[2]; out[2] = t; break; case 3: out[0] = p; out[1] = q; out[2] = in[2]; break; case 4: out[0] = t; out[1] = p; out[2] = in[2]; break; case 5: default: out[0] = in[2]; out[1] = p; out[2] = q; break; } //cout << out[0] << " " << out[1] << " " << out[2] << endl; return out; } bool sort_by_smallest_x(Point a, Point b){ return a.x < b.x; } bool sort_by_smallest_y(Point a, Point b){ return a.y < b.y; } bool sort_by_largest_x(Point a, Point b){ return a.x > b.x; } bool sort_by_largest_y(Point a, Point b){ return a.y > b.y; } bool sort_by_larger_area(vector<Point> p0, vector<Point> p1) { if(p0.size() == 0 || p1.size() == 0) return false; return contourArea(p0) < contourArea(p1); } bool area_limit(vector<Point> p){ if(contourArea(p) < MIN_ROBOT_AREA || contourArea(p) > MAX_ROBOT_AREA){ return 1; } return 0; } bool ball_area_limit(vector<Point> p){ if(contourArea(p) > MAX_BALL_AREA){ return 1; } return 0; } pair <double, double> Low_pass_filter_coeff (float cutoff) { pair <double, double> coeff; double a; double b; a = ( 1 - sin(cutoff) ) / cos(cutoff); b = ( 1 - a)/2; coeff.first = a; coeff.second = b; return coeff; } Point Low_pass_filter_Centroid(Point centroid, Point last_centroid, Point last_proc_centroid, pair<double, double> coeff) { double x; double y; x = coeff.second * centroid.x + coeff.second * last_centroid.x + coeff.first * last_proc_centroid.x; y = coeff.second * centroid.y + coeff.second * last_centroid.y + coeff.first * last_proc_centroid.y; Point centroid_proc = Point(x, y); return centroid_proc; } double Low_pass_filter_Theta(double angle, double last_angle, double last_proc_angle, pair<double, double> coeff) { return coeff.second * angle + coeff.second * last_angle + coeff.first * last_proc_angle; }
mateus558/RinoBot-System
utils.cpp
C++
gpl-3.0
6,141
/* * Copyright (c) 2015 OpenSilk Productions LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opensilk.music.library.client; import android.content.Context; import android.database.ContentObserver; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import org.opensilk.bundleable.Bundleable; import org.opensilk.common.core.dagger2.ForApplication; import org.opensilk.common.core.rx.RxLoader; import org.opensilk.common.core.util.Preconditions; import org.opensilk.music.library.internal.IBundleableObserver; import org.opensilk.music.library.provider.LibraryExtras; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import timber.log.Timber; import static org.opensilk.music.library.provider.LibraryMethods.LIST; /** * Created by drew on 9/28/15. */ public class TypedBundleableLoader<T extends Bundleable> implements RxLoader<T> { class UriObserver extends ContentObserver { UriObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { reset(); for (ContentChangedListener l : contentChangedListeners) { l.reload(); } } @Override public void onChange(boolean selfChange, Uri uri) { onChange(selfChange); } } private final Set<ContentChangedListener> contentChangedListeners = new LinkedHashSet<>(); private final Context context; private Uri uri; private String sortOrder; private String method = LIST; private Scheduler observeOnScheduler = AndroidSchedulers.mainThread(); private UriObserver uriObserver; private Observable<List<T>> cachedObservable; @Inject public TypedBundleableLoader(@ForApplication Context context) { this.context = context; } public static <T extends Bundleable> TypedBundleableLoader<T> create(Context context) { return new TypedBundleableLoader<>(context.getApplicationContext()); } public Observable<List<T>> getListObservable() { registerContentObserver(); //The reason we cache it is for layout changes if (cachedObservable == null) { cachedObservable = createObservable() .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { reset(); dump(throwable); } }) .observeOn(observeOnScheduler) .cache(); } return cachedObservable; } public Observable<T> getObservable() { return getListObservable().flatMap(new Func1<List<T>, Observable<T>>() { @Override public Observable<T> call(List<T> bundleables) { return Observable.from(bundleables); } }); } public Observable<List<T>> createObservable() { return Observable.using( new Func0<LibraryClient>() { @Override public LibraryClient call() { //We use a client to help ensure the provider //wont disappear while sending us the list return LibraryClient.create(context, uri); } }, new Func1<LibraryClient, Observable<? extends List<T>>>() { @Override public Observable<? extends List<T>> call(final LibraryClient libraryClient) { return Observable.create(new Observable.OnSubscribe<List<T>>() { @Override public void call(final Subscriber<? super List<T>> subscriber) { IBundleableObserver callback = new BundleableObserver<T>(subscriber); LibraryExtras.Builder extras = LibraryExtras.b() .putUri(uri) .putSortOrder(sortOrder) .putBundleableObserverCallback(callback); Bundle ok = libraryClient.makeCall(method, extras.get()); if (!LibraryExtras.getOk(ok)) { subscriber.onError(LibraryExtras.getCause(ok)); } } }); } }, new Action1<LibraryClient>() { @Override public void call(LibraryClient libraryClient) { libraryClient.release(); } }, true //We may not receive an unsubscribe ); } public void reset() { cachedObservable = null; } protected void registerContentObserver() { if (uriObserver == null) { uriObserver = new UriObserver(new Handler(Looper.getMainLooper())); context.getContentResolver().registerContentObserver(uri, true, uriObserver); } } public void addContentChangedListener(ContentChangedListener l) { contentChangedListeners.add(l); } public void removeContentChangedListener(ContentChangedListener l) { contentChangedListeners.remove(l); } public TypedBundleableLoader<T> setUri(Uri uri) { this.uri = uri; return this; } public TypedBundleableLoader<T> setSortOrder(String sortOrder) { this.sortOrder = sortOrder; return this; } public TypedBundleableLoader<T> setMethod(String method) { this.method = method; return this; } public TypedBundleableLoader<T> setObserveOnScheduler(Scheduler scheduler) { this.observeOnScheduler = Preconditions.checkNotNull(scheduler, "Scheduler must not be null"); return this; } protected void emmitError(Throwable t, Subscriber<? super Bundleable> subscriber) { if (subscriber.isUnsubscribed()) return; subscriber.onError(t); dump(t); } protected void dump(Throwable throwable) { Timber.e(throwable, "BundleableLoader(\nuri=%s\nsortOrder=%s\n) ex=", uri, sortOrder); } }
OpenSilk/Orpheus
core-library-client/src/main/java/org/opensilk/music/library/client/TypedBundleableLoader.java
Java
gpl-3.0
7,305
/** * This software is provided by NOAA for full, free and open release. It is * understood by the recipient/user that NOAA assumes no liability for any * errors contained in the code. Although this software is released without * conditions or restrictions in its use, it is expected that appropriate * credit be given to its author and to the National Oceanic and Atmospheric * Administration should the software be included by the recipient as an * element in other product development. */ package ncBrowse.sgt.dm; import ncBrowse.sgt.SGLabel; import ncBrowse.sgt.geom.GeoDate; import ncBrowse.sgt.geom.SoTPoint; import ncBrowse.sgt.geom.SoTRange; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; /** * <code>SimplePoint</code> provides an implementation of the * <code>SGTPoint</code> and <code>Cartesian</code> interfaces. * * @author Donald Denbo * @version $Revision: 1.14 $, $Date: 2003/08/22 23:02:38 $ * @since 1.0 * @see SGTPoint * @see Cartesian */ public class SimplePoint implements SGTPoint, Cartesian, Cloneable, Serializable { protected double xloc_ = Double.NaN; protected double yloc_ = Double.NaN; protected long tloc_; protected boolean xTime_ = false; protected boolean yTime_ = false; protected double value_; protected String title_; protected SGLabel keyTitle_ = null; protected String id_ = null; /**@shapeType AggregationLink * @clientRole value*/ protected SGTMetaData valueMetaData_; /** * @link aggregation * @clientRole x */ protected SGTMetaData xMetaData_; /** * @link aggregation * @clientRole y*/ protected SGTMetaData yMetaData_; protected boolean hasValue_ = false; private PropertyChangeSupport changes_ = new PropertyChangeSupport(this); /** * Default constructor. */ public SimplePoint() { } /** * Simple Point constructor. * * @param xloc X coordinate * @param yloc Y coordinate * @param title the title */ public SimplePoint(double xloc,double yloc,String title) { xloc_ = xloc; yloc_ = yloc; title_ = title; } /** * Simple Point constructor. * * @since 3.0 * * @param loc SoTPoint * @param title the title */ public SimplePoint(SoTPoint loc, String title) { xTime_ = loc.isXTime(); yTime_ = loc.isYTime(); if(xTime_) { tloc_ = loc.getX().getLongTime(); } else { xloc_ = ((Number)loc.getX().getObjectValue()).doubleValue(); } if(yTime_) { tloc_ = loc.getY().getLongTime(); } else { yloc_ = ((Number)loc.getY().getObjectValue()).doubleValue(); } title_ = title; } /** * Create a copy. * * @since 2.0 * @see SGTData */ public SGTData copy() { SGTPoint newPoint; try { newPoint = (SGTPoint)clone(); } catch (CloneNotSupportedException e) { newPoint = new SimplePoint(); } return newPoint; } /** * Get the X coordinate. */ public double getX() { return xloc_; } /** * Get the Y coordinate */ public double getY() { return yloc_; } /** * Get the associated value. */ public double getValue() { return value_; } /** * Is there an associated value? */ public boolean hasValue() { return hasValue_; } /** * Get the time coordinate. */ public GeoDate getTime() { return new GeoDate(tloc_); } /** * Get the time in <code>long</code> referenced * to 1970-01-01 * * @since 3.0 */ public long getLongTime() { return tloc_; } /** * Set the time coordinate * * @since 3.0 */ public void setTime(GeoDate date) { setTime(date.getTime()); } /** * @since 3.0 */ public void setTime(long t) { long old = tloc_; tloc_ = t; changes_.firePropertyChange("dataModified", old, tloc_); } /** * Is the X coordinate Time? */ public boolean isXTime() { return xTime_; } /** * Is the Y coordinate Time? */ public boolean isYTime() { return yTime_; } /** * Get the title. */ public String getTitle() { return title_; } /** * Set the title. */ public void setTitle(String title) { title_ = title; } public SGLabel getKeyTitle() { return keyTitle_; } /** Set the title formatted for the <code>VectorKey</code>. */ public void setKeyTitle(SGLabel title) { keyTitle_ = title; } /** * Get the unique identifier. The presence of the identifier * is optional, but if it is present it should be unique. This * field is used to search for the layer that contains the data. * * @since 2.0 * @return unique identifier * @see ncBrowse.sgt.Pane * @see ncBrowse.sgt.Layer */ public String getId() { return id_; } /** * Set the unique identifier. */ public void setId(String ident) { id_ = ident; } /** * Get the associated value SGTMetaData. */ public SGTMetaData getValueMetaData() { return valueMetaData_; } /** * Set the X coordinate. * <BR><B>Property Change:</B> <code>dataModified</code>. */ public void setX(double xloc) { double old = xloc_; xloc_ = xloc; changes_.firePropertyChange("dataModified", old, xloc_); } /** * Set the Y coordinate. * <BR><B>Property Change:</B> <code>dataModified</code>. */ public void setY(double yloc) { double old = yloc_; yloc_ = yloc; changes_.firePropertyChange("dataModified", old, yloc_); } /** * The the associated value and basic metadata. * <BR><B>Property Change:</B> <code>associatedDataModified</code>. * * @param value associated data * @param name values name * @param units values units */ public void setValue(double value,String name,String units) { double old = value_; value_ = value; valueMetaData_ = new SGTMetaData(name, units); hasValue_ = true; changes_.firePropertyChange("associatedDataModified", old, value_); } /** * Set the <code>SGTMetaData</code> associated with the x * coordinate * * @since 2.0 */ public void setXMetaData(SGTMetaData md) { xMetaData_ = md; } /** * Set the <code>SGTMetaData</code> associated with the y * coordinate * * @since 2.0 */ public void setYMetaData(SGTMetaData md) { yMetaData_ = md; } public SGTMetaData getXMetaData() { return xMetaData_; } public SGTMetaData getYMetaData() { return yMetaData_; } public SoTRange getXRange() { if(xTime_) { return new SoTRange.Time(tloc_, tloc_); } else { return new SoTRange.Double(xloc_, xloc_); } } public SoTRange getYRange() { if(yTime_) { return new SoTRange.Time(tloc_, tloc_); } else { return new SoTRange.Double(yloc_, yloc_); } } public void addPropertyChangeListener(PropertyChangeListener l) { changes_.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { changes_.removePropertyChangeListener(l); } }
MaxwellM/ncBrowse-revamp-CAPSTONE
src/ncBrowse/sgt/dm/SimplePoint.java
Java
gpl-3.0
7,850
<?php /** * @version $Id: openbay.php 3583 2014-04-11 11:27:28Z mic $ * @package Translation German * @author mic - http://osworx.net * @copyright 2013 OSWorX - http://osworx.net * @license GPL - www.gnu.org/copyleft/gpl.html */ // Heading $_['lang_heading_title'] = 'OpenBay Pro'; $_['lang_text_manager'] = 'OpenBay Pro Verwaltung'; // Text $_['text_install'] = '<span style="color:grey;">Installieren</span>'; $_['text_uninstall'] = '<span style="color:red;">Deinstallieren</span>'; $_['lang_text_success'] = 'Einstellungen erfolgreich gespeichert'; $_['lang_text_no_results'] = 'Keine Ergebnisse vorhanden'; $_['lang_checking_version'] = 'Überprüfe Softwareversion'; $_['lang_btn_manage'] = 'Verwalten'; $_['lang_btn_retry'] = 'Wiederholen'; $_['lang_btn_save'] = 'Speichern'; $_['lang_btn_cancel'] = 'Abbrechen'; $_['lang_btn_update'] = 'Update'; $_['lang_btn_settings'] = 'Einstellungen'; $_['lang_btn_patch'] = 'Patch'; $_['lang_btn_test'] = 'Verbindungstest'; $_['lang_latest'] = 'Die neueste Version ist in Verwendung'; $_['lang_installed_version'] = 'Installierte Version'; $_['lang_admin_dir'] = 'Adminverzeichnis'; $_['lang_admin_dir_desc'] = 'Wurde das Adminverzeichnis (Standard admin) geändert, dann hier den neuen Ordnernamen angeben'; $_['lang_version_old_1'] = 'Eine neue Version ist verfügbar - die installierte ist'; $_['lang_version_old_2'] = 'die neueste ist'; $_['lang_use_beta'] = 'Verwende eine Betarelease'; $_['lang_use_beta_2'] = '<span style="color:red;">NICHT empfohlen!</span>'; $_['lang_test_conn'] = 'Teste FTP-Verbindung'; $_['lang_text_run_1'] = 'Update ausführen'; $_['lang_text_run_2'] = 'Los'; $_['lang_no'] = 'Nein'; $_['lang_yes'] = 'Ja'; $_['lang_language'] = 'API Antwortsprache'; $_['lang_getting_messages'] = 'Hole OpenBay Pro Nachrichten'; // Column $_['lang_column_name'] = 'Pluginname'; $_['lang_column_status'] = 'Status'; $_['lang_column_action'] = 'Aktion'; // Error $_['error_permission'] = 'Hinweis: keine Rechte zum Bearbeiten dieses Moduls!'; $_['lang_error_retry'] = 'Kann keine Verbindung zum OpenBay-Server aufbauen.'; // Updates $_['lang_use_pasv'] = 'Verwende passives FTP'; $_['field_ftp_user'] = 'FTP Benutzername'; $_['field_ftp_pw'] = 'FTP Passwort'; $_['field_ftp_server_address'] = 'FTP Serveradresse'; $_['field_ftp_root_path'] = 'FTP Pfad auf Server'; $_['field_ftp_root_path_info'] = '(Keine führenden Slashes z.B. httpdocs/www)'; $_['desc_ftp_updates'] = 'Updates aktivieren bedeutet kein manuelles Bearbeiten. Es werden keine FTP-Daten an die API gesendet.<br />'; //Updates $_['lang_run_patch_desc'] = 'Update Patch angeben<span class="help">Nur notwendig bei einem manuellem Update</span>'; $_['lang_run_patch'] = 'Wende Patch an'; $_['update_error_username'] = 'Benutzername fehlt'; $_['update_error_password'] = 'Passwort fehlt'; $_['update_error_server'] = 'Serveradresse fehlt'; $_['update_error_admindir'] = 'Adminverzeichnis fehlt'; $_['update_okcon_noadmin'] = 'Verbindung OK, aber das lokale Adminverzeichnis kann nicht gefunden werden'; $_['update_okcon_nofiles'] = 'Verbindung OK, aber das lokale Shopverzeichnis kann nicht gefunden werden - ist der root-Pfad richtig?'; $_['update_okcon'] = 'Verbindung OK, Shopverzeichnis gefunden'; $_['update_failed_user'] = 'Mit diesem Benutzer ist keine Anmeldung möglich'; $_['update_failed_connect'] = 'Kann den Server nicht erreichen'; $_['update_success'] = 'Modul wurde aktualisiert (v.%s)'; $_['lang_patch_notes1'] = 'Änderungen aktueller und früherer Updates'; $_['lang_patch_notes2'] = 'hier klicken'; $_['lang_patch_notes3'] = 'Dieses Tool ändert Shopdateien! Bitte vorher eine Datensicherung durchführen!'; //Help tab $_['lang_help_title'] = 'Hilfe &amp; Unterstützung'; $_['lang_help_support_title'] = 'Unterstützung'; $_['lang_help_support_description'] = 'Bitte zuerst die <a href="http://shop.openbaypro.com/index.php?route=information/faq" title="OpenBay Pro für OpenCart FAQ" target="_blank">FAQ</a> lesen, eventuell gibt es schon eine Antwort auf die Frage. <br />Falls dennoch nicht, kann <a href="http://support.welfordmedia.co.uk" title="OpenBay Pro für OpenCart Support" target="_blank">hier</a> ein neues Ticket erstellt werden'; $_['lang_help_template_title'] = 'Neue eBay Vorlage'; $_['lang_help_template_description'] = 'Informationen für Entwickler &amp; Designer zur Vorlagenerstellung <a href="http://shop.openbaypro.com/index.php?route=information/faq&topic=30" title="OpenBay Pro HTML Vorlagen für eBay" target="_blank">hier</a>'; $_['lang_tab_help'] = 'Hilfe'; $_['lang_help_guide'] = 'Benutzeranweisungen'; $_['lang_help_guide_description'] = 'Downladen und lokal Handbücher für eBay &amp; Amazon ansehen <a href="http://shop.openbaypro.com/index.php?route=information/faq&topic=37" title="OpenBay Pro Benutzeranweisungen" target="_blank">hier klicken</a>'; $_['lang_mcrypt_text_false'] = 'Die PHP-Funktion "mcrypt_encrypt" ist nicht aktiviert - bitte Provider kontaktieren.'; $_['lang_mb_text_false'] = 'Die PHP-Bibliothek "mb strings" ist nicht aktiviert - bitte Provider kontaktieren.'; $_['lang_ftp_text_false'] = 'Einige PHP FTP-Funktionen sind nicht verfügbar - bitte Provider kontaktieren.'; $_['lang_error_oc_version'] = 'Die installierte Shopversion wurde noch nicht mit diesem Modul getestet - es können unerwartete Probleme auftauchen.'; $_['lang_patch_applied'] = 'Patch angewendet'; $_['faqbtn'] = 'FAQ ansehen'; $_['lang_clearfaq'] = 'Bereinige versteckte FAQ popups'; $_['lang_clearfaqbtn'] = 'Reinigen'; // Ajax elements $_['lang_ajax_ebay_shipped'] = 'Der Auftrag wird bei eBay automatisch als versendet markiert'; $_['lang_ajax_play_shipped'] = 'Der Auftrag wird bei play.com automatisch als versendet markiert'; $_['lang_ajax_amazoneu_shipped'] = 'Der Auftrag wird bei Amazon EU automatisch als versendet markiert'; $_['lang_ajax_amazonus_shipped'] = 'Der Auftrag wird bei Amazon US automatisch als versendet markiert'; $_['lang_ajax_play_refund'] = 'Eine Rückerstattung für dieses Auftrag wird bei play.com automatisch erstellt'; $_['lang_ajax_refund_reason'] = 'Grund für Rückerstattung'; $_['lang_ajax_refund_message'] = 'Rückerstattung Nachricht'; $_['lang_ajax_refund_entermsg'] = 'Es muss eine Nachricht zur Rückersattung angegeben werden'; $_['lang_ajax_refund_charmsg'] = 'Rückerstattungsnachricht muss weniger als 1.000 Zeichen lang sein'; $_['lang_ajax_refund_charmsg2'] = 'Die Nachricht darf kein < sowie > enthalten'; $_['lang_ajax_courier'] = 'Botendienst'; $_['lang_ajax_courier_other'] = 'Anderer Botendienst'; $_['lang_ajax_tracking'] = 'Nachverfolgungsnr.'; $_['lang_ajax_tracking_msg'] = 'Es muss eine Nachverfolgungsnr. angegeben werden, falls keine vorhanden dann "none" angeben'; $_['lang_ajax_tracking_msg2'] = 'Die Nachverfolgungsnr. darf keine < sowie > enthalten'; $_['lang_ajax_tracking_msg3'] = 'Es muss ein Botendienst ausgewählt werden wenn eine Nachverfolgungsnr. hochgeladen werden soll.'; $_['lang_ajax_tracking_msg4'] = 'Feld für Botendienst leer lassen wenn keiner verwendet wird.'; $_['lang_title_help'] = 'Hilfe zu OpenBay Pro benötigt?'; $_['lang_pod_help'] = 'Hilfe'; $_['lang_title_manage'] = 'Verwaltet OpenBay Pro; Updates, Einstellungen und mehr'; $_['lang_pod_manage'] = 'Verwalten'; $_['lang_title_shop'] = 'OpenBay Pro Shop; Eerweiterungen, Vorlagen und mehr'; $_['lang_pod_shop'] = 'Shop'; $_['lang_checking_messages'] = 'Überprüfe auf Nachrichten'; $_['lang_title_messages'] = 'Nachrichten &amp; Mitteilungen'; $_['lang_error_retry'] = 'Keine Verbindung zum OpenBay-Server möglich.'; ?>
Vitronic/kaufreund.de
admin/language/de_DE/extension/openbay.php
PHP
gpl-3.0
8,765
<?php /** * The plugin bootstrap file * * This file is read by WordPress to generate the plugin information in the plugin * admin area. This file also includes all of the dependencies used by the plugin, * registers the activation and deactivation functions, and defines a function * that starts the plugin. * * @link http://www.coderscom.com/ * @since 1.0.0 * @package Wp_Odoo_Form_Integrator * * @wordpress-plugin * Plugin Name: WP Odoo Form Integrator * Plugin URI: http://www.coderscom.com/ * Description: WP Odoo Form Integrator plugin is a bridge between several highly used Wordpress form plugins and Odoo. * Version: 1.0.0 * Author: Coderscom * Author URI: http://www.coderscom.com/ * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt * Text Domain: wp-odoo-form-integrator * Domain Path: /languages */ // If this file is called directly, abort. if ( ! defined( 'WPINC' ) ) { die; } // Register class name of modules here. $wp_odoo_form_modules = array( 'Wp_Odoo_Form_Integrator_Form_Contact_7', 'Wp_Odoo_Form_Integrator_Ninja_Forms', 'Wp_Odoo_Form_Integrator_Formidable_Forms' ); /** * Include all of the form integration files */ foreach ( glob( dirname( __FILE__ ) . "/modules/*.*" ) as $filename ) { require_once $filename; } /** * The code that runs during plugin activation. * This action is documented in includes/class-wp-odoo-form-integrator-activator.php */ function activate_wp_odoo_form_integrator() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-wp-odoo-form-integrator-activator.php'; Wp_Odoo_Form_Integrator_Activator::activate(); } /** * The code that runs during plugin deactivation. * This action is documented in includes/class-wp-odoo-form-integrator-deactivator.php */ function deactivate_wp_odoo_form_integrator() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-wp-odoo-form-integrator-deactivator.php'; Wp_Odoo_Form_Integrator_Deactivator::deactivate(); } register_activation_hook( __FILE__, 'activate_wp_odoo_form_integrator' ); register_deactivation_hook( __FILE__, 'deactivate_wp_odoo_form_integrator' ); /** * The core plugin class that is used to define internationalization, * admin-specific hooks, and public-facing site hooks. */ require plugin_dir_path( __FILE__ ) . 'includes/class-wp-odoo-form-integrator.php'; /** * Begins execution of the plugin. * * Since everything within the plugin is registered via hooks, * then kicking off the plugin from this point in the file does * not affect the page life cycle. * * @since 1.0.0 */ function run_wp_odoo_form_integrator() { $plugin = new Wp_Odoo_Form_Integrator(); $plugin->run(); } run_wp_odoo_form_integrator();
coderscom/wp-odoo-form-integrator
wp-odoo-form-integrator.php
PHP
gpl-3.0
2,847
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from caed import views urlpatterns = patterns('', # Examples: # url(r'^$', 'project.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^$',views.last_incidents,name='index'), )
julianofischer/caederm
project/urls.py
Python
gpl-3.0
377
package uk.ac.bbsrc.tgac.miso.migration.source; import static org.junit.Assert.*; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.Before; import org.junit.Test; import uk.ac.bbsrc.tgac.miso.core.data.Pool; import uk.ac.bbsrc.tgac.miso.core.data.Run; import uk.ac.bbsrc.tgac.miso.core.data.SequencerPartitionContainer; import uk.ac.bbsrc.tgac.miso.migration.MigrationData; import uk.ac.bbsrc.tgac.miso.migration.MigrationProperties; public class LoadGeneratorSourceTest { private static final String testProperties = "target/test-classes/LoadGeneratorTest.properties"; private LoadGeneratorSource sut; @Before public void setUp() throws FileNotFoundException, IOException { sut = new LoadGeneratorSource(new MigrationProperties(testProperties)); } @Test public void testGetMigrationData() { MigrationData data = sut.getMigrationData(); assertNotNull(data.getProjects()); assertEquals(5, data.getProjects().size()); assertNotNull(data.getSamples()); assertEquals(100, data.getSamples().size()); assertNotNull(data.getLibraries()); assertEquals(100, data.getLibraries().size()); assertNotNull(data.getLibraryAliquots()); assertEquals(100, data.getLibraryAliquots().size()); assertNotNull(data.getPools()); assertEquals(100, data.getPools().size()); Pool p = data.getPools().iterator().next(); assertNotNull(p.getPoolContents()); assertEquals(5, p.getPoolContents().size()); assertNotNull(data.getRuns()); assertEquals(100, data.getRuns().size()); Run r = data.getRuns().iterator().next(); assertNotNull(r.getSequencerPartitionContainers()); assertEquals(1, r.getSequencerPartitionContainers().size()); SequencerPartitionContainer spc = r.getSequencerPartitionContainers().get(0); assertNotNull(spc.getPartitions()); assertEquals(8, spc.getPartitions().size()); } }
TGAC/miso-lims
migration/src/test/java/uk/ac/bbsrc/tgac/miso/migration/source/LoadGeneratorSourceTest.java
Java
gpl-3.0
1,926
// Copyright 2002-2013, University of Colorado Boulder /** * Detector for absorbance (A) and percent transmittance (%T). * * @author Chris Malley (PixelZoom, Inc.) */ define( function( require ) { 'use strict'; // modules var ATDetector = require( 'BEERS_LAW_LAB/beerslaw/model/ATDetector' ); var Image = require( 'SCENERY/nodes/Image' ); var inherit = require( 'PHET_CORE/inherit' ); var MeterBodyNode = require( 'SCENERY_PHET/MeterBodyNode' ); var MovableDragHandler = require( 'SCENERY_PHET/input/MovableDragHandler' ); var Node = require( 'SCENERY/nodes/Node' ); var Path = require( 'SCENERY/nodes/Path' ); var PhetFont = require( 'SCENERY_PHET/PhetFont' ); var AquaRadioButton = require( 'SUN/AquaRadioButton' ); var Shape = require( 'KITE/Shape' ); var StringUtils = require( 'PHETCOMMON/util/StringUtils' ); var Text = require( 'SCENERY/nodes/Text' ); var Util = require( 'DOT/Util' ); var Vector2 = require( 'DOT/Vector2' ); //strings var absorbanceString = require( 'string!BEERS_LAW_LAB/absorbance' ); var pattern_0percent = require( 'string!BEERS_LAW_LAB/pattern.0percent' ); var transmittanceString = require( 'string!BEERS_LAW_LAB/transmittance' ); // images var bodyLeftImage = require( 'image!BEERS_LAW_LAB/at-detector-body-left.png' ); var bodyCenterImage = require( 'image!BEERS_LAW_LAB/at-detector-body-center.png' ); var bodyRightImage = require( 'image!BEERS_LAW_LAB/at-detector-body-right.png' ); var probeImage = require( 'image!BEERS_LAW_LAB/at-detector-probe.png' ); // constants var BUTTONS_X_MARGIN = 25; // specific to image files var BUTTONS_Y_OFFSET = 66; // specific to image files var VALUE_X_MARGIN = 30; // specific to image files var VALUE_CENTER_Y = 24; // specific to image files var ABSORBANCE_DECIMAL_PLACES = 2; var TRANSMITTANCE_DECIMAL_PLACES = 2; var NO_VALUE = '-'; var PROBE_CENTER_Y_OFFSET = 55; // specific to image file /** * The body of the detector, where A and T values are displayed. * Note that while the body is a Movable, we have currently decided not to allow it to be moved, * so it has no drag handler * @param {ATDetector} detector * @param {ModelViewTransform2} modelViewTransform * @constructor */ function BodyNode( detector, modelViewTransform ) { var thisNode = this; Node.call( thisNode ); // buttons for changing the detector 'mode' var textOptions = { font: new PhetFont( 18 ), fill: 'white' }; var transmittanceButton = new AquaRadioButton( detector.mode, ATDetector.Mode.TRANSMITTANCE, new Text( transmittanceString, textOptions ) ); var absorbanceButton = new AquaRadioButton( detector.mode, ATDetector.Mode.ABSORBANCE, new Text( absorbanceString, textOptions ) ); // group the buttons var buttonGroup = new Node(); buttonGroup.addChild( transmittanceButton ); buttonGroup.addChild( absorbanceButton ); absorbanceButton.x = transmittanceButton.x; absorbanceButton.top = transmittanceButton.bottom + 6; // value display var maxValue = 100; var valueNode = new Text( maxValue.toFixed( ABSORBANCE_DECIMAL_PLACES ), { font: new PhetFont( 24 ) } ); // background image, sized to fit var bodyWidth = Math.max( buttonGroup.width, valueNode.width ) + ( 2 * BUTTONS_X_MARGIN ); var backgroundNode = new MeterBodyNode( bodyWidth, bodyLeftImage, bodyCenterImage, bodyRightImage ); // rendering order thisNode.addChild( backgroundNode ); thisNode.addChild( buttonGroup ); thisNode.addChild( valueNode ); // layout buttonGroup.left = BUTTONS_X_MARGIN; buttonGroup.top = BUTTONS_Y_OFFSET; valueNode.x = VALUE_X_MARGIN; valueNode.top = VALUE_CENTER_Y; // body location detector.body.locationProperty.link( function( location ) { thisNode.translation = modelViewTransform.modelToViewPosition( location ); } ); // update the value display var valueUpdater = function() { var value = detector.value.get(); if ( isNaN( value ) ) { valueNode.text = NO_VALUE; valueNode.centerX = backgroundNode.centerX; } else { if ( detector.mode.get() === ATDetector.Mode.TRANSMITTANCE ) { valueNode.text = StringUtils.format( pattern_0percent, value.toFixed( TRANSMITTANCE_DECIMAL_PLACES ) ); } else { valueNode.text = value.toFixed( ABSORBANCE_DECIMAL_PLACES ); } valueNode.right = backgroundNode.right - VALUE_X_MARGIN; // right justified } }; detector.value.link( valueUpdater ); detector.mode.link( valueUpdater ); } inherit( Node, BodyNode ); /** * The probe portion of the detector. * @param {Movable} probe * @param {Light} light * @param {ModelViewTransform2} modelViewTransform * @constructor */ function ProbeNode( probe, light, modelViewTransform ) { var thisNode = this; Node.call( thisNode ); var imageNode = new Image( probeImage ); thisNode.addChild( imageNode ); imageNode.x = -imageNode.width / 2; imageNode.y = -PROBE_CENTER_Y_OFFSET; // location probe.locationProperty.link( function( location ) { thisNode.translation = modelViewTransform.modelToViewPosition( location ); } ); // interactivity thisNode.cursor = 'pointer'; thisNode.addInputListener( new MovableDragHandler( probe, modelViewTransform, { endDrag: function() { // If the light is on and the probe is close enough to the beam... if ( light.on.get() && ( probe.locationProperty.get().x >= light.location.x ) && ( Math.abs( probe.locationProperty.get().y - light.location.y ) <= 0.5 * light.lensDiameter ) ) { // ... snap the probe to the center of beam. probe.locationProperty.set( new Vector2( probe.locationProperty.get().x, light.location.y ) ); } } } ) ); // touch area var dx = 0.25 * imageNode.width; var dy = 0 * imageNode.height; thisNode.touchArea = Shape.rectangle( imageNode.x - dx, imageNode.y - dy, imageNode.width + dx + dx, imageNode.height + dy + dy ); } inherit( Node, ProbeNode ); /** * Wire that connects the body and probe. * @param {Movable} body * @param {Movable} probe * @param {Node} bodyNode * @param {Node} probeNode * @constructor */ function WireNode( body, probe, bodyNode, probeNode ) { var thisNode = this; Path.call( this, new Shape(), { stroke: 'gray', lineWidth: 8, lineCap: 'square', lineJoin: 'round', pickable: false } ); var updateCurve = function() { // connection points var bodyConnectionPoint = new Vector2( bodyNode.centerX, bodyNode.bottom ); var probeConnectionPoint = new Vector2( probeNode.centerX, probeNode.bottom ); // control points // The y coordinate of the body's control point varies with the x distance between the body and probe. var c1Offset = new Vector2( 0, Util.linear( 0, 800, 0, 200, bodyNode.centerX - probeNode.left ) ); // x distance -> y coordinate var c2Offset = new Vector2( 50, 150 ); var c1 = new Vector2( bodyConnectionPoint.x + c1Offset.x, bodyConnectionPoint.y + c1Offset.y ); var c2 = new Vector2( probeConnectionPoint.x + c2Offset.x, probeConnectionPoint.y + c2Offset.y ); // cubic curve thisNode.shape = new Shape() .moveTo( bodyConnectionPoint.x, bodyConnectionPoint.y ) .cubicCurveTo( c1.x, c1.y, c2.x, c2.y, probeConnectionPoint.x, probeConnectionPoint.y ); }; body.locationProperty.link( updateCurve ); probe.locationProperty.link( updateCurve ); } inherit( Path, WireNode ); /** * @param {ATDetector} detector * @param {Light} light * @param {ModelViewTransform2} modelViewTransform * @constructor */ function ATDetectorNode( detector, light, modelViewTransform ) { Node.call( this ); var bodyNode = new BodyNode( detector, modelViewTransform ); var probeNode = new ProbeNode( detector.probe, light, modelViewTransform ); var wireNode = new WireNode( detector.body, detector.probe, bodyNode, probeNode ); this.addChild( wireNode ); this.addChild( bodyNode ); this.addChild( probeNode ); } return inherit( Node, ATDetectorNode ); } );
concord-consortium/beers-law-lab
js/beerslaw/view/ATDetectorNode.js
JavaScript
gpl-3.0
8,297
/** * <p>Title: ShowAllEmojiPackage.java</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2014</p> * <p>Company: ColdWorks</p> * @author xuming * @date 2014-9-23 * @version 1.0 */ package com.lengtoo.impress.web.struts1.action.client2; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.google.gson.Gson; import com.lengtoo.impress.returndata.ReturnData; import com.lengtoo.impress.service.ILengtooEmojipackageService; /** * <p>Title: ShowAllEmojiPackage.java</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2014</p> * <p>Company: ColdWorks</p> * @author xuming * @date 2014-9-23 * Email: vip6ming@126.com */ public class ShowAllEmojiPackage extends Action{ private ILengtooEmojipackageService eService; public void seteService(ILengtooEmojipackageService eService) { this.eService = eService; } @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Map result = new HashMap(); Map paramsMap = new HashMap(); boolean success = false; int msg = 0; boolean isOk = false; boolean refresh = Boolean.parseBoolean(request.getParameter("refresh")); String date = null; if(refresh) { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); date = sf.format(new Date()); }else { date = request.getParameter("date"); } int limit; try { limit = Integer.parseInt(request.getParameter("limit")); } catch (Exception e) { limit = 10; } if(limit>20 || limit<0) { limit = 10; } paramsMap.put("date", date); paramsMap.put("limit", limit); try { List<Map> list = eService.getAllEmojipackage_client(paramsMap); isOk = true; if(list.size() !=0) { success = true; msg = 11;//success }else { success = true; msg = 12;//数据为空 } result.put("emojipackagelist", list); Gson g = new Gson(); String json = g.toJson(list); } catch (Exception e) { e.printStackTrace(); msg = 2; } ReturnData.returnData(response, result, success, msg); return null; } }
DuoLife/lengtooyinxiang
src/com/lengtoo/impress/web/struts1/action/client2/ShowAllEmojiPackage.java
Java
gpl-3.0
2,459
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2021 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.journal; import com.shatteredpixel.shatteredpixeldungeon.Badges; import com.shatteredpixel.shatteredpixeldungeon.items.Item; import com.shatteredpixel.shatteredpixeldungeon.items.armor.ClothArmor; import com.shatteredpixel.shatteredpixeldungeon.items.armor.HuntressArmor; import com.shatteredpixel.shatteredpixeldungeon.items.armor.LeatherArmor; import com.shatteredpixel.shatteredpixeldungeon.items.armor.MageArmor; import com.shatteredpixel.shatteredpixeldungeon.items.armor.MailArmor; import com.shatteredpixel.shatteredpixeldungeon.items.armor.PlateArmor; import com.shatteredpixel.shatteredpixeldungeon.items.armor.RogueArmor; import com.shatteredpixel.shatteredpixeldungeon.items.armor.ScaleArmor; import com.shatteredpixel.shatteredpixeldungeon.items.armor.WarriorArmor; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.AlchemistsToolkit; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.ChaliceOfBlood; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.CloakOfShadows; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.DriedRose; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.EtherealChains; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.HornOfPlenty; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.MasterThievesArmband; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.SandalsOfNature; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.TalismanOfForesight; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.TimekeepersHourglass; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.UnstableSpellbook; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfExperience; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfFrost; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfHaste; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfHealing; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfInvisibility; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfLevitation; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfLiquidFlame; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfMindVision; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfParalyticGas; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfPurity; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfStrength; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfToxicGas; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfAccuracy; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfElements; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfEnergy; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfEvasion; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfForce; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfFuror; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfHaste; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfMight; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfSharpshooting; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfTenacity; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfWealth; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfIdentify; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfLullaby; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfMagicMapping; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfMirrorImage; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfRage; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfRecharging; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfRemoveCurse; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfRetribution; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfTeleportation; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfTerror; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfTransmutation; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfUpgrade; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfBlastWave; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfCorrosion; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfCorruption; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfDisintegration; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfFireblast; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfFrost; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfLightning; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfLivingEarth; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfMagicMissile; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfPrismaticLight; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfRegrowth; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfTransfusion; import com.shatteredpixel.shatteredpixeldungeon.items.wands.WandOfWarding; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.AssassinsBlade; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.BattleAxe; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Crossbow; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Dagger; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Dirk; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Flail; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Gauntlet; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Glaive; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Gloves; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Greataxe; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Greatshield; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Greatsword; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.HandAxe; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Longsword; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Mace; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.MagesStaff; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Quarterstaff; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.RoundShield; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.RunicBlade; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Sai; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Scimitar; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Shortsword; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Spear; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Sword; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.WarHammer; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.Whip; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.WornShortsword; import com.watabou.utils.Bundle; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; public enum Catalog { WEAPONS, ARMOR, WANDS, RINGS, ARTIFACTS, POTIONS, SCROLLS; private LinkedHashMap<Class<? extends Item>, Boolean> seen = new LinkedHashMap<>(); public Collection<Class<? extends Item>> items(){ return seen.keySet(); } public boolean allSeen(){ for (Class<?extends Item> item : items()){ if (!seen.get(item)){ return false; } } return true; } static { WEAPONS.seen.put( WornShortsword.class, false); WEAPONS.seen.put( Gloves.class, false); WEAPONS.seen.put( Dagger.class, false); WEAPONS.seen.put( MagesStaff.class, false); WEAPONS.seen.put( Shortsword.class, false); WEAPONS.seen.put( HandAxe.class, false); WEAPONS.seen.put( Spear.class, false); WEAPONS.seen.put( Quarterstaff.class, false); WEAPONS.seen.put( Dirk.class, false); WEAPONS.seen.put( Sword.class, false); WEAPONS.seen.put( Mace.class, false); WEAPONS.seen.put( Scimitar.class, false); WEAPONS.seen.put( RoundShield.class, false); WEAPONS.seen.put( Sai.class, false); WEAPONS.seen.put( Whip.class, false); WEAPONS.seen.put( Longsword.class, false); WEAPONS.seen.put( BattleAxe.class, false); WEAPONS.seen.put( Flail.class, false); WEAPONS.seen.put( RunicBlade.class, false); WEAPONS.seen.put( AssassinsBlade.class, false); WEAPONS.seen.put( Crossbow.class, false); WEAPONS.seen.put( Greatsword.class, false); WEAPONS.seen.put( WarHammer.class, false); WEAPONS.seen.put( Glaive.class, false); WEAPONS.seen.put( Greataxe.class, false); WEAPONS.seen.put( Greatshield.class, false); WEAPONS.seen.put( Gauntlet.class, false); ARMOR.seen.put( ClothArmor.class, false); ARMOR.seen.put( LeatherArmor.class, false); ARMOR.seen.put( MailArmor.class, false); ARMOR.seen.put( ScaleArmor.class, false); ARMOR.seen.put( PlateArmor.class, false); ARMOR.seen.put( WarriorArmor.class, false); ARMOR.seen.put( MageArmor.class, false); ARMOR.seen.put( RogueArmor.class, false); ARMOR.seen.put( HuntressArmor.class, false); WANDS.seen.put( WandOfMagicMissile.class, false); WANDS.seen.put( WandOfLightning.class, false); WANDS.seen.put( WandOfDisintegration.class, false); WANDS.seen.put( WandOfFireblast.class, false); WANDS.seen.put( WandOfCorrosion.class, false); WANDS.seen.put( WandOfBlastWave.class, false); WANDS.seen.put( WandOfLivingEarth.class, false); WANDS.seen.put( WandOfFrost.class, false); WANDS.seen.put( WandOfPrismaticLight.class, false); WANDS.seen.put( WandOfWarding.class, false); WANDS.seen.put( WandOfTransfusion.class, false); WANDS.seen.put( WandOfCorruption.class, false); WANDS.seen.put( WandOfRegrowth.class, false); RINGS.seen.put( RingOfAccuracy.class, false); RINGS.seen.put( RingOfEnergy.class, false); RINGS.seen.put( RingOfElements.class, false); RINGS.seen.put( RingOfEvasion.class, false); RINGS.seen.put( RingOfForce.class, false); RINGS.seen.put( RingOfFuror.class, false); RINGS.seen.put( RingOfHaste.class, false); RINGS.seen.put( RingOfMight.class, false); RINGS.seen.put( RingOfSharpshooting.class, false); RINGS.seen.put( RingOfTenacity.class, false); RINGS.seen.put( RingOfWealth.class, false); ARTIFACTS.seen.put( AlchemistsToolkit.class, false); //ARTIFACTS.seen.put( CapeOfThorns.class, false); ARTIFACTS.seen.put( ChaliceOfBlood.class, false); ARTIFACTS.seen.put( CloakOfShadows.class, false); ARTIFACTS.seen.put( DriedRose.class, false); ARTIFACTS.seen.put( EtherealChains.class, false); ARTIFACTS.seen.put( HornOfPlenty.class, false); //ARTIFACTS.seen.put( LloydsBeacon.class, false); ARTIFACTS.seen.put( MasterThievesArmband.class, false); ARTIFACTS.seen.put( SandalsOfNature.class, false); ARTIFACTS.seen.put( TalismanOfForesight.class, false); ARTIFACTS.seen.put( TimekeepersHourglass.class, false); ARTIFACTS.seen.put( UnstableSpellbook.class, false); POTIONS.seen.put( PotionOfHealing.class, false); POTIONS.seen.put( PotionOfStrength.class, false); POTIONS.seen.put( PotionOfLiquidFlame.class, false); POTIONS.seen.put( PotionOfFrost.class, false); POTIONS.seen.put( PotionOfToxicGas.class, false); POTIONS.seen.put( PotionOfParalyticGas.class, false); POTIONS.seen.put( PotionOfPurity.class, false); POTIONS.seen.put( PotionOfLevitation.class, false); POTIONS.seen.put( PotionOfMindVision.class, false); POTIONS.seen.put( PotionOfInvisibility.class, false); POTIONS.seen.put( PotionOfExperience.class, false); POTIONS.seen.put( PotionOfHaste.class, false); SCROLLS.seen.put( ScrollOfIdentify.class, false); SCROLLS.seen.put( ScrollOfUpgrade.class, false); SCROLLS.seen.put( ScrollOfRemoveCurse.class, false); SCROLLS.seen.put( ScrollOfMagicMapping.class, false); SCROLLS.seen.put( ScrollOfTeleportation.class, false); SCROLLS.seen.put( ScrollOfRecharging.class, false); SCROLLS.seen.put( ScrollOfMirrorImage.class, false); SCROLLS.seen.put( ScrollOfTerror.class, false); SCROLLS.seen.put( ScrollOfLullaby.class, false); SCROLLS.seen.put( ScrollOfRage.class, false); SCROLLS.seen.put( ScrollOfRetribution.class, false); SCROLLS.seen.put( ScrollOfTransmutation.class, false); } public static LinkedHashMap<Catalog, Badges.Badge> catalogBadges = new LinkedHashMap<>(); static { catalogBadges.put(WEAPONS, Badges.Badge.ALL_WEAPONS_IDENTIFIED); catalogBadges.put(ARMOR, Badges.Badge.ALL_ARMOR_IDENTIFIED); catalogBadges.put(WANDS, Badges.Badge.ALL_WANDS_IDENTIFIED); catalogBadges.put(RINGS, Badges.Badge.ALL_RINGS_IDENTIFIED); catalogBadges.put(ARTIFACTS, Badges.Badge.ALL_ARTIFACTS_IDENTIFIED); catalogBadges.put(POTIONS, Badges.Badge.ALL_POTIONS_IDENTIFIED); catalogBadges.put(SCROLLS, Badges.Badge.ALL_SCROLLS_IDENTIFIED); } public static boolean isSeen(Class<? extends Item> itemClass){ for (Catalog cat : values()) { if (cat.seen.containsKey(itemClass)) { return cat.seen.get(itemClass); } } return false; } public static void setSeen(Class<? extends Item> itemClass){ for (Catalog cat : values()) { if (cat.seen.containsKey(itemClass) && !cat.seen.get(itemClass)) { cat.seen.put(itemClass, true); Journal.saveNeeded = true; } } Badges.validateItemsIdentified(); } private static final String CATALOG_ITEMS = "catalog_items"; public static void store( Bundle bundle ){ Badges.loadGlobal(); ArrayList<Class> seen = new ArrayList<>(); //if we have identified all items of a set, we use the badge to keep track instead. if (!Badges.isUnlocked(Badges.Badge.ALL_ITEMS_IDENTIFIED)) { for (Catalog cat : values()) { if (!Badges.isUnlocked(catalogBadges.get(cat))) { for (Class<? extends Item> item : cat.items()) { if (cat.seen.get(item)) seen.add(item); } } } } bundle.put( CATALOG_ITEMS, seen.toArray(new Class[0]) ); } public static void restore( Bundle bundle ){ Badges.loadGlobal(); //logic for if we have all badges if (Badges.isUnlocked(Badges.Badge.ALL_ITEMS_IDENTIFIED)){ for ( Catalog cat : values()){ for (Class<? extends Item> item : cat.items()){ cat.seen.put(item, true); } } return; } //catalog-specific badge logic for (Catalog cat : values()){ if (Badges.isUnlocked(catalogBadges.get(cat))){ for (Class<? extends Item> item : cat.items()){ cat.seen.put(item, true); } } } //general save/load if (bundle.contains(CATALOG_ITEMS)) { List<Class> seenClasses = new ArrayList<>(); if (bundle.contains(CATALOG_ITEMS)) { seenClasses = Arrays.asList(bundle.getClassArray(CATALOG_ITEMS)); } for (Catalog cat : values()) { for (Class<? extends Item> item : cat.items()) { if (seenClasses.contains(item)) { cat.seen.put(item, true); } } } } } }
00-Evan/shattered-pixel-dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/journal/Catalog.java
Java
gpl-3.0
17,606
#!/usr/bin/env python3 # Version 1.0 # Author Alexis Blanchet-Cohen # Date: 09/06/2014 import argparse import glob import os import subprocess import util # Read the command line arguments. parser = argparse.ArgumentParser(description="Generates Picard target list scripts.") parser.add_argument("-s", "--scriptsDirectory", help="Scripts directory. DEFAULT=collectinsertsizemetrics", default="collectinsertsizemetrics") parser.add_argument("-i", "--inputDirectory", help="Input directory with BAM files. DEFAULT=../results/bamtools_merge", default="../results/star") parser.add_argument("-o", "--outputDirectory", help="Output directory with filterd BAM files. DEFAULT=../results/collectinsertsizemetrics", default="../results/collectinsertsizemetrics") parser.add_argument("-q", "--submitJobsToQueue", help="Submit jobs to queue immediately.", choices=["yes", "no", "y", "n"], default="no") args = parser.parse_args() # If not in the scripts directory, cd to the scripts directory util.cdMainScriptsDirectory() # Process the command line arguments. inputDirectory = os.path.abspath(args.inputDirectory) outputDirectory = os.path.abspath(args.outputDirectory) scriptsDirectory = os.path.abspath(args.scriptsDirectory) # Read configuration files config = util.readConfigurationFiles() header = config.getboolean("server", "PBS_header") picard_folder = config.get("picard", "folder") genome = config.get("project", "genome") genomeFile = config.get(genome, "genomeFile") # Read samples file. samplesFile = util.readSamplesFile() samples = samplesFile["sample"] # Create script and output directories, if they do not exist yet. util.makeDirectory(outputDirectory) util.makeDirectory(scriptsDirectory) # CD to scripts directory os.chdir(scriptsDirectory) # Write scripts for sample in samples: scriptName = "collectinsertsizemetrics_" + sample + ".sh" script = open(scriptName, "w") if header: util.writeHeader(script, config, "collectinsertsizemetrics") # Reorder script.write("java -Xmx4g -jar " + os.path.join(picard_folder, "CollectInsertSizeMetrics.jar") + " \\\n") script.write("VALIDATION_STRINGENCY=LENIENT " + "\\\n") script.write("HISTOGRAM_FILE=" + os.path.join(outputDirectory, sample + "_picard_insert_size_plot.pdf") + " \\\n") script.write("INPUT=" + os.path.join(inputDirectory, sample + ".filtered.bam") + " \\\n") script.write("OUTPUT=" + os.path.join(outputDirectory, sample + "_picard_insert_size_metrics.txt") + " \\\n") script.write("&> " + scriptName + ".log") script.close()
blancha/abcngspipelines
utils/collectinsertsizemetrics.py
Python
gpl-3.0
2,567
"""Current-flow betweenness centrality measures for subsets of nodes.""" import networkx as nx from networkx.algorithms.centrality.flow_matrix import flow_matrix_row from networkx.utils import not_implemented_for, reverse_cuthill_mckee_ordering __all__ = [ "current_flow_betweenness_centrality_subset", "edge_current_flow_betweenness_centrality_subset", ] @not_implemented_for("directed") def current_flow_betweenness_centrality_subset( G, sources, targets, normalized=True, weight=None, dtype=float, solver="lu" ): r"""Compute current-flow betweenness centrality for subsets of nodes. Current-flow betweenness centrality uses an electrical current model for information spreading in contrast to betweenness centrality which uses shortest paths. Current-flow betweenness centrality is also known as random-walk betweenness centrality [2]_. Parameters ---------- G : graph A NetworkX graph sources: list of nodes Nodes to use as sources for current targets: list of nodes Nodes to use as sinks for current normalized : bool, optional (default=True) If True the betweenness values are normalized by b=b/(n-1)(n-2) where n is the number of nodes in G. weight : string or None, optional (default=None) Key for edge data used as the edge weight. If None, then use 1 as each edge weight. dtype: data type (float) Default data type for internal matrices. Set to np.float32 for lower memory consumption. solver: string (default='lu') Type of linear solver to use for computing the flow matrix. Options are "full" (uses most memory), "lu" (recommended), and "cg" (uses least memory). Returns ------- nodes : dictionary Dictionary of nodes with betweenness centrality as the value. See Also -------- approximate_current_flow_betweenness_centrality betweenness_centrality edge_betweenness_centrality edge_current_flow_betweenness_centrality Notes ----- Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$ time [1]_, where $I(n-1)$ is the time needed to compute the inverse Laplacian. For a full matrix this is $O(n^3)$ but using sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the Laplacian matrix condition number. The space required is $O(nw)$ where $w$ is the width of the sparse Laplacian matrix. Worse case is $w=n$ for $O(n^2)$. If the edges have a 'weight' attribute they will be used as weights in this algorithm. Unspecified weights are set to 1. References ---------- .. [1] Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. http://algo.uni-konstanz.de/publications/bf-cmbcf-05.pdf .. [2] A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005). """ from networkx.utils import reverse_cuthill_mckee_ordering try: import numpy as np except ImportError as e: raise ImportError( "current_flow_betweenness_centrality requires NumPy ", "http://numpy.org/" ) from e if not nx.is_connected(G): raise nx.NetworkXError("Graph not connected.") n = G.number_of_nodes() ordering = list(reverse_cuthill_mckee_ordering(G)) # make a copy with integer labels according to rcm ordering # this could be done without a copy if we really wanted to mapping = dict(zip(ordering, range(n))) H = nx.relabel_nodes(G, mapping) betweenness = dict.fromkeys(H, 0.0) # b[v]=0 for v in H for row, (s, t) in flow_matrix_row(H, weight=weight, dtype=dtype, solver=solver): for ss in sources: i = mapping[ss] for tt in targets: j = mapping[tt] betweenness[s] += 0.5 * np.abs(row[i] - row[j]) betweenness[t] += 0.5 * np.abs(row[i] - row[j]) if normalized: nb = (n - 1.0) * (n - 2.0) # normalization factor else: nb = 2.0 for v in H: betweenness[v] = betweenness[v] / nb + 1.0 / (2 - n) return {ordering[k]: v for k, v in betweenness.items()} @not_implemented_for("directed") def edge_current_flow_betweenness_centrality_subset( G, sources, targets, normalized=True, weight=None, dtype=float, solver="lu" ): r"""Compute current-flow betweenness centrality for edges using subsets of nodes. Current-flow betweenness centrality uses an electrical current model for information spreading in contrast to betweenness centrality which uses shortest paths. Current-flow betweenness centrality is also known as random-walk betweenness centrality [2]_. Parameters ---------- G : graph A NetworkX graph sources: list of nodes Nodes to use as sources for current targets: list of nodes Nodes to use as sinks for current normalized : bool, optional (default=True) If True the betweenness values are normalized by b=b/(n-1)(n-2) where n is the number of nodes in G. weight : string or None, optional (default=None) Key for edge data used as the edge weight. If None, then use 1 as each edge weight. dtype: data type (float) Default data type for internal matrices. Set to np.float32 for lower memory consumption. solver: string (default='lu') Type of linear solver to use for computing the flow matrix. Options are "full" (uses most memory), "lu" (recommended), and "cg" (uses least memory). Returns ------- nodes : dict Dictionary of edge tuples with betweenness centrality as the value. See Also -------- betweenness_centrality edge_betweenness_centrality current_flow_betweenness_centrality Notes ----- Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$ time [1]_, where $I(n-1)$ is the time needed to compute the inverse Laplacian. For a full matrix this is $O(n^3)$ but using sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the Laplacian matrix condition number. The space required is $O(nw)$ where $w$ is the width of the sparse Laplacian matrix. Worse case is $w=n$ for $O(n^2)$. If the edges have a 'weight' attribute they will be used as weights in this algorithm. Unspecified weights are set to 1. References ---------- .. [1] Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. http://algo.uni-konstanz.de/publications/bf-cmbcf-05.pdf .. [2] A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005). """ try: import numpy as np except ImportError as e: raise ImportError( "current_flow_betweenness_centrality requires NumPy " "http://numpy.org/" ) from e if not nx.is_connected(G): raise nx.NetworkXError("Graph not connected.") n = G.number_of_nodes() ordering = list(reverse_cuthill_mckee_ordering(G)) # make a copy with integer labels according to rcm ordering # this could be done without a copy if we really wanted to mapping = dict(zip(ordering, range(n))) H = nx.relabel_nodes(G, mapping) edges = (tuple(sorted((u, v))) for u, v in H.edges()) betweenness = dict.fromkeys(edges, 0.0) if normalized: nb = (n - 1.0) * (n - 2.0) # normalization factor else: nb = 2.0 for row, (e) in flow_matrix_row(H, weight=weight, dtype=dtype, solver=solver): for ss in sources: i = mapping[ss] for tt in targets: j = mapping[tt] betweenness[e] += 0.5 * np.abs(row[i] - row[j]) betweenness[e] /= nb return {(ordering[s], ordering[t]): v for (s, t), v in betweenness.items()}
SpaceGroupUCL/qgisSpaceSyntaxToolkit
esstoolkit/external/networkx/algorithms/centrality/current_flow_betweenness_subset.py
Python
gpl-3.0
8,195
import { app } from 'mobx-app'; import { inject, observer } from 'mobx-react'; import React, { SFC } from 'react'; import { Redirect as ReactRedirect, RedirectProps as ReactRedirectProps } from 'react-router-dom'; interface RedirectProps extends ReactRedirectProps { authedOnly?: boolean; unauthedOnly?: boolean; } export const Redirect: SFC<RedirectProps> = inject(app('state'))(observer((props) => { const { authedOnly, state, unauthedOnly } = props; const { isAuthed } = state; if ( (authedOnly && !isAuthed) || (unauthedOnly && isAuthed) ) return null; return <ReactRedirect {...props} />; }));
nielsrowinbik/seaman
src/components/Redirect/Redirect.tsx
TypeScript
gpl-3.0
614
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; using Yavsc.Attributes.Validation; namespace Yavsc.Models.Workflow { public class UserActivity { [YaRequired] public string UserId { get; set; } [ForeignKey("UserId")] public virtual PerformerProfile User { get; set; } [YaRequired] public string DoesCode { get; set; } [ForeignKey("DoesCode")] public virtual Activity Does { get; set; } [Range(0,100)] public int Weight { get; set; } [NotMapped,JsonIgnore] public object Settings { get; internal set; } } }
pazof/yavsc
src/Yavsc.Server/Models/Workflow/UserActivity.cs
C#
gpl-3.0
698
require 'csv' MovieGenre.delete_all Genre.delete_all puts 'Creating genres' start = Time.zone.now # load genre and movie data csv_text = File.read('db/seeds_data/movies.csv') csv = CSV.parse(csv_text, headers: true) csv.each do |row| movie = row.to_hash movie_saved = Movie.find_by(id: movie['movieId']) genres = movie['genres'].split('|') genres.each do |g| genre = Genre.find_by(name: g) if genre.nil? genre = Genre.create( name: g ) end MovieGenre.create( movie_id: movie_saved.id, genre_id: genre.id ) unless movie_saved.nil? end end puts Time.zone.now - start
dreyxvx/recommender_system_api
db/tasks/genres_seed.rb
Ruby
gpl-3.0
629
var util = require('util'); var https = require('https'); var querystring = require('querystring'); var emitter = require('events').EventEmitter; var retry = require('retry'); function FCM(apiKey) { if (apiKey) { this.apiKey = apiKey; } else { throw Error('No apiKey is given.'); } this.fcmOptions = { host: 'android.googleapis.com', port: 443, path: '/gcm/send', method: 'POST', headers: {} }; } util.inherits(FCM, emitter); exports.FCM = FCM; FCM.prototype.send = function(packet, cb) { var self = this; if (cb) this.once('sent', cb); var operation = retry.operation(); operation.attempt(function(currentAttempt) { var postData = querystring.stringify(packet); var headers = { 'Host': self.fcmOptions.host, 'Authorization': 'key=' + self.apiKey, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'Content-length': postData.length }; self.fcmOptions.headers = headers; if (self.keepAlive) headers.Connection = 'keep-alive'; var request = https.request(self.fcmOptions, function(res) { var data = ''; if (res.statusCode == 503) { // If the server is temporary unavailable, the C2DM spec requires that we implement exponential backoff // and respect any Retry-After header if (res.headers['retry-after']) { var retrySeconds = res.headers['retry-after'] * 1; // force number if (isNaN(retrySeconds)) { // The Retry-After header is a HTTP-date, try to parse it retrySeconds = new Date(res.headers['retry-after']).getTime() - new Date().getTime(); } if (!isNaN(retrySeconds) && retrySeconds > 0) { operation._timeouts['minTimeout'] = retrySeconds; } } if (!operation.retry('TemporaryUnavailable')) { self.emit('sent', operation.mainError(), null); } // Ignore all subsequent events for this request return; } function respond() { var error = null, id = null; if (data.indexOf('Error=') === 0) { error = data.substring(6).trim(); } else if (data.indexOf('id=') === 0) { id = data.substring(3).trim(); } else { // No id nor error? error = 'InvalidServerResponse'; } // Only retry if error is QuotaExceeded or DeviceQuotaExceeded if (operation.retry(['QuotaExceeded', 'DeviceQuotaExceeded', 'InvalidServerResponse'].indexOf(error) >= 0 ? error : null)) { return; } // Success, return message id (without id=) self.emit('sent', error, id); } res.on('data', function(chunk) { data += chunk; }); res.on('end', respond); res.on('close', respond); }); request.on('error', function(error) { self.emit('sent', error, null); }); request.end(postData); }); };
matso165/islands-of-tribes
StoneAge/server/node_modules/fcm/lib/fcm.js
JavaScript
gpl-3.0
3,559
var panfeedModule = angular.module('panfeedModule', []); panfeedModule.config(function($interpolateProvider) { $interpolateProvider.startSymbol('[['); $interpolateProvider.endSymbol(']]'); }); /* https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax */ jQuery(document).ajaxSend(function(event, xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function sameOrigin(url) { // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } function safeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } if (!safeMethod(settings.type) && sameOrigin(settings.url)) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } }); $(function() { $('#confirmDeleteModal .button-close').click(function() { $('#confirmDeleteModal').modal("hide"); }); $("input[name=_method][value=DELETE] + button[type=submit]").click(function(event) { event.preventDefault(); var button = $(this); $('#confirmDeleteModal .button-delete').unbind("click").click(function() { button.parent("div").parent("form").submit(); $('#confirmDeleteModal').modal("hide"); }); $('#confirmDeleteModal').modal("show"); }); });
Landric/PANFeed
panfeed/static/panfeed/scripts/initapp.js
JavaScript
gpl-3.0
2,447
/* * VITacademics * Copyright (C) 2015 Aneesh Neelam <neelam.aneesh@gmail.com> * Copyright (C) 2015 Gaurav Agerwala <gauravagerwala@gmail.com> * Copyright (C) 2015 Karthik Balakrishnan <karthikb351@gmail.com> * Copyright (C) 2015 Pulkit Juneja <pulkit.16296@gmail.com> * Copyright (C) 2015 Hemant Jain <hemanham@gmail.com> * * This file is part of VITacademics. * VITacademics is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VITacademics is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VITacademics. If not, see <http://www.gnu.org/licenses/>. */ package com.karthikb351.vitinfo2.fragment.details; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.karthikb351.vitinfo2.R; import com.karthikb351.vitinfo2.contract.Attendance; import com.karthikb351.vitinfo2.contract.AttendanceDetail; import com.karthikb351.vitinfo2.contract.Course; import com.karthikb351.vitinfo2.utility.DateTimeCalender; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class AttendanceListAdapter extends RecyclerView.Adapter<AttendanceListAdapter.AttendanceViewHolder> { private int layoutId; private Context context; private Course course; private Attendance attendance; private List<AttendanceDetail> attendanceDetails; private int conducted, attended, classLength, miss = 0, attend = 0; public AttendanceListAdapter(Context context, Course course) { this.context = context; this.course = course; if (course.getAttendance().isSupported()) { this.attendance = course.getAttendance(); this.attendanceDetails = attendance.getDetails(); this.conducted = attendance.getTotalClasses(); this.attended = attendance.getAttendedClasses(); if (!(this.attendanceDetails == null || this.attendanceDetails.isEmpty())) { Collections.reverse(this.attendanceDetails); } } else { this.attendanceDetails = new ArrayList<>(); this.attendance = new Attendance(context.getString(R.string.registration_date_unavailable), 0, 0, 0, attendanceDetails, true); } classLength = course.getClassLength(); } @Override public AttendanceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(viewType, parent, false); return new AttendanceViewHolder(view); } @SuppressWarnings("deprecation") private void setProgressBarDrawable(ProgressBar progressBar) { if (getPercentage() >= 80) { progressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.ring_attendance_green)); } else if (getPercentage() >= 75 && getPercentage() < 80) { progressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.ring_attendance_orange)); } else { progressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.ring_attendance_red)); } } private void updateHolder(AttendanceViewHolder holder) { holder.attendanceClasses.setText(context.getString(R.string.label_attendance_classes, attended + attend, conducted + attend + miss)); holder.txtAttend.setText(context.getString(R.string.label_class_go, attend)); holder.txtMiss.setText(context.getString(R.string.label_class_miss, miss)); holder.attendancePercent.setText(Integer.toString(getPercentage())); holder.progressBarAttendance.setProgress(getPercentage()); setProgressBarDrawable(holder.progressBarAttendance); } private int getPercentage() { return ((int) Math.ceil((double) (attended + attend) / (conducted + attend + miss) * 100)); } @Override public void onBindViewHolder(final AttendanceViewHolder holder, int position) { if (position == 0) { View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View view) { if (view == holder.attendPlus) { attend += classLength; if (!holder.attendMinus.isClickable()) holder.attendMinus.setClickable(true); } else if (view == holder.attendMinus) { if (attend == 0) holder.attendMinus.setClickable(false); else attend -= classLength; } else if (view == holder.missPlus) { miss += classLength; if (!holder.missMinus.isClickable()) holder.missMinus.setClickable(true); } else if (view == holder.missMinus) { if (miss == 0) holder.missMinus.setClickable(false); else miss -= classLength; } updateHolder(holder); } }; updateHolder(holder); holder.courseName.setText(course.getCourseTitle()); holder.courseCode.setText(course.getCourseCode()); holder.attendPlus.setOnClickListener(onClickListener); holder.attendMinus.setOnClickListener(onClickListener); holder.missPlus.setOnClickListener(onClickListener); holder.missMinus.setOnClickListener(onClickListener); } else { try { holder.date.setText(DateTimeCalender.parseISO8601Date(attendanceDetails.get(position - 1).getDate())); } catch (ParseException ex) { ex.printStackTrace(); holder.date.setText(attendanceDetails.get(position - 1).getDate()); } holder.detailStatus.setText(attendanceDetails.get(position - 1).getStatus()); holder.classUnits.setText(context.getString(R.string.attendance_class_units_earned, attendanceDetails.get(position - 1).getClassUnits())); holder.reason.setText(attendanceDetails.get(position - 1).getReason()); } } @Override public int getItemCount() { if (attendanceDetails == null || attendanceDetails.isEmpty()) { return 1; } return (attendanceDetails.size() + 1); } @Override public int getItemViewType(int position) { if (position == 0) { layoutId = R.layout.card_attendance_summary; } else { layoutId = R.layout.card_attendance_detail; } return layoutId; } public class AttendanceViewHolder extends RecyclerView.ViewHolder { public TextView date, detailStatus, classUnits, reason, txtMiss, txtAttend; public TextView courseName, courseCode, attendanceClasses, attendancePercent; public ProgressBar progressBarAttendance; public Button attendPlus, attendMinus, missPlus, missMinus; public AttendanceViewHolder(View view) { super(view); attendPlus = (Button) view.findViewById(R.id.button_attend_plus); attendMinus = (Button) view.findViewById(R.id.button_attend_minus); missPlus = (Button) view.findViewById(R.id.button_miss_plus); missMinus = (Button) view.findViewById(R.id.button_miss_minus); txtMiss = (TextView) view.findViewById(R.id.txt_miss); txtAttend = (TextView) view.findViewById(R.id.txt_attend); date = (TextView) view.findViewById(R.id.date); detailStatus = (TextView) view.findViewById(R.id.detail_status); classUnits = (TextView) view.findViewById(R.id.class_units); reason = (TextView) view.findViewById(R.id.reason); courseName = (TextView) view.findViewById(R.id.course_name); courseCode = (TextView) view.findViewById(R.id.course_code); attendanceClasses = (TextView) view.findViewById(R.id.attendance_classes); attendancePercent = (TextView) view.findViewById(R.id.attendance_percent); progressBarAttendance = (ProgressBar) view.findViewById(R.id.progress_bar_attendance); } } }
CollegeCODE/VITacademics-Android
app/src/main/java/com/karthikb351/vitinfo2/fragment/details/AttendanceListAdapter.java
Java
gpl-3.0
9,017
/******************************************************************************* * Copyright (c) 2011-2014 SirSengir. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.core.items; import java.util.Arrays; import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; public abstract class ItemForestryTool extends ItemForestry { private final ItemStack remnants; protected float efficiencyOnProperMaterial; private final List<Block> blocksEffectiveAgainst; protected ItemForestryTool(Block[] blocksEffectiveAgainst, ItemStack remnants) { this.blocksEffectiveAgainst = Arrays.asList(blocksEffectiveAgainst); this.maxStackSize = 1; efficiencyOnProperMaterial = 6F; setMaxDamage(200); this.remnants = remnants; } @Override public float func_150893_a(ItemStack itemstack, Block block) { if (blocksEffectiveAgainst.contains(block)) { return efficiencyOnProperMaterial; } return 1.0F; } @Override public float getDigSpeed(ItemStack itemstack, Block block, int md) { if (ForgeHooks.isToolEffective(itemstack, block, md)) { return efficiencyOnProperMaterial; } return func_150893_a(itemstack, block); } @SubscribeEvent public void onDestroyCurrentItem(PlayerDestroyItemEvent event) { if (event.original == null || event.original.getItem() != this) { return; } if (!event.entityPlayer.worldObj.isRemote && remnants != null) { EntityItem entity = new EntityItem(event.entityPlayer.worldObj, event.entityPlayer.posX, event.entityPlayer.posY, event.entityPlayer.posZ, remnants.copy()); event.entityPlayer.worldObj.spawnEntityInWorld(entity); } } @Override public boolean onBlockDestroyed(ItemStack itemstack, World world, Block block, int j, int k, int l, EntityLivingBase entityliving) { itemstack.damageItem(1, entityliving); return true; } @Override public boolean isFull3D() { return true; } }
AnodeCathode/ForestryMC
src/main/java/forestry/core/items/ItemForestryTool.java
Java
gpl-3.0
2,632
<?php // Array type declaration - PHP 5.1+ function foo(array $a) {} function foo( array $a ) {} // Test extra spacing. // Callable type declaration - PHP 5.4+ function foo(callable $a) {} // Scalar type declarations - PHP 7.0+ function foo(bool $a) {} function foo(int $a) {} function foo(float $a) {} function foo(string $a) {} // Iterable type declaration - PHP 7.1+ function foo(iterable $a) {} // (Very likely) Invalid type declarations - will be treated as class/interface names. function foo(boolean $a) {} function foo(integer $a) {} class MyOtherClass extends MyClass { function foo(parent $a) {} function bar(static $a) {} } // Class/interface type declaration - PHP 5.0+ function foo(stdClass $a) {} // Class/interface type declaration with self keyword - PHP 5.0+ class MyClass { function foo(self $a) {} } function foo(self $a) {} // Invalid - not within a class. namespace test { class foo { function foo(self $a) {} } function foo(self $a) {} // Invalid - not within a class. } // Ok: No function parameters or no type hints. function foo() {} function foo( $a, $b ) {} // Type hints in closures. function (callable $a) {} function(int $a) {} // Deal with nullable type hints. function foo(?callable $a) {} function foo(?int $a) {}
AmrataRamchandani/moodle
local/codechecker/PHPCompatibility/Tests/sniff-examples/new_scalar_type_declarations.php
PHP
gpl-3.0
1,296
from ert_gui.models import ErtConnector from ert_gui.models.mixins import SpinnerModelMixin class LocalMaxRunning(ErtConnector, SpinnerModelMixin): def getMaxValue(self): """ @rtype: int """ return 1000 def getMinValue(self): """ @rtype: int """ return 1 def getSpinnerValue(self): """ @rtype: int """ return self.ert().siteConfig().getMaxRunningLocal() def setSpinnerValue(self, value): self.ert().siteConfig().setMaxRunningLocal(value)
iLoop2/ResInsight
ThirdParty/Ert/devel/python/python/ert_gui/models/connectors/queue_system/local_max_running.py
Python
gpl-3.0
519
package l2s.gameserver.network.l2.s2c; import java.util.ArrayList; import java.util.Collection; import l2s.gameserver.data.xml.holder.ProductDataHolder; import l2s.gameserver.model.Player; import l2s.gameserver.templates.item.product.ProductItem; import l2s.gameserver.templates.item.product.ProductItemComponent; public class ExBR_RecentProductListPacket extends L2GameProductPacket { private Collection<ProductItem> products; public ExBR_RecentProductListPacket(Player activeChar) { this.products = new ArrayList<>(); int[] products = activeChar.getRecentProductList(); if (products != null) { for (int productId : products) { ProductItem product = ProductDataHolder.getInstance().getProduct(productId); if (product == null) { continue; } this.products.add(product); } } } @Override protected void writeImpl() { writeD(0x01); // UNK writeD(products.size()); for (ProductItem product : products) { writeD(product.getId()); //product id writeH(product.getCategory()); //category 1 - enchant 2 - supplies 3 - decoration 4 - package 5 - other writeD(product.getPrice(true)); //points writeD(product.getTabId()); // show tab 2-th group - 1 показывает окошко про итем writeD(product.getSection()); // категория главной страницы (0 - не показывать на главное (дефолт), 1 - верхнее окно, 2 - рекомендуемый товар, 3 - неизвестно, 4 - популярные товары) // Glory Days 488 writeD((int) (product.getStartTimeSale() / 1000)); // start sale unix date in seconds writeD((int) (product.getEndTimeSale() / 1000)); // end sale unix date in seconds writeC(127); // day week (127 = not daily goods) writeC(product.getStartHour()); // start hour writeC(product.getStartMin()); // start min writeC(product.getEndHour()); // end hour writeC(product.getEndMin()); // end min writeD(0); // stock writeD(-1); // max stock // Glory Days 488 writeD(product.getDiscount()); // % скидки //writeD(1); // Увеличение уровня (Дефолт = 1) writeD(product.getComponents().size()); // Количество итемов в продукте. writeComponents(product); } } }
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/network/l2/s2c/ExBR_RecentProductListPacket.java
Java
gpl-3.0
2,625
/* Copyright (C) 2008-2015 Teddy Michel This file is part of TEngine. TEngine is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TEngine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with TEngine. If not, see <http://www.gnu.org/licenses/>. */ /** * \file Game/Entities/IBaseAnimating.hpp * \date 11/04/2009 Création de la classe IBaseAnimating. * \date 13/07/2010 Le nombre de points de vie est désormais géré par cette classe. * \date 14/07/2010 Ajout de la méthode WeaponImpact. * \date 16/07/2010 Ajout de la méthode ProjectileImpact. * \date 18/11/2010 Ajout de la méthode getClassName. * \date 08/12/2010 Plus de méthodes inline, suppression du paramètre name. * \date 01/03/2011 Ajout du paramètre parent au constructeur. * \date 02/03/2011 Création des méthodes isPlayer et isNPC. * \date 07/04/2011 Les entités sont identifiées par un nom à la place d'un nombre. */ #ifndef T_FILE_ENTITIES_IBASEANIMATING_HPP_ #define T_FILE_ENTITIES_IBASEANIMATING_HPP_ /*-------------------------------* * Includes * *-------------------------------*/ #include "Game/Export.hpp" #include "IBrushEntity.hpp" namespace Ted { class IBaseProjectile; /** * \class IBaseAnimating * \ingroup Game * \brief Classe de base des entités animées. ******************************/ class T_GAME_API IBaseAnimating : public IBrushEntity { public: // Constructeur et destructeur explicit IBaseAnimating(const CString& name = CString(), ILocalEntity * parent = nullptr); virtual ~IBaseAnimating() = 0; // Accesseurs virtual CString getClassName() const; float getHealth() const; bool isAlive() const; virtual bool isPlayer() const; virtual bool isNPC() const; // Mutateurs void addHealth(float health); void setHealth(float health = 100.0f); // Méthodes publiques virtual void weaponImpact(float damage, IBaseCharacter * character, IBaseWeapon * weapon); virtual void projectileImpact(float damage, IBaseProjectile * projectile); virtual void frame(unsigned int frameTime); protected: // Donnée protégée float m_health; ///< Points de vie (si négatifs, l'entité est morte, 100 par défaut). }; } // Namespace Ted #endif // T_FILE_ENTITIES_IBASEANIMATING_HPP_
teddy-michel/TEngine
include/Game/Entities/IBaseAnimating.hpp
C++
gpl-3.0
2,717
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using PagedList.Core; namespace Marigold { public class ReservationsController : Controller { private IUnitOfWork unitOfWork; private IReservationsBll _bll; public ReservationsController(IReservationsBll bll, IUnitOfWork uow) { _bll = bll; unitOfWork = uow; } public async Task<IActionResult> Index(int? page) { var pageIndex = !page.HasValue || page <= 0 ? 1 : page.Value; var list = _bll.Reservations(pageIndex - 1, 10); ViewBag.RoomUnitDescription = await _bll.RoomUnitDescription(); return View(list); } public async Task<IActionResult> Create() { return View(await _bll.ReservationInput()); } [HttpPost] public async Task<IActionResult> Create(ReservationInputDto input) { if (!ModelState.IsValid) return View(input); await _bll.Create(input); return Redirect("Index"); } public async Task<IActionResult> Checkout(string id) { var input = await _bll.CheckoutView(id); if (input == null) return new NotFoundResult(); ViewBag.RoomUnitDescription = await _bll.RoomUnitDescription(); return View(input); } [HttpPost] public async Task<IActionResult> Checkout(ReservationInputDto input) { var res = await _bll.Checkout(input); if (!res) return new NotFoundResult(); return RedirectToAction("Index"); } public async Task<IActionResult> Bill(string id) { var output = await _bll.Bill(id); if(output == null) return new NotFoundResult(); ViewBag.Currency = "grams of gold"; return View(output); } } }
catalintoma/Mary-Gold
Controllers/ReservationsController.cs
C#
gpl-3.0
2,215
<?php /* * 2007-2013 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <contact@prestashop.com> * @copyright 2007-2013 PrestaShop SA * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ // // IMPORTANT : don't forget to delete the underscore _ in the file name if you want to use it ! // $GLOBALS['debugtoolbar'] = array(); if (file_exists(_PS_MODULE_DIR_.'debugtoolbar/debugtoolbar.php')) require_once(_PS_MODULE_DIR_.'debugtoolbar/debugtoolbar.php'); function developpementErrorHandler($errno, $errstr, $errfile, $errline) { if (!(error_reporting() & $errno)) return; switch($errno) { case E_ERROR: echo '[PHP Error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_WARNING: echo '[PHP Warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_PARSE: echo '[PHP Parse #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_NOTICE: echo '[PHP Notice #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_CORE_ERROR: echo '[PHP Core #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_CORE_WARNING: echo '[PHP Core warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_COMPILE_ERROR: echo '[PHP Compile #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_COMPILE_WARNING: echo '[PHP Compile warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_USER_ERROR: echo '[PHP Error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_USER_WARNING: echo '[PHP User warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_USER_NOTICE: echo '[PHP User notice #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_STRICT: echo '[PHP Strict #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_RECOVERABLE_ERROR: echo '[PHP Recoverable error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; default: echo '[PHP Unknown error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; } die; return true; } function debug($debug, $name = null) { $GLOBALS['debugtoolbar'] = (($name !== null) ? '<b>Debug var :</b> '.$name.'<br />' : '').'<pre>'.print_r($debug, true).'</pre>'; } /** * Converts bytes into human readable file size. * * @param string $bytes * @return string human readable file size (2,87 Мб) * @author Mogilev Arseny */ function FileSizeConvert($bytes) { $bytes = floatval($bytes); $arBytes = array( 0 => array( "UNIT" => "tB", "VALUE" => pow(1024, 4) ), 1 => array( "UNIT" => "gB", "VALUE" => pow(1024, 3) ), 2 => array( "UNIT" => "mB", "VALUE" => pow(1024, 2) ), 3 => array( "UNIT" => "kB", "VALUE" => 1024 ), 4 => array( "UNIT" => "bytes", "VALUE" => 1 ), ); $result = ''; foreach($arBytes as $arItem) { if($bytes >= $arItem["VALUE"]) { $result = $bytes / $arItem["VALUE"]; $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"]; break; } } return $result; } if (!function_exists('getallheaders')) { function getallheaders() { $headers = ''; foreach ($_SERVER as $name => $value) if (substr($name, 0, 5) == 'HTTP_') $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; return $headers; } } function getUrl() { $url = Tools::getShopDomainSsl(true); $url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : ""; $url .= $_SERVER["REQUEST_URI"]; return $url; } function smarty_modifier_debug_print_var ($var, $depth = 0, $length = 40) { $_replace = array("\n" => '<i>\n</i>', "\r" => '<i>\r</i>', "\t" => '<i>\t</i>' ); switch (gettype($var)) { case 'array' : $results = '<b>Array (' . count($var) . ')</b>'; foreach ($var as $curr_key => $curr_val) { $results .= '<br>' . str_repeat('&nbsp;', $depth * 2) . '<b>' . strtr($curr_key, $_replace) . '</b> =&gt; ' . smarty_modifier_debug_print_var($curr_val, ++$depth, $length); $depth--; } break; case 'object' : $object_vars = get_object_vars($var); $results = '<b>' . get_class($var) . ' Object (' . count($object_vars) . ')</b>'; foreach ($object_vars as $curr_key => $curr_val) { $results .= '<br>' . str_repeat('&nbsp;', $depth * 2) . '<b> -&gt;' . strtr($curr_key, $_replace) . '</b> = ' . smarty_modifier_debug_print_var($curr_val, ++$depth, $length); $depth--; } break; case 'boolean' : case 'NULL' : case 'resource' : if (true === $var) { $results = 'true'; } elseif (false === $var) { $results = 'false'; } elseif (null === $var) { $results = 'null'; } else { $results = htmlspecialchars((string) $var); } $results = '<i>' . $results . '</i>'; break; case 'integer' : case 'float' : $results = htmlspecialchars((string) $var); break; case 'string' : $results = strtr($var, $_replace); if (Smarty::$_MBSTRING) { if (mb_strlen($var, Smarty::$_CHARSET) > $length) { $results = mb_substr($var, 0, $length - 3, Smarty::$_CHARSET) . '...'; } } else { if (isset($var[$length])) { $results = substr($var, 0, $length - 3) . '...'; } } $results = htmlspecialchars('"' . $results . '"'); break; case 'unknown type' : default : $results = strtr((string) $var, $_replace); if (Smarty::$_MBSTRING) { if (mb_strlen($results, Smarty::$_CHARSET) > $length) { $results = mb_substr($results, 0, $length - 3, Smarty::$_CHARSET) . '...'; } } else { if (strlen($results) > $length) { $results = substr($results, 0, $length - 3) . '...'; } } $results = htmlspecialchars($results); } return $results; } abstract class Controller extends ControllerCore { public $_memory = array(); public $_time = array(); private static $_footer = true; public static function disableParentCalls() { self::$_footer = false; } private function displayMemoryColor($n) { $n /= 1048576; if ($n > 3) return '<span style="color:#ff4141">'.round($n, 2).' Mb</span>'; if ($n > 1) return '<span style="color:#ef8400">'.round($n, 2).' Mb</span>'; return '<span style="color:#90bd00">'.round($n, 2).' Mb</span>'; } private function displayPeakMemoryColor($n) { $n /= 1048576; if ($n > 16) return '<span style="color:#ff4141">'.round($n, 1).' Mb</span>'; if ($n > 12) return '<span style="color:#ef8400">'.round($n, 1).' Mb</span>'; return '<span style="color:#90bd00">'.round($n, 1).' Mb</span>'; } private function displaySQLQueries($n) { if ($n > 150) return '<span style="color:#ff4141">'.$n.' queries</span>'; if ($n > 100) return '<span style="color:#ef8400">'.$n.' queries</span>'; return '<span style="color:#90bd00">'.$n.' quer'.($n == 1 ? 'y' : 'ies').'</span>'; } private function displayRowsBrowsed($n) { if ($n > 200) return '<span style="color:#ff4141">'.$n.' rows browsed</span>'; if ($n > 50) return '<span style="color:#ef8400">'.$n.' rows browsed</span>'; return '<span style="color:#90bd00">'.$n.' row'.($n == 1 ? '' : 's').' browsed</span>'; } private function displayLoadTimeColor($n, $pre = false) { $balise = ($pre ? 'pre' : 'span'); if ($n > 1) return '<'.$balise.' style="color:#ff4141">'.round($n, 3).'s</'.$balise.'>'; if ($n > 0.5) return '<'.$balise.' style="color:#ef8400">'.round($n * 1000).'ms</'.$balise.'>'; return '<'.$balise.' style="color:#90bd00">'.round($n * 1000).'ms</'.$balise.'>'; } private function getTimeColor($n) { if ($n > 4) return 'style="color:#ff4141"'; if ($n > 2) return 'style="color:#ef8400"'; return 'style="color:#90bd00"'; } private function getQueryColor($n) { if ($n > 5) return 'style="color:#ff4141"'; if ($n > 2) return 'style="color:#ef8400"'; return 'style="color:#90bd00"'; } private function getTableColor($n) { if ($n > 30) return 'style="color:#ff4141"'; if ($n > 20) return 'style="color:#ef8400"'; return 'style="color:#90bd00"'; } private function getObjectModelColor($n) { if ($n > 50) return 'style="color:#ff4141"'; if ($n > 10) return 'style="color:#ef8400"'; return 'style="color:#90bd00"'; } public function __construct() { parent::__construct(); // error management set_error_handler('developpementErrorHandler'); ini_set('html_errors', 'on'); ini_set('display_errors', 'on'); error_reporting(E_ALL | E_STRICT); if (!self::$_footer) return; $this->_memory['config'] = memory_get_usage(); $this->_mempeak['config'] = memory_get_peak_usage(); $this->_time['config'] = microtime(true); parent::__construct(); $this->_memory['constructor'] = memory_get_usage(); $this->_mempeak['constructor'] = memory_get_peak_usage(); $this->_time['constructor'] = microtime(true); } public function run() { if (!class_exists('DebugToolbar')) return parent::run(); if (!DebugToolbar::isEnable()) return parent::run(); $this->init(); $this->_memory['init'] = memory_get_usage(); $this->_mempeak['init'] = memory_get_peak_usage(); $this->_time['init'] = microtime(true); if ($this->checkAccess()) { $this->_memory['checkAccess'] = memory_get_usage(); $this->_mempeak['checkAccess'] = memory_get_peak_usage(); $this->_time['checkAccess'] = microtime(true); if (!$this->content_only && ($this->display_header || (isset($this->className) && $this->className))) $this->setMedia(); $this->_memory['setMedia'] = memory_get_usage(); $this->_mempeak['setMedia'] = memory_get_peak_usage(); $this->_time['setMedia'] = microtime(true); // postProcess handles ajaxProcess $this->postProcess(); $this->_memory['postProcess'] = memory_get_usage(); $this->_mempeak['postProcess'] = memory_get_peak_usage(); $this->_time['postProcess'] = microtime(true); if (!empty($this->redirect_after)) $this->redirect(); if (!$this->content_only && ($this->display_header || (isset($this->className) && $this->className))) $this->initHeader(); $this->_memory['initHeader'] = memory_get_usage(); $this->_mempeak['initHeader'] = memory_get_peak_usage(); $this->_time['initHeader'] = microtime(true); $this->initContent(); $this->_memory['initContent'] = memory_get_usage(); $this->_mempeak['initContent'] = memory_get_peak_usage(); $this->_time['initContent'] = microtime(true); if (!$this->content_only && ($this->display_footer || (isset($this->className) && $this->className))) $this->initFooter(); $this->_memory['initFooter'] = memory_get_usage(); $this->_mempeak['initFooter'] = memory_get_peak_usage(); $this->_time['initFooter'] = microtime(true); // default behavior for ajax process is to use $_POST[action] or $_GET[action] // then using displayAjax[action] if ($this->ajax) { $action = Tools::getValue('action'); if (!empty($action) && method_exists($this, 'displayAjax'.Tools::toCamelCase($action))) $this->{'displayAjax'.$action}(); elseif (method_exists($this, 'displayAjax')) $this->displayAjax(); } else $this->displayDebug(); } else { $this->initCursedPage(); $this->displayDebug(); } } private function ini_get_display_errors() { $a = 'display_errors'; $b = ini_get($a); switch (strtolower($b)) { case 'on': case 'yes': case 'true': return 'assert.active' !== $a; case 'stdout': case 'stderr': return 'display_errors' === $a; default: return (bool)(int)$b; } } private function sizeofvar($var) { $start_memory = memory_get_usage(); try { $tmp = Tools::unSerialize(serialize($var)); } catch (Exception $e) { $tmp = $this->getVarData($var); } $size = memory_get_usage() - $start_memory; return $size; } private function getVarData($var) { if (is_object($var)) return $var; return (string)$var; } public function displayDebug() { global $start_time; $this->display(); $this->_memory['display'] = memory_get_usage(); $this->_mempeak['display'] = memory_get_peak_usage(); $this->_time['display'] = microtime(true); if (!$this->ini_get_display_errors()) return; $memory_peak_usage = memory_get_peak_usage(); $hr = '<hr style="color:#F5F5F5;margin:2px" />'; $totalSize = 0; foreach (get_included_files() as $file) $totalSize += filesize($file); $totalQueryTime = 0; foreach (Db::getInstance()->queries as $data) $totalQueryTime += $data['time']; $hooktime = Hook::getHookTime(); arsort($hooktime); $totalHookTime = 0; foreach ($hooktime as $time) $totalHookTime += $time; $hookMemoryUsage = Hook::getHookMemoryUsage(); arsort($hookMemoryUsage); $totalHookMemoryUsage = 0; foreach ($hookMemoryUsage as $usage) $totalHookMemoryUsage += $usage; $globalSize = array(); $totalGlobalSize = 0; foreach ($GLOBALS as $key => $value) if ($key != 'GLOBALS') { $totalGlobalSize += ($size = $this->sizeofvar($value)); if ($size > 1024) $globalSize[$key] = round($size / 1024, 1); } arsort($globalSize); $cache = Cache::retrieveAll(); $totalCacheSize = $this->sizeofvar($cache); $output = ''; $output .= '<link href="'.Tools::getHttpHost(true).__PS_BASE_URI__.'modules/debugtoolbar/views/assets/css/debugtoolbar.css" rel="stylesheet" type="text/css" media="all">'; $output .= ' <div class="debugtoolbar"> <div class="debugtoolbar-window"> <div class="debugtoolbar-content-area"> '; /* LOAD TIME */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-load-times">'; $output .= ' <table> <tr> <th>Name</th> <th>Running Time (ms)</th> </tr> <tr> <td class="debugtoolbar-table-first">Global Application</td> <td>'.$this->displayLoadTimeColor($this->_time['display'] - $start_time, true).'</td> </tr> '; $last_time = $start_time; foreach ($this->_time as $k => $time) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.ucfirst($k).'</td> <td>'.$this->displayLoadTimeColor($time - $last_time, true).'</td> </tr> '; $last_time = $time; } $output .= ' </table> '; $output .= ' </div>'; /* /LOAD TIME */ /* HOOK PROCESSING */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-hook-processing">'; $output .= ' <table> <tr> <th>Name</th> <th>Running Time (ms) / Memory Usage</th> </tr> <tr> <td class="debugtoolbar-table-first">Global Hook</td> <td><pre>'.$this->displayLoadTimeColor($totalHookTime).' / '.$this->displayMemoryColor($totalHookMemoryUsage).'</pre></td> </tr> '; foreach ($hooktime as $hook => $time) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.ucfirst($hook).'</td> <td><pre>'.$this->displayLoadTimeColor($time).' / '.$this->displayMemoryColor($hookMemoryUsage[$hook]).'</pre></td> </tr> '; } $output .= ' </table> '; $output .= ' </div>'; /* /HOOK PROCESSING */ /* MEMORY PEAK USAGE */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-memory-peak-usage">'; $output .= ' <table> <tr> <th>Name</th> <th>Memory Usage (Global)</th> </tr> <tr> <td class="debugtoolbar-table-first">Global Memory</td> <td><pre>'.$this->displayPeakMemoryColor($memory_peak_usage).'</pre></td> </tr> '; foreach ($this->_memory as $k => $memory) { $last_memory = 0; $output .= ' <tr> <td class="debugtoolbar-table-first">'.ucfirst($k).'</td> <td><pre>'.$this->displayMemoryColor($memory - $last_memory).' ('.$this->displayPeakMemoryColor($this->_mempeak[$k]).')</pre></td> </tr> '; $last_memory = $memory; } $output .= ' </table> '; $output .= ' </div>'; /* /MEMORY PEAK USAGE */ /* INCLUDED FILES */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-included-files">'; $output .= ' <table> <tr> <th>#</th> <th>File</th> <th>Size</th> </tr> <tr> <td class="debugtoolbar-table-first">Size global files</td> <td><pre>'.$this->displayMemoryColor($totalSize).'</pre></td> <td>-</td> </tr> '; $i = 1; foreach (get_included_files() as $file) { $f = ltrim(str_replace('\\', '/', str_replace(_PS_ROOT_DIR_, '', $file)), '/'); $f = dirname($file).'/<span style="color: #0080b0">'.basename($file).'</span>'; $output .= ' <tr> <td class="debugtoolbar-table-first">'.$i.'</td> <td><pre>'.$f.'</pre></td> <td>'.FileSizeConvert(@filesize($file)).'</td> </tr> '; $i++; } $output .= ' </table> '; $output .= ' </div>'; /* /INCLUDED FILES */ /* SQL QUERIES */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-sql-queries">'; $output .= ' <table> <tr> <th>Time</th> <th>Query</th> </tr> '; $array_queries = array(); $queries = Db::getInstance()->queries; uasort($queries, 'prestashop_querytime_sort'); foreach ($queries as $data) { $query_row = array( 'time' => $data['time'], 'query' => $data['query'], 'location' => $data['file'].':<span style="color:#0080b0">'.$data['line'].'</span>', 'filesort' => false, 'rows' => 1, 'group_by' => false ); if (preg_match('/^\s*select\s+/i', $data['query'])) { $explain = Db::getInstance()->executeS('explain '.$data['query']); if (stristr($explain[0]['Extra'], 'filesort')) $query_row['filesort'] = true; foreach ($explain as $row) $query_row['rows'] *= $row['rows']; if (stristr($data['query'], 'group by') && !preg_match('/(avg|count|min|max|group_concat|sum)\s*\(/i', $data['query'])) $query_row['group_by'] = true; } $array_queries[] = $query_row; } foreach ($array_queries as $data) { $filestortGroup = ''; if (preg_match('/^\s*select\s+/i', $data['query'])) { if ($data['filesort']) $filestortGroup .= '<b '.$this->getTimeColor($data['time'] * 1000).'>USING FILESORT</b> - '; $filestortGroup .= $this->displayRowsBrowsed($data['rows']); if ($data['group_by']) $filestortGroup .= ' - <b>Useless GROUP BY need to be removed</b>'; } $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Query in : </strong>'.$data['location'].' - '.$filestortGroup.'</td> </tr> <tr> <td class="debugtoolbar-table-first"><span '.$this->getTimeColor($data['time'] * 1000).'>'.round($data['time'] * 1000, 3).' ms</span></td> <td><pre>'.htmlspecialchars($data['query'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> '; } $output .= ' </table> '; $output .= ' </div>'; /* /SQL QUERIES */ /* TABLES */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-sql-table">'; $output .= ' <table> <tr> <th>Nb call</th> <th>Table</th> </tr> '; $tables = Db::getInstance()->tables; arsort($tables); foreach ($tables as $table => $nb) { $output .= ' <tr> <td class="debugtoolbar-table-first"><b '.$this->getTableColor($nb).'>'.$nb.'</b></td> <td><pre>'.$table.'</pre></td> </tr> '; } $output .= ' </table> '; $output .= ' </div>'; /* /TABLES */ /* OBJECTMODEL */ if (isset(ObjectModel::$debug_list)) { $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-objectmodel-instance">'; $output .= ' <table> <tr> <th>Nb call</th> <th>ObjectModel Instance</th> </tr> '; $list = ObjectModel::$debug_list; uasort($list, create_function('$a,$b', 'return (count($a) < count($b)) ? 1 : -1;')); $i = 0; foreach ($list as $class => $info) { echo ''; echo ''; $i++; $output .= ' <tr> <td class="debugtoolbar-table-first"><b '.$this->getObjectModelColor(count($info)).'>'.count($info).'</b></td> <td><a href="#" onclick="$(\'#object_model_'.$i.'\').css(\'display\', $(\'#object_model_'.$i.'\').css(\'display\') == \'none\' ? \'block\' : \'none\'); return false" style="color:#0080b0">'.$class.'</a> <pre id="object_model_'.$i.'" style="display: none">'; foreach ($info as $trace) $output .= ltrim(str_replace(array(_PS_ROOT_DIR_, '\\'), array('', '/'), $trace['file']), '/').' ['.$trace['line'].']<br />'; $output .= '</pre></td> </tr> '; } $output .= ' </table> '; $output .= ' </div>'; } /* /OBJECTMODEL */ /* GETALLHEADERS */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-getallheader">'; $output .= ' <table> <tr> <th>Name</th> <th>Value</th> </tr> '; $getallheaders = getallheaders(); foreach ($getallheaders as $name => $value) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td><pre>'.$value.'</pre></td> </tr> '; } stream_context_set_default(array('http' => array('method' => 'HEAD'))); $url = getUrl(); if ($get_headers = get_headers($url, 1)) { foreach ($get_headers as $name => $value) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td><pre>'.(is_array($value) ? $value[0] : $value).'</pre></td> </tr> '; } } $output .= ' </table> '; $output .= ' </div>'; /* /GETALLHEADERS */ /* DATA */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-getpost-data">'; $output .= ' <table> <tr> <th>Name</th> <th>Value</th> </tr> <tr> <td class="debugtoolbar-table-title" colspan="2">Post Data</td> </tr> '; $post = isset($_POST) ? $_POST : array(); if(!count($post)) $output .= '<tr><td colspan="2">No POST Data Found</td></tr>'; else { foreach ($post as $name => $value) { if(!is_array($value)) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td><pre>'.$value.'</pre></td> </tr> '; } else { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td> '; foreach ($value as $k => $v) { $output .= ' <pre>'.$k.' : '.$v.'</pre> '; } $output .= ' </td> </tr> '; } } } $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2">Get Data</td> </tr> '; $get = isset($_GET) ? $_GET : array(); if(!count($get)) $output .= '<tr><td colspan="2">No GET Data Found</td></tr>'; else { foreach ($get as $name => $value) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td><pre>'.$value.'</pre></td> </tr> '; } } $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2">Server Data</td> </tr> '; $server = isset($_SERVER) ? $_SERVER : array(); if(!count($server)) $output .= '<tr><td colspan="2">No SERVER Data Found</td></tr>'; else { foreach ($server as $name => $value) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td><pre>'.$value.'</pre></td> </tr> '; } } $output .= ' </table> '; $output .= ' </div>'; /* /DATA */ /* DEBUG */ if(count($GLOBALS['debugtoolbar'])) { $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-debug">'; $output .= ' <table> <tr> <th>Debug</th> </tr> '; $output .= ' <tr> <td colspan="2">'.$GLOBALS['debugtoolbar'].'</td> </tr> '; $output .= ' </table> '; $output .= ' </div>'; } /* /DEBUG */ /* PS INFOS */ if (isset($this->context->employee->id)) : $ps_infos = array( 'version' => array( 'php' => phpversion(), 'server' => $_SERVER['SERVER_SOFTWARE'], 'memory_limit' => ini_get('memory_limit'), 'max_execution_time' => ini_get('max_execution_time') ), 'database' => array( 'version' => Db::getInstance()->getVersion(), 'prefix' => _DB_PREFIX_, 'engine' => _MYSQL_ENGINE_, ), 'uname' => function_exists('php_uname') ? php_uname('s').' '.php_uname('v').' '.php_uname('m') : '', 'apache_instaweb' => Tools::apacheModExists('mod_instaweb'), 'shop' => array( 'ps' => _PS_VERSION_, 'url' => Tools::getHttpHost(true).__PS_BASE_URI__, 'theme' => _THEME_NAME_, ), 'mail' => Configuration::get('PS_MAIL_METHOD') == 1, 'smtp' => array( 'server' => Configuration::get('PS_MAIL_SERVER'), 'user' => Configuration::get('PS_MAIL_USER'), 'password' => Configuration::get('PS_MAIL_PASSWD'), 'encryption' => Configuration::get('PS_MAIL_SMTP_ENCRYPTION'), 'port' => Configuration::get('PS_MAIL_SMTP_PORT'), ), 'user_agent' => $_SERVER['HTTP_USER_AGENT'], ); $tests = ConfigurationTest::getDefaultTests(); $tests_op = ConfigurationTest::getDefaultTestsOp(); $params_required_results = ConfigurationTest::check($tests); $params_optional_results = ConfigurationTest::check($tests_op); $tests_errors = array( 'phpversion' => 'Update your PHP version', 'upload' => 'Configure your server to allow file uploads', 'system' => 'Configure your server to allow the creation of directories and files with write permissions.', 'gd' => 'Enable the GD library on your server.', 'mysql_support' => 'Enable the MySQL support on your server.', 'config_dir' => 'Set write permissions for the "config" folder.', 'cache_dir' => 'Set write permissions for the "cache" folder.', 'sitemap' => 'Set write permissions for the "sitemap.xml" file.', 'img_dir' => 'Set write permissions for the "img" folder and subfolders.', 'log_dir' => 'Set write permissions for the "log" folder and subfolders.', 'mails_dir' => 'Set write permissions for the "mails" folder and subfolders.', 'module_dir' => 'Set write permissions for the "modules" folder and subfolders.', 'theme_lang_dir' => 'Set the write permissions for the "themes'._THEME_NAME_.'/lang/" folder and subfolders, recursively.', 'translations_dir' => 'Set write permissions for the "translations" folder and subfolders.', 'customizable_products_dir' => 'Set write permissions for the "upload" folder and subfolders.', 'virtual_products_dir' => 'Set write permissions for the "download" folder and subfolders.', 'fopen' => 'Allow the PHP fopen() function on your server', 'register_globals' => 'Set PHP "register_global" option to "Off"', 'gz' => 'Enable GZIP compression on your server.' ); $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-ps-info">'; $output .= " <script type=\"text/javascript\"> $(document).ready(function() { $.ajax({ type: 'GET', url: '".$this->context->link->getAdminLink('AdminInformation')."', data: { 'action': 'checkFiles', 'ajax': 1 }, dataType: 'json', success: function(json) { var tab = { 'missing': 'Missing files', 'updated': 'Updated files' }; if (json.missing.length || json.updated.length) $('#changedFilesDebugtoolbar').html('<div style=\"color:#ef8400;\">Changed/missing files have been detected.</div>'); else $('#changedFilesDebugtoolbar').html('<div style=\"color:#0080b0;\">No change has been detected in your files</div>'); $.each(tab, function(key, lang) { if (json[key].length) { var html = $('<ul>').attr('id', key+'_files'); $(json[key]).each(function(key, file) { html.append($('<li>').html(file)) }); $('#changedFilesDebugtoolbar') .append($('<h3>').html(lang+' ('+json[key].length+')')) .append(html); } }); } }); }); </script> "; $output .= ' <table> <tr> <th>Name</th> <th>Value</th> </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Server Informations</strong></td> </tr> <tr> <td class="debugtoolbar-table-first">Server</td> <td><pre>'.htmlspecialchars($ps_infos['uname'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Logiciel Serveur</td> <td><pre>'.htmlspecialchars($ps_infos['version']['server'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">PHP Version</td> <td><pre>'.htmlspecialchars($ps_infos['version']['php'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Memory Limit</td> <td><pre>'.htmlspecialchars($ps_infos['version']['memory_limit'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Max Execution Time</td> <td><pre>'.htmlspecialchars($ps_infos['version']['max_execution_time'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Database Informations</strong></td> </tr> <tr> <td class="debugtoolbar-table-first">MySQL Version</td> <td><pre>'.htmlspecialchars($ps_infos['database']['version'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">MySQL Engine</td> <td><pre>'.htmlspecialchars($ps_infos['database']['engine'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">MySQL Prefix</td> <td><pre>'.htmlspecialchars($ps_infos['database']['prefix'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Store Informations</strong></td> </tr> <tr> <td class="debugtoolbar-table-first">PrestaShop Version</td> <td><pre>'.htmlspecialchars($ps_infos['shop']['ps'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Store Url</td> <td><pre>'.htmlspecialchars($ps_infos['shop']['url'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Themes Use</td> <td><pre>'.htmlspecialchars($ps_infos['shop']['theme'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> '; if(!empty($ps_infos['mail'])) : $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Email Setting</strong></td> </tr> <tr> <td colspan="2"><pre>You are using the PHP mail function.</pre></td> </tr> '; else : $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Email Setting</strong></td> </tr> <tr> <td class="debugtoolbar-table-first">SMTP Server</td> <td><pre>'.htmlspecialchars($ps_infos['smtp']['server'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Cryptage</td> <td><pre>'.htmlspecialchars($ps_infos['smtp']['encryption'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Port</td> <td><pre>'.htmlspecialchars($ps_infos['smtp']['port'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Login</td> <td><pre>'.(!empty($ps_infos['smtp']['user']) ? '<span style="color:#90bd00;font-weight:bold;">OK</span>' : '<span style="color:#ff4141;font-weight:bold;">Not defined</span>').'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Password</td> <td><pre>'.(!empty($ps_infos['smtp']['password']) ? '<span style="color:#90bd00;font-weight:bold;">OK</span>' : '<span style="color:#ff4141;font-weight:bold;">Not defined</span>').'</pre></td> </tr> '; endif; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Your information</strong></td> </tr> <tr> <td class="debugtoolbar-table-first">Your web browser</td> <td><pre>'.htmlspecialchars($ps_infos['user_agent'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Check your configuration</strong></td> </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-first">Required parameters</td> '; if (!in_array('fail', $params_required_results)) : $output .= ' <td><pre><span style="color:#90bd00;font-weight:bold;">OK</span></pre></td> '; else : $output .= ' <td> <pre><span style="color:#ff4141;font-weight:bold;">Please fix the following error(s)</span></pre> <ul> '; foreach ($params_required_results as $key => $value) if ($value == 'fail') $output .= ' <li>'.$tests_errors[$key].'</li>'; $output .= ' </ul> </td> '; endif; $output .= ' </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-first">Optional parameters</td> '; if (!in_array('fail', $params_optional_results)) : $output .= ' <td><pre><span style="color:#90bd00;font-weight:bold;">OK</span></pre></td> '; else : $output .= ' <td> <pre><span style="color:#ff4141;font-weight:bold;">Please fix the following error(s)</span></pre> <ul> '; foreach ($params_optional_results as $key => $value) if ($value == 'fail') $output .= ' <li>'.$key.'</li>'; $output .= ' </ul> </td> '; endif; $output .= ' </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>List of changed files</strong></td> </tr> '; $output .= ' <tr> <td colspan="2"><div id="changedFilesDebugtoolbar"><img src="../img/admin/ajax-loader.gif" /> Checking files...</div></td> </tr> '; $output .= ' </table> '; $output .= ' </div>'; else : $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-ps-info">'; $output .= ' <table> <tr> <td><pre><span style="color:#ff4141;font-weight:bold;">Not display in Front office</span></pre></td> </tr> </table> </div> '; endif; /* /PS INFOS */ /* SMARTY DEBUG */ $this->context->smarty->loadPlugin('Smarty_Internal_Debug'); // Smarty_Internal_Debug::display_debug($this->context->smarty); $SID = new Smarty_Internal_Debug(); $obj = $this->context->smarty; $ptr = $SID::get_debug_vars($obj); if ($obj instanceof Smarty) { $smarty = clone $obj; } else { $smarty = clone $obj->smarty; } $_assigned_vars = $ptr->tpl_vars; ksort($_assigned_vars); $_config_vars = $ptr->config_vars; ksort($_config_vars); $smarty->registered_filters = array(); $smarty->autoload_filters = array(); $smarty->default_modifiers = array(); $smarty->force_compile = false; $smarty->left_delimiter = '{'; $smarty->right_delimiter = '}'; $smarty->debugging = false; $smarty->force_compile = false; if ($obj instanceof Smarty_Internal_Template) $template_name = $obj->source->type . ':' . $obj->source->name; if ($obj instanceof Smarty) $template_name = $SID::$template_data; else $template_name = null; $execution_time = microtime(true) - $smarty->start_time; $assigned_vars = $_assigned_vars; $config_vars = $_config_vars; // echo 'assigned_vars<pre>'.print_r($assigned_vars['SCRIPT_NAME'], true).'</pre>';die; $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-smarty-debug">'; $output .= ' <table> <tr> <th colspan="2">Smarty Debug Console - '.((isset($template_name) && count($template_name)) ? $template_name : 'Total Time '.number_format($execution_time, 5, '.', '')).'</th> </tr> '; if (isset($template_name) && count($template_name)) { foreach ($template_name as $template) { $output .= ' <tr> <td class="debugtoolbar-table-first"><font color=brown>'.$template['name'].'</font></td> <td> <span style="font-size: 0.8em;font-style: italic;"> '.number_format($template['compile_time'], 5, '.', '').' '.number_format($template['render_time'], 5, '.', '').' '.number_format($template['cache_time'], 5, '.', '').' </span> </td> </tr> '; } } $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Assigned template variables</strong></td> </tr> '; foreach ($assigned_vars as $key => $vars) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$key.'</td> <td><pre>'.smarty_modifier_debug_print_var($vars).'</pre></td> </tr> '; } $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><trong>Assigned config file variables (outer template scope)</strong></td> </tr> '; foreach ($config_vars as $key => $vars) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$key.'</td> <td><pre>'.smarty_modifier_debug_print_var($vars).'</pre></td> </tr> '; } $output .= ' </table> '; $output .= ' </div>'; /* SMARTY DEBUG */ /* ADMINER */ if (isset($this->context->employee->id)) : $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-adminer">'; $output .= ' <table> <tr> <th>Adminer</th> </tr> '; $output .= ' <tr> <td colspan="2"> <iframe src="'.Tools::getHttpHost(true).__PS_BASE_URI__.'modules/debugtoolbar/tools/adminer/display.php?server='._DB_SERVER_.'&username='._DB_USER_.'&db='._DB_NAME_.'" frameborder="0" height="880" width="100%" id="adminerFrame"></iframe> <script type="text/javascript"> $(\'#adminerFrame\').load(function(){ $self = $(this).contents(); $self.find("input[name=\'auth[server]\']").val("'._DB_SERVER_.'"); $self.find("input[name=\'auth[username]\']").val("'._DB_USER_.'"); $self.find("input[name=\'auth[password]\']").val("'._DB_PASSWD_.'"); $self.find("input[name=\'auth[db]\']").val("'._DB_NAME_.'"); }); </script> </td> </tr> '; $output .= ' </table> '; $output .= ' </div>'; else : $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-adminer">'; $output .= ' <table> <tr> <td><pre><span style="color:#ff4141;font-weight:bold;">Not display in Front office</span></pre></td> </tr> </table> </div> '; endif; /* /ADMINER */ $output .= ' </div> </div> <ul id="debugtoolbar-open-tabs" class="debugtoolbar-tabs"> <!-- LOAD TIME --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-load-times">Time <span class="debugtoolbar-count">'.$this->displayLoadTimeColor($this->_time['display'] - $start_time).'</span></a></li> <!-- /LOAD TIME --> <!-- HOOK PROCESSING --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-hook-processing">Hook <span class="debugtoolbar-count">'.$this->displayLoadTimeColor($totalHookTime).' / '.$this->displayMemoryColor($totalHookMemoryUsage).'</span></a></li> <!-- /HOOK PROCESSING --> <!-- MEMORY PEAK USAGE --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-memory-peak-usage">Memory <span class="debugtoolbar-count">'.$this->displayPeakMemoryColor($memory_peak_usage).'</span></a></li> <!-- /MEMORY PEAK USAGE --> <!-- INCLUDED FILES --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-included-files">Files <span class="debugtoolbar-count">'.sizeof(get_included_files()).'</span></a></li> <!-- /INCLUDED FILES --> <!-- SQL QUERIES --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-sql-queries">Sql <span class="debugtoolbar-count">'.$this->displaySQLQueries(count(Db::getInstance()->queries)).'</span><span class="debugtoolbar-count">'.$this->displayLoadTimeColor($totalQueryTime).'</span></a></li> <!-- /SQL QUERIES --> <!-- TABLE --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-sql-table">Table</a></li> <!-- /TABLE --> <!-- OBJECTMODEL --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-objectmodel-instance">ObjectModel</a></li> <!-- /OBJECTMODEL --> <!-- GETALLHEADERS --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-getallheader">Header</a></li> <!-- /GETALLHEADERS --> <!-- DATA --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-getpost-data">Data</a></li> <!-- /DATA --> <!-- PS INFOS --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-ps-info">Infos</a></li> <!-- /PS INFOS --> <!-- SMARTY DEBUG --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-smarty-debug">Smarty</a></li> <!-- /SMARTY DEBUG --> <!-- ADMINER --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-adminer">Adminer</a></li> <!-- /ADMINER --> '; if(count($GLOBALS['debugtoolbar'])) { $output .= ' <!-- DEBUG --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-debug">Debug</a></li> <!-- /DEBUG --> '; } $output .= ' <li class="debugtoolbar-tab-right"><a id="debugtoolbar-hide" href="#">&#8614;</a></li> <li class="debugtoolbar-tab-right"><a id="debugtoolbar-close" href="#">&times;</a></li> <li class="debugtoolbar-tab-right"><a id="debugtoolbar-zoom" href="#">&#8645;</a></li> </ul> <ul id="debugtoolbar-closed-tabs" class="debugtoolbar-tabs"> <li><a id="debugtoolbar-show" href="#">&#8612;</a></li> </ul> </div> '; $output .= '<script type="text/javascript" src="'.Tools::getHttpHost(true).__PS_BASE_URI__.'modules/debugtoolbar/views/assets/js/debugtoolbar.js"></script>'; echo $output; } } function prestashop_querytime_sort($a, $b) { if ($a['time'] == $b['time']) return 0; return ($a['time'] > $b['time']) ? -1 : 1; }
Prestaspirit/debugtoolbar
override/classes/controller/Controller.php
PHP
gpl-3.0
48,323
// Simple 3D Model Viewer // Copyright (C) 2012 Ingo Ruhnke <grumbel@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef HEADER_ASSERT_GL_HPP #define HEADER_ASSERT_GL_HPP #include <sstream> #include <stdexcept> #include "opengl.hpp" #include "format.hpp" #define assert_gl(...) assert_gl_1(__FILE__, __LINE__, __VA_ARGS__) template<typename ...Arg> inline void assert_gl_1(const char* file, int line, const std::string& fmt, Arg... arg) { GLenum error = glGetError(); if(error != GL_NO_ERROR) { #ifdef HAVE_OPENGLES2 throw std::runtime_error(format("%s:%d: OpenGLError while '%s': %s", file, line, format(fmt, arg...), error)); #else throw std::runtime_error(format("%s:%d: OpenGLError while '%s': %s", file, line, format(fmt, arg...), gluErrorString(error))); #endif } } #endif /* EOF */
Grumbel/viewer
src/assert_gl.hpp
C++
gpl-3.0
1,656
<?php /** * Template part for displaying page content in page.php. * * @link https://codex.wordpress.org/Template_Hierarchy * * @package lorainccc */ ?> <?php $whattodisplay = 'lccc-events'; $today = getdate(); $currentDay = $today['mday']; $month = $today['mon']; $year = $today['year']; $firsteventdate =''; $nexteventdate =''; $todaysevents = ''; $temp = strLen($currentDay); $twoDay = ''; $nextTwoDay = ''; if ($temp < 2){ $twoDay = '0' . $currentDay; }else{ $twoDay = $currentDay; } $twomonth = ''; $tempmonth = strLen($month); if ($tempmonth < 2){ $twomonth = '0' . $month; }else{ $twomonth = $month; } $nextDay = $currentDay + 1; if ($temp < 2){ $nextTwoDay = '0' . $currentDay; }else{ $nextTwoDay = $currentDay; } $starteventdate = event_meta_box_get_meta('event_start_date'); $starteventtime = event_meta_box_get_meta('event_start_time'); $endeventdate = event_meta_box_get_meta('event_end_date'); $endtime = event_meta_box_get_meta('event_end_time'); $starttimevar=strtotime($starteventtime); $starttime= date("h:i a",$starttimevar); $starteventtimehours = date("G",$starttimevar); $starteventtimeminutes = date("i",$starttimevar); $startdate=strtotime($starteventdate); $eventstartdate=date("Y-m-d",$startdate); $eventstartmonth=date("M",$startdate); $eventstartmonthfull=date("F",$startdate); $eventstartday =date("j",$startdate); $eventstartyear =date("Y",$startdate); $endeventtimevar=strtotime($endtime); $endeventtime = date("h:i a",$endeventtimevar); $endeventtimehours = date("G",$endeventtimevar); $endeventtimeminutes = date("i",$endeventtimevar); $enddate=strtotime($endeventdate); $endeventdate = date("Y-m-d",$enddate); $duration = ''; if($endeventtimehours == 0){ $endeventtimehours =24; } $durationhours = $endeventtimehours - $starteventtimehours; if($durationhours > 0){ if($durationhours == 24){ $duration .= '1 day'; }else{ $duration .= $durationhours.'hrs'; } } $durationminutes = $endeventtimeminutes - $starteventtimeminutes; if($durationminutes > 0){ $duration .= $durationminutes.'mins'; } $location = event_meta_box_get_meta('event_meta_box_event_location'); $cost = event_meta_box_get_meta('event_meta_box_ticket_price_s_'); $bgcolor = event_meta_box_get_meta('event_meta_box_stoccker_bg_color'); $ticketlink = event_meta_box_get_meta('event_meta_box_stocker_ticket_link'); $eventsubheading = event_meta_box_get_meta('event_meta_box_sub_heading'); ?> <article id="post-<?php the_ID(); ?>"> <div class="small-12 medium-12 large-12 columns"> <?php the_title( '<h1 class="entry-title indiv-event">', '</h1>' ); ?> <?php if( $eventsubheading != ''){ ?> <h4 class="event-sub-heading"><?php echo $eventsubheading;?> </h4> <?php } ?> </div> <div class="small-12 medium-2 large-2 columns"> <?php echo '<div class="small-12 medium-12 large-12 columns event-date">'; echo '<div class="small-12 medium-12 large-12 columns calender">'; echo '<p class="stocker-month">'.$eventstartmonth.'</p>'; echo '<p class="stocker-day">'.$eventstartday.'</p>'; echo '</div>'; echo '</div>'; ?> </div> <div class="small-12 medium-10 large-10 columns nopadding"> <header class="entry-header"> <div class="taxonomies"> <?php echo get_the_term_list( $post->ID, 'event_categories','', ' , ' , ''); ?> </div> <p><?php echo 'Date: '.$eventstartmonthfull.' '.$eventstartday.' , '.$eventstartyear; ?></p> <p><?php echo 'Time: '.$starttime; ?></p> <p><?php echo 'Location: '.$location; ?></p> <?php if($cost != ''){ ?> <p><?php echo 'Cost: '.$cost; ?></p> <?php } ?> <?php if($ticketlink != ''){ ?> <a href=" <?php echo $ticketlink; ?>" class="buy-ticket-link">Buy Tickets</a> <?php } ?> </header><!-- .entry-header --> </div> <div class="small-12 medium-12large-12 columns content-container"> <div class="entry-content"> <div class="small-12 medium-12large-12 columns nopadding"> <?php the_content(); ?> </div> <div class="small-12 medium-4 large-4 columns nopadding"> <?php echo '<br /> <br /> <a class="button" href="'.get_post_type_archive_link( 'lccc_events' ).'">Back To All Events </a>';?> </div> <div class="small-12 medium-8 large-8 columns"> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'lorainccc' ), 'after' => '</div>', ) ); ?> </div> </div><!-- .entry-content --> </div> <?php if ( get_edit_post_link() ) : ?> <?php edit_post_link( sprintf( /* translators: %s: Name of current post */ esc_html__( 'Edit %s', 'lorainccc' ), the_title( '<span class="screen-reader-text">"', '"</span>', false ) ), '<span class="edit-link">', '</span>' ); ?> <?php endif; ?> </article><!-- #post-## -->
lorainccc/themes
lorainccc_stocker/template-parts/content-lccc-event.php
PHP
gpl-3.0
5,375
#include <vigir_footstep_planning_default_plugins/world_model/terrain_model.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <vigir_footstep_planning_lib/helper.h> #include <vigir_footstep_planning_lib/math.h> #include <vigir_terrain_classifier/terrain_model.h> namespace vigir_footstep_planning { TerrainModel::TerrainModel(const std::string& name) : TerrainModelPlugin(name) { } bool TerrainModel::initialize(const vigir_generic_params::ParameterSet& params) { if (!TerrainModelPlugin::initialize(params)) return false; // get foot dimensions getFootSize(nh_, foot_size); // subscribe std::string topic; getParam("terrain_model_topic", topic, std::string("terrain_model"), true); terrain_model_sub = nh_.subscribe(topic, 1, &TerrainModel::setTerrainModel, this); return true; } bool TerrainModel::loadParams(const vigir_generic_params::ParameterSet& params) { if (!TerrainModelPlugin::loadParams(params)) return false; params.getParam("foot_contact_support/min_sampling_steps_x", min_sampling_steps_x); params.getParam("foot_contact_support/min_sampling_steps_y", min_sampling_steps_y); params.getParam("foot_contact_support/max_sampling_steps_x", max_sampling_steps_x); params.getParam("foot_contact_support/max_sampling_steps_y", max_sampling_steps_y); params.getParam("foot_contact_support/max_intrusion_z", max_intrusion_z); params.getParam("foot_contact_support/max_ground_clearance", max_ground_clearance); params.getParam("foot_contact_support/minimal_support", minimal_support); return true; } void TerrainModel::reset() { TerrainModelPlugin::reset(); boost::unique_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); if (terrain_model) terrain_model->reset(); } bool TerrainModel::isAccessible(const State& s) const { return s.getGroundContactSupport() >= minimal_support; } bool TerrainModel::isAccessible(const State& next, const State& /*current*/) const { return isAccessible(next); } bool TerrainModel::isTerrainModelAvailable() const { return terrain_model && terrain_model->hasTerrainModel(); } void TerrainModel::setTerrainModel(const vigir_terrain_classifier::TerrainModelMsg::ConstPtr& terrain_model) { boost::unique_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); // update terrain model if (!this->terrain_model) this->terrain_model.reset(new vigir_terrain_classifier::TerrainModel(*terrain_model)); else this->terrain_model->fromMsg(*terrain_model); } double TerrainModel::getResolution() const { boost::shared_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); return terrain_model->getResolution(); } bool TerrainModel::getPointWithNormal(const pcl::PointNormal& p_search, pcl::PointNormal& p_result) const { boost::shared_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); return terrain_model->getPointWithNormal(p_search, p_result); } bool TerrainModel::getHeight(double x, double y, double& height) const { boost::shared_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); return terrain_model->getHeight(x, y, height); } bool TerrainModel::getFootContactSupport(const geometry_msgs::Pose& p, double &support, pcl::PointCloud<pcl::PointXYZI>::Ptr checked_positions) const { tf::Pose p_tf; tf::poseMsgToTF(p, p_tf); return getFootContactSupport(p_tf, support, checked_positions); } bool TerrainModel::getFootContactSupport(const tf::Pose& p, double& support, pcl::PointCloud<pcl::PointXYZI>::Ptr checked_positions) const { if (!getFootContactSupport(p, support, min_sampling_steps_x, min_sampling_steps_y, checked_positions)) return false; // refinement of solution if needed if (support == 0.0) // collision, no refinement { return true; } else if (support < 0.95) { if (!getFootContactSupport(p, support, max_sampling_steps_x, max_sampling_steps_y, checked_positions)) return false; } return true; } bool TerrainModel::getFootContactSupport(const tf::Pose& p, double &support, unsigned int sampling_steps_x, unsigned int sampling_steps_y, pcl::PointCloud<pcl::PointXYZI>::Ptr checked_positions) const { /// TODO: find efficient solution to prevent inconsistency //boost::shared_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); support = 0.0; unsigned int contacts = 0; unsigned int unknown = 0; unsigned int total = 0; tf::Vector3 orig_pos; orig_pos.setZ(0.0); double foot_size_half_x = 0.5*foot_size.x; double foot_size_half_y = 0.5*foot_size.y; double sampling_step_x = foot_size.x/(double)(sampling_steps_x-1); double sampling_step_y = foot_size.y/(double)(sampling_steps_y-1); for (double y = -foot_size_half_y; y <= foot_size_half_y; y+=sampling_step_y) { orig_pos.setY(y); for (double x = -foot_size_half_x; x <= foot_size_half_x; x+=sampling_step_x) { total++; // determine point in world frame and get height at this point orig_pos.setX(x); const tf::Vector3 &trans_pos = p * orig_pos; double height = 0.0; if (!getHeight(trans_pos.getX(), trans_pos.getY(), height)) { //ROS_WARN_THROTTLE(1.0, "getFootSupportArea: No height data found at %f/%f", p.getOrigin().getX(), p.getOrigin().getY()); unknown++; continue; } // diff heights double diff = trans_pos.getZ()-height; // save evaluated point for visualization if (checked_positions) { pcl::PointXYZI p_checked; p_checked.x = trans_pos.getX(); p_checked.y = trans_pos.getY(); p_checked.z = trans_pos.getZ(); p_checked.intensity = std::abs(diff); checked_positions->push_back(p_checked); //ROS_INFO("%f %f | %f %f | %f", x, y, p.z, height, diff); } // check diff in z if (diff < -max_intrusion_z) // collision -> no support! return true; else if (diff < max_ground_clearance) // ground contact contacts++; } } if (unknown == total) { return false; } else { /// @ TODO: refinement (center of pressure) support = static_cast<double>(contacts)/static_cast<double>(total); return true; } } bool TerrainModel::update3DData(geometry_msgs::Pose& p) const { return terrain_model->update3DData(p); } bool TerrainModel::update3DData(State& s) const { /// TODO: find efficient solution to prevent inconsistency //boost::shared_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); bool result = true; // get z double z = s.getZ(); if (!getHeight(s.getX(), s.getY(), z)) { //ROS_WARN_THROTTLE(1.0, "No height data found at %f/%f", s.getX(), s.getY()); result = false; } else { s.setZ(z); } // get roll and pitch pcl::PointNormal p_n; p_n.x = s.getX(); p_n.y = s.getY(); p_n.z = s.getZ(); if (!getPointWithNormal(p_n, p_n)) { //ROS_WARN_THROTTLE(1.0, "No normal data found at %f/%f", s.getX(), s.getY()); result = false; } else { s.setNormal(p_n.normal_x, p_n.normal_y, p_n.normal_z); } // determine ground contact support double support = 0.0; if (!getFootContactSupport(s.getPose(), support)) { //ROS_WARN_THROTTLE(1.0, "Couldn't determine ground contact support at %f/%f", s.getX(), s.getY()); result = false; } else { s.setGroundContactSupport(support); } return result; } } #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(vigir_footstep_planning::TerrainModel, vigir_footstep_planning::TerrainModelPlugin)
team-vigir/vigir_footstep_planning_core
vigir_footstep_planning_default_plugins/src/world_model/terrain_model.cpp
C++
gpl-3.0
7,592
<?php /***************************************************************************\ * SPIP, Système de publication pour l'internet * * * * Copyright © avec tendresse depuis 2001 * * Arnaud Martin, Antoine Pitrou, Philippe Rivière, Emmanuel Saint-James * * * * Ce programme est un logiciel libre distribué sous licence GNU/GPL. * * Pour plus de détails voir le fichier COPYING.txt ou l'aide en ligne. * \***************************************************************************/ if (!defined('_ECRIRE_INC_VERSION')) { return; } include_spip('base/abstract_sql'); function install_etape_2_dist() { $adresse_db = defined('_INSTALL_HOST_DB') ? _INSTALL_HOST_DB : _request('adresse_db'); if (preg_match(',(.*):(.*),', $adresse_db, $r)) { [, $adresse_db, $port] = $r; } else { $port = ''; } $login_db = defined('_INSTALL_USER_DB') ? _INSTALL_USER_DB : _request('login_db'); $pass_db = defined('_INSTALL_PASS_DB') ? _INSTALL_PASS_DB : _request('pass_db'); $server_db = defined('_INSTALL_SERVER_DB') ? _INSTALL_SERVER_DB : _request('server_db'); $name_db = defined('_INSTALL_NAME_DB') ? _INSTALL_NAME_DB : ''; $chmod = _request('chmod'); $link = spip_connect_db($adresse_db, $port, $login_db, $pass_db, $name_db, $server_db); $GLOBALS['connexions'][$server_db] = $link; $GLOBALS['connexions'][$server_db][$GLOBALS['spip_sql_version']] = $GLOBALS['spip_' . $server_db . '_functions_' . $GLOBALS['spip_sql_version']]; echo install_debut_html(); // prenons toutes les dispositions possibles pour que rien ne s'affiche ! /* * /!\ sqlite3/PDO : erreur sur join(', ', $link) * L'objet PDO ne peut pas etre transformee en chaine * Un echo $link ne fonctionne pas non plus * Il faut utiliser par exemple print_r($link) */ //echo "\n<!--\n", join(', ', $link), " $login_db "; $db_connect = 0; // revoirfunction_exists($ferrno) ? $ferrno() : 0; //echo join(', ', $GLOBALS['connexions'][$server_db]); //echo "\n-->\n"; if (($db_connect == '0') && $link) { echo "<div class='success'><b>" . _T('info_connexion_ok') . '</b></div>'; echo info_progression_etape(2, 'etape_', 'install/'); echo info_etape(_T('menu_aide_installation_choix_base') . aider('install2', true)); echo "\n", '<!-- ', sql_version($server_db), ' -->'; [$checked, $res] = install_etape_2_bases($login_db, $server_db); $hidden = (defined('_SPIP_CHMOD') ? '' : ("\n<input type='hidden' name='chmod' value='" . spip_htmlspecialchars($chmod) . "' />")) . predef_ou_cache($adresse_db . ($port ? ':' . $port : ''), $login_db, $pass_db, $server_db); echo install_etape_2_form($hidden, $checked, $res, 3); } else { echo info_progression_etape(1, 'etape_', 'install/', true); echo "<div class='error'>"; echo info_etape(_T('info_connexion_base')); echo '<h3>' . _T('avis_connexion_echec_1') . '</h3>'; echo '<p>' . _T('avis_connexion_echec_2') . '</p>'; echo "<p style='font-size: small;'>", _T('avis_connexion_echec_3'), '</p></div>'; } echo install_fin_html(); } // Liste les bases accessibles, // avec une heuristique pour preselectionner la plus probable function install_etape_2_bases($login_db, $server_db) { $res = install_etape_liste_bases($server_db, $login_db); if ($res) { [$checked, $bases] = $res; return [ $checked, "<label for='choix_db'><b>" . _T('texte_choix_base_2') . '</b><br />' . _T('texte_choix_base_3') . '</label>' . "<ul>\n<li>" . join("</li>\n<li>", $bases) . "</li>\n</ul><p>" . _T('info_ou') . ' ' ]; } $res = '<b>' . _T('avis_lecture_noms_bases_1') . '</b> ' . _T('avis_lecture_noms_bases_2') . '<p>'; $checked = false; if ($login_db) { // Si un login comporte un point, le nom de la base est plus // probablement le login sans le point -- testons pour savoir $test_base = $login_db; $ok = sql_selectdb($test_base, $server_db); $test_base2 = str_replace('.', '_', $test_base); if (sql_selectdb($test_base2, $server_db)) { $test_base = $test_base2; $ok = true; } if ($ok) { $res .= _T('avis_lecture_noms_bases_3') . '<ul>' . '<li><input name="choix_db" value="' . $test_base . "\" type='radio' id='stand' checked='checked' />" . "<label for='stand'>" . $test_base . "</label></li>\n" . '</ul>' . '<p>' . _T('info_ou') . ' '; $checked = true; } } return [$checked, $res]; } function install_etape_2_form($hidden, $checked, $res, $etape) { return generer_form_ecrire('install', ( "\n<input type='hidden' name='etape' value='$etape' />" . $hidden . (defined('_INSTALL_NAME_DB') ? '<h3>' . _T('install_nom_base_hebergeur') . ' <tt>' . _INSTALL_NAME_DB . '</tt>' . '</h3>' : "\n<fieldset><legend>" . _T('texte_choix_base_1') . "</legend>\n" . $res . "\n<input name=\"choix_db\" value=\"new_spip\" type='radio' id='nou'" . ($checked ? '' : " checked='checked'") . " />\n<label for='nou'>" . _T('info_creer_base') . "</label></p>\n<p>" . "\n<input type='text' name='table_new' class='text' value=\"spip\" size='20' /></p></fieldset>\n" ) . ((defined('_INSTALL_TABLE_PREFIX') or $GLOBALS['table_prefix'] != 'spip') ? '<h3>' . _T('install_table_prefix_hebergeur') . ' <tt>' . $GLOBALS['table_prefix'] . '</tt>' . '</h3>' : '<fieldset><legend>' . _T('texte_choix_table_prefix') . "</legend>\n" . "<p><label for='table_prefix'>" . _T('info_table_prefix') . '</label></p><p>' . "\n<input type='text' id='tprefix' name='tprefix' class='text' value='" . 'spip' # valeur par defaut . "' size='20' /></p></fieldset>" ) . bouton_suivant())); }
spip/SPIP
ecrire/install/etape_2.php
PHP
gpl-3.0
5,813
<div class="container"> <h4 class="form-signin-heading"><?php echo $lang['ADMIN_COMMANDS_START_SPOOLING']; ?></h4> <br> <a style="color: white;" href="index.php?commands&startservice"><button type="button" class="btn btn-success btn-lg"><?php echo $lang['ADMIN_COMMANDS_APPLY']; ?></button></a> <br> <hr> <h4 class="form-signin-heading"><?php echo $lang['ADMIN_COMMANDS_STOP_SPOOLING']; ?></h4> <br> <a style="color: white;" href="index.php?commands&stopservice"><button type="button" class="btn btn-success btn-lg"><?php echo $lang['ADMIN_COMMANDS_APPLY']; ?></button></a> <br> <hr> <h4 class="form-signin-heading"><?php echo $lang['ADMIN_COMMANDS_RESTART_SPOOLING']; ?></h4> <br> <a style="color: white;" href="index.php?commands&restartservice"><button type="button" class="btn btn-success btn-lg"><?php echo $lang['ADMIN_COMMANDS_APPLY']; ?></button></a> <br> <hr> <h4 class="form-signin-heading"><?php echo $lang['ADMIN_COMMANDS_REMOVE_ALL_JOBS']; ?></h4> <br> <a style="color: white;" href="index.php?commands&removealljobs"><button type="button" class="btn btn-success btn-lg"><?php echo $lang['ADMIN_COMMANDS_APPLY']; ?></button></a> <br> <hr> </div>
akshinmustafayev/PrinterSetupSystem
app/views/commands.php
PHP
gpl-3.0
1,265
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.Xml; using System.Xml.Serialization; namespace Fibonatix.CommDoo.Kalixa.Entities.Response { [Serializable()] [XmlRoot("executePaymentActionResponse", Namespace = "http://www.cqrpayments.com/PaymentProcessing")] public class CaptureResponse : Response { [Required] [XmlElement(ElementName = "statusCode")] public string statusCode { get; set; } [XmlArray("actionResults")] [XmlArrayItem(typeof(keyStringValuePair), ElementName = "result")] public dataList actionResults { get; set; } public static CaptureResponse DeserializeFromXmlDocument(XmlDocument doc) { XmlSerializer seri = new XmlSerializer(typeof(CaptureResponse)); var reader = new XmlNodeReader(doc.DocumentElement); CaptureResponse entry = (CaptureResponse)seri.Deserialize(reader); return entry; } public static CaptureResponse DeserializeFromString(string xmlData) { XmlDocument xml = new XmlDocument(); xml.LoadXml(xmlData); return DeserializeFromXmlDocument(xml); } public static CaptureResponse DeserializeFromStringSafe(string xmlData) { CaptureResponse ret = null; try { ret = DeserializeFromString(xmlData); } catch (Exception) { } return ret; } } }
alexeybezverkhiy/fibonatix
PSP/Fibonatix.CommDoo/Kalixa/Entities/Responses/CaptureResponse.cs
C#
gpl-3.0
1,577
/******************************************************************************* * This file is part of RedReader. * * RedReader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RedReader is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with RedReader. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.quantumbadger.redreader.receivers.announcements; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; public final class Payload { private final HashMap<String, String> mStrings = new HashMap<>(); private final HashMap<String, Long> mLongs = new HashMap<>(); private final HashMap<String, Boolean> mBooleans = new HashMap<>(); private static final byte HEADER_EOF = 0; private static final byte HEADER_ENTRY_STRING = 1; private static final byte HEADER_ENTRY_LONG = 2; private static final byte HEADER_ENTRY_BOOLEAN = 3; public void setString(@NonNull final String key, @NonNull final String value) { mStrings.put(key, value); } public void setLong(@NonNull final String key, final long value) { mLongs.put(key, value); } public void setBoolean(@NonNull final String key, final boolean value) { mBooleans.put(key, value); } @Nullable public String getString(@NonNull final String key) { return mStrings.get(key); } @Nullable public Long getLong(@NonNull final String key) { return mLongs.get(key); } @Nullable public Boolean getBoolean(@NonNull final String key) { return mBooleans.get(key); } @NonNull public byte[] toBytes() { final ByteArrayOutputStream result = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(result); try { for(final Map.Entry<String, String> entry : mStrings.entrySet()) { if(entry.getValue() == null) { continue; } dos.writeByte(HEADER_ENTRY_STRING); dos.writeUTF(entry.getKey()); dos.writeUTF(entry.getValue()); } for(final Map.Entry<String, Long> entry : mLongs.entrySet()) { if(entry.getValue() == null) { continue; } dos.writeByte(HEADER_ENTRY_LONG); dos.writeUTF(entry.getKey()); dos.writeLong(entry.getValue()); } for(final Map.Entry<String, Boolean> entry : mBooleans.entrySet()) { if(entry.getValue() == null) { continue; } dos.writeByte(HEADER_ENTRY_BOOLEAN); dos.writeUTF(entry.getKey()); dos.writeBoolean(entry.getValue()); } dos.writeByte(HEADER_EOF); dos.flush(); dos.close(); } catch(final IOException e) { throw new RuntimeException(e); } return result.toByteArray(); } @NonNull public static Payload fromBytes(@NonNull final byte[] data) throws IOException { try(DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data))) { final Payload result = new Payload(); while(true) { final byte header = dis.readByte(); switch(header) { case HEADER_EOF: return result; case HEADER_ENTRY_STRING: result.setString(dis.readUTF(), dis.readUTF()); break; case HEADER_ENTRY_LONG: result.setLong(dis.readUTF(), dis.readLong()); break; case HEADER_ENTRY_BOOLEAN: result.setBoolean(dis.readUTF(), dis.readBoolean()); break; default: throw new IOException("Unknown entry header " + header); } } } } }
QuantumBadger/RedReader
src/main/java/org/quantumbadger/redreader/receivers/announcements/Payload.java
Java
gpl-3.0
4,046
<?php header('Content-Type:text/html; charset=utf-8'); define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PWD', 'yangfan'); define('DB_NAME', 'blog'); $conn = @mysql_connect(DB_HOST, DB_USER, DB_PWD) or die('数据库链接失败:'.mysql_error()); @mysql_select_db(DB_NAME) or die('数据库错误:'.mysql_error()); @mysql_query('SET NAMES UTF8') or die('字符集错误:'.mysql_error()); ?>
shoushou70/blog_1
blog/config.php
PHP
gpl-3.0
431
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SCA.Interface.DatabaseAccess; using SCA.Interface; using System.Data.OleDb; using System.Data; using System.Collections; /* ============================== * * Author : William * Create Date: 2016/10/26 15:40:54 * FileName : MSAccessDatabaseAccess * Description:微软Access数据库处理类 * Version:V1 * =============================== */ namespace SCA.DatabaseAccess { public class MSAccessDatabaseAccess:IDatabaseService { private static Object _locker = new Object(); //并行锁 private OleDbConnection _db = null; private ILogRecorder _logRecorder; //日志处理 private IFileService _fileService; //文件处理 private OleDbCommand _dbCommand = null; //Command命令 protected string connectionString = ""; //数据库连接串 public MSAccessDatabaseAccess(string connString, ILogRecorder logRecorder, IFileService fileService) { connectionString = connString; _logRecorder = logRecorder; _fileService = fileService; } /// <summary> /// 获取数据为连接对象 /// </summary> /// <returns></returns> public OleDbConnection GetInstance() { if (_db == null) { //"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\你的数据库名.mdb; User ID=admin; Password=" return _db = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + connectionString + "; User ID=; Password=");//("Driver= {MicrosoftAccessDriver(*.mdb)};DBQ="+_connectionString+";Uid=;Pwd="); } else { lock (_locker) { return _db; } } } public object GetObjectValue(StringBuilder sql) { return GetObjectValue(sql, null); } public object GetObjectValue(StringBuilder sql, object[] param) { object result=null; OleDbConnection conn = (OleDbConnection)this.GetInstance(); try { //打开连接 conn.Open(); OleDbCommand cmd = new OleDbCommand(sql.ToString(), conn); if (param != null) { cmd.Parameters.AddRange(param); } result = cmd.ExecuteScalar(); } catch (Exception e) { _logRecorder.WriteException(e); } finally { conn.Close(); } return result; } public int ExecuteBySql(StringBuilder sql) { return ExecuteBySql(sql, null); } public int ExecuteBySql(StringBuilder sql, object[] param) { int num = 0; //创建连接 OleDbConnection conn = (OleDbConnection)this.GetInstance(); try { conn.Open(); //创建指令 String strSQL = sql.ToString(); String[] arraySql = strSQL.Split(';'); for (int i = 0; i < arraySql.Length; i++) { OleDbCommand cmd = new OleDbCommand(arraySql[i].ToString(), conn); OleDbTransaction DbTrans = conn.BeginTransaction(); if (param != null) { cmd.Parameters.AddRange(param); } try { Console.WriteLine("tryExecute"); cmd.Transaction = DbTrans; num = cmd.ExecuteNonQuery(); DbTrans.Commit(); } catch (Exception e) { Console.WriteLine("first:" + e.Message); DbTrans.Rollback(); num = -1; this._logRecorder.WriteException(e); Console.Write(_logRecorder.GetType().ToString()); } } //finally //{ // conn.Close(); // conn.Dispose(); //} } catch (Exception e) { Console.WriteLine("Second" + e.Message); _logRecorder.WriteException(e); } finally { conn.Close(); // conn.Dispose(); } return num; } public int BatchExecuteBySql(object[] sqls, object[] param) { throw new NotImplementedException(); } public System.Data.DataTable GetDataTableBySQL(StringBuilder sql) { return GetDataTableBySQL(sql, null); } public System.Data.DataTable GetDataTableBySQL(StringBuilder sql, object[] param) { OleDbConnection conn = (OleDbConnection)this.GetInstance(); try { conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.CommandText = sql.ToString(); cmd.CommandType = CommandType.Text; if (param != null) { cmd.Parameters.AddRange(param); } return DbReader.ReaderToDataTable(cmd.ExecuteReader()); } catch (Exception e) { this._logRecorder.WriteException(e); return null; } finally { conn.Close(); } } public System.Data.DataSet GetDataSetBySQL(StringBuilder sql) { throw new NotImplementedException(); } public System.Data.DataSet GetDataSetBySQL(StringBuilder sql, object[] param) { throw new NotImplementedException(); } public System.Collections.IList GetDataListBySQL<T>(StringBuilder sql) { throw new NotImplementedException(); } public System.Collections.IList GetDataListBySQL<T>(StringBuilder sql, object[] param) { throw new NotImplementedException(); } public System.Data.DataTable GetPageList(string sql, object[] param, string orderField, string orderType, int pageIndex, int pageSize, ref int count) { throw new NotImplementedException(); } public System.Data.DataTable GetPageList(string sql, string orderField, string orderType, int pageIndex, int pageSize, ref int count) { throw new NotImplementedException(); } public System.Collections.IList GetPageList<T>(string sql, object[] param, string orderField, string orderType, int pageIndex, int pageSize, ref int count) { throw new NotImplementedException(); } public System.Collections.IList GetPageList<T>(string sql, string orderField, string orderType, int pageIndex, int pageSize, ref int count) { throw new NotImplementedException(); } public bool BulkInsert(System.Data.DataTable dt) { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } public void CreateDBFile() { throw new NotImplementedException(); } } }
A1X71/twilight
SCA.WPF/SCA.DatabaseAccess/Utility/MSAccessDatabaseAccess.cs
C#
gpl-3.0
7,896
package regalowl.hyperconomy.command; import regalowl.hyperconomy.HyperConomy; import regalowl.hyperconomy.HyperEconomy; import regalowl.hyperconomy.shop.Shop; import regalowl.hyperconomy.tradeobject.TradeObject; import regalowl.hyperconomy.tradeobject.TradeObjectType; import regalowl.hyperconomy.transaction.PlayerTransaction; import regalowl.hyperconomy.transaction.TransactionResponse; import regalowl.hyperconomy.transaction.TransactionType; public class Sell extends BaseCommand implements HyperCommand { public Sell(HyperConomy hc) { super(hc, true); } @Override public CommandData onCommand(CommandData data) { if (!validate(data)) return data; try { if (args.length == 0) { data.addResponse(L.get("SELL_INVALID")); return data; } HyperEconomy he = hp.getHyperEconomy(); Shop s = dm.getHyperShopManager().getShop(hp); TradeObject ho = he.getTradeObject(args[0], dm.getHyperShopManager().getShop(hp)); if (ho == null) { data.addResponse(L.get("OBJECT_NOT_IN_DATABASE")); return data; } int amount = 1; if (args.length > 1) { if (args[1].equalsIgnoreCase("max")) { if (ho.getType() == TradeObjectType.ITEM) { amount = hp.getInventory().count(ho.getItem()); } else if (ho.getType() == TradeObjectType.EXPERIENCE) { amount = hp.getTotalXpPoints(); } else if (ho.getType() == TradeObjectType.ENCHANTMENT) { amount = 1; } } else { try { amount = Integer.parseInt(args[1]); if (amount > 10000) amount = 10000; } catch (Exception e) { data.addResponse(L.get("SELL_INVALID")); return data; } } } if (amount > 10000) { amount = 10000; } PlayerTransaction pt = new PlayerTransaction(TransactionType.SELL); pt.setObeyShops(true); pt.setHyperObject(ho); pt.setAmount(amount); if (s != null) pt.setTradePartner(s.getOwner()); TransactionResponse response = hp.processTransaction(pt); response.sendMessages(); } catch (Exception e) { hc.gSDL().getErrorWriter().writeError(e); } return data; } }
RegalOwl/HyperConomy
src/main/java/regalowl/hyperconomy/command/Sell.java
Java
gpl-3.0
2,152
from PyQt5 import QtCore import subprocess from pyconrad import * import numpy as np import jpype import time class forward_project_thread(QtCore.QThread): forward_project_finsihed = QtCore.pyqtSignal(str) def init(self, use_cl, ForwardProj, Phantom): self.use_cl = use_cl self.ForwardProj = ForwardProj self.Phantom = Phantom def get_fanogram(self): return self.fanogram def run(self): jpype.attachThreadToJVM() if self.use_cl: self.fanogram = self.ForwardProj.projectRayDrivenCL(self.Phantom.grid) else: self.fanogram = self.ForwardProj.projectRayDriven(self.Phantom) # time.sleep(5) jpype.detachThreadFromJVM() self.forward_project_finsihed.emit('finished')
alPreuhs/InteractiveReconstruction
Threads/forward_projection_thread.py
Python
gpl-3.0
783
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.web.magma.support; import java.io.File; import javax.validation.constraints.NotNull; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.obiba.magma.DatasourceFactory; import org.obiba.magma.datasource.crypt.DatasourceEncryptionStrategy; import org.obiba.magma.support.BatchDatasourceFactory; import org.obiba.magma.support.IncrementalDatasourceFactory; import org.obiba.magma.support.Initialisables; import org.obiba.opal.core.identifiers.IdentifierGenerator; import org.obiba.opal.core.magma.IdentifiersMappingDatasourceFactory; import org.obiba.opal.core.runtime.OpalRuntime; import org.obiba.opal.core.service.IdentifiersTableService; import org.obiba.opal.core.service.NoSuchIdentifiersMappingException; import org.obiba.opal.web.model.Identifiers; import org.obiba.opal.web.model.Magma; import org.obiba.opal.web.model.Magma.DatasourceFactoryDto; import org.springframework.beans.factory.annotation.Autowired; public abstract class AbstractDatasourceFactoryDtoParser implements DatasourceFactoryDtoParser { @Autowired private OpalRuntime opalRuntime; @Autowired private IdentifiersTableService identifiersTableService; @Autowired private IdentifierGenerator participantIdentifier; @Override public DatasourceFactory parse(DatasourceFactoryDto dto, DatasourceEncryptionStrategy encryptionStrategy) { DatasourceFactory factory = internalParse(dto, encryptionStrategy); // apply wrappers factory = applyIdentifiersMapping(dto, factory); factory = applyIncremental(dto, factory); factory = applyBatch(dto, factory); Initialisables.initialise(factory); return factory; } private DatasourceFactory applyIdentifiersMapping(DatasourceFactoryDto dto, DatasourceFactory factory) { if(!dto.hasIdConfig()) return factory; Identifiers.IdentifiersMappingConfigDto idConfig = dto.getIdConfig(); String idMapping = idConfig.getName(); if(!identifiersTableService.hasIdentifiersMapping(idMapping)) { throw new NoSuchIdentifiersMappingException(idMapping); } return new IdentifiersMappingDatasourceFactory(factory, idMapping, identifiersTableService, idConfig.getAllowIdentifierGeneration() ? participantIdentifier : null, idConfig.getIgnoreUnknownIdentifier()); } private DatasourceFactory applyIncremental(DatasourceFactoryDto dto, DatasourceFactory factory) { if(!dto.hasIncrementalConfig()) return factory; Magma.DatasourceIncrementalConfigDto incrementalConfig = dto.getIncrementalConfig(); if(incrementalConfig.getIncremental() && incrementalConfig.hasIncrementalDestinationName()) { return new IncrementalDatasourceFactory(factory, incrementalConfig.getIncrementalDestinationName()); } return factory; } private DatasourceFactory applyBatch(DatasourceFactoryDto dto, DatasourceFactory factory) { if(!dto.hasBatchConfig()) return factory; return new BatchDatasourceFactory(factory, dto.getBatchConfig().getLimit()); } @NotNull protected abstract DatasourceFactory internalParse(DatasourceFactoryDto dto, DatasourceEncryptionStrategy encryptionStrategy); @SuppressWarnings("UnusedDeclaration") protected OpalRuntime getOpalRuntime() { return opalRuntime; } protected FileObject resolveFileInFileSystem(String path) throws FileSystemException { return opalRuntime.getFileSystem().getRoot().resolveFile(path); } protected File resolveLocalFile(String path) { try { // note: does not ensure that file exists return opalRuntime.getFileSystem().getLocalFile(resolveFileInFileSystem(path)); } catch(FileSystemException e) { throw new IllegalArgumentException(e); } } }
apruden/opal
opal-core-ws/src/main/java/org/obiba/opal/web/magma/support/AbstractDatasourceFactoryDtoParser.java
Java
gpl-3.0
4,236
#!/usr/bin/env python # encoding: utf-8 # # Copyright 2009 !j Incorporated # # This file is part of Canner. # # Canner is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Canner is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Canner. If not, see <http://www.gnu.org/licenses/>. # """ parse-config.py """ import sys, os, re from canner import taglib def main(filename): lines = open(filename, 'rU') n = 0 ssh_version = None ssh_enable = False for line in lines: n += 1 # hostname m = re.match(r'set hostname ([\w\d.-]+)', line) if m: host = m.group(1) taglib.tag("hostname", host).implied_by(taglib.env_tags.device, line=n) continue # time m = re.match(r'set ntp server( backup\d)? "?([\w\d.-]+)"?', line) if m: server = m.group(2) if not server == '0.0.0.0': taglib.tag("NTP server", server).implied_by(taglib.env_tags.device, line=n) continue # dns m = re.match(r'set domain ([\w\d.-]+)', line) if m: domain = m.group(1) taglib.tag("domain name", domain).implied_by(taglib.env_tags.device, line=n) continue m = re.match(r'set dns host dns\d ([\w\d.-]+)', line) if m: server = m.group(1) taglib.tag("name server", server).implied_by(taglib.env_tags.device, line=n) continue m = re.match(r'set xauth ([\w\d.-]+) dns\d ([\w\d.-]+)', line) if m: server = m.group(2) taglib.tag("name server", server).implied_by(taglib.env_tags.device, line=n) continue m = re.match(r'set l2tp dns\d ([\w\d.-]+)', line) if m: server = m.group(1) taglib.tag("name server", server).implied_by(taglib.env_tags.device, line=n) continue # interfaces m = re.match(r'set interface ([\w\d]+) ip ([\d.]+)/([\d.]+)( secondary)?', line) if m: name, ipaddress, plen, secondary = m.groups() address = ipaddress + "/" + plen ifaddr_tag = taglib.ip_address_tag(address, "interface address") address_tag = taglib.ip_address_tag(address) subnet_tag = taglib.ip_subnet_tag(address) name_tag = taglib.tag("interface", "%s %s" % (taglib.env_tags.device.name, name)) name_tag.implied_by(taglib.env_tags.snapshot, line=n) name_tag.implies(taglib.env_tags.device, line=n) name_tag.implies(ifaddr_tag, line=n) ifaddr_tag.implies(address_tag, line=n) address_tag.implies(subnet_tag, line=n) continue # accounts m = re.match(r'set admin user "?([\w\d.-]+)"?\s+.*', line) if m: account = m.group(1) taglib.tag("user", account).implied_by(taglib.env_tags.device, line=n) continue # services m = re.match(r'set ssh version ([\w\d]+)', line) if m: ssh_version = m.group(1) ssh_version_line = n continue m = re.match(r'set ssh enable', line) if m: ssh_enable = True taglib.tag("service", 'SSH').implied_by(taglib.env_tags.device, n) continue m = re.match(r'set scp enable', line) if m: taglib.tag("service", 'SCP').implied_by(taglib.env_tags.device, n) continue # post parse phase if ssh_enable: if ssh_version: taglib.tag("service", 'SSH' + ssh_version).implied_by(taglib.env_tags.device, ssh_version_line) if __name__ == '__main__': main(taglib.default_filename) taglib.output_tagging_log()
pusateri/canner
taggers/OS--ScreenOS/file--config.netscreen/parse-config.py
Python
gpl-3.0
4,229
# Copyright (C) 2006-2007 Red Hat, Inc. # Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging from gi.repository import GObject import dbus from gi.repository import TelepathyGLib CONNECTION = TelepathyGLib.IFACE_CONNECTION CONNECTION_STATUS_CONNECTED = TelepathyGLib.ConnectionStatus.CONNECTED from sugar3 import profile from jarabe.util.telepathy import connection_watcher CONNECTION_INTERFACE_BUDDY_INFO = 'org.laptop.Telepathy.BuddyInfo' _owner_instance = None class BaseBuddyModel(GObject.GObject): __gtype_name__ = 'SugarBaseBuddyModel' def __init__(self, **kwargs): self._key = None self._nick = None self._color = None self._tags = None self._current_activity = None GObject.GObject.__init__(self, **kwargs) def get_nick(self): return self._nick def set_nick(self, nick): self._nick = nick nick = GObject.Property(type=object, getter=get_nick, setter=set_nick) def get_key(self): return self._key def set_key(self, key): if isinstance(key, bytes): key = key.decode('utf-8') self._key = key key = GObject.Property(type=object, getter=get_key, setter=set_key) def get_color(self): return self._color def set_color(self, color): self._color = color color = GObject.Property(type=object, getter=get_color, setter=set_color) def get_tags(self): return self._tags tags = GObject.Property(type=object, getter=get_tags) def get_current_activity(self): return self._current_activity def set_current_activity(self, current_activity): if self._current_activity != current_activity: self._current_activity = current_activity self.notify('current-activity') current_activity = GObject.Property(type=object, getter=get_current_activity, setter=set_current_activity) def is_owner(self): raise NotImplementedError class OwnerBuddyModel(BaseBuddyModel): __gtype_name__ = 'SugarOwnerBuddyModel' def __init__(self): BaseBuddyModel.__init__(self) self.props.nick = profile.get_nick_name() self.props.color = profile.get_color() self.props.key = profile.get_profile().pubkey self.connect('notify::nick', self.__property_changed_cb) self.connect('notify::color', self.__property_changed_cb) bus = dbus.SessionBus() bus.add_signal_receiver( self.__name_owner_changed_cb, signal_name='NameOwnerChanged', dbus_interface='org.freedesktop.DBus') bus_object = bus.get_object(dbus.BUS_DAEMON_NAME, dbus.BUS_DAEMON_PATH) for service in bus_object.ListNames( dbus_interface=dbus.BUS_DAEMON_IFACE): if service.startswith(CONNECTION + '.'): path = '/%s' % service.replace('.', '/') conn_proxy = bus.get_object(service, path) self._prepare_conn(path, conn_proxy) def _prepare_conn(self, object_path, conn_proxy): self.connection = {} self.object_path = object_path self.conn_proxy = conn_proxy self.conn_ready = False self.connection[CONNECTION] = \ dbus.Interface(self.conn_proxy, CONNECTION) self.connection[CONNECTION].GetInterfaces( reply_handler=self.__conn_get_interfaces_reply_cb, error_handler=self.__error_handler_cb) def __conn_get_interfaces_reply_cb(self, interfaces): for interface in interfaces: self.connection[interface] = dbus.Interface( self.conn_proxy, interface) self.conn_ready = True self.__connection_ready_cb(self.connection) def __connection_ready_cb(self, connection): if not self.conn_ready: return self._sync_properties_on_connection(connection) def __name_owner_changed_cb(self, name, old, new): if name.startswith(CONNECTION + '.') and not old and new: path = '/' + name.replace('.', '/') self.conn_proxy = dbus.Bus().get_object(name, path) self._prepare_conn(path, self.conn_proxy) def __property_changed_cb(self, buddy, pspec): self._sync_properties() def _sync_properties(self): conn_watcher = connection_watcher.get_instance() for connection in conn_watcher.get_connections(): self._sync_properties_on_connection(connection) def _sync_properties_on_connection(self, connection): if CONNECTION_INTERFACE_BUDDY_INFO in connection: properties = {} if self.props.key is not None: properties['key'] = dbus.ByteArray( self.props.key.encode('utf-8')) if self.props.color is not None: properties['color'] = self.props.color.to_string() logging.debug('calling SetProperties with %r', properties) connection[CONNECTION_INTERFACE_BUDDY_INFO].SetProperties( properties, reply_handler=self.__set_properties_cb, error_handler=self.__error_handler_cb) def __set_properties_cb(self): logging.debug('__set_properties_cb') def __error_handler_cb(self, error): raise RuntimeError(error) def is_owner(self): return True def get_owner_instance(): global _owner_instance if _owner_instance is None: _owner_instance = OwnerBuddyModel() return _owner_instance class BuddyModel(BaseBuddyModel): __gtype_name__ = 'SugarBuddyModel' def __init__(self, **kwargs): self._account = None self._contact_id = None self._handle = None BaseBuddyModel.__init__(self, **kwargs) def is_owner(self): return False def get_account(self): return self._account def set_account(self, account): self._account = account account = GObject.Property(type=object, getter=get_account, setter=set_account) def get_contact_id(self): return self._contact_id def set_contact_id(self, contact_id): self._contact_id = contact_id contact_id = GObject.Property(type=object, getter=get_contact_id, setter=set_contact_id) def get_handle(self): return self._handle def set_handle(self, handle): self._handle = handle handle = GObject.Property(type=object, getter=get_handle, setter=set_handle)
sugarlabs/sugar
src/jarabe/model/buddy.py
Python
gpl-3.0
7,314
/* * Copyright (C) 2014 David Gutiérrez Rubio <davidgutierrezrubio@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package gui.DatosEditor.Docencia; import data.MyConstants; import data.profesores.Profesor; import java.awt.Image; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import javax.swing.JComponent; import javax.swing.JTree; import javax.swing.TransferHandler; /** * * @author David Gutiérrez Rubio <davidgutierrezrubio@gmail.com> */ public class JTreeProfesoresTransferHandler extends TransferHandler { @Override protected Transferable createTransferable(JComponent c) { ProfesorDraggable resul = null; JTree jtree = (JTree) c; Object value = jtree.getSelectionPath().getLastPathComponent(); if (value instanceof Profesor) { resul = new ProfesorDraggable((Profesor) value); } return resul; } @Override public Image getDragImage() { MyConstants mc = new MyConstants(); return mc.PROFESOR_ICON.getImage(); } @Override public int getSourceActions(JComponent c) { return DnDConstants.ACTION_MOVE; } @Override protected void exportDone(JComponent source, Transferable data, int action) { //System.out.println("ExportDone"); // Here you need to decide how to handle the completion of the transfer, // should you remove the item from the list or not... } @Override public boolean canImport(TransferHandler.TransferSupport support) { return (support.getComponent() instanceof JTree) && support.isDataFlavorSupported(TramoDraggable.MY_FLAVOR); } }
joaquinpintos/kairos
src/gui/DatosEditor/Docencia/JTreeProfesoresTransferHandler.java
Java
gpl-3.0
2,284
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace NeoComp.Networks.Computational.Neural { [Serializable] [DataContract(IsReference = true, Namespace = NeoComp.xmlns, Name = "afLin")] public sealed class LinearActivationFunction : IActivationFunction { #region Constructors public LinearActivationFunction() { Alpha = 1.0; } public LinearActivationFunction(double alpha) { Alpha = alpha; } #endregion #region Properties [DataMember(Name = "a")] public double Alpha { get; set; } #endregion #region Calculate public double Function(double value) { double result = (value * Alpha); if (result < -Alpha) return -Alpha; else if (result > Alpha) return Alpha; return result; } public double Derivate(double value) { //if (value < -Alpha) return -0.000001; //if (value > Alpha) return 0.000001; //if (value < -Alpha || value > Alpha) return 0; return Alpha; } #endregion } }
unbornchikken/Neuroflow
_vault/NFBak/NeoComp02/NeoComp/Neocomp Framework/!OLD/NeoComp/Networks/Computational/Neural/_ActivationFunctions/LinearActivationFunction.cs
C#
gpl-3.0
1,252
module Api module V21 class InterfacesController < V2::InterfacesController include Api::Version21 def index super render :json => @interfaces, :each_serializer => InterfaceSerializer end def show render :json => @interface, :serializer => InterfaceSerializer end end end end
daviddavis/foretello_api_v21
app/controllers/api/v21/interfaces_controller.rb
Ruby
gpl-3.0
346
/* * Copyright 2015 Jeff Simpson. * * This file is part of the Argo MQTT Transport plugin. * * Argo MQTT Transport plugin is free software: you can redistribute it * and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Foobar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ package ws.argo.responder.plugin.repeater.mqtt; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import ws.argo.plugin.probehandler.ProbeHandlerConfigException; import ws.argo.plugin.probehandler.ProbeHandlerPlugin; import ws.argo.plugin.transport.exception.TransportConfigException; import ws.argo.plugin.transport.exception.TransportException; import ws.argo.plugin.transport.sender.Transport; import ws.argo.probe.Probe; import ws.argo.probe.ProbeSender; import ws.argo.probe.ProbeSenderException; import ws.argo.probe.transport.sender.mqtt.MqttSenderTransport; import ws.argo.wireline.probe.ProbeWrapper; import ws.argo.wireline.probe.XMLSerializer; import ws.argo.wireline.response.ResponseWrapper; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import static java.lang.Integer.parseInt; /** * The MqttRepeaterProbeHandlerPlugin does pretty much what it says. It takes probes * that were handled by the Responder via whatever transports it has configured and then * repeats them out onto a MQTT Sender transport that is separately configured as part * of this probe handler plugin. * * <p>This handler should be used in handling discovery domain gateways. However, if * this repeater resends the probe on the same MQTT channel as it received it, it could * cause very odd behavior. It should NOT resend on a channel that would cause a loop * back or other feedback issues. * * Created by jmsimpson on 10/27/15. */ public class MqttRepeaterProbeHandlerPlugin implements ProbeHandlerPlugin { private static final Logger LOGGER = Logger.getLogger(MqttRepeaterProbeHandlerPlugin.class.getName()); // Properties private ProbeSender _sender; /** * The probe handler will simply resend the probe via the sender it setup with it * initialized. It then will return an empty response back to the Responder as * it isn't actually finding any services to return. * * @param probeWrapper the wireline probe payload to repeat * @return the empty ResponseWrapper */ @Override public ResponseWrapper handleProbeEvent(ProbeWrapper probeWrapper) { LOGGER.fine("MqttRepeaterProbeHandlerPlugin handling probe: " + probeWrapper.asXML()); ResponseWrapper response = new ResponseWrapper(probeWrapper.getProbeId()); Probe probe = new Probe(probeWrapper); try { _sender.sendProbe(probe); } catch (ProbeSenderException e) { LOGGER.log(Level.WARNING, "Unable to repeat probe to MQTT Transport.", e); } return response; } /** * Read in the XML configuration file provided. This should contain the data it needs to * make the MQTT connection and setup the probe sender. * * @param xmlConfigFilename the name of the XML config file * @throws ProbeHandlerConfigException if something goes wrong */ @Override public void initializeWithPropertiesFilename(String xmlConfigFilename) throws ProbeHandlerConfigException { Properties properties; try { properties = processPropertiesFile(xmlConfigFilename); initializeProbeSender(properties); } catch (TransportConfigException e) { throw new ProbeHandlerConfigException("Error reading config [" + xmlConfigFilename + "]", e); } catch (SocketException | UnknownHostException e) { throw new ProbeHandlerConfigException("Error initializing MQTT Repeater", e); } } @Override public String pluginName() { return "MQTT Repeater"; } private void initializeProbeSender(Properties properties) throws UnknownHostException, SocketException, TransportConfigException { Transport transport = new MqttSenderTransport(); NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); String macAddr = ni.getHardwareAddress().toString(); String clientId = "MQTT-Repeater-Client-" + macAddr; properties.put("clientId", clientId); transport.initialize(properties, ""); _sender = new ProbeSender(transport); } /** * Digs through the xml file to get the particular configuration items necessary to * run this responder transport. * * @param xmlConfigFilename the name of the xml configuration file * @return an XMLConfiguration object * @throws TransportConfigException if something goes awry */ private Properties processPropertiesFile(String xmlConfigFilename) throws TransportConfigException { Properties props = new Properties(); XMLConfiguration config; try { config = new XMLConfiguration(xmlConfigFilename); } catch (ConfigurationException e) { throw new TransportConfigException(e.getLocalizedMessage(), e); } props.put("mqttTopic", config.getString("mqttTopic")); props.put("qos", config.getString("qos", "0")); props.put("broker", config.getString("broker")); props.put("clientId", config.getString("clientId", "NO CLIENT ID")); if (config.getString("username") != null) props.put("username", config.getString("username")); if (config.getString("password") != null) props.put("password", config.getString("password")); return props; } }
argoPlugins/mqttTransportPlugin
src/main/java/ws/argo/responder/plugin/repeater/mqtt/MqttRepeaterProbeHandlerPlugin.java
Java
gpl-3.0
6,368
<?php /* * This file is part of Totara LMS * * Copyright (C) 2010-2012 Totara Learning Solutions LTD * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @author Piers Harding <piers@catalyst.net.nz> * @package totara * @subpackage message */ /** * Displays collaborative features for the current user */ require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); require_once($CFG->dirroot.'/totara/reportbuilder/lib.php'); // initialise jquery requirements require_once($CFG->dirroot.'/totara/core/js/lib/setup.php'); require_login(); global $SESSION,$USER; $format = optional_param('format', '',PARAM_TEXT); //export format // default to current user $id = $USER->id; $context = context_system::instance(); $PAGE->set_context($context); $PAGE->set_url('/totara/message/tasks.php'); $PAGE->set_pagelayout('noblocks'); // users can only view their own and their staff's pages // or if they are an admin if (($USER->id != $id && !totara_is_manager($id) && !has_capability('totara/message:viewallmessages',$context))) { print_error('youcannotview', 'totara_message'); } $strheading = get_string('tasks', 'totara_message'); $shortname = 'tasks'; $data = array( 'userid' => $id, ); if (!$report = reportbuilder_get_embedded_report($shortname, $data)) { print_error('error:couldnotgenerateembeddedreport', 'totara_reportbuilder'); } $report->defaultsortcolumn = 'message_values_sent'; $report->defaultsortorder = 3; if ($format!='') { add_to_log(SITEID, 'reportbuilder', 'export report', 'report.php?id='. $report->_id, $report->fullname); $report->export_data($format); die; } add_to_log(SITEID, 'reportbuilder', 'view report', 'report.php?id='. $report->_id, $report->fullname); $report->include_js(); $PAGE->requires->js_init_call('M.totara_message.init'); /// /// Display the page /// $PAGE->navbar->add($strheading); $PAGE->set_title($strheading); $PAGE->set_button($report->edit_button()); $PAGE->set_heading($strheading); $output = $PAGE->get_renderer('totara_reportbuilder'); echo $output->header(); echo $output->heading($strheading, 1); echo html_writer::tag('p', html_writer::link("{$CFG->wwwroot}/my/", "<< " . get_string('mylearning', 'totara_core'))); // display table here $fullname = $report->fullname; $countfiltered = $report->get_filtered_count(); $countall = $report->get_full_count(); // display heading including filtering stats if ($countfiltered == $countall) { echo $output->heading("$countall ".get_string('records', 'totara_reportbuilder')); } else { echo $output->heading("$countfiltered/$countall".get_string("recordsshown", "totara_plan")); } if (empty($report->description)) { $report->description = get_string('task_description', 'totara_message'); } echo $output->print_description($report->description, $report->_id); $report->display_search(); $PAGE->requires->string_for_js('reviewitems', 'block_totara_alerts'); $PAGE->requires->js_init_call('M.totara_message.dismiss_input_toggle'); if ($countfiltered > 0) { echo $output->showhide_button($report->_id, $report->shortname); echo html_writer::start_tag('form', array('id' => 'totara_messages', 'name' => 'totara_messages', 'action' => new moodle_url('/totara/message/action.php'), 'method' => 'post')); $report->display_table(); echo totara_message_action_button('dismiss'); echo totara_message_action_button('accept'); echo totara_message_action_button('reject'); $out = $output->box_start('generalbox', 'totara_message_actions'); $out .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'returnto', 'value' => $FULLME)); $out .= html_writer::start_tag('center'); $tab = new html_table(); $tab->attributes = array('class', 'fullwidth'); $dismisslink = html_writer::empty_tag('input', array('type' => 'submit', 'name' => 'dismiss', 'id' => 'totara-dismiss', 'disabled' => 'true', 'value' => get_string('dismiss', 'totara_message'), 'style' => 'display:none;')). html_writer::tag('noscript', get_string('noscript', 'totara_message')); $tab->data[] = new html_table_row(array(get_string('withselected', 'totara_message'), $dismisslink)); $out .= html_writer::table($tab); $out .= html_writer::end_tag('center'); $out .= $output->box_end(); echo $out; echo html_writer::end_tag('form'); // export button $output->export_select($report->_id); echo totara_message_checkbox_all_none(); } echo $output->footer(); ?>
danielbonetto/twig_MVC
totara/message/tasks.php
PHP
gpl-3.0
5,091
<?php //TODO EM_Events is currently static, better we make this non-static so we can loop sets of events, and standardize with other objects. /** * Use this class to query and manipulate sets of events. If dealing with more than one event, you probably want to use this class in some way. * */ class EM_Events extends EM_Object { /** * Returns an array of EM_Events that match the given specs in the argument, or returns a list of future evetnts in future * (see EM_Events::get_default_search() ) for explanation of possible search array values. You can also supply a numeric array * containing the ids of the events you'd like to obtain * * @param array $args * @return EM_Event array() */ public static function get( $args = array(), $count=false ) { global $wpdb; $events_table = EM_EVENTS_TABLE; $locations_table = EM_LOCATIONS_TABLE; //Quick version, we can accept an array of IDs, which is easy to retrieve if( self::array_is_numeric($args) ){ //Array of numbers, assume they are event IDs to retreive //We can just get all the events here and return them $events = array(); foreach($args as $event_id){ $events[$event_id] = em_get_event($event_id); } return apply_filters('em_events_get', $events, $args); } //We assume it's either an empty array or array of search arguments to merge with defaults $args = self::get_default_search($args); $limit = ( $args['limit'] && is_numeric($args['limit'])) ? "LIMIT {$args['limit']}" : ''; $offset = ( $limit != "" && is_numeric($args['offset']) ) ? "OFFSET {$args['offset']}" : ''; $groupby_sql = array(); //Get the default conditions $conditions = self::build_sql_conditions($args); //Put it all together $where = ( count($conditions) > 0 ) ? " WHERE " . implode ( " AND ", $conditions ):''; //Get ordering instructions $EM_Event = new EM_Event(); $EM_Location = new EM_Location(); $orderby = self::build_sql_orderby($args, array_keys(array_merge($EM_Event->fields, $EM_Location->fields)), get_option('dbem_events_default_order')); //Now, build orderby sql $orderby_sql = ( count($orderby) > 0 ) ? 'ORDER BY '. implode(', ', $orderby) : ''; //Create the SQL statement and execute if( !$count && $args['array'] ){ $selectors_array = array(); foreach( array_keys($EM_Event->fields) as $field_selector){ $selectors_array[] = $events_table.'.'.$field_selector; } $selectors = implode(',', $selectors_array); }elseif( EM_MS_GLOBAL ){ $selectors = $events_table.'.post_id, '.$events_table.'.blog_id'; $groupby_sql[] = $events_table.'.post_id, '. $events_table.'.blog_id'; }else{ $selectors = $events_table.'.post_id'; $groupby_sql[] = $events_table.'.post_id'; //prevent duplicates showing in lists } if( $count ){ $selectors = 'SQL_CALC_FOUND_ROWS *'; $limit = 'LIMIT 1'; $offset = 'OFFSET 0'; } //add group_by if needed $groupby_sql = !empty($groupby_sql) && is_array($groupby_sql) ? 'GROUP BY '.implode(',', $groupby_sql):''; $sql = apply_filters('em_events_get_sql'," SELECT $selectors FROM $events_table LEFT JOIN $locations_table ON {$locations_table}.location_id={$events_table}.location_id $where $groupby_sql $orderby_sql $limit $offset ", $args); //If we're only counting results, return the number of results if( $count ){ $wpdb->query($sql); return apply_filters('em_events_get_count', $wpdb->get_var('SELECT FOUND_ROWS()'), $args); } $results = $wpdb->get_results( $sql, ARRAY_A); //If we want results directly in an array, why not have a shortcut here? if( $args['array'] == true ){ return apply_filters('em_events_get_array',$results, $args); } //Make returned results EM_Event objects $results = (is_array($results)) ? $results:array(); $events = array(); if( EM_MS_GLOBAL ){ foreach ( $results as $event ){ $events[] = em_get_event($event['post_id'], $event['blog_id']); } }else{ foreach ( $results as $event ){ $events[] = em_get_event($event['post_id'], 'post_id'); } } return apply_filters('em_events_get', $events, $args); } /** * Returns the number of events on a given date * @param $date * @return int */ public static function count_date($date){ global $wpdb; $table_name = EM_EVENTS_TABLE; $sql = "SELECT COUNT(*) FROM $table_name WHERE (event_start_date like '$date') OR (event_start_date <= '$date' AND event_end_date >= '$date');"; return apply_filters('em_events_count_date', $wpdb->get_var($sql)); } public static function count( $args = array() ){ return apply_filters('em_events_count', self::get($args, true), $args); } /** * Will delete given an array of event_ids or EM_Event objects * @param unknown_type $id_array */ public static function delete( $array ){ global $wpdb; //Detect array type and generate SQL for event IDs $results = array(); if( !empty($array) && @get_class(current($array)) != 'EM_Event' ){ $events = self::get($array); }else{ $events = $array; } $event_ids = array(); foreach ($events as $EM_Event){ $event_ids[] = $EM_Event->event_id; $results[] = $EM_Event->delete(); } //TODO add better error feedback on events delete fails return apply_filters('em_events_delete', in_array(false, $results), $event_ids); } /** * Output a set of matched of events. You can pass on an array of EM_Events as well, in this event you can pass args in second param. * Note that you can pass a 'pagination' boolean attribute to enable pagination, default is enabled (true). * @param array $args * @param array $secondary_args * @return string */ public static function output( $args ){ global $EM_Event; $EM_Event_old = $EM_Event; //When looping, we can replace EM_Event global with the current event in the loop //get page number if passed on by request (still needs pagination enabled to have effect) $page_queryvar = !empty($args['page_queryvar']) ? $args['page_queryvar'] : 'pno'; if( !empty($args['pagination']) && !array_key_exists('page',$args) && !empty($_REQUEST[$page_queryvar]) && is_numeric($_REQUEST[$page_queryvar]) ){ $page = $args['page'] = $_REQUEST[$page_queryvar]; } //Can be either an array for the get search or an array of EM_Event objects if( is_object(current($args)) && get_class((current($args))) == 'EM_Event' ){ $func_args = func_get_args(); $events = $func_args[0]; $args = (!empty($func_args[1]) && is_array($func_args[1])) ? $func_args[1] : array(); $args = apply_filters('em_events_output_args', self::get_default_search($args), $events); $limit = ( !empty($args['limit']) && is_numeric($args['limit']) ) ? $args['limit']:false; $offset = ( !empty($args['offset']) && is_numeric($args['offset']) ) ? $args['offset']:0; $page = ( !empty($args['page']) && is_numeric($args['page']) ) ? $args['page']:1; $events_count = count($events); }else{ //Firstly, let's check for a limit/offset here, because if there is we need to remove it and manually do this $args = apply_filters('em_events_output_args', self::get_default_search($args)); $limit = ( !empty($args['limit']) && is_numeric($args['limit']) ) ? $args['limit']:false; $offset = ( !empty($args['offset']) && is_numeric($args['offset']) ) ? $args['offset']:0; $page = ( !empty($args['page']) && is_numeric($args['page']) ) ? $args['page']:1; $args_count = $args; $args_count['limit'] = false; $args_count['offset'] = false; $args_count['page'] = false; $events_count = self::count($args_count); $events = self::get( $args ); } //What format shall we output this to, or use default $format = ( empty($args['format']) ) ? get_option( 'dbem_event_list_item_format' ) : $args['format'] ; $output = ""; $events = apply_filters('em_events_output_events', $events); if ( $events_count > 0 ) { foreach ( $events as $EM_Event ) { $output .= $EM_Event->output($format); } //Add headers and footers to output if( $format == get_option( 'dbem_event_list_item_format' ) ){ //we're using the default format, so if a custom format header or footer is supplied, we can override it, if not use the default $format_header = empty($args['format_header']) ? get_option('dbem_event_list_item_format_header') : $args['format_header']; $format_footer = empty($args['format_footer']) ? get_option('dbem_event_list_item_format_footer') : $args['format_footer']; }else{ //we're using a custom format, so if a header or footer isn't specifically supplied we assume it's blank $format_header = !empty($args['format_header']) ? $args['format_header'] : '' ; $format_footer = !empty($args['format_footer']) ? $args['format_footer'] : '' ; } $output = $format_header . $output . $format_footer; //Pagination (if needed/requested) if( !empty($args['pagination']) && !empty($limit) && $events_count > $limit ){ $output .= self::get_pagination_links($args, $events_count); } } else { $output = get_option ( 'dbem_no_events_message' ); } //TODO check if reference is ok when restoring object, due to changes in php5 v 4 $EM_Event = $EM_Event_old; $output = apply_filters('em_events_output', $output, $events, $args); return $output; } /** * Generate a grouped list of events by year, month, week or day. * * There is a nuance with this function, long_events won't work unless you add a limit of 0. The reason is because this won't work with pagination, due to the fact * that you need to alter the event total count to reflect each time an event is displayed in a time range. e.g. if an event lasts 2 days and it's daily grouping, * then that event would count as 2 events for pagination purposes. For that you need to count every single event and calculate date range etc. which is too resource * heavy and not scalabale, therefore we've added this limitation. * * @since 5.4.4.2 * @param array $args * @return string */ public static function output_grouped( $args = array() ){ //Reset some args to include pagination for if pagination is requested. $args['limit'] = isset($args['limit']) ? $args['limit'] : get_option('dbem_events_default_limit'); $args['page'] = (!empty($args['page']) && is_numeric($args['page']) )? $args['page'] : 1; $args['page'] = (!empty($args['pagination']) && !empty($_REQUEST['pno']) && is_numeric($_REQUEST['pno']) )? $_REQUEST['pno'] : $args['page']; $args['offset'] = ($args['page']-1) * $args['limit']; $args['orderby'] = 'event_start_date,event_start_time,event_name'; // must override this to display events in right cronology. $args['mode'] = !empty($args['mode']) ? $args['mode'] : get_option('dbem_event_list_groupby'); $args['header_format'] = !empty($args['header_format']) ? $args['header_format'] : get_option('dbem_event_list_groupby_header_format', '<h2>#s</h2>'); //Reset some vars for counting events and displaying set arrays of events $atts = (array) $args; $atts['pagination'] = false; $atts['limit'] = false; $atts['page'] = false; $atts['offset'] = false; //decide what form of dates to show $events_count = self::count($atts); ob_start(); if( $events_count > 0 ){ $EM_Events = self::get($args); switch ( $args['mode'] ){ case 'yearly': //go through the events and put them into a monthly array $format = (!empty($args['date_format'])) ? $args['date_format']:'Y'; $events_dates = array(); foreach($EM_Events as $EM_Event){ /* @var $EM_Event EM_Event */ $year = date('Y',$EM_Event->start); $events_dates[$year][] = $EM_Event; //if long events requested, add event to other dates too if( empty($args['limit']) && !empty($args['long_events']) && $EM_Event->event_end_date != $EM_Event->event_start_date ) { $next_year = $year + 1; $year_end = date('Y', $EM_Event->end); while( $next_year <= $year_end ){ $events_dates[$next_year][] = $EM_Event; $next_year = $next_year + 1; } } } foreach ($events_dates as $year => $events){ echo str_replace('#s', date_i18n($format,strtotime($year.'-01-01', current_time('timestamp'))), $args['header_format']); echo self::output($events, $atts); } break; case 'monthly': //go through the events and put them into a monthly array $format = (!empty($args['date_format'])) ? $args['date_format']:'M Y'; $events_dates = array(); foreach($EM_Events as $EM_Event){ $events_dates[date('Y-m-'.'01', $EM_Event->start)][] = $EM_Event; //if long events requested, add event to other dates too if( empty($args['limit']) && !empty($args['long_events']) && $EM_Event->event_end_date != $EM_Event->event_start_date ) { $next_month = strtotime("+1 Month", $EM_Event->start); while( $next_month <= $EM_Event->end ){ $events_dates[date('Y-m-'.'01',$next_month)][] = $EM_Event; $next_month = strtotime("+1 Month", $next_month); } } } foreach ($events_dates as $month => $events){ echo str_replace('#s', date_i18n($format, strtotime($month, current_time('timestamp'))), $args['header_format']); echo self::output($events, $atts); } break; case 'weekly': $format = (!empty($args['date_format'])) ? $args['date_format']:get_option('date_format'); $events_dates = array(); foreach($EM_Events as $EM_Event){ $start_of_week = get_option('start_of_week'); $day_of_week = date('w',$EM_Event->start); $day_of_week = date('w',$EM_Event->start); $offset = $day_of_week - $start_of_week; if($offset<0){ $offset += 7; } $offset = $offset * 60*60*24; //days in seconds $start_day = strtotime($EM_Event->start_date); $events_dates[$start_day - $offset][] = $EM_Event; //if long events requested, add event to other dates too if( empty($args['limit']) && !empty($args['long_events']) && $EM_Event->event_end_date != $EM_Event->event_start_date ) { $next_week = $start_day - $offset + (86400 * 7); while( $next_week <= $EM_Event->end ){ $events_dates[$next_week][] = $EM_Event; $next_week = $next_week + (86400 * 7); } } } foreach ($events_dates as $event_day_ts => $events){ echo str_replace('#s', date_i18n($format,$event_day_ts). get_option('dbem_dates_separator') .date_i18n($format,$event_day_ts+(60*60*24*6)), $args['header_format']); echo self::output($events, $atts); } break; default: //daily //go through the events and put them into a daily array $format = (!empty($args['date_format'])) ? $args['date_format']:get_option('date_format'); $events_dates = array(); foreach($EM_Events as $EM_Event){ $event_start_date = strtotime($EM_Event->start_date); $events_dates[$event_start_date][] = $EM_Event; //if long events requested, add event to other dates too if( empty($args['limit']) && !empty($args['long_events']) && $EM_Event->event_end_date != $EM_Event->event_start_date ) { $tomorrow = $event_start_date + 86400; while( $tomorrow <= $EM_Event->end ){ $events_dates[$tomorrow][] = $EM_Event; $tomorrow = $tomorrow + 86400; } } } foreach ($events_dates as $event_day_ts => $events){ echo str_replace('#s', date_i18n($format,$event_day_ts), $args['header_format']); echo self::output($events, $atts); } break; } //Show the pagination links (unless there's less than $limit events) if( !empty($args['pagination']) && !empty($args['limit']) && $events_count > $args['limit'] ){ echo self::get_pagination_links($args, $events_count, 'search_events_grouped'); } }else{ echo get_option ( 'dbem_no_events_message' ); } return ob_get_clean(); } public static function get_pagination_links($args, $count, $search_action = 'search_events', $default_args = array()){ //get default args if we're in a search, supply to parent since we can't depend on late static binding until WP requires PHP 5.3 or later if( empty($default_args) && (!empty($args['ajax']) || !empty($_REQUEST['action']) && $_REQUEST['action'] == $search_action) ){ $default_args = self::get_default_search(); $default_args['limit'] = get_option('dbem_events_default_limit'); } return parent::get_pagination_links($args, $count, $search_action, $default_args); } /* (non-PHPdoc) * DEPRECATED - this class should just contain static classes, * @see EM_Object::can_manage() */ function can_manage($event_ids = false , $admin_capability = false, $user_to_check = false ){ global $wpdb; if( current_user_can('edit_others_events') ){ return apply_filters('em_events_can_manage', true, $event_ids); } if( EM_Object::array_is_numeric($event_ids) ){ $condition = implode(" OR event_id=", $event_ids); //we try to find any of these events that don't belong to this user $results = $wpdb->get_var("SELECT COUNT(*) FROM ". EM_EVENTS_TABLE ." WHERE event_owner != '". get_current_user_id() ."' event_id=$condition;"); return apply_filters('em_events_can_manage', ($results == 0), $event_ids); } return apply_filters('em_events_can_manage', false, $event_ids); } public static function get_post_search($args = array(), $filter = false, $request = array(), $accepted_args = array()){ //supply $accepted_args to parent argument since we can't depend on late static binding until WP requires PHP 5.3 or later $accepted_args = !empty($accepted_args) ? $accepted_args : array_keys(self::get_default_search()); return apply_filters('em_events_get_post_search', parent::get_post_search($args, $filter, $request, $accepted_args)); } /* Overrides EM_Object method to apply a filter to result * @see wp-content/plugins/events-manager/classes/EM_Object#build_sql_conditions() */ public static function build_sql_conditions( $args = array() ){ self::$context = EM_POST_TYPE_EVENT; global $wpdb; $conditions = parent::build_sql_conditions($args); if( !empty($args['search']) ){ $like_search = array('event_name',EM_EVENTS_TABLE.'.post_content','location_name','location_address','location_town','location_postcode','location_state','location_country','location_region'); $like_search_string = '%'.$wpdb->esc_like($args['search']).'%'; $like_search_strings = array(); foreach( $like_search as $v ) $like_search_strings[] = $like_search_string; $like_search_sql = "(".implode(" LIKE %s OR ", $like_search). " LIKE %s)"; $conditions['search'] = $wpdb->prepare($like_search_sql, $like_search_strings); } $conditions['status'] = "(`event_status` >= 0 )"; //shows pending & published if not defined if( array_key_exists('status',$args) ){ if( is_numeric($args['status']) ){ $conditions['status'] = "(`event_status`={$args['status']})"; //pending or published }elseif( $args['status'] == 'pending' ){ $conditions['status'] = "(`event_status`=0)"; //pending }elseif( $args['status'] == 'publish' ){ $conditions['status'] = "(`event_status`=1)"; //published }elseif( $args['status'] === null || $args['status'] == 'draft' ){ $conditions['status'] = "(`event_status` IS NULL )"; //show draft items }elseif( $args['status'] == 'trash' ){ $conditions['status'] = "(`event_status` = -1 )"; //show trashed items }elseif( $args['status'] == 'all'){ $conditions['status'] = "(`event_status` >= 0 OR `event_status` IS NULL)"; //search all statuses that aren't trashed }elseif( $args['status'] == 'everything'){ unset($conditions['status']); //search all statuses } } //private events if( empty($args['private']) ){ $conditions['private'] = "(`event_private`=0)"; }elseif( !empty($args['private_only']) ){ $conditions['private_only'] = "(`event_private`=1)"; } if( EM_MS_GLOBAL && !empty($args['blog']) ){ if( is_numeric($args['blog']) ){ if( is_main_site($args['blog']) ){ $conditions['blog'] = "(".EM_EVENTS_TABLE.".blog_id={$args['blog']} OR ".EM_EVENTS_TABLE.".blog_id IS NULL)"; }else{ $conditions['blog'] = "(".EM_EVENTS_TABLE.".blog_id={$args['blog']})"; } }else{ if( !is_array($args['blog']) && preg_match('/^([\-0-9],?)+$/', $args['blog']) ){ $conditions['blog'] = "(".EM_EVENTS_TABLE.".blog_id IN ({$args['blog']}) )"; }elseif( is_array($args['blog']) && self::array_is_numeric($args['blog']) ){ $conditions['blog'] = "(".EM_EVENTS_TABLE.".blog_id IN (".implode(',',$args['blog']).") )"; } } } if( $args['bookings'] === 'user' && is_user_logged_in()){ //get bookings of user $EM_Person = new EM_Person(get_current_user_id()); $booking_ids = $EM_Person->get_bookings(true); if( count($booking_ids) > 0 ){ $conditions['bookings'] = "(event_id IN (SELECT event_id FROM ".EM_BOOKINGS_TABLE." WHERE booking_id IN (".implode(',',$booking_ids).")))"; }else{ $conditions['bookings'] = "(event_id = 0)"; } } //post search if( !empty($args['post_id'])){ if( is_array($args['post_id']) ){ $conditions['post_id'] = "(".EM_EVENTS_TABLE.".post_id IN (".implode(',',$args['post_id'])."))"; }else{ $conditions['post_id'] = "(".EM_EVENTS_TABLE.".post_id={$args['post_id']})"; } } //events with or without locations if( !empty($args['has_location']) ){ $conditions['has_location'] = '('.EM_EVENTS_TABLE.'.location_id IS NOT NULL AND '.EM_EVENTS_TABLE.'.location_id != 0)'; }elseif( !empty($args['no_location']) ){ $conditions['no_location'] = '('.EM_EVENTS_TABLE.'.location_id IS NULL OR '.EM_EVENTS_TABLE.'.location_id = 0)'; } return apply_filters( 'em_events_build_sql_conditions', $conditions, $args ); } /* Overrides EM_Object method to apply a filter to result * @see wp-content/plugins/events-manager/classes/EM_Object#build_sql_orderby() */ public static function build_sql_orderby( $args, $accepted_fields, $default_order = 'ASC' ){ self::$context = EM_POST_TYPE_EVENT; $accepted_fields[] = 'event_date_modified'; $accepted_fields[] = 'event_date_created'; return apply_filters( 'em_events_build_sql_orderby', parent::build_sql_orderby($args, $accepted_fields, get_option('dbem_events_default_order')), $args, $accepted_fields, $default_order ); } /* * Adds custom Events search defaults * @param array $array_or_defaults may be the array to override defaults * @param array $array * @return array * @uses EM_Object#get_default_search() */ public static function get_default_search( $array_or_defaults = array(), $array = array() ){ self::$context = EM_POST_TYPE_EVENT; $defaults = array( 'orderby' => get_option('dbem_events_default_orderby'), 'order' => get_option('dbem_events_default_order'), 'bookings' => false, //if set to true, only events with bookings enabled are returned 'status' => 1, //approved events only 'town' => false, 'state' => false, 'country' => false, 'region' => false, 'has_location' => false, 'no_location' => false, 'blog' => get_current_blog_id(), 'private' => current_user_can('read_private_events'), 'private_only' => false, 'post_id' => false ); //sort out whether defaults were supplied or just the array of search values if( empty($array) ){ $array = $array_or_defaults; }else{ $defaults = array_merge($defaults, $array_or_defaults); } //specific functionality if( EM_MS_GLOBAL && (!is_admin() || defined('DOING_AJAX')) ){ if( empty($array['blog']) && is_main_site() && get_site_option('dbem_ms_global_events') ){ $array['blog'] = false; } } if( is_admin() && !defined('DOING_AJAX') ){ //figure out default owning permissions $defaults['owner'] = !current_user_can('edit_others_events') ? get_current_user_id() : false; if( !array_key_exists('status', $array) && current_user_can('edit_others_events') ){ $defaults['status'] = false; //by default, admins see pending and live events } } return apply_filters('em_events_get_default_search', parent::get_default_search($defaults,$array), $array, $defaults); } } ?>
dexxtr/osbb-web-manager
www/wp-content/plugins/events-manager/classes/em-events.php
PHP
gpl-3.0
24,240
/* * Children Immunization Registry System (IRS). Copyright (C) 2011 PATH (www.path.org) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Author: Tran Trung Hieu * Email: htran282@gmail.com */ package org.hil.core.model; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.GrantedAuthority; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.*; @Entity @Table(name = "system_account") public class SystemAccount extends AbstractEntity implements Serializable, UserDetails { @Column(name = "account_name", length = 50, unique = true) private String accountName; @Column(name = "password", length = 100) private String password; @Column(name = "expired") private Boolean expired = new Boolean(false); @Column(name = "locked") private Boolean locked = new Boolean(false); @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "system_account_role", joinColumns = { @JoinColumn(name = "id_system_account") }, inverseJoinColumns = @JoinColumn(name = "id_system_role")) private Set<SystemRole> roles = new HashSet<SystemRole>(); public Set<SystemRole> getRoles() { return roles; } public void setRoles(Set<SystemRole> roles) { this.roles = roles; } public void addRole(SystemRole role) { getRoles().add(role); } /** * @return the accountName */ public String getAccountName() { return accountName; } /** * @param accountName the accountName to set */ public void setAccountName(String accountName) { this.accountName = accountName; } @Transient public GrantedAuthority[] getAuthorities() { return roles.toArray(new GrantedAuthority[0]); } @Transient public String getUsername() { return getAccountName(); } @Transient public boolean isAccountNonExpired() { return true; } @Transient public boolean isAccountNonLocked() { return true; } @Transient public boolean isCredentialsNonExpired() { return true; } @Transient public boolean isEnabled() { return true; } public Boolean getExpired() { return expired; } public void setExpired(Boolean expired) { this.expired = expired; } public Boolean getLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked; } public void setPassword(String password) { this.password = password; } @Transient public String getPassword() { return password; } }
htran282/IRS
src/main/java/org/hil/core/model/SystemAccount.java
Java
gpl-3.0
3,183
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ispd.motor.filas; import ispd.motor.filas.servidores.CS_Comunicacao; import ispd.motor.filas.servidores.implementacao.CS_Internet; import ispd.motor.filas.servidores.implementacao.CS_Maquina; import ispd.motor.filas.servidores.CS_Processamento; import ispd.motor.filas.servidores.implementacao.CS_MaquinaCloud; import ispd.motor.filas.servidores.implementacao.CS_VirtualMac; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Possui listas de todos os icones presentes no modelo utilizado para buscas e * para o motor de simulação * * @author denison_usuario */ public class RedeDeFilasCloud extends RedeDeFilas{ /** * Todos os mestres existentes no sistema incluindo o front-node dos * clusters */ private List<CS_Processamento> mestres; /** * Todas as máquinas que não são mestres */ private List<CS_MaquinaCloud> maquinasCloud; /** * Todas as conexões */ private List<CS_Comunicacao> links; /** * Todos icones de internet do modelo */ private List<CS_Internet> internets; /** * Mantem lista dos usuarios da rede de filas */ private List<String> usuarios; /** * Mantem a lista de máquinas virtuais */ private List<CS_VirtualMac> VMs; /** * Armazena listas com a arquitetura de todo o sistema modelado, utilizado * para buscas das métricas e pelo motor de simulação * * @param mestres * @param maquinas * @param vms * @param links * @param internets */ public RedeDeFilasCloud(List<CS_Processamento> mestres, List<CS_MaquinaCloud> maquinas, List<CS_VirtualMac> vms, List<CS_Comunicacao> links, List<CS_Internet> internets) { super(mestres,null,links, internets); this.maquinasCloud = maquinas; this.VMs = vms; } public List<CS_MaquinaCloud> getMaquinasCloud() { return maquinasCloud; } public void setMaquinasCloud(List<CS_MaquinaCloud> maquinasCloud) { this.maquinasCloud = maquinasCloud; } public List<CS_VirtualMac> getVMs() { return VMs; } public void setVMs(List<CS_VirtualMac> VMs) { this.VMs = VMs; } /** * Cria falhas para ocorrer durante a simulação usando a distribuição de Weibull. * A distribuição de Weibull indica o momento que ocorre a falha, * enquanto a uniforme indica o tempo de recuperação do recurso * @param min número mínimo de falhas que ocorrerão * @param max número máximo do falahas que ocorrerão * @param scale parâmetro de escala da distribuição de Weibull * @param shape parâmetro de forma da distribuição de Weibull * @param recMin tempo mínimo para recuperação do recurso que falhou * @param recMax tempo máximo para recuperação do recurso que falhou * @param recuperavel indica se a falha tem recuperação automática */ @Override public void setFalhas(int min, int max, double scale, double shape, double recMin, double recMax, boolean recuperavel) { Random rd = new Random(); int numFalhas = min + rd.nextInt(max - min); List<Double> falhas = new ArrayList<Double>(); for (int i = 0; i < numFalhas; i++) { falhas.add(scale * Math.pow(-Math.log(1 - rd.nextDouble()), 1 / shape)); } Collections.sort(falhas); while(!falhas.isEmpty()){ int next = rd.nextInt(maquinasCloud.size()); System.out.println("Falha "+falhas.get(0)+" no "+maquinasCloud.get(next).getId()); maquinasCloud.get(next).addFalha(falhas.remove(0), recMin, recuperavel); } } }
joaoamr/iSPD
src/ispd/motor/filas/RedeDeFilasCloud.java
Java
gpl-3.0
3,854
package yt.bam.library.modules; import java.util.ArrayList; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.permissions.Permission; import org.bukkit.plugin.Plugin; import yt.bam.library.*; import yt.bam.library.commands.*; /** * CommandModule * @author FR34KYN01535 * @version 1.1 */ public class CommandModule { public static final Logger logger = Bukkit.getLogger(); public Plugin Plugin; public static TranslationModule TranslationManager; public static ArrayList<String> RootCommands; public static ArrayList<ICommand> Commands; public CommandModule(Plugin plugin,TranslationModule translationManager,String[] rootCommands,ArrayList<ICommand> commands){ Plugin = plugin; TranslationManager = translationManager; RootCommands = new ArrayList<String>(); for(String rootCommand :rootCommands) { RootCommands.add(rootCommand.toLowerCase()); } Commands = commands; } public static boolean onCommand(CommandSender sender, org.bukkit.command.Command root, String commandLabel, String[] args) { if (RootCommands.contains(root.getName().toLowerCase())) { ICommand command=null; if(args.length==0){ command = new CmdHelp(); }else{ for(ICommand cmd : Commands){ String[] cmdargs = cmd.getName(); if(args.length >= cmdargs.length){ int index = 0; boolean found = true; for(String cmdarg : cmdargs){ if(!cmdarg.equals(args[index])){ found =false; } } if(found){ command=cmd; break; } } } } if (command == null) { Helpers.sendMessage(sender, ChatColor.RED + TranslationManager.getTranslation("COMMAND_MANAGER_UNKNOWN_COMMAND")); return true; } try { Permission permission = command.getPermissions(); if(permission == null || hasPermission(sender,permission)){ if(!command.allowedInConsole() && !(sender instanceof Player)){ Helpers.sendMessage(sender, ChatColor.RED + TranslationManager.getTranslation("COMMAND_MANAGER_ONLY_CHAT")); }else{ command.execute(sender, commandLabel, args); // Execute } return true; } } catch (Exception e) { sender.sendMessage(commandLabel); logger.info(e.getMessage()); } finally { return true; } } return false; } public static boolean hasPermission(CommandSender player, Permission permission){ if(player.hasPermission(permission)){ return true; }else{ Helpers.sendMessage(player, ChatColor.RED + TranslationManager.getTranslation("COMMAND_MANAGER_NO_PERMISSION")+ " ("+permission.getName()+")"); return false; } } public void onEnable() { } public void onDisable() { // } }
BAMdevelopment/BAMLibrary
src/main/java/yt/bam/library/modules/CommandModule.java
Java
gpl-3.0
3,547
/* * * DATA SCENE * */ // Fait la moyenne des data sommé par le hub function getSensorData() { var result = {}; if (motion.counter != 0) { result.motion = { acceleration : { x : motion.acceleration.x / motion.counter, y : motion.acceleration.y / motion.counter, z : motion.acceleration.z / motion.counter }, rotationRate: { betaDeg : motion.rotationRate.betaDeg / motion.counter, gammaDeg : motion.rotationRate.gammaDeg / motion.counter, alphaDeg : motion.rotationRate.alphaDeg / motion.counter }, interval : motion.interval }; } else { result.motion = previousData.motion; } if (orientation.counter != 0) { result.orientation = { betaDeg : orientation.betaDeg / orientation.counter, gammaDeg : orientation.gammaDeg/ orientation.counter, alphaDeg : orientation.alphaDeg/ orientation.counter }; } else { result.orientation = previousData.orientation; } if (nipple.counter != 0) { result.nipple = { force : nipple.force / nipple.counter, angleRad : nipple.angleRad / nipple.counter }; } else { result.nipple = previousData.nipple; } if(result.motion.interval >= 1000/60) { result.motion.interval = 1000/60; } // Kalman rate init and interval ! kalmanAlpha.setRate(result.motion.rotationRate.alphaDeg); kalmanBeta.setRate(result.motion.rotationRate.betaDeg); kalmanGamma.setRate(result.motion.rotationRate.gammaDeg); kalmanBeta.setDeltat(result.motion.interval/1000); kalmanGamma.setDeltat(result.motion.interval/1000); kalmanAlpha.setDeltat(result.motion.interval/1000); //previousData = result; return result; } // Reset to 0 sensor data function resetSensorData() { motion.counter = 0; motion.acceleration.x = 0; motion.acceleration.y = 0; motion.acceleration.z = 0; motion.rotationRate.betaDeg = 0; motion.rotationRate.gammaDeg = 0; motion.rotationRate.alphaDeg = 0; motion.interval = 0; orientation.counter = 0; orientation.betaDeg = 0; orientation.gammaDeg = 0; orientation.alphaDeg = 0; nipple.counter = 0; nipple.force = 0; nipple.angleRad = 0; }
sandros06/R-3D
apps/base_websocket/public/javascripts/scripts/data_scene.js
JavaScript
gpl-3.0
2,528
<?php ob_start ("ob_gzhandler"); header("Content-type: text/css; charset= UTF-8"); header("Cache-Control: must-revalidate"); $expires_time = 1440; $offset = 60 * $expires_time ; $ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT"; header($ExpStr); ?> /*** kunena.forum.css ***/ @charset "utf-8"; /** * @version $Id$ * Kunena Component * @package Kunena * * @Copyright (C) 2008 - 2011 Kunena Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org * * Based on FireBoard Component * @Copyright (C) 2006 - 2007 Best Of Joomla All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.bestofjoomla.com * **/ /* ------------------------- FONT SIZES FOR BLUE EAGLE PX EM PCT PT 6px .5em 50% 5pt 7px .583em 58.3% 5pt 8px .667em 66.7% 6pt 9px .75em 75% 7pt 10px .833em 83.3% 8pt 11px .917em 91.7% 8pt 12px 1em 100% 9pt (Base size) 13px 1.083em 108.3% 10pt 14px 1.167em 116.7% 11pt 15px 1.25em 125% 11pt 16px 1.333em 133.3% 12pt 17px 1.417em 141.7% 13pt 18px 1.5em 150% 14pt 19px 1.583em 158.3% 14pt 20px 1.667em 166.7% 15pt 21px 1.75em 175% 16pt 22px 1.833em 183.3% 17pt 23px 1.917em 191.7% 17pt 24px 2em 200% 18pt ----------------------------------------------------------*/ /* ----------------------------------------------------------------------------------------------- */ /* MAIN STYLES ----------------------------------------------------------------------------------------------- */ #Kunena { padding: 0; margin: 0; line-height: 1.333em; } #Kunena td, #Kunena table, #Kunena th, #Kunena div, #Kunena p, #Kunena span { font-size: 1em; } #Kunena sup { vertical-align: super; } #Kunena sub { vertical-align: sub; } #Kunena ul li { background: none; margin: 0; } #Kunena .clr { clear:both; height:1px; overflow:hidden;} #Kunena .fltlft {float:left;} #Kunena .fltrt {float:right;} #Kunena .kright {text-align:right;} #Kunena .kleft {text-align:left;} #Kunena .kcenter {text-align:center;} #Kunena .nowrap {white-space:nowrap;} #Kunena .divider {margin:0 3px;} #Kunena .hidden {overflow:hidden;} #Kunena a { text-decoration: none; font-weight: normal; } #Kunena a:link, #Kunena a:visited, #Kunena a:active {} #Kunena a:focus {outline: none;} #Kunena a:hover {} #Kunena .overflow { display: table; table-layout:fixed; width: 100%; } #Kunena .kxs { /* 9px */ font-size: .75em; } #Kunena .kms { /* 10px */ font-size: .833em; } #Kunena .ks { /* 11px */ font-size: .917em; } #Kunena .km { /* 12px */ font-size: 1em; } #Kunena .kl { /* 16px */ font-size: 1.333em; } #Kunena .kxl { /* 17px */ font-size: 1.417em; } #Kunena .kxxl { /* 20px */ font-size: 1.667em; } #Kunena input.ksmall { width: 25%; } #Kunena input.kmedium { width: 45%; } #Kunena input.klarge { width: 95%; } #Kunena textarea, #Kunena textarea.kmedium { font-size: 1em; width: 95%; height: 10em; } #Kunena textarea.ksmall { height: 5em; } #Kunena textarea.klarge { height: 20em; } #Kunena .knewchar { font-weight: bold; margin-left: 3px; font-size: .75em; vertical-align:top; white-space:nowrap; } #Kunena table { width :100%; border-collapse:collapse; padding:0; margin:0; } /* Block styling ----------------------------------------------------------------------------------------------- */ #Kunena div.kblock { display: table; table-layout:fixed; width: 100%; border: none; margin: 5px 0 0 0; clear: both; border-bottom:4px solid; } #Kunena .kblock div.kheader { border-bottom:2px solid; padding:0 10px 0 10px; background: #5388B4 !important; } #Kunena .kheader h2, #Kunena .kheader h2 a { font-weight: bold; margin-bottom: 0; padding: 0; } #Kunena div.kblock div.ktitle { text-align: left; display: table-row; width:100%; margin: 0; word-wrap: break-word; overflow: hidden; } #Kunena div.kblock div.ktitle h1, #Kunena div.kblock div.ktitle h2 { border: none; display: block; line-height: 1.9em; font-size:1.333em; text-indent: 0px; padding-top: 2px; margin: 0 10px; padding: 2px 0; width: auto; } #Kunena div.kblock span.ktoggler { float: right; top: 1px; right: -10px; height: 1px; position: relative; } #Kunena .ktoggler a:hover { color:#ff0000; background: url("../../default/images/expand.gif") no-repeat scroll 0 0 transparent; } #Kunena div.kblock span.select-toggle { float: right; top: 5px; right: 13px; height: 1px; position: relative; } #Kunena div.kblock div.kcontainer { display: table-row; } #Kunena div.kblock div.kbody { border-style:solid; border-width:0px 1px; overflow: hidden; word-wrap: break-word; } #Kunena div.kblock label { clear: both; /*display: block;*/ } #Kunena div.kblock div.khelprulescontent, #Kunena div.kblock div.kfheadercontent { vertical-align: top; padding: 15px; /*border: 1px solid;*/ } #Kunena div.kblock div.khelprulesjump { border: 1px solid; } #Kunena div.kblock div.kactions { padding: 5px 10px; line-height: 13px; } #Kunena div.kblock div.kactions a { color: #FFF !important; background-color:transparent !important } #Kunena table.kblock { width: 100%; margin: 5px 0 0 0; clear: both; border-spacing: 0; } #Kunena tr.krow1 td { padding: 4px 8px; } #Kunena tr.krow2 td { padding: 4px 8px; } #Kunena table.kblock .kcol { padding: 4px 8px; } #Kunena .kcol-annid { text-align: center; width: 5%; } #Kunena .kcol-anndate { width: 15%; } #Kunena .kcol-anntitle { width: 50%; } #Kunena .kcol-annpublish { text-align: center; width: 10%; } #Kunena .kcol-annedit { text-align: center; width: 10%; } #Kunena .kcol-anndelete { text-align: center; width: 10%; } #Kunena table.kblocktable .knewchar { font-size: .583em; } #Kunena tr.ksth { font-size: 1em; } #Kunena tr.ksth th{ padding: 3px 5px; text-align: center; } #Kunena td#kpost-buttons { text-align:center; } #Kunena tr.krow1 td.kcc-row1, #Kunena tr.krow2 td.kcc-row1 { background: none; } #Kunena td.kcol-ktopicreplies { text-align: center; width:1%; } #Kunena td.kcol-ktopicreplies strong { display: block; font-size: 2.091em; font-weight: normal; margin: 4px 0; } #Kunena span.kcat-topics, #Kunena span.kcat-replies { text-align:center; font-size: 1em; } #Kunena span.kcat-topics-number, #Kunena span.kcat-replies-number { display:block; font-size: 1.417em; margin:5px 0; } #Kunena .ktopic-latest-post, #Kunena .ktopic-date { font-size: .917em; } #Kunena a.ktopic-title { font-weight: bold; font-size: 1.25em; } #Kunena div.ktopic-title-cover { text-align:left; } #Kunena div.ktopic-details { clear:left; font-size: .977em; } #Kunena .klatest-avatar, #Kunena .ktopic-latest-post-avatar { display: block; height: auto; width: 36px; padding: 1px; margin: 4px 6px 2px 0; border: 1px solid; float: left; } #Kunena img.klist-avatar { height: auto; width: 36px; border: 0px } #Kunena .klatest-post-info { display:block; } #Kunena .kcredits { height: 31px; line-height: 26px; /*font-size: .833em;*/ } #Kunena td.kcredits-kintro { vertical-align: middle; padding: 0 15px; } #Kunena .kfooter { font-size: .833em; } #Kunena .kfooter-time { } #Kunena .kalert { } #Kunena td.kcol-first { border-left: none; border-bottom: 1px solid; padding: 4px 8px; vertical-align: middle; white-space:nowrap; } #Kunena td.kcol-mid { border-left: 1px solid; border-bottom: 1px solid; padding: 4px 8px; vertical-align: middle; } #Kunena td.kcol-last { border-left: 1px solid; border-bottom: 1px solid; padding: 4px 8px; vertical-align: middle; } #Kunena td.ktopicmodule { padding: 0; } #Kunena td.ktopicmoderation { width: 1%; vertical-align: middle; } #Kunena td.kcol-ktopiclastpost { font-size: .917em; width: 25%; vertical-align: middle; } /* COLOR ADMINISTRATOR AND MODERATOR ----------------------------------------------------------------------------------------------- */ #Kunena .kwho-admin { } #Kunena .kwho-globalmoderator { } #Kunena .kwho-moderator { } #Kunena .kwho-user { } #Kunena .kwho-guest { } #Kunena .kwho-banned { } #Kunena .kwho-blocked { } /* MENU ----------------------------------------------------------------------------------------------- */ #Kunena #ktop { margin: 0; border-style: solid; border-top-width: 0; border-right-width: 0; border-bottom-width: 3px; border-left-width: 0; vertical-align: bottom; line-height: 0; } #Kunena #ktop span.ktoggler { margin:-16px 0; padding:1px 1px 0; } #Kunena #ktopmenu { margin:0.33em 0; display: inline; } #Kunena #ktab { margin:0 20px 0 0; top: 0; } #Kunena #ktab ul { margin: 0; padding: 0; list-style: none; display: inline-block; } #Kunena #ktab ul ul { margin: -2px 2px; padding: 0; list-style: none; float: left; } #Kunena #ktab li, #Kunena #ktab div.moduletable ul.menu li { display: inline; float: left; margin: 2px 2px 0 0!important; padding: 0; border: 0; } #ktab div.moduletable { background: none; margin-bottom: 0; } #ktab div.moduletable ul.menu, #ktab div.moduletable ul.menu li a, #ktab div.moduletable ul.menu li a span { background-image:none!important; font-size: 1em; line-height: 2em; } #Kunena #ktab a { margin: 0; padding: 0 10px; text-decoration: none; border: 0; display: block; float: left; border-radius: 5px 5px 0 0; -moz-border-radius: 5px 5px 0 0; -webkit-border-radius: 5px 5px 0 0; color: #fff !important; font-size: 1em; line-height: 2.3em; text-indent: 0; } #Kunena #ktab a span { display: block; font-size: 1em; line-height: 2.3em; text-indent: 0; padding: 0; } #Kunena #ktab a:hover, #Kunena #ktab li.Kunena-item-active a { background-position: right bottom; } #Kunena #ktab a:hover span, #Kunena #ktab li.Kunena-item-active a span { background-position: left bottom; font-style: normal; text-decoration: none; } #Kunena select#searchlist { margin-bottom: 10px; float:left; } #Kunena select, #Kunena select:focus, #Kunena select:hover { /* background: none repeat scroll 0 0; */ /*font-size: .917em;*/ border: 1px solid; padding: 0px; } #Kunena td.td-1 { vertical-align:top; } /* Using a Joomla menu module */ #Kunena div.moduletable { margin: 0; padding: 0; border:none; } #Kunena #ktab ul.menu li.active a { /* Do not specify background color: template parameter */ } #Kunena option { background: none repeat scroll 0 0; font-size: .917em; padding: 0px 10px 0px 2px; } #Kunena .button, #Kunena .kbutton { background: none repeat scroll 0 0; font-size: .917em; border: 1px solid; padding: 0px 4px; margin-right: 10px; } #Kunena .kbutton-back { } #Kunena .kbutton-container { margin-top: 20px; text-align:center; } #Kunena .kbutton-container input.kbutton, #Kunena .kbutton-container .kbutton, #Kunena .kbutton-container .kbutton:hover, #Kunena .kbutton-container .kbutton:focus { font-size:1em; font-weight:bold; padding:4px; } #Kunena input.kinput { border: 1px solid; } #Kunena table.klist-bottom td { padding: 0 5px; height: 20px; line-height: 20px; text-align:center; } #Kunena table.klist-bottom td.klist-moderators { text-align:left; } #Kunena .kbutton:hover, #Kunena .kbutton:focus { background: none repeat scroll 0 0; font-size: .917em; border: 1px solid; padding: 0px 4px; } #Kunena .klist-actions { border: 1px solid; margin-top: -1px; } #Kunena .klist-actions td { vertical-align:middle; padding: 0 10px; white-space:nowrap; } #Kunena .klist-actions-bottom { border: 1px solid; margin-bottom: -1px; } #Kunena .klist-actions-info { float: left; font-weight: bold; height: 28px; line-height: 28px; padding-left: 15px; padding-right: 10px; } #Kunena .klist-actions-info a { text-decoration: underline; } #Kunena .klist-pages { border-left: 1px solid; float: right; font-size: 1.333em; font-weight: bold; height: 28px; line-height: 28px; padding-left: 10px; padding-right: 5px; } #Kunena .klist-times { border-left: 1px solid; height: 28px; line-height: 28px; padding-left: 5px; padding-right: 10px; } #Kunena a.klist-pages-link:link, #Kunena a.klist-pages-link:visited { text-decoration: underline; } #Kunena .klist-pages-link { padding: 0pt 5px; } #Kunena .klist-actions-info-all { font-weight: bold; height: 28px; line-height: 28px; padding-left: 15px; padding-right: 10px; width: 100%; } #Kunena .klist-actions-goto { height: 28px; padding: 0px 2px 0px 2px; width: 1%; vertical-align: middle; } #Kunena .klist-actions-forum { border-left: 1px solid; height: 28px; padding: 1px 4px 1px 4px; white-space: nowrap; vertical-align: middle; width: 10%; } #Kunena .klist-pages-all { border-left: 1px solid; font-size: 1.333em; font-weight: bold; height: 28px; line-height: 28px; padding-left: 5px; padding-right: 3px; vertical-align: middle; text-align: right; } #Kunena .klist-times-all { width: 1%; border-left: 1px solid; height: 28px; line-height: 28px; padding-left: 5px; padding-right: 5px; } #Kunena .klist-jump-all { width: 1%; border-left: 1px solid; height: 20px; line-height: 20px; padding-left: 5px; padding-right: 5px; white-space: nowrap; } #Kunena .klist-jump-all form { display: table; } #Kunena .klist-times-all .inputboxusl { /*font-size: .833em;*/ margin: 0pt; padding: 0pt; width: 100px; } #Kunena .klist-jump-all form .inputbox { /*font-size: .833em;*/ margin: 0pt; padding: 0pt; width: 150px; } #Kunena .klist-pages-all table tr td { height: 28px; line-height: 28px; white-space: nowrap; } #Kunena td.klist-jump-all input.kjumpgo { display: none; } #Kunena .klist-top { background: none; border: 1px solid; margin: -1px 0px 0px; width: 100%; } #Kunena .klist-bottom { background:none; border:1px solid; margin:0 0 5px; min-height:2.33em; padding:1px 5px; } #Kunena .klist-moderators { clear: left; } #Kunena .klist-markallcatsread { min-height: 27px; padding: 0px; overflow: hidden; border: 1px solid; } #Kunena .klist-markallcatsread input.kbutton { padding:0; margin: 4px; } #Kunena .klist-categories { border-left: 1px solid; /* height: 28px; line-height: 28px; */ padding: 0 5px 0 10px; white-space: nowrap; margin: 0; } #Kunena div.bannergroup { text-align:center; } /*---------- Pagination ------------- */ #Kunena ul.kpagination{ border:0; margin:0; padding:0 5px 0 0; } #Kunena .kpagination li{ border:0; margin:0; padding:0; font-size: .667em; list-style-type:none; line-height: .667em; display:inline-block; } #Kunena #kflattable ul.kpagination { width: auto; font-size: 1.167em; line-height: 1.167em; } #Kunena .kpagination a { border:solid 1px; } #Kunena .kpagination li.page { margin-right:2px; } #Kunena .kpagination li.more { padding:4px 2px; font-weight:bold; } #Kunena .kpagination .active { border:solid 1px; font-weight:bold; padding:3px 5px; margin: 2px; } #Kunena .kpagination a:link, #Kunena .kpagination a:visited { display:block; padding:3px 5px; margin: 2px; text-decoration:none; } #Kunena #kflattable .kpagination a:link, #Kunena #kflattable .kpagination a:visited { margin: 0; } #Kunena .kpagination a:hover{ border:solid 1px; } /* Inline pagination in topics */ #Kunena div.ktopic-title-cover ul.kpagination { padding-top: 2px; text-align:left; /* display:inline; */ } #Kunena div.ktopic-title-cover ul.kpagination li{ font-size:.833em; } #Kunena div.ktopic-title-cover ul.kpagination li.page { float:left; padding:4px 3px 0 0; } #Kunena div.ktopic-title-cover ul.kpagination a { border:solid 1px; } #Kunena div.ktopic-title-cover ul.kpagination a:hover{ border:solid 1px; } #Kunena #kflattable ul.kpagination li { margin-right: 5px; } #Kunena span.ktopic-posted-time { display: block; float:left; font-size: .917em; } #Kunena span.ktopic-category { float:left; clear:left; font-size: .917em; } #Kunena span.ktopic-views { text-align:center; } #Kunena span.ktopic-views-number { display: block; font-size: 1.455em; margin:5px 0; text-align:center; } #Kunena span.ktopic-by { float:left; } #Kunena span.ktopic-locked { margin-left: 3px; text-align: left; } /* HEADER ----------------------------------------------------------------------------------------------- */ #Kunena td.kprofileboxcnt { text-align:left; width: 95%; vertical-align:middle; padding:5px; } #Kunena td.kprofileboxcnt ul { margin: 5px 0 5px 5px; padding-left: 0; } #Kunena td.kprofileboxcnt ul.kprofilebox-link { margin: 5px 0; } #Kunena td.kprofileboxcnt ul.kprofilebox-link li { height: 10px; line-height: 10px; font-size: .917em; margin-top: 5px; padding-left:10px !important; } #Kunena td.kprofileboxcnt ul li { list-style-type:none; display: block; background: 0 none; } #Kunena td.kprofileboxcnt ul.kprofilebox-welcome li { padding: 2px; } #Kunena td.kprofileboxcnt ul.kprofilebox-welcome li input.kbutton { margin: 0; } #Kunena td.kprofileboxcnt ul.kprofilebox-welcome li input.kbutton:hover { } #Kunena .kpbox { margin: 0!important; padding:0; } #Kunena div#kforum-head { padding: 5px 10px; vertical-align:middle; border-left: 1px solid; border-right: 1px solid; border-bottom: 1px solid; } #Kunena table#kforumsearch input.kbutton { margin: 10px; } #Kunena div#kmoderatorslist div.kbody { border:1px solid; height:25px; line-height:25px; margin:-6px 0 0; padding:5px; } #Kunena div.kmoderatorslist-jump form#jumpto { margin:5px; } #Kunena table.kblock .kcol-search-subject { width: 70%; } #Kunena table.kblock .kcol-search-author { width: 10%; } #Kunena table.kblock .kcol-search-date { width: 20%; } /* SEARCH ----------------------------------------------------------------------------------------------- */ #Kunena fieldset { border:1px solid; padding:15px; margin-bottom: 15px; } #Kunena fieldset legend { font-size: 1.182em; padding-left: 5px; padding-right: 5px; margin: 0 0 0 -5px; font-weight: bold; } #Kunena select#catids option{ padding-left: 5px; } #Kunena label.searchlabel { display:block; margin-bottom: 5px; margin-right: 100px; } #Kunena input#keywords, #Kunena input#username { /*width:250px;*/ margin-right: 10px; } #Kunena select#catids { float:left; margin-bottom: 20px; } #Kunena label#childforums-lbl{ float:left; clear:left; } #Kunena fieldset#search-posts-date select, #Kunena fieldset#search-posts-sort select { margin-right: 10px; } #Kunena fieldset#search-posts-start select { margin-left: 10px; } #Kunena div.ksearchresult-desc { padding: 5px; } #Kunena div#ksearchresult div.resultmsg { padding: 15px 0; clear:left; } #Kunena div#ksearchresult span.kmsgtitle a { font-weight: bold; } #Kunena div#ksearchresult span.kmsgdate { float: left; } #Kunena div#ksearchresult div.kresult-title { border-bottom: 1px solid; overflow:hidden; padding-bottom:5px; } #Kunena div#ksearchresult td.resultmsg { padding: 0 10px 10px; } #Kunena div#ksearchresult div.resultcat { padding: 5px 0 0 0; border-top: 1px dotted; } #Kunena div.kadvsearch td.kcol-first, #Kunena div.kadvsearch td.kcol-mid { width: 50%; vertical-align: top; } /* PROFILEBOX AND LOGINBOX ----------------------------------------------------------------------------------------------- */ #Kunena ul.kprofilebox-link { float:right; } #Kunena ul.kprofilebox-link li { background: url("../../default/images/icons/arrow.png") no-repeat left !important; padding-left: 12px; display: inline; padding-right:10px; } #Kunena .kprofilebox-left { width: 5%; padding: 8px; border-right: 1px solid; vertical-align: middle; } #Kunena .kprofilebox-right { border-left: 1px solid; padding: 8px; } #Kunena .klink-block { padding-top: 5px; } #Kunena div.kpbox { border-bottom: 1px solid; } /* CATEGORY LIST ----------------------------------------------------------------------------------------------- */ #Kunena td.kmycount, #Kunena td.kcol-kcattopics, #Kunena td.kcol-kcatreplies, #Kunena td.kcol-ktopicicon, #Kunena td.kcol-ktopicviews { white-space:nowrap; text-align:center; width: 1%; vertical-align: middle; } .kcol-ktopicicon img { border: 0 none; } #Kunena td.kcol-kcatlastpost { width: 25%; text-align:left; vertical-align: middle; } #Kunena td.kcol-knoposts { width: 25%; text-align:center; vertical-align: middle; } #Kunena td.kcol-category-icon { width: 1%; } #Kunena #kblock4, #Kunena #kblock1, #Kunena .k-bt-cvr1 { margin-top: 5px; } #Kunena table.kblocktable { border-style: solid; border-width: 0px 0px 0px 0px; text-align: left; } #Kunena h1, #Kunena h2 { text-align: left; display: block; width:100%; line-height: 1.5em; font-size:1.333em; padding-top: 2px; min-height: 1.6em; margin-top: 0px; margin-bottom: 0px; font-weight:bold; text-transform: none; } #Kunena h2 a { font-weight: bold; } #Kunena h1 a:hover, #Kunena h2 a:hover { text-decoration: underline; } #Kunena h1 a:link, #Kunena h1 a:active, #Kunena h1 a:visited { } #Kunena h2 span.kright { float: right; margin: 0 10px; } #Kunena h2 span.kheadbtn { margin: 0 !important; } #Kunena h2 span.kheadbtn a { font-size: 11px; line-height: 23px; border: 1px solid; padding-top: 1px; padding-bottom: 3px; padding-left: 3px; padding-right: 3px; } #Kunena h2 span.kheadbtn:hover a { text-decoration: none; border: 1px solid; } #Kunena div.ktitle-desc { margin-top:-3px; padding:0 0 6px; } #Kunena .kcheckbox { float:right; margin-right: -14px; width: 20px; } #Kunena div.kfavorite { background: url("../../default/images/icons/favoritestar.png") no-repeat left top; height: 18px; width: 18px; display: inline-block; margin:-25px 4px 0; float: right; } #Kunena .ktitle, #Kunena a.ktitle { font-weight: bold; display: block; text-decoration: none; float:left; } #Kunena .ktitle a { font-weight: bold; text-decoration: none; } #Kunena div.kthead-title a { font-size: .917em; display: inline-block; float: left; padding-bottom: 0; margin-bottom: 3px; font-weight: bold; } #Kunena div.kthead-desc, #Kunena div.kthead-moderators { clear: left; line-height: 1.2em; } #Kunena div.kthead-moderators { margin-top: 5px; font-size: .833em; } #Kunena div.kthead-desc a { font-weight:bold; } #Kunena div.kthead-desc a:hover { text-decoration:underline; } #Kunena div.kthead-child { clear: left; border-top: 1px dotted; margin-top: 4px; } #Kunena table.kcc-table tr td { border: 0px solid; } #Kunena div.kcc-childcat-title { width: 100%; display: inline-block; vertical-align: top; padding-top: 4px; line-height: 2em; text-transform: uppercase; font-size: .833em; } #Kunena div.kcc-table { display: inline; } #Kunena span.kchildcount { margin-left: 2px; margin-right: 6px; display: inline; font-size: 0.833em; line-height: 17px; } #Kunena div.klatest-subject, #Kunena div.klatest-subject-by { margin-left: 5px; } #Kunena div.kcc-subcat { float: left; display: inline-block; vertical-align: top; padding-top: 2px; } #Kunena div.kcc-subcat a { font-size: .917em; vertical-align: bottom; } /* SHOW CATEGORY ----------------------------------------------------------------------------------------------- */ #Kunena img.stickyicon, #Kunena img.attachicon { float: right; border: 0; margin: 2px; } #Kunena img.catavatar { width: 20px; height: 20px; margin-left: 4px; border: 1px solid; } #Kunena .kcontenttablespacer { border-left: 0px; border-right: 0px; border-bottom: 1px solid; line-height:0.5em; } #Kunena .krow1-stickymsg { } #Kunena .krow2-stickymsg { } /* VIEW PAGE -------------------------------------------------------------------- */ #Kunena div.kmsg-header { border-bottom:2px solid; padding:0; } #Kunena div.kmsg-header h2 { font-size:.917em; padding:3px 0; margin-bottom: 0; } #Kunena div.kmsg-header-top span.kmsgdate-top, #Kunena div.kmsg-header-bottom span.kmsgdate-bottom, #Kunena div.kmsg-header-right span.kmsgdate-right, #Kunena div.kmsg-header-left span.kmsgdate-left { width: 180px; text-align: center; line-height:1.8em; padding-left: 10px; } #Kunena div.kmsg-header-left span.kmsgdate-left { float: none; padding: 0; padding-bottom: 5px; } #Kunena div.kmsg-header-top span.kmsg-title-top, #Kunena div.kmsg-header-bottom span.kmsg-title-bottom, #Kunena div.kmsg-header-left span.kmsg-title-left, #Kunena div.kmsg-header-right span.kmsg-title-right { /*padding-left:15px;*/ margin-left:5px; } #Kunena div.kmsg-header-top span.kmsg-id-top, #Kunena div.kmsg-header-bottom span.kmsg-id-bottom, #Kunena div.kmsg-header-left span.kmsg-id-left, #Kunena div.kmsg-header-right span.kmsg-id-right { float: right; margin:0 10px 0 0; padding: 0 } #Kunena span.kpost-thankyou { float: right; margin-right: 15px; font-size:0.917em; } #Kunena div.kpost-thankyou { margin-top:4px; } #Kunena span.kmsgusertype { font-weight: normal; text-decoration: none; text-decoration: none; font-style: italic; } #Kunena span.kavatar img { border: 1px solid; padding: 1px; margin: 5px; max-width: 100px; max-height: 150px; } #Kunena span.kmsgtitle, #Kunena span.kmsgtitle-new { font-weight: bold; text-decoration: none; background: url("../../default/images/msgtitleicon.gif") no-repeat left center; padding-left: 25px; line-height: 22px; font-size: 1.333em; } #Kunena span.kmsgtitle-new { background: url("../../default/images/msgtitlenew.gif") no-repeat left center; } #Kunena table.kmsg th.kmsg-date { vertical-align: middle !important; } #Kunena th.kmsg-date span.ktopbottom, #Kunena th.kmsg-date span.kheader-right { float: left; margin:2px 25px; } #Kunena span.kmsgdate { font-weight: normal; text-decoration: none; padding-left: 5px; /*font-size: .833em;*/ white-space: nowrap; /*float: left;*/ } #Kunena div.kmsgbody { display: table; table-layout: fixed; width: 100%; padding: 10px 0 0 0; margin-top: 5px; min-height: 180px; } #Kunena div.kmsgbody div.kmsgtext { overflow: auto; word-wrap:break-word; } #Kunena td.kmessage-right div.kmsgbody, #Kunena td.kmessage-left div.kmsgbody, #Kunena td.kmessage-top div.kmsgbody, #Kunena td.kmessage-bottom div.kmsgbody { width: 97%; } #Kunena div.kmsgbody div.kmsgtext { overflow: auto; word-wrap:break-word; } #Kunena div.kmsgbody div.kmsgtext img { max-width:100%; max-height: 800px; } #Kunena div.kmsgbody div.kmsgtext ul > li { list-style-type:disc; } #Kunena div.kmsgattach { overflow: hidden; padding: 8px; margin-top: 8px; background:none; border:1px dotted; display:block; } #Kunena ul.kfile-attach, #Kunena ul.kfile-attach-editing { margin:0 0 8px 0; padding:0; } #Kunena ul.kfile-attach li { list-style-type: none; margin-top: 10px; padding-left: 30px; background:url("../../default/images/icons/attachment.png") no-repeat; height: 32px; line-height: 32px; width: auto; float: left; } #Kunena ul.kfile-attach li span { padding-left: 10px; vertical-align:top; font-size: .833em; } #Kunena ul.kfile-attach-editing li span { vertical-align:top; padding-left: 2px; } #Kunena ul.kfile-attach-editing li { list-style-type: none; margin-top: 10px; line-height: 32px; } #Kunena ul.kfile-attach li a img, #Kunena ul.kfile-attach-editing li a img { max-width: 32px; max-height: 32px; margin-left: 10px; } #Kunena span.kmsgtext-xs { font-size: 0.5em; } #Kunena span.kmsgtext-s { font-size: 0.75em; } #Kunena span.kmsgtext-m { font-size: 1em; } #Kunena span.kmsgtext-l { font-size: 1.25em; } #Kunena span.kmsgtext-xl { font-size: 1.50em; } #Kunena span.kmsgtext-xxl { font-size: 2em; } #Kunena div.kmsgtext pre, #Kunena div.kmsgtext code { border-left: 5px solid; border-right: 1px solid; border-top: 1px solid; border-bottom: 1px solid; font-weight: normal; line-height: 1.5; margin: 3px 0 10px 0; padding: 10px 15px; overflow: auto; width: auto; word-wrap:normal; max-height: 25em; } #Kunena table.kmsg th a { float: right; } #Kunena div.kmessage-editmarkup-cover { padding-top: 5px; text-align: right; border-bottom: 1px dotted; } #Kunena span.kmessage-editmarkup { background: no-repeat left center; height: 16px; border-left: 1px dotted; border-right: 1px dotted; border-top: 1px dotted; padding: 2px 5px 2px 5px; margin-left: 3px; font-size: .75em; } #Kunena span.kmessage-informmarkup { height: 16px; border-left: 1px dotted; border-right: 1px dotted; border-top: 1px dotted; padding: 2px 5px 2px 5px; margin-left: 3px; font-size: .75em; } #Kunena div.kmsgsignature { border-top:1px dotted; font-size: .833em; margin:15px 0; padding:5px 0; text-align:left; } #Kunena div.kmsgsignature img { max-width:100%; max-height: 100px; } #Kunena div.kmessage-buttons-cover { float: right; } #Kunena div.kmessage-buttons-row { text-align: left; height: 15px; line-height: 15px; margin: 3px 0px; line-height: 14px; white-space: nowrap; font-size: .917em; } #Kunena div.kmessage-thankyou{ border-top: 1px dotted; clear: both; } #Kunena .kreply-form { border: 1px solid; padding: 0.5em; } #Kunena .kreply-form .inputbox { border: 1px solid; margin: 2px 0px; } #Kunena div.kmsgtext-article, #Kunena div.kmsgtext-quote, #Kunena div.kmsgtext-hide, #Kunena div.kmsgtext-confidential { display: block; border: 1px dotted; margin: 5px 0pt; padding: 5px; font-style: italic; } #Kunena div.kmsgtext-article { } #Kunena div.kmsgtext-hide { } #Kunena div.kmsgtext-confidential { } #Kunena div.khide { background: url("../../default/images/bullet-tips.gif") no-repeat scroll 5px center; border: 1px dotted; font-size: 1.3em; padding: 10px 10px 10px 25px; } /* AVATAR POSITION ----------------------------------------------------------------------- */ #Kunena div.kmsgtitle { /*border-bottom:1px solid; padding-bottom: 5px;*/ } /* right ----------------------------------------*/ #Kunena td.kprofile-right { width: 170px; min-width: 170px; border-bottom: 1px solid; border-left: 1px solid; vertical-align:top; } #Kunena td.kmessage-right { width: 100%; overflow: hidden; padding: 10px 10px 0px 10px; vertical-align: top; } #Kunena td.kbuttonbar-right { vertical-align:bottom; width: 100%; height: 1em; margin: 3px; border-bottom: 1px solid; padding: 3px 10px; } /* left ----------------------------------------*/ #Kunena td.kprofile-left { vertical-align: top; width: 170px; min-width: 170px; border-bottom: 1px solid; border-right: 1px solid; } #Kunena td.kmessage-left { overflow: hidden; width: 100%; padding: 10px 10px 0px 10px; vertical-align: top !important; } #Kunena td.kbuttonbar-left { vertical-align:bottom; width: 100%; height: 1em; margin: 3px; border-bottom: 1px solid; padding: 3px 10px; } #Kunena .kunapproved td { } #Kunena .kdeleted td { } #Kunena div.kprofile { text-align: center; padding: 5px; } /* User info on posts ----------------------------------------*/ /* Left and right layouts */ #Kunena ul.kpost-profile li { padding: 0px; } #Kunena ul.kpost-profile { margin:8px 0; padding: 0; text-align:center; line-height: 1.5em; } #Kunena ul.kpost-profile li { list-style-type: none; display:block; padding-bottom: 1px; text-align:center !important; } #Kunena ul.kpost-profile li.kpost-username {font-size: 1.333em;} #Kunena ul.kpost-profile li.kpost-usertype {} #Kunena ul.kpost-profile li.kpost-avatar{} #Kunena ul.kpost-profile li.kpost-userrank{} #Kunena ul.kpost-profile li.kpost-userrank-img {} #Kunena ul.kpost-profile li.kpost-userrank-img img{vertical-align: text-top;} #Kunena ul.kpost-profile li.kpost-online-img{} #Kunena ul.kpost-profile li.kpost-online-img img {vertical-align: text-top;} #Kunena ul.kpost-profile li.kpost-karma {} #Kunena li.kpost-karma span.kmsgkarma { } #Kunena span.kkarma-minus { background: url("../../default/media/iconsets/profile/default/default.png") no-repeat 0px -294px; height: 14px; width: 14px; display: inline-block; margin: -2px 0; } #Kunena span.kkarma-plus { background: url("../../default/media/iconsets/profile/default/default.png") no-repeat 0px -313px; height: 14px; width: 14px; display: inline-block; margin: -2px 0; } #Kunena li.kpost-userposts{ margin : 0px; } #Kunena ul.kpost-profile li.kpost-smallicons{ margin: 0px auto; width: 90%; } #Kunena ul.kpost-profile li.kpost-personal{ text-align: center; font-style:italic; } #Kunena span.kpost-online-status-yes { display:inline-block; background: url("../../default/images/icons/online.gif") no-repeat; height: 15px; width: 74px; vertical-align: text-top; } #Kunena span.kpost-online-status-no { display:inline-block; background: url("../../default/images/icons/offline.gif") no-repeat; height: 15px; width: 74px; vertical-align: text-top; } #Kunena li.kpost-online-status-top-yes { display:block; float: left; padding-right:5px; background: url("../../default/images/icons/online.gif") no-repeat; height: 15px; width: 74px; } #Kunena li.kpost-online-status-top-no { display:block; float: left; padding-right:5px; background: url("../../default/images/icons/offline.gif") no-repeat; height: 15px; width: 74px; } /* Top and bottom layouts */ #Kunena ul#kpost-profiletop { margin:0; padding: 0; } #Kunena ul#kpost-profiletop li { list-style-type: none; display:block; padding: 0; } #Kunena ul#kpost-profiletop li.kpost-avatar{ float:left; clear:left; margin-right: 5px; } #Kunena ul#kpost-profiletop li.kpost-userrank{ padding-right: 5px; } #Kunena ul#kpost-profiletop li.kpost-smallicons{ float:right; width: auto; padding-top: 5px; } #Kunena ul#kpost-profiletop li.kpost-personal{ text-align: center; font-style:italic; float:right; width: 40%; padding-top: 5px; } /* top ----------------------------------------*/ #Kunena ul#kpost-profiletop li.kpost-userrank-img { display: block; } #Kunena td.kprofile-top { vertical-align: top; border-bottom: 1px solid; padding: 5px; } #Kunena td.kmessage-top { width: 100%; padding: 10px 10px 0px 10px; } #Kunena td.kbuttonbar-top { width: 100%; margin: 3px; border-bottom: 1px solid; padding: 3px 10px; } #Kunena div.ktopbottom-avatar { float: left; } #Kunena div.kprofile-mid { padding: 0px 5px; display: inline; text-align: left; vertical-align: middle; float:left; } #Kunena div.kprofile-right { display: inline; vertical-align: middle; float:right; width: 15%; text-align:right; } #Kunena div.kpersonal { padding: 0px 20px; display: inline; text-align: left; vertical-align: middle; float:left; } /* bottom ----------------------------------------*/ #Kunena td.kprofile-bottom { vertical-align: bottom; border-bottom: 1px solid; border-top: 1px solid; padding: 5px; } #Kunena td.kmessage-bottom { width: 100%; overflow: hidden; padding: 10px 10px 0px 10px; } #Kunena td.kbuttonbar-bottom { width: 100%; margin: 3px; padding: 3px 10px; } /* Stats on main page */ #Kunena ul#kstatslistleft, #Kunena ul#kstatslistright { margin: 0; padding: 0; } #Kunena ul#kstatslistleft li, #Kunena ul#kstatslistright li { list-style-type:none; display:block; margin-left: 0; padding: 1px 0px 1px 0; background: none; line-height: 1.333em; } #Kunena ul#kstatslistright li strong a { font-weight:bold; } /* POST PAGE -------------------------------------------------------------------- */ #Kunena #kpost-message .postinput { width: 94%; border: 1px solid; padding: 3px 5px; } #Kunena #kpost-message .postinput:hover, #Kunena #kpost-message .postinput:focus { width: 94%; border: 1px solid; padding: 3px 5px; } #Kunena #kpostmessage tr.krow2 td.kcol-ktopicicons table { width: 95%; } #Kunena #kpostmessage tr.krow2 td.kcol-ktopicicons td { border: 1px solid; width: 99%; } #Kunena #kpostmessage tr.krow1 .kpostbuttonset td.kposthint { border: 1px solid; padding: 2px 5px; } #Kunena table#kpostmessage .kposthint .kinputbox { border: 0px solid; width: 99%; } #Kunena .kpostbuttonset { width: 95%; margin: 2px; border: 1px solid; } #Kunena tr.krow1 .kpostbuttons { border: 1px solid; } #Kunena table#kpostmessage .ktxtarea { overflow: auto; /* IMPORTANT: height must be set in px */ height: 200px; border: 1px solid; } #Kunena table.kreview-table td.author { width: 15%; text-align: center; } #Kunena td.kcaptcha { text-align: left; vertical-align:middle; height: 35px; } #Kunena div#khistory td.kauthor, #Kunena div#ksearchresult td.kresultauthor { text-align:center; } #Kunena div#khistory td.khistorymsg { text-align:left; padding: 10px; } #Kunena div#khistory span.khistory-msgdate { float:left; padding-left: 10px; } #Kunena div#khistory tr.ksth a { float:right; padding-right: 10px; } /* ---- Post Previews ---- */ #Kunena textarea#kbbcode-message { width: 95%; float: left; } #Kunena #kbbcode-preview { /* IMPORTANT: do not set height - controlled by js */ border: 1px solid; overflow: scroll; } #Kunena div.kbbcode-preview-bottom { /* IMPORTANT: do not set height - controlled by js */ float:left; clear:left; width: 95%; margin-top: 10px; } #Kunena div.kbbcode-preview-right { /* IMPORTANT: do not set height - controlled by js */ float:right; width: 48%; margin-right: 10px; } #Kunena #kpostmessage tr.krow1 .kpostbuttonset td, #Kunena #kpostmessage tr.krow2 .kpostbuttonset td { border-bottom: 1px solid; } #Kunena #kpost-message td.kcol-first { width: 15%; text-align: right; vertical-align: middle; } #Kunena #kpost-result div { border: 1px solid; font-size: 1em; } #Kunena #kpost-buttons { padding: 4px; } #Kunena #kpost-buttons .kbutton { padding: 4px; font-weight: bold; font-size: 1em; } #Kunena div#kcolor-palette, #Kunena div#link, #Kunena div#image, #Kunena div#video { border-bottom: 1px solid; margin-bottom: 5px; padding-bottom: 5px; } /* FORUM ICON BUTTONS ----------------------------------------------------------------------------------------------- */ #Kunena .kicon-button { text-transform: uppercase; /* We need to use fixed font size: button does not grow */ font-size: 11px; text-decoration: none; cursor: pointer; line-height: 145%; display: inline-block; background-image: url("../../default/media/iconsets/buttons/default/default.png") !important; background-repeat: repeat-x; border: none; margin:0 5px; } /* #Kunena a.kicon-button:hover { background-position: 0 -480px !important; } */ #Kunena .kicon-button span { background-image: inherit; background-repeat: no-repeat; display: inline-block; margin:0 -5px; } #Kunena .kicon-button span span { height: 18px; display: inline-block; margin: 0; padding: 0 7px 0 20px; background-repeat: no-repeat; } #Kunena a.kicon-button span span:hover { text-decoration: underline; } /* Need the hover states to fix Beez in Joomla 1.6 */ #Kunena .kbuttonuser, #Kunena .kbuttonuser:hover { background-position: 0 -360px; } #Kunena .kbuttononline-yes, #Kunena .kbuttonmod, #Kunena .kbuttononline-yes:hover, #Kunena .kbuttonmod:hover{ background-position: 0 -200px; } #Kunena .kbuttononline-no, #Kunena .kbuttongen, #Kunena .kbuttoncomm, #Kunena .kbuttononline-no:hover, #Kunena .kbuttongen:hover, #Kunena .kbuttoncomm:hover { background-position: 0 -480px; } #Kunena .kbuttononline-yes span span, #Kunena .kbuttonmod span span, #Kunena .kbuttononline-yes span span:hover, #Kunena .kbuttonmod span span:hover{ background-position: right -220px; } #Kunena .kbuttonuser span span, #Kunena .kbuttonuser span span:hover { background-position: right -380px; } #Kunena .kbuttononline-no span span, #Kunena .kbuttongen span span, #Kunena .kbuttoncomm span span, #Kunena .kbuttononline-no span span:hover, #Kunena .kbuttongen span span:hover, #Kunena .kbuttoncomm span span:hover { background-position: right -500px; } #Kunena .kbuttononline-yes span span, #Kunena .kbuttononline-no span span { padding: 0 7px; height: 15px; } #Kunena .kbuttononline-yes span.online-yes {background-position: 0 0px;} #Kunena .kbuttononline-no span.online-no {background-position: 0 -400px;} #Kunena .kbuttoncomm span.reply {background-position: 0 -460px;} #Kunena .kbuttoncomm span.quote {background-position: 0 -440px;} #Kunena .kbuttoncomm span.newtopic {background-position: 0 -420px;} #Kunena .kbuttonuser span.layout-flat {background-position: 0 -240px} #Kunena .kbuttonuser span.layout-flat span {padding: 0 7px;} #Kunena .kbuttonuser span.layout-threaded {background-position: 0 -240px} #Kunena .kbuttonuser span.layout-threaded span {padding: 0 7px;} #Kunena .kbuttonuser span.layout-indented {background-position: 0 -240px} #Kunena .kbuttonuser span.layout-indented span {padding: 0 7px;} #Kunena .kbuttonuser span.thankyou {background-position: 0 -340px;} #Kunena .kbuttonuser span.favorite {background-position: 0 -260px;} #Kunena .kbuttonuser span.subscribe {background-position: 0 -320px;} #Kunena .kbuttonuser span.markread {background-position: 0 -300px;} #Kunena .kbuttonuser span.report {background-position: 0 -320px;} #Kunena .kbuttonmod span.merge {background-position: 0 -100px;} #Kunena .kbuttonmod span.edit {background-position: 0 -60px;} #Kunena .kbuttonmod span.delete {background-position: 0 -40px;} #Kunena .kbuttonmod span.permdelete {background-position: 0 -40px;} #Kunena .kbuttonmod span.undelete {background-position: 0 -20px;} #Kunena .kbuttonmod span.move {background-position: 0 -140px;} #Kunena .kbuttonmod span.sticky {background-position: 0 -180px;} #Kunena .kbuttonmod span.lock {background-position: 0 -80px;} #Kunena .kbuttonmod span.split {background-position: 0 -160px;} #Kunena .kbuttonmod span.approve {background-position: 0 -180px;} #Kunena .kbuttonmod span.moderate {background-position: 0 -120px;} /* Goto Up/down buttons */ #Kunena a.kbuttongoto { } #Kunena a.kbuttongoto span.top { background: url("../../default/images/icons/top_arrow.gif") no-repeat left top; height: 18px; width: 18px; display: block; } #Kunena a.kbuttongoto span.bottom { background: url("../../default/images/icons/bottom_arrow.gif") no-repeat left top; height: 18px; width: 18px; display: block; } #Kunena div#kreport-container { /*border:1px solid;*/ height:1%; overflow:auto; padding:10px 10px 30px; } #Kunena form.kform-report, #Kunena form.kform-report label, #Kunena form.kform-report input, #Kunena form.kform-report textarea { float:left; clear:both; } #Kunena form.kform-report label { margin-top: 15px; } #Kunena form.kform-report input, #Kunena form.kform-report textarea { border:1px solid; } #Kunena div.kreportstatus { text-align:center; margin: 30px 0; } /* BBCODE BUTTONS -------------------------------------------------------------------- */ #Kunena img.kbbcode { cursor: pointer; margin-top: 4px; margin-right: 1px; padding: 0px; } #Kunena img.kbbcode:hover { cursor: pointer; margin-top: 4px; margin-right: 1px; padding: 0px; } #Kunena .kbbcode-colortable { cursor: pointer; width: 100%; margin-left: auto; margin-right: auto; } #Kunena div#kbbcode-size-options { margin:2px 0 0; } #Kunena div#kbbcode-size-options span { vertical-align: middle; display: inline-block; line-height: 24px; } #Kunena div#kbbcode-size-options span:hover { cursor: pointer; padding: 0px; } #Kunena table.kpostbuttonset tr td.kpostbuttons select.kslcbox { position: relative; bottom: 5px; } #Kunena #kbbcode-toolbar { list-style-position:inside; list-style-type:none; height:18px; margin:2px 0 2px; padding:0; position:relative; } #Kunena #kbbcode-toolbar li { float:left; list-style-image:none !important; list-style-type:none !important; margin:0; padding:0; } #Kunena #kbbcode-toolbar li a { background-repeat: no-repeat; display:block; height:18px; width:18px; margin-right: 2px; } #Kunena #kbbcode-toolbar li a:hover { cursor: pointer; padding: 0px; } #Kunena #kbbcode-toolbar li span { display:none; } #Kunena ul#kbbcode-toolbar li a#kbbcode-separator1, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator2, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator3, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator4, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator5, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator6, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator7, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator8 { background-position:-400px 0; width: 8px; cursor: default; } #Kunena ul#kbbcode-toolbar li a#kbbcode-bold-button {background-position:0 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-italic-button {background-position:-18px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-underline-button {background-position:-36px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-strike-button {background-position:-54px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-sub-button {background-position:-72px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-sup-button {background-position:-90px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-size-button {background-position:-108px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-color-button {background-position:-126px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-spoiler-button {background-position:-144px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-hide-button {background-position:-162px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-ulist-button {background-position:-180px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-olist-button {background-position:-198px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-list-button {background-position:-216px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-left-button {background-position:-234px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-center-button {background-position:-252px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-right-button {background-position:-270px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-quote-button {background-position:-288px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-code-button {background-position:-306px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-image-button {background-position:-324px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-link-button {background-position:-342px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-table-button {background-position:0 -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-module-button {background-position:-18px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-ebay-button {background-position:-360px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-video-button {background-position:-378px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-map-button {background-position:-72px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-attach-button {background-position:-36px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-gallery-button {background-position:-54px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-poll-button {background-position:-90px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-previewbottom-button {background-position:-252px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-previewright-button {background-position:-270px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-help-button {background-position:-396px -18px;} #Kunena .kspoiler { cursor:pointer; } #Kunena .kattachment .hasTip { display: inline; } #Kunena .kattachment .kbutton { /* font-size: 1em; */ } #Kunena #kattachments { line-height:18px; } #Kunena #kattachments a { background-repeat: no-repeat; display:inline-block; height:18px; width:18px; margin-right: 2px; } #Kunena #kattachments a { background-position:-216px -18px; } /* Define default image if not set in admin config */ #Kunena #kbbcode-toolbar li a, #Kunena #kattachments a { background-image:url("../../default/media/iconsets/editor/default/default.png"); } /* Multi file upload for bbcode editor -------------------------------------------------------------------- */ #kfilename {} #Kunena .kfile-input-textbox {/* float: left; */ display: inline-block; } #kupload {} #Kunena .kfile-hide { position: relative; width: 100px; height: 23px; overflow: hidden; } #Kunena .kfile-input-button, #Kunena .kfile-input-button:hover, #Kunena .kfile-input-button:focus { top: 0px; background: none; font-size: .833em !important; border: 1px solid; padding: 3px 6px; cursor:pointer; } #Kunena .kfile-input-button:hover, #Kunena .kfile-input-button:focus { background: none; border: 1px solid; } #Kunena .kattachment-remove, #Kunena .kattachment-insert { background: none; font-size: .917em !important; border: 1px solid; padding: 3px 6px; } #Kunena .kattachment-remove:hover, #Kunena .kattachment-insert:hover { font-size:0.917em !important; padding: 3px 6px; } #Kunena .kattachment-insert { margin-left: 20px; } #Kunena .kfile-input { font-size: 23px; position: absolute; right: 0px; top: -10px; /* CSS3 standard */ opacity: 0; /* For IE */ filter:alpha(opacity=0); } #Kunena #kbbcode-filelist { padding: 0; list-style: none; margin: 0; } #Kunena #kbbcode-filelist .file-invalid { cursor: pointer; padding-left: 48px; line-height: 24px; margin-bottom: 1px; } #Kunena #kbbcode-filelist .file-invalid span { padding: 1px; } #Kunena #kbbcode-filelist .file { line-height: 2em; padding-left: 22px; } #Kunena #kbbcode-filelist .file span, #Kunena #kbbcode-filelist .file a { padding: 0 4px; } #Kunena #kbbcode-filelist .file .file-size { } #Kunena #kbbcode-filelist .file .file-error { } #Kunena #kbbcode-filelist .file .file-progress { width: 125px; height: 12px; vertical-align: middle; } /* POLLS -------------------------------------------------------------------- */ label.kpoll-title-lbl { display:inline-block; margin: 10px 15px 10px 5px; } label.kpoll-term-lbl { display:inline-block; margin: 10px 15px 10px 30px; } #kpoll-text-help { font-weight: bold; padding: 0px 10px; margin: 3px; } #kpoll-text-help p { padding: 5px 10px; } #kpoll-form-vote fieldset { border: 0 none; margin:0; padding:0; } #kpoll-form-vote legend { text-indent: -9999px; } #kpoll-form-vote ul { margin:0 0 0 20px; padding: 0; } #kpoll-form-vote ul li { list-style-type:none; line-height: 30px; list-style: none !important; } #kpoll-btns { margin: 5px 0 20px 20px; } #Kunena div.kpolldesc td.kpoll-option { text-align: left; width: 60%; padding: 3px 8px; } #Kunena div.kpolldesc td.kpoll-bar { text-align: left; width: 20%; } #Kunena div.kpolldesc td.kpoll-number, #Kunena div.kpolldesc td.kpoll-percent { text-align: center; width: 10%; } #Kunena #kpoll-button-vote { margin: 20px 20px 20px 30px; } /* PATHWAY ----------------------------------------------------------------------------------------------- */ #Kunena .kforum-pathway { padding: 5px; line-height: 18px; margin: -5px 0 0; border-left: 1px solid; border-right: 1px solid; } #Kunena .kforum-pathway-bottom { padding: 3px; line-height: 18px; margin: -1px 0 5px 0; border: 1px solid; } #Kunena .kforum-pathway-bottom img { vertical-align:text-bottom; } #Kunena .path-element-first { font-weight: normal; height: 18px; line-height: 18px; background: url("../../default/images/pathway_start.gif") no-repeat left center; display: inline; padding: 1px 3px 1px 22px; } #Kunena .path-element-first a:link, #Kunena .path-element-first a:visited { font-weight: normal; text-decoration: none; background: none; } #Kunena .path-element-last, #Kunena .path-element-last a:link { font-weight: bold; text-decoration: none; text-indent: 5px; display: inline; } #Kunena .kforum-pathway .path-element, #Kunena .kforum-pathway-bottom .path-element { background: url("../../default/images/icons/arrow.png") no-repeat left center; padding-left: 12px; display: inline; font-weight: normal; height: 18px; line-height: 18px; padding-right: 3px; } #Kunena .kforum-pathway .path-element-last, #Kunena .kforum-pathway-bottom .path-element-last { height: 18px; line-height: 18px; background: url("../../default/images/pathway_finallink.gif") no-repeat left center; padding: 1px 5px 1px 37px; } #Kunena .path-element-users { display: inline; margin-top: 21px; } /* FORUM HEADER DESCRIPTION -------------------------------------------------------------------- */ #Kunena .kforum-headerdesc { padding: 3px; line-height: 18px; margin: -1px 0 0 0; border: 1px solid; } #Kunena .kforum-headerdesc td{ padding: 8px; } /* HELP, RULES, UPLOAD AVATAR, ANNOUNCEMENT -------------------------------------------------------------------- */ #Kunena div.kannouncement h2 { table-layout:fixed; word-wrap:break-word; } #Kunena div#kannouncement .kanndesc { padding: 5px 10px; } #Kunena img.calendar { margin: 5px 0 -5px 5px; } #Kunena td.kuadesc, #Kunena td.kcreditsdesc { vertical-align: top; padding: 15px; /*border: 1px solid;*/ } #Kunena td.kcreditsdesc div.kfooter { text-align:center; } #Kunena .kcredits-intro { margin:5px; padding:15px 30px; text-align:left; border: 1px solid; border-radius: 15px; -moz-border-radius: 15px; -webkit-border-radius: 15px; } #Kunena .kteam { margin: 0; padding: 0; } #Kunena .kteammember { list-style-type:circle; margin:0 10px; padding:0; text-align:left; background: transparent none; border-radius: 15px; -moz-border-radius: 15px; -webkit-border-radius: 15px; } #Kunena .kcredits-more { padding: 10px 20px; margin: 15px; border: 1px solid; border-radius: 15px; -moz-border-radius: 15px; -webkit-border-radius: 15px; } #Kunena .kcredits-language { padding: 10px 20px; border: 1px solid; margin: 15px; border-radius: 15px; -moz-border-radius: 15px; -webkit-border-radius: 15px; } #Kunena .kstatsicon { background: url("../../default/images/icons/stats.png") no-repeat center top; width: 32px; height: 32px; } #Kunena div#searchuser_tbody div.search-user { padding:5px 10px; float: left; } #Kunena div#searchuser_tbody div.userlist-jump { float: right; } #Kunena tr.userlist th { padding: 3px; text-align: center; } #Kunena tr.userlist th a { color: #FFF !important; } #Kunena div#userlist_tbody td, #Kunena table#kuserlist_bottom th { padding: 4px 8px; } #Kunena div#userlist-tbody td { text-align: center; } #Kunena table#kuserlist-bottom div { text-align: center; padding: 3px; } /* STATISTICS PAGE ------------------------------------------------------------------- */ #Kunena tr.ksth th.kname { width: 50%; text-align: left; } #Kunena tr.ksth th.kbar { width: 40%; } #Kunena tr.ksth th.knr { width: 10%; } #Kunena div.kwhoisonline td.kcol-first, #Kunena div.kgenstats td.kcol-first, #Kunena div.kfrontstats td.kcol-first { width: 1%; } #Kunena div.kgenstats th { text-align: left !important; } #Kunena div.kedituser td.kcol-first, #Kunena div.keditavatar td.kcol-first, #Kunena div.keditprofile td.kcol-first, #Kunena div.keditsettings td.kcol-first { width: 120px; } #Kunena div.klogin div.kbody, #Kunena div.kinfomessage div.kbody { padding: 15px; text-align: center; } /* WHO IS ONLINE ------------------------------------------------------------------- */ #Kunena .kwhoicon { background: url("../../default/images/icons/who_is_online.png") no-repeat center top; width: 32px; height: 32px; } #Kunena khidden-ktitle {} #Kunena kwho-total {} #Kunena .kwholegend { border-top: 1px dotted; width: 100%; margin-top: 5px; padding-top: 5px; } #Kunena .kwhoonline { border-bottom: 1px dotted; width: 100%; padding-bottom: 5px; } #Kunena #kwhoispage td.td-3 { text-align:left; } /* MODERATOR PAGE -------------------------------------------------------------------- */ #Kunena div#kmod-container { /*border: 1px solid;*/ margin: 0; padding: 10px 10px 30px 10px; overflow:hidden; height: 1%; clear:left; } #Kunena div#kmod-container div { padding: 5px 0; } #Kunena div#kmod-leftcol { width: 47%; float:left; clear:left; } #Kunena div#kmod-rightcol { width: 47%; float:right; } #Kunena div.kmoderate-message { border:1px solid; padding:5px !important; margin:5px 0; display:inline-block; width:98%; } #Kunena div.kmoderate-message h4 { margin:0; padding:0; } #Kunena div.kmoderate-message div.kmessage-avatar { float:left; padding:5px 5px 0 0; } #Kunena div.kmoderate-message div.kmessage-msgtext { margin-left: 42px; } #Kunena td.krowmoderation input.kbutton { margin: 0 0 0 5px;; } #Kunena table#kaddban td.kcol-first { width: 35%; } #Kunena table#kaddban td.kcol-mid textarea { width: 100%; height: 50px; } #Kunena table#kaddban td.kcol-mid input { width: 100%; } #Kunena table#kforumsearch th { padding: 0px; } #Kunena td.krowmoderation { text-align: right; } #Kunena div.banhistory th.kid { width:2%; } #Kunena div.banhistory th.kbanfrom { width:14%; } #Kunena div.banhistory th.kbanstart, #Kunena div.banhistory th.kbanexpire, #Kunena div.banhistory th.kbancreate { width:20%; } #Kunena div.banhistory th.kbanmodify { width:24%; } /* PROFILE -------------------------------------------------------------------- */ #Kunena .kicon-profile { background-repeat: no-repeat; width: 16px; height: 16px; display: inline-block; vertical-align: text-top; margin-right: 3px; background-image: url("../../default/media/iconsets/profile/default/default.png"); } #Kunena span.kicon-profile-website, #Kunena span.kicon-profile-pm { vertical-align: top; margin-top: 3px; } #Kunena .kicon-profile-aim { background-position: 0 0; } #Kunena .kicon-profile-bebo { background-position: 0 -21px; } #Kunena .kicon-profile-birthdate { background-position: 0 -42px; } #Kunena .kicon-profile-blogspot { background-position: 0 -63px; } #Kunena .kicon-profile-delicious { background-position: 0 -84px; } #Kunena .kicon-profile-digg { background-position: 0 -105px; } #Kunena .kicon-profile-email { background-position: 0 -126px; } #Kunena .kicon-profile-facebook { background-position: 0 -147px; } #Kunena .kicon-profile-gender-female { background-position: 0 -168px; } #Kunena .kicon-profile-flickr { background-position: 0 -189px; } #Kunena .kicon-profile-friendfeed { background-position: 0 -210px; } #Kunena .kicon-profile-gender-unknown { background-position: 0 -231px; } #Kunena .kicon-profile-gtalk { background-position: 0 -252px; } #Kunena .kicon-profile-icq { background-position: 0 -273px; } #Kunena .kicon-profile-karmaminus { background-position: 0 -294px; } #Kunena .kicon-profile-karmaplus { background-position: 0 -313px; } #Kunena .kicon-profile-linkedin { background-position: 0 -332px; } #Kunena .kicon-profile-location { background-position: 0 -353px; } #Kunena .kicon-profile-gender-male { background-position: 0 -374px; } #Kunena .kicon-profile-msn { background-position: 0 -395px; } #Kunena .kicon-profile-myspace { background-position: 0 -416px; } #Kunena .kicon-profile-pm { background-position: 0 -437px; } #Kunena .kicon-profile-remind { background-position: 0 -458px; } #Kunena .kicon-profile-skype { background-position: 0 -479px; } #Kunena .kicon-profile-twitter { background-position: 0 -500px; } #Kunena .kicon-profile-website { background-position: 0 -521px; } #Kunena .kicon-profile-yim { background-position: 0 -542px; } #Kunena .kicon-profile-aim-off { background-position: 0 -563px; } #Kunena .kicon-profile-bebo-off { background-position: 0 -584px; } #Kunena .kicon-profile-birthday-off { background-position: 0 -605px; } #Kunena .kicon-profile-blogspot-off { background-position: 0 -626px; } #Kunena .kicon-profile-delicious-off { background-position: 0 -647px; } #Kunena .kicon-profile-digg-off { background-position: 0 -668px; } #Kunena .kicon-profile-facebook-off { background-position: 0 -689px; } #Kunena .kicon-profile-flickr-off { background-position: 0 -710px; } #Kunena .kicon-profile-friendfeed-off { background-position: 0 -731px; } #Kunena .kicon-profile-gender-off { background-position: 0 -752px; } #Kunena .kicon-profile-gtalk-off { background-position: 0 -773px; } #Kunena .kicon-profile-icq-off { background-position: 0 -794px; } #Kunena .kicon-profile-linkedin-off { background-position: 0 -815px; } #Kunena .kicon-profile-msn-off { background-position: 0 -836px; } #Kunena .kicon-profile-myspace-off { background-position: 0 -857px; } #Kunena .kicon-profile-pm-off { background-position: 0 -878px; } #Kunena .kicon-profile-remind-off { background-position: 0 -899px; } #Kunena .kicon-profile-skype-off { background-position: 0 -920px; } #Kunena .kicon-profile-twitter-off { background-position: 0 -941px; } #Kunena .kicon-profile-website-off { background-position: 0 -962px; } #Kunena .kicon-profile-yim-off { background-position: 0 -983px; } #Kunena div#kprofile-leftcol { width: 200px; font-size: 1em; float:left; /*margin-right: 10px;*/} #Kunena div.kavatar-lg { width: 200px; height: 200px; border: 1px solid; display: table-cell; vertical-align:middle; text-align:center; } #Kunena div.kavatar-lg img { } #Kunena div#kprofile-stats { margin-top: 15px;} #Kunena div#kprofile-stats ul { margin: 0 0 0 3px; padding: 0;} #Kunena div#kprofile-stats ul li { list-style-type: none; padding-top: 5px; clear:both; font-size:.917em ;} #Kunena div#kprofile-stats ul li span.konline-status-yes { display:block; background: url("../../default/images/icons/online.gif") no-repeat; height: 16px; width: 70px; } #Kunena div#kprofile-stats ul li span.konline-status-no { display:block; background: url("../../default/images/icons/offline.gif") no-repeat; height: 16px; width: 70px; } div#kprofile-stats ul li span.krankname { display:block; margin-right: 5px; font-weight:bold; float:left; } div#kprofile-stats ul li span.krank-admin { display:block; background: url("../../default/images/ranks/rankadmin.gif") no-repeat; height: 16px; width: 70px; margin-right: 5px; float:right; margin-top: 0; } #Kunena div#kprofile-rightcol { /*display:inline-block; float:left; margin-left:10px; width:75%;*/ } #Kunena table#kprofile td.kcol-left { padding: 10px 10px 30px; vertical-align: top; } #Kunena table#kprofile td.kcol-right { border-left: 0; padding: 10px 10px 30px; vertical-align: top; } #Kunena div#kprofile-rightcoltop {width: 100%;} #Kunena div.kprofile-rightcol1 { width: 45%; } #Kunena div.kprofile-rightcol1 ul {margin: 0;padding: 0;} #Kunena div.kprofile-rightcol1 ul li, #Kunena div.kprofile-rightcol2 ul li { list-style-type: none !important; background: 0 none; padding-bottom: 8px; padding-left: 0; } #Kunena div#kprofile-stats ul li { list-style-type: none !important; background: 0 none; padding-left: 0; } #Kunena li.bd a { margin-left: 10px; } #Kunena div.kiconrow { width: 121px; padding-right: 10px; padding-bottom: 5px; float:left; } #Kunena div.kiconrow span, #Kunena div.kiconprofile span { background-repeat: no-repeat; display:block; float:left; margin: 0 5px 5px 0; border: 0 none; } #Kunena div.kiconprofile span.birthday { background-image: none; border: 0 none; } #Kunena div.clrline { clear:both; border-top: 1px solid; margin: 15px 0 20px 0; line-height: 10px; } #Kunena div#kprofile-rightcolbot { } #Kunena div.kprofile-rightcol1 h4 { margin:10px 0 0 0; padding: 0; font-size: 1em; font-weight:bold;} #Kunena div.kprofile-rightcol1 p { margin:0; padding: 0;} #Kunena div.kprofile-rightcol2 { float:right; width: 45%; margin-left: 10px;} #Kunena div.kprofile-rightcol2 ul {margin: 0;padding: 0;} #Kunena div.kprofile-rightcol2 ul li {list-style-type: none !important; padding-bottom: 8px;} #Kunena div.kprofile-rightcol2 ul li span.email { float:left; display:block; background: url("../../default/images/icons/email.png") no-repeat; height: 16px; width: 16px; margin-right: 5px; } #Kunena div.kprofile-rightcol2 ul li span.website { float:left; margin-right: 5px; } #Kunena dd.kprofile-modtools h4 { margin-bottom: 5px; margin-left: 5px; } #Kunena dd.kprofile-modtools ul li span { margin-right: 15px; } #Kunena dd.kprofile-modtools ul li { padding-bottom: 5px; } #Kunena li.usertype { font-weight:bold; } #Kunena li.kprofile-rank { } #Kunena li.kprofile-rank img { } /* Tabs ----------------------------------*/ #Kunena #kprofile-tabs { width: 100%; margin-top: 0px; } #Kunena dl.tabs { float: left; margin: 10px 0 -1px 0; z-index: 50; } #Kunena dl.tabs dt { float: left; padding: 4px 10px; border-left: 1px solid; border-right: 1px solid; border-top: 1px solid; margin-left: 3px; } #Kunena dl.tabs dt.open { border-bottom: 1px solid; z-index: 100; } #Kunena div.current { clear: both; border: 1px solid; padding: 10px 10px; overflow: hidden; } #Kunena div.current dd { padding: 0; margin: 0; } #Kunena dt.kprofile-modbtn { } #Kunena dd.kprofile-modtools ul { margin:0; padding:0; margin-left: 5px; } #Kunena dd.kprofile-modtools ul li { list-style-type:none; } #Kunena dd.kprofile-modtools .kcheckbox { float:left; clear:left; } #Kunena dd.kprofile-modtools label { float:left; clear:right; margin: 3px 10px 10px 5px; } #Kunena input.kbutton { margin: 10px 0 0 5px; } #Kunena form#jumpto { margin: 5px; } #Kunena form#jumpto input.kbutton { margin: 0px;} #Kunena table.klist-top td.klist-markallcatsread input.kbutton { vertical-align:middle; margin: 5px;} /* SLIDERS ----------------------------------------------------------------------------------------------- */ #Kunena span#kprofilebox-status { font-weight:bold; display:block; height: 14px; width: 15px; } #Kunena #kprofilebox-toggle { display:block; height: 15px; width: 15px; margin-right: 1px; margin-top: -14px; border: 1px solid; } #Kunena a.close { display:block; background: url("../../default/images/shrink.gif") no-repeat; height: 15px; width: 15px; } #Kunena a.open { display:block; background: url("../../default/images/expand.gif") no-repeat; height: 15px; width: 15px; } /* FOOTER ----------------------------------------------------------------------------------------------- */ #Kunena .kcredits { text-align: center; } #Kunena .kfooter { text-align: center; } #Kunena img.rsslink { float:right; margin-top: 10px; margin-right: 3px; } /* Mootools Autocompleter CSS classes ----------------------------------------------------------------------------------------------- */ /* DO NOT ADD #Kunena into these rules! */ ul.autocompleter-choices { position: absolute; margin: 0; padding: 0; list-style: none; border: 1px solid; text-align: left; z-index: 50; } ul.autocompleter-choices li { position: relative; margin: -2px 0 0 0; padding: 0.2em 1.5em 0.2em 1em; display: block; float: none !important; cursor: pointer; font-weight: normal; white-space: nowrap; font-size: 1em; line-height: 1.5em; } ul.autocompleter-choices li.kautocompleter-selected { } ul.autocompleter-choices span.kautocompleter-queried { display: inline; float: none; font-weight: bold; margin: 0; padding: 0; } ul.autocompleter-choices li.kautocompleter-selected span.kautocompleter-queried { } /* for form-validation ------------------------------------------------------ */ #Kunena #kpost-message .invalid { border: 1px solid !important; } /* SHOW ICONS ----------------------------------------------------------------------------------------------- */ #Kunena span.kicon { background: none; border: 0; margin: 0; padding: 0; display: inline-block; } #Kunena span.ktopicattach { background: url("../../default/images/icons/attachment.png") no-repeat left center; margin: 2px; width: 32px; height: 32px; float:right; } #Kunena span.kfavoritestar { background: url("../../default/images/icons/favoritestar.png") no-repeat left center; width: 16px; height: 16px; } #Kunena span.kfavoritestar-grey { background: url("../../default/images/icons/favoritestar-grey.png") no-repeat left center; width: 16px; height: 16px; } #Kunena span.ktopiclocked, #Kunena span.kforumlocked { background: url("../../default/images/icons/lock_sm.png") no-repeat left center; width: 16px; height: 16px; } #Kunena span.ktopicsticky { background: url("../../default/images/icons/tsticky.png") no-repeat left center; width: 27px; height: 44px; float:right; margin-right: -5px; } #Kunena span.kforumbottom { background: url("../../default/images/icons/bottom_arrow.gif") no-repeat left center; width: 18px; height: 15px; } #Kunena span.kforumtop { background: url("../../default/images/icons/top_arrow.gif") no-repeat left center; width: 18px; height: 15px; } #Kunena span.krss { background: url("../../default/images/icons/rss.png") no-repeat left center; width: 24px; height: 24px; margin: 5px 5px 0 -29px; } #Kunena span.kpdf { background: url("../../default/images/icons/pdf.png") no-repeat left center; width: 24px; height: 24px; margin: 5px 33px 0 -29px; } #Kunena div.krss-block { float: right; } #Kunena span.kforummoderated { background: url("../../default/images/icons/tmoder.gif") no-repeat left center; width: 16px; height: 16px; } #Kunena span.kreadforum, #Kunena span.knotloginforum { background: url("../../default/images/icons/folder_nonew.png") no-repeat left center; width: 32px; height: 32px; } #Kunena span.kunreadforum { background: url("../../default/images/icons/folder.png") no-repeat left center; width: 32px; height: 32px; } #Kunena span.kreadforum-sm, #Kunena span.knotloginforum-sm { background: url("../../default/images/icons/folder_nonew_sm.png") no-repeat left center; width: 12px; height: 12px; margin-right: 3px; vertical-align: middle; } #Kunena span.kunreadforum-sm { background: url("../../default/images/icons/folder_sm.png") no-repeat left center; width: 12px; height: 12px; margin-right: 3px; vertical-align: middle; } .kgooglemap { width: 100%; display:block; height:480px; overflow:hidden; position:relative; } .kgooglemap img { max-width:none !important; } /* Fix for Atomic Template */ #ktab .joomla-nav { background-color: transparent; border: 0 none; } /* Threaded view ----------------------------------------------------------------------------------------------- */ #Kunena .ktree { width: 15px; height: 27px; margin: -9px 0; display: inline-block; background: url("../../default/images/treenodes.png") no-repeat left center; } #Kunena .ktree-crossedge { background-position: -45px 0; } #Kunena .ktree-lastedge { background-position: -75px 0; } #Kunena .ktree-root { background-position: -15px 0; } #Kunena .ktree-single { background-position: 0 0; } #Kunena .ktree-leaf { background-position: -90px 0; } #Kunena .ktree-node { background-position: -60px 0; } #Kunena .ktree-edge { background-position: -30px 0; } #Kunena .ktree-gap { background-position: -105px 0; } #Kunena .ktree-empty { background: none; } /*** kunena.default.css ***/ @charset "utf-8"; /** * @version $Id$ * Kunena Component * @package Kunena * * @Copyright (C) 2008 - 2011 Kunena Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org * * Based on FireBoard Component * @Copyright (C) 2006 - 2007 Best Of Joomla All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.bestofjoomla.com * **/ /* ------------------------- COLOR PALETTE FOR BLUE EAGLE Dark blue color: #5388B4 RGB: 83/136/180 Medium blue color: #609FBF RGB: 96/159/191 Light grey color: #F2F1EE RGB: 242/241/238 Medium grey color: #999999 RGB: 153/153/153 Dark grey color: #737373 RGB: 115/115/115 Border grey color: #BFC3C6 RGB: 191/195/198 Yellow highlight: #FFFFCC RGB: 255/255/204 Grey text color: #999999 RGB: 153/153/153 Red hover color: #FF0000 RGB: 255/0/0 Forum highlight/dark colors Green forum highlight: #d2f8db RGB: 210/248/219 Green forum dark: #bfe5c7 RGB: 191/229/199 Orange forum highlight: #ffeb8c RGB: 255/235/140 Orange forum dark: #ffd475 RGB: 255/212/117 Blue forum highlight: #c3f0ff RGB: 195/240/255 Blue forum dark: #b1e3ff RGB: 177/227/255 Grey forum highlight: #e5e5e5 RGB: 229/229/229 Grey forum dark: #d5d5d5 RGB: 213/213/213 Pink forum highlight: #ffddff RGB: 255/221/255 Pink forum dark: #ffd0ff RGB: 255/208/255 ----------------------------------------------------------*/ /* ----------------------------------------------------------------------------------------------- */ /* MAIN STYLES ----------------------------------------------------------------------------------------------- */ #Kunena td, #Kunena table, #Kunena th, #Kunena div, #Kunena p, #Kunena span { font-family: Arial, Helvetica, sans-serif; } #Kunena ul li { background: none; } #Kunena .divider {color:#999999;} #Kunena a:link, #Kunena a:visited, #Kunena a:active, #Kunena a:focus { color: #5388B4 !important; background-color:transparent !important;} #Kunena a:hover { color: #FF0000 !important; background-color:transparent !important; } #Kunena .knewchar { color: #009900; font-family: Arial, Helvetica, sans-serif; } /* Block styling ----------------------------------------------------------------------------------------------- */ #Kunena div.kblock { border-bottom-color:#BFC3C6; background-color: #FFFFFF; } #Kunena .kblock div.kheader { border-bottom-color:#D9D9D9; color: #FFFFFF; } #Kunena .kheader h2, #Kunena .kheader h2 a { color: #fff !important; } #Kunena div.kblock div.ktitle { background-color: #5388B4; color: #FFFFFF; } #Kunena div.kblock div.ktitle h1, #Kunena div.kblock div.ktitle h2 { color: #FFFFFF; } #Kunena div.kblock div.kbody { border-color:#BFC3C6; } #Kunena div.kblock div.khelprulescontent, #Kunena div.kblock div.kfheadercontent { background-color: #FFFFFF; color: #000000; } #Kunena div.kblock div.khelprulesjump { border-color: #BFC3C6; background-color: #FFFFFF; color: #000000; } #Kunena div.kblock div.kactions { background-color: #737373; color:#FFFFFF ; } #Kunena div.kblock div.kactions a { color:#FFFFFF !important; } #Kunena tr.krow1 td { background-color: #F2F1EE; } #Kunena tr.krow2 td { background-color: #FFFFFF; } #Kunena tr.ksth { background-color: #737373; color: #fff; font-family: Arial, Helvetica, sans-serif; } #Kunena td.kcol-ktopicreplies { color: #999999; } #Kunena td.kcol-ktopicreplies strong { color: #999999; } #Kunena span.kcat-topics, #Kunena span.kcat-replies { color:#999999; } #Kunena span.kcat-topics-number, #Kunena span.kcat-replies-number { color: #999999; } #Kunena .klatest-avatar, #Kunena .ktopic-latest-post-avatar { border-color: #BFC3C6; } #Kunena .kfooter-time { color: #999999; } #Kunena .kalert { color: #FF0000; } #Kunena td.kcol-first { border-bottom-color: #BFC3C6; } #Kunena td.kcol-mid { border-left-color: #BFC3C6; border-bottom-color: #BFC3C6; } #Kunena td.kcol-last { border-left-color: #BFC3C6; border-bottom-color: #BFC3C6; } #Kunena td.ktopicmodule { border-bottom-color: #BFC3C6; } /* COLOR ADMINISTRATOR AND MODERATOR ----------------------------------------------------------------------------------------------- */ #Kunena .kwho-admin, #Kunena a.kwho-admin { color: #FF0000 !important; } #Kunena .kwho-globalmoderator, #Kunena a.kwho-globalmoderator { color: #800000 !important; } #Kunena .kwho-moderator, #Kunena a.kwho-moderator { color: #0000FF !important; } #Kunena .kwho-user, #Kunena a.kwho-user { color: #5388B4 !important; } #Kunena .kwho-guest, #Kunena a.kwho-guest { color: #666666 !important; } #Kunena .kwho-banned , #Kunena a.kwho-banned { color: #A39D49 !important; } #Kunena .kwho-blocked, #Kunena a.kwho-blocked { color: #ff0000 !important; } /* MENU ----------------------------------------------------------------------------------------------- */ #Kunena #ktop { background-color: transparent; color: #000000; } #ktab div.moduletable ul.menu, #ktab div.moduletable ul.menu li a, #ktab div.moduletable ul.menu li a span { background-image:none!important; } #Kunena #ktab a { background-color: #737373; } #Kunena #ktab a span { font-family: Arial, Helvetica, sans-serif; color: #FFFFFF; } #Kunena #ktab a:hover span, #Kunena #ktab li.Kunena-item-active a span { color: #FFFFFF; } #Kunena select, #Kunena select:focus, #Kunena select:hover { border-color: #999999; color: #000000; } /* Using a Joomla menu module */ #Kunena option { background-color: #FFFFFF; color: #000000; } #Kunena .button, #Kunena .kbutton { background-color: #F2F1EE; border-color: #999999; color: #000000; } #Kunena .kbutton-back { color: #000000; } #Kunena input.kinput { border-color: #999999; } #Kunena .kbutton:hover, #Kunena .kbutton:focus { background-color: #609FBF; border-color: #5388B4; color: #FFFFFF; } #Kunena .klist-actions { background-color: #FFFFFF; color: #000000; border-color: #BFC3C6; } #Kunena .klist-actions-bottom { background-color: #FFFFFF; color: #000000; border-color: #BFC3C6; } #Kunena .klist-actions-info a { color: #009933; } #Kunena .klist-pages { border-left-color: #BFC3C6; color: #666666; font-family: Arial, Helvetica, sans-serif; } #Kunena .klist-times { border-left-color: #BFC3C6; color: #666666; } #Kunena .klist-actions-info-all { color: #999999; } #Kunena .klist-actions-forum { border-left-color: #BFC3C6; } #Kunena .klist-pages-all { border-left-color: #BFC3C6; color: #666666; font-family: Arial, Helvetica, sans-serif; } #Kunena .klist-times-all { border-left-color: #BFC3C6; color: #666666; } #Kunena .klist-jump-all { border-left-color: #BFC3C6; color: #666666; } #Kunena .klist-top { background-color: #FFFFFF; border-color: #BFC3C6; } #Kunena .klist-bottom { background-color:#FFFFFF; border-color:#BFC3C6; } #Kunena .klist-markallcatsread { border-color: #BFC3C6; background-color: #FFFFFF; } #Kunena .klist-categories { border-left-color: #BFC3C6; color: #666666; } /*---------- Pagination ------------- */ #Kunena .kpagination a { border-color:#5388B4; background-color: #ffffff !important; } #Kunena .kpagination .active { border-color:#5388B4; background-color:#5388B4; color:#FFFFFF; } #Kunena .kpagination a:link, #Kunena .kpagination a:visited { color:#5388B4; } #Kunena .kpagination a:hover{ border-color:#5388B4; color: #ffffff; background-color: #609FBF; } #Kunena div.ktopic-title-cover ul.kpagination li.page { color:#999; } #Kunena div.ktopic-title-cover ul.kpagination a { border-color:#bcbcbc; background-color: #ffffff; } #Kunena div.ktopic-title-cover ul.kpagination a:hover{ border-color:#5388B4; color: #ffffff; background-color: #609FBF; } #Kunena span.ktopic-views { color:#999999; } #Kunena span.ktopic-views-number { color: #999999; } /* HEADER ----------------------------------------------------------------------------------------------- */ #Kunena td.kprofileboxcnt ul.kprofilebox-welcome li input.kbutton { background-color: #fff; } #Kunena td.kprofileboxcnt ul.kprofilebox-welcome li input.kbutton:hover { background-color: #609FBF; } #Kunena div#kforum-head { border-left-color: #BFC3C6; border-right-color: #BFC3C6; border-bottom-color: #BFC3C6; } #Kunena div#kmoderatorslist div.kbody { border-color:#CCCCCC; background-color: #FFFFFF; } /* SEARCH ----------------------------------------------------------------------------------------------- */ #Kunena fieldset { background-color: #fff; border-color:#CCCCCC; } #Kunena div#ksearchresult div.kresult-title { border-bottom-color: #DDDDDD; } #Kunena div#ksearchresult div.resultcat { border-top-color: #BFC3C6; } /* PROFILEBOX AND LOGINBOX ----------------------------------------------------------------------------------------------- */ #Kunena .kprofilebox-left { border-right-color: #BFC3C6; background-color: #EEEEEE; } #Kunena .kprofilebox-right { border-left-color: #BFC3C6; } #Kunena div.kpbox { border-bottom-color: #BFC3C6; } /* CATEGORY LIST ----------------------------------------------------------------------------------------------- */ #Kunena table.kblocktable { border-color: #BFC3C6; } #Kunena h1, #Kunena h2 { color: #FFFFFF; } #Kunena h2 a { color: #FFFFFF !important; } #Kunena h1 a:link, #Kunena h1 a:active, #Kunena h1 a:visited { color: #FFFFFF; } #Kunena h2 span.kheadbtn a { border-color: #FFF; background-color: #609FBF; } #Kunena h2 span.kheadbtn:hover a { border-color: #FFF; } #Kunena .ktitle, #Kunena a.ktitle { color: #FFFFFF; } #Kunena .ktitle a { font-family: Arial, Helvetica, sans-serif; color: #FFFFFF; } #Kunena div.kthead-title a { font-family: Lucida Grande, Lucida, Arial, Helvetica, sans-serif; } #Kunena div.kthead-moderators { color: #666; } #Kunena div.kthead-child { border-top-color: #DDD5BF; } #Kunena table.kcc-table tr td { border-color: #FFFFFF; } #Kunena div.kcc-childcat-title { color: #666666; } #Kunena span.kchildcount { color: #999999; } /* SHOW CATEGORY ----------------------------------------------------------------------------------------------- */ #Kunena img.catavatar { border-color: #BFC3C6; } #Kunena .kcontenttablespacer { border-bottom-color: #BFC3C6; } #Kunena .krow1-stickymsg { background-color: #FFFFCC; } #Kunena .krow2-stickymsg { background-color: #FFFFCC; } /* VIEW PAGE -------------------------------------------------------------------- */ #Kunena div.kmsg-header { border-bottom-color:#D9D9D9; background-color: #5388B4; color: #FFFFFF; } #Kunena div.kmsg-header h2 { background-color: #737373; } #Kunena .kpost-profile span.kavatar img, #Kunena .kprofilebox .kavatar { border-color: #BFC3C6; } #Kunena span.kmsgdate { font-family: Arial, Helvetica, sans-serif; color: #FFFFFF; } #Kunena div.kmsgattach { background-color:#F8F7EF; border-color:#BFC3C6; } #Kunena div.kmsgtext pre, #Kunena div.kmsgtext code { border-left-color: #F4A94F; border-right-color: #BFC3C6; border-top-color: #BFC3C6; border-bottom-color: #BFC3C6; font-family: "Courier News", Courier, monospace; } #Kunena table.kmsg th a { color: #FFFFFF; } #Kunena div.kmessage-editmarkup-cover { border-bottom-color: #BFC3C6; } #Kunena span.kmessage-editmarkup { background-color: #F2F1EE no-repeat left center; border-left-color: #BFC3C6; border-right-color: #BFC3C6; border-top-color: #BFC3C6; color: #666666; } #Kunena span.kmessage-informmarkup { background-color: #F2F1EE; border-left-color: #BFC3C6; border-right-color: #BFC3C6; border-top-color: #BFC3C6; color: #666666; } #Kunena div.kmsgsignature { border-top-color:#BFC3C6; color:#999999; } #Kunena div.kmessage-thankyou{ border-top-color: #BFC3C6; } #Kunena .kreply-form { border-color: #BFC3C6; } #Kunena .kreply-form .inputbox { border-color: #999999; background-color: #FFFFFF; color: #000000; } #Kunena div.kmsgtext-article, #Kunena div.kmsgtext-quote, #Kunena div.kmsgtext-hide, #Kunena div.kmsgtext-confidential { border-color: #BFC3C6; font-family: Arial, Helvetica, sans-serif; background-color: #F2F1EE; } #Kunena div.kmsgtext-article { background-color: #FFFFFF; } #Kunena div.kmsgtext-hide { background-color: #FFFFCC; } #Kunena div.kmsgtext-confidential { background-color: #FAE0F8; } #Kunena div.khide { background-color: #F2F1EE; border-color: #F2CAB7; } #Kunena .kmsgtitle { color: #fff ; } #Kunena div.kmsg-header-top span.kmsg-id-top a, #Kunena div.kmsg-header-bottom span.kmsg-id-bottom a, #Kunena div.kmsg-header-left span.kmsg-id-left a, #Kunena div.kmsg-header-right span.kmsg-id-right a { color: #fff !important; } /* AVATAR POSITION ----------------------------------------------------------------------- */ /* right ----------------------------------------*/ #Kunena td.kprofile-right { background-color: #EFF0F4; border-bottom-color: #BFC3C6; border-left-color: #DDDDDD; } #Kunena td.kbuttonbar-right { border-bottom-color: #BFC3C6; } /* left ----------------------------------------*/ #Kunena td.kprofile-left { background-color: #EFF0F4; border-bottom-color: #BFC3C6; border-right-color: #DDDDDD; } #Kunena td.kbuttonbar-left { border-bottom-color: #BFC3C6; } #Kunena .kunapproved td { background-color: #DDDDDD !important; } #Kunena .kdeleted td { background-color: #CCCCCC !important; } /* User info on posts ----------------------------------------*/ #Kunena td.kprofile-top { background-color: #EFF0F4; border-bottom-color: #DDDDDD; } #Kunena td.kbuttonbar-top { border-bottom-color: #BFC3C6; } /* bottom ----------------------------------------*/ #Kunena td.kprofile-bottom { background-color: #EFF0F4; border-bottom-color: #BFC3C6; border-top-color: #DDDDDD; } /* POST PAGE -------------------------------------------------------------------- */ #Kunena #kpost-message .postinput { background-color: #FFFFFF; color: #000000; border-color: #BFC3C6; } #Kunena #kpost-message .postinput:hover, #Kunena #kpost-message .postinput:focus { background-color: #FFFFFF; color: #000000; border-color: #BFC3C6; } #Kunena #kpostmessage tr.krow2 td.kcol-ktopicicons td { background-color: #FFFFFF; color: #000000; border-color: #BFC3C6; } #Kunena #kpostmessage tr.krow1 .kpostbuttonset td.kposthint { background-color: #FFFFCC; border-color: #DDD5BF; } #Kunena table#kpostmessage .kposthint .kinputbox { background-color: #FFFFCC; border-color: #FFFFCC; } #Kunena .kpostbuttonset { border-color: #BFC3C6 } #Kunena tr.krow1 .kpostbuttons { border-color: #BFC3C6; } #Kunena table#kpostmessage .ktxtarea { border-color: #BFC3C6; } #Kunena div#khistory tr.ksth a { color: #ffffff; } /* ---- Post Previews ---- */ #Kunena #kbbcode-preview { border-color: #BFC3C6; background-color: #F2F1EE; } #Kunena #kpostmessage tr.krow1 .kpostbuttonset td, #Kunena #kpostmessage tr.krow2 .kpostbuttonset td { border-bottom-color: #BFC3C6; } #Kunena #kpost-result div { border-color: #999; } #Kunena div#kcolor-palette, #Kunena div#link, #Kunena div#image, #Kunena div#video { border-bottom-color: #BFC3C6; } /* FORUM ICON BUTTONS ----------------------------------------------------------------------------------------------- */ #Kunena .kicon-button { color: #FFF; } #Kunena .kicon-button span span { color: #ffffff; } #Kunena form.kform-report input, #Kunena form.kform-report textarea { border-color:#BFC3C6; } /* BBCODE BUTTONS -------------------------------------------------------------------- */ #Kunena img.kbbcode:hover { background-color: #e4e4e4; } #Kunena div#kbbcode-size-options span:hover { background-color: #e4e4e4; } #Kunena #kbbcode-toolbar li a:hover { background-color: #e4e4e4; } #Kunena ul#kbbcode-toolbar li a#kbbcode-separator1, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator2, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator3, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator4, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator5, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator6, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator7, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator8 { background-color: #eeeeee; } #Kunena .kattachment .kbutton { color: #000000; } /* Multi file upload for bbcode editor -------------------------------------------------------------------- */ #Kunena .kfile-input-button, #Kunena .kfile-input-button:hover, #Kunena .kfile-input-button:focus { background-color: #F2F1EE; border-color: #999999; color: #000000; } #Kunena .kfile-input-button:hover, #Kunena .kfile-input-button:focus { background-color: #609FBF; border-color: #5388B4; color: #FFFFFF; } #Kunena .kattachment-remove, #Kunena .kattachment-insert { background-color: #F2F1EE; border-color: #999999; color: #000000; } #Kunena .kattachment-remove:hover, #Kunena .kattachment-insert:hover { color: #FFFFFF; } #Kunena #kbbcode-filelist .file-invalid { color: #514721; } #Kunena #kbbcode-filelist .file-invalid span { background-color: #fff6bf; } #Kunena #kbbcode-filelist .file .file-size { color: #666; } #Kunena #kbbcode-filelist .file .file-error { color: #8a1f11; } /* POLLS -------------------------------------------------------------------- */ #kpoll-text-help { background-color: #ff8f4f; } #kpoll-form-vote fieldset { background-color:#FFFFFF; } /* PATHWAY ----------------------------------------------------------------------------------------------- */ #Kunena .kforum-pathway { border-left-color: #BFC3C6; border-right-color: #BFC3C6; color: #000000; background-color: #F2F1EE; } #Kunena .kforum-pathway-bottom { border-color: #BFC3C6; color: #000000; background-color: #F2F1EE; } /* FORUM HEADER DESCRIPTION -------------------------------------------------------------------- */ #Kunena .kforum-headerdesc { border-color: #BFC3C6; color: #000000; background-color: #FFF; } /* HELP, RULES, UPLOAD AVATAR, ANNOUNCEMENT -------------------------------------------------------------------- */ #Kunena td.kuadesc, #Kunena td.kcreditsdesc { /*border-color: #BFC3C6;*/ background-color: #FFFFFF; color: #000000; } #Kunena .kcredits-intro { border-color: #BFC3C6; } #Kunena .kcredits-more { background-color: #F2F1EE; border-color: #BFC3C6; } #Kunena .kcredits-language { border-color: #BFC3C6; } #Kunena tr.userlist th a { color: #FFFFFF; } /* WHO IS ONLINE ------------------------------------------------------------------- */ #Kunena .kwholegend { border-top-color: #CCCCCC; } #Kunena .kwhoonline { border-bottom-color: #CCCCCC; } /* MODERATOR PAGE -------------------------------------------------------------------- */ #Kunena div#kmod-container { /*border-color: #BFC3C6;*/ } #Kunena div.kmoderate-message { border-color:#CCCCCC; } } /* PROFILE -------------------------------------------------------------------- */ #Kunena div.kavatar-lg { background-color: #FFF; border-color: #999999; } #Kunena div#kprofile-stats ul li span.konline-status-yes { color: #fff; } #Kunena div#kprofile-stats ul li span.konline-status-no { color:#fff; } #Kunena div.clrline { border-top-color: #BFC3C6; } #Kunena div.kprofile-rightcol1 h4 { color: #333333;} /* Tabs ----------------------------------*/ #Kunena dl.tabs dt { border-left-color: #BFC3C6; border-right-color: #BFC3C6; border-top-color: #BFC3C6; background-color: #f0f0f0; color: #666; } #Kunena dl.tabs dt.open { background-color: #F9F9F9; border-bottom-color: #F9F9F9; color: #000; } #Kunena div.current { border-color: #BFC3C6; } #Kunena dt.kprofile-modbtn { background-color:#999999 !important; color: #FFF !important; } /* SLIDERS ----------------------------------------------------------------------------------------------- */ #Kunena span#kprofilebox-status { color: #fff; background-color: #5388B4; } #Kunena #kprofilebox-toggle { border-color: #fff; } /* Mootools Autocompleter CSS classes ----------------------------------------------------------------------------------------------- */ /* DO NOT ADD #Kunena into these rules! */ ul.autocompleter-choices { border-color: #7c7c7c; border-left-color: #c3c3c3; border-right-color: #c3c3c3; border-bottom-color: #ddd; background-color: #fff; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; background-color: #fff; } ul.autocompleter-choices li.kautocompleter-selected { background-color: #444; color: #fff; } ul.autocompleter-choices li.kautocompleter-selected span.kautocompleter-queried { color: #9FCFFF; } /* CSS suffix support for category specific styling (Leave this section at the bottom) ----------------------------------------------------------------------------------------------- */ /* -red category suffix ------------------------------------------------------ */ #Kunena .kforum-headerdesc-red { color: #000000; background-color: #FFDDDD; } #Kunena tr.krow1-red td { background-color: #FFDDDD; } #Kunena tr.krow2-red td { background-color: #FFCFCF; } /* -green category suffix ----------------------------------------------------- */ #Kunena .kforum-headerdesc-green { background-color: #d2f8db; } #Kunena tr.krow1-green td { background-color: #d2f8db; } #Kunena tr.krow2-green td { background-color: #bfe5c7; } /* -yellow category suffix ------------------------------------------------------ */ #Kunena .kforum-headerdesc-yellow { color: #000000; background-color: #FFFFCC; } #Kunena tr.krow1-yellow td { background-color: #FFFFCC; } #Kunena tr.krow2-yellow td { background-color: #FFFFAA; } /* -blue category suffix ------------------------------------------------------- */ #Kunena .kforum-headerdesc-blue { color: #000000; background-color: #c3f0ff; } #Kunena tr.krow1-blue td { background-color: #c3f0ff; } #Kunena tr.krow2-blue td { background-color: #b1e3ff; } /* -grey category suffix ------------------------------------------------------ */ #Kunena .kforum-headerdesc-grey { color: #000000; background-color: #e5e5e5; } #Kunena tr.krow1-grey td { background-color: #e5e5e5; } #Kunena tr.krow2-grey td { background-color: #d5d5d5; } /* -pink category suffix ---------------------------------------------------- */ #Kunena .kforum-headerdesc-pink { color: #000000; background-color: #ffddff; } #Kunena tr.krow1-pink td { background-color: #ffddff; } #Kunena tr.krow2-pink td { background-color: #ffd0ff; } /* for form-validation ------------------------------------------------------ */ #Kunena #kpost-message .invalid { border-color: red !important; background-color: #FFDDDD !important; } /* SHOW ICONS ----------------------------------------------------------------------------------------------- */ .kgooglemap { background-color:#E5E3DF; }
crosslink/huai
components/com_kunena/template/example/css/css-ad511544f6303b617227b4948cdd904d.php
PHP
gpl-3.0
93,030
const merge = require("merge"); function fakeOne(modelName, overrides) { const model = require("../models/" + modelName); const fakeData = require("../fakers/" + modelName); instance = new model(merge.recursive(true, fakeData(), overrides)); return instance.save(); } module.exports = (modelName, count, overrides) => new Promise((resolve, reject) => { if (!overrides) { overrides = {}; } if (!count) { return resolve(fakeOne(modelName, overrides)); } const instances = []; for (let i = 0; i < count; i++) { instances[i] = fakeOne(modelName, overrides); } Promise.all(instances) .then(x => resolve(x)) .catch(e => reject(e)); });
BlackChaosNL/dragontide
lib/fake.js
JavaScript
gpl-3.0
660
var searchData= [ ['flash_2ec',['flash.c',['../flash_8c.html',1,'']]], ['flash_2eh',['flash.h',['../flash_8h.html',1,'']]], ['flash_5fcommon_5ff234_2ec',['flash_common_f234.c',['../flash__common__f234_8c.html',1,'']]], ['flash_5fcommon_5ff234_2ed',['flash_common_f234.d',['../flash__common__f234_8d.html',1,'']]], ['flash_5fcommon_5ff234_2eh',['flash_common_f234.h',['../flash__common__f234_8h.html',1,'']]], ['flash_5fcommon_5ff24_2ec',['flash_common_f24.c',['../flash__common__f24_8c.html',1,'']]], ['flash_5fcommon_5ff24_2ed',['flash_common_f24.d',['../flash__common__f24_8d.html',1,'']]], ['flash_5fcommon_5ff24_2eh',['flash_common_f24.h',['../flash__common__f24_8h.html',1,'']]] ];
Aghosh993/TARS_codebase
libopencm3/doc/stm32f2/html/search/files_4.js
JavaScript
gpl-3.0
703
// Copyright 2016 Mustafa Serdar Sanli // // This file is part of HexArtisan. // // HexArtisan is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // HexArtisan is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with HexArtisan. If not, see <http://www.gnu.org/licenses/>. #include <string> #include "unicode/umachine.h" #include "unicode/uchar.h" #include "unicode/unistr.h" #include "unicode/utf.h" #include "Endianness.hpp" #include "Unicode.hpp" using namespace std; // TODO FIXME u_isgraph ignores spaces. // Checks whether the give code point belongs to one of the following char // categories: // * Me. U_ENCLOSING_MARK, // * Mn. U_NON_SPACING_MARK // * Mc. U_COMBINING_SPACING_MARK // // See runtime/tools/unicode.vim from vim repo. bool IsComposingCodePoint(char32_t code_point) { UCharCategory category = static_cast<UCharCategory>( u_getIntPropertyValue(code_point, UCHAR_GENERAL_CATEGORY)); return (category == U_ENCLOSING_MARK || category == U_NON_SPACING_MARK || category == U_COMBINING_SPACING_MARK); } bool IsControlCodePoint(char32_t code_point) { UCharCategory category = static_cast<UCharCategory>( u_getIntPropertyValue(code_point, UCHAR_GENERAL_CATEGORY)); return category == U_CONTROL_CHAR; } int GetCodePointWidth(char32_t code_point) { if (IsComposingCodePoint(code_point)) return 0; UEastAsianWidth width = static_cast<UEastAsianWidth>( u_getIntPropertyValue(code_point, UCHAR_EAST_ASIAN_WIDTH)); // TODO some of the enum values are not well defined. // Need some tests for these. if (width == U_EA_FULLWIDTH || width == U_EA_WIDE) return 2; return 1; } void AppendCodePointAsUtf8(std::string &s, char32_t code_point) { UnicodeString((UChar32)code_point).toUTF8String(s); }
mserdarsanli/HexArtisan
src/Unicode.cpp
C++
gpl-3.0
2,209
// // // LiveFlight Connect // // UsbNotification.cs // Source: http://stackoverflow.com/questions/16245706/check-for-device-change-add-remove-events // // Licensed under GPL-V3. // https://github.com/LiveFlightApp/Connect-Windows/blob/master/LICENSE // using System; using System.Runtime.InteropServices; namespace LiveFlight { public static class UsbNotification { public const int DbtDevicearrival = 0x8000; // system detected a new device public const int DbtDeviceremovecomplete = 0x8004; // device is gone public const int WmDevicechange = 0x0219; // device change event private const int DbtDevtypDeviceinterface = 5; private static readonly Guid GuidDevinterfaceUSBDevice = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED"); // USB devices private static IntPtr notificationHandle; /// <summary> /// Registers a window to receive notifications when USB devices are plugged or unplugged. /// </summary> /// <param name="windowHandle">Handle to the window receiving notifications.</param> public static void RegisterUsbDeviceNotification(IntPtr windowHandle) { DevBroadcastDeviceinterface dbi = new DevBroadcastDeviceinterface { DeviceType = DbtDevtypDeviceinterface, Reserved = 0, ClassGuid = GuidDevinterfaceUSBDevice, Name = 0 }; dbi.Size = Marshal.SizeOf(dbi); IntPtr buffer = Marshal.AllocHGlobal(dbi.Size); Marshal.StructureToPtr(dbi, buffer, true); notificationHandle = RegisterDeviceNotification(windowHandle, buffer, 0); } /// <summary> /// Unregisters the window for USB device notifications /// </summary> public static void UnregisterUsbDeviceNotification() { UnregisterDeviceNotification(notificationHandle); } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr RegisterDeviceNotification(IntPtr recipient, IntPtr notificationFilter, int flags); [DllImport("user32.dll")] private static extern bool UnregisterDeviceNotification(IntPtr handle); [StructLayout(LayoutKind.Sequential)] private struct DevBroadcastDeviceinterface { internal int Size; internal int DeviceType; internal int Reserved; internal Guid ClassGuid; internal short Name; } } }
LiveFlightApp/Connect-Windows
LiveFlight-Connect/UsbNotification.cs
C#
gpl-3.0
2,599
/*This file is part of Packet Sniffer * Copyright (C) 2009,2010 Daniel Myers dan<at>moird.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /// This is the class that sets the adapter into Promisucus Listen mode. /// Promisucus mode basically is that any Internet Traffic the Program recieves /// it processes. Unfotunately probably due to windows limitations this only /// includes traffic that is specifically being sent to the adapter being listened /// with and it's IP address, so it will NOT pick up other traffic on the network using System; using System.Net; using System.Net.Sockets; using System.Threading; namespace PacketSniffer { public class Listen { #region Fields private const int p_PacketBufferSize = 65536; // this is the Maximum size that a packet will ever be private byte[] p_PacketBuffer = new byte[p_PacketBufferSize]; //Packet Buffer private string p_HostIP; #endregion //Fields private PacketRecieveEvent p_PRE; private Socket ListenSocket; #region HostIP /// <summary> /// Set the Adapter that we are Listening On /// </summary> public string HostIP { set { p_HostIP = value; } } #endregion //HostIP public Listen(PacketRecieveEvent PRE) { p_PRE = PRE; } public void RunReciever() { ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); try { // Setup the Socket ListenSocket.Bind(new IPEndPoint(IPAddress.Parse(p_HostIP), 0)); ListenSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1); ListenSocket.IOControl(unchecked((int) 0x98000001), new byte[4] {1, 0, 0, 0}, new byte[4]); while (true) //Infinite Loop keeps the Socket in Listen { ListenSocket.BeginReceive(p_PacketBuffer, 0, p_PacketBufferSize, SocketFlags.None, new AsyncCallback(CallReceive), this); while (ListenSocket.Available == 0) // If no Data Sleep the thread for 1ms then check to see if there is data to be read { Thread.Sleep(1); } } } catch (ThreadAbortException){}// Catch the ThreadAbort Exception that gets generated whenever a thread is closed with the Thread.Abort() method catch (Exception e) {new ErrorHandle(e);} finally //Shutdown the Socket when finished { if (ListenSocket != null) { ListenSocket.Shutdown(SocketShutdown.Both); ListenSocket.Close(); } } } protected virtual void CallReceive(IAsyncResult ar) { new PacketHandler(p_PRE, ref p_PacketBuffer); } } }
moird/PacketSniffer
PacketSniffer/Listen.cs
C#
gpl-3.0
3,625
package ocpp.cs._2012._06; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für ReadingContext. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * <p> * <pre> * &lt;simpleType name="ReadingContext"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="Interruption.Begin"/&gt; * &lt;enumeration value="Interruption.End"/&gt; * &lt;enumeration value="Sample.Clock"/&gt; * &lt;enumeration value="Sample.Periodic"/&gt; * &lt;enumeration value="Transaction.Begin"/&gt; * &lt;enumeration value="Transaction.End"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "ReadingContext") @XmlEnum public enum ReadingContext { @XmlEnumValue("Interruption.Begin") INTERRUPTION_BEGIN("Interruption.Begin"), @XmlEnumValue("Interruption.End") INTERRUPTION_END("Interruption.End"), @XmlEnumValue("Sample.Clock") SAMPLE_CLOCK("Sample.Clock"), @XmlEnumValue("Sample.Periodic") SAMPLE_PERIODIC("Sample.Periodic"), @XmlEnumValue("Transaction.Begin") TRANSACTION_BEGIN("Transaction.Begin"), @XmlEnumValue("Transaction.End") TRANSACTION_END("Transaction.End"); private final String value; ReadingContext(String v) { value = v; } public String value() { return value; } public static ReadingContext fromValue(String v) { for (ReadingContext c: ReadingContext.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
dtag-dev-sec/emobility
dist/src/centralsystem/target/generated-sources/ocpp/cs/_2012/_06/ReadingContext.java
Java
gpl-3.0
1,773
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "PackageManager" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "PackageManager" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2011" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "3358174b-eb3b-4242-aa5d-b54afc2f9487" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )]
bretambrose/CCGOnlinePublic
CCGOnline/CCGOnline/PackageManager/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,446
/* * Copyright (C) 2018 Stuart Howarth <showarth@marxoft.co.uk> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "categories.h" #include "clipboardurlmodel.h" #include "decaptchapluginmanager.h" #include "definitions.h" #include "downloadrequestmodel.h" #include "logger.h" #include "mainwindow.h" #include "pluginsettings.h" #include "recaptchapluginmanager.h" #include "request.h" #include "servicepluginmanager.h" #include "settings.h" #include "transfermodel.h" #include "urlcheckmodel.h" #include "urlretrievalmodel.h" #include <QApplication> #include <QNetworkAccessManager> Q_DECL_EXPORT int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setApplicationName("QDL-Client"); app.setApplicationVersion(VERSION_NUMBER); app.setWindowIcon(QIcon::fromTheme("qdl2-client")); const QStringList args = app.arguments(); const int verbosity = args.indexOf("-v") + 1; if ((verbosity > 1) && (verbosity < args.size())) { Logger::setVerbosity(qMax(1, args.at(verbosity).toInt())); } else { Logger::setFileName(Settings::loggerFileName()); Logger::setVerbosity(Settings::loggerVerbosity()); } QNetworkAccessManager manager; Request::setNetworkAccessManager(&manager); QScopedPointer<Categories> categories(Categories::instance()); QScopedPointer<ClipboardUrlModel> clipboard(ClipboardUrlModel::instance()); QScopedPointer<DecaptchaPluginManager> decaptchaManager(DecaptchaPluginManager::instance()); QScopedPointer<DownloadRequestModel> requester(DownloadRequestModel::instance()); QScopedPointer<PluginSettings> pluginSettings(PluginSettings::instance()); QScopedPointer<RecaptchaPluginManager> recaptchaManager(RecaptchaPluginManager::instance()); QScopedPointer<ServicePluginManager> serviceManager(ServicePluginManager::instance()); QScopedPointer<Settings> settings(Settings::instance()); QScopedPointer<TransferModel> transfers(TransferModel::instance()); QScopedPointer<UrlCheckModel> checker(UrlCheckModel::instance()); QScopedPointer<UrlRetrievalModel> retriever(UrlRetrievalModel::instance()); clipboard.data()->setEnabled(Settings::clipboardMonitorEnabled()); clipboard.data()->restore(); transfers.data()->setAutoReloadEnabled(Settings::autoReloadEnabled()); MainWindow window; window.show(); QObject::connect(settings.data(), SIGNAL(clipboardMonitorEnabledChanged(bool)), clipboard.data(), SLOT(setEnabled(bool))); QObject::connect(settings.data(), SIGNAL(autoReloadEnabledChanged(bool)), transfers.data(), SLOT(setAutoReloadEnabled(bool))); return app.exec(); }
marxoft/qdl2
client/src/desktop/main.cpp
C++
gpl-3.0
3,225
/** AirCasting - Share your Air! Copyright (C) 2011-2012 HabitatMap, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You can contact the authors by email at <info@habitatmap.org> */ package pl.llp.aircasting.screens.sessionRecord; import pl.llp.aircasting.Intents; import pl.llp.aircasting.R; import pl.llp.aircasting.screens.common.helpers.SettingsHelper; import pl.llp.aircasting.screens.common.ToastHelper; import pl.llp.aircasting.screens.common.sessionState.CurrentSessionManager; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.inject.Inject; import pl.llp.aircasting.screens.common.base.DialogActivity; import roboguice.inject.InjectView; public class ContributeActivity extends DialogActivity { @Inject CurrentSessionManager currentSessionManager; @Inject Context context; @Inject SettingsHelper settingsHelper; @InjectView(R.id.yes) Button yes; @InjectView(R.id.no) Button no; @Override protected void onResume() { super.onResume(); if (!settingsHelper.hasCredentials()) { ToastHelper.show(context, R.string.account_reminder, Toast.LENGTH_LONG); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.contribute); initDialogToolbar("Contribute Session"); if(!getIntent().hasExtra(Intents.SESSION_ID)) { throw new RuntimeException("Should have arrived here with a session id"); } final long sessionId = getIntent().getLongExtra(Intents.SESSION_ID, 0); yes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentSessionManager.finishSession(sessionId, true); finish(); } }); no.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentSessionManager.finishSession(sessionId, false); finish(); } }); } @Override public void onBackPressed() { currentSessionManager.continueSession(); finish(); } }
HabitatMap/AirCastingAndroidClient
src/main/java/pl/llp/aircasting/screens/sessionRecord/ContributeActivity.java
Java
gpl-3.0
2,765
/* * Copyright (C) 2017 zsel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.neology.lastdays; import com.neology.data.model.Frame; import com.neology.data.model.LoginData; import io.reactivex.Observable; import io.reactivex.Single; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.PUT; /** * * @author obsidiam */ public interface LastDaysService { @FormUrlEncoded @POST("/api/login") Single<LoginData> postCredential(@Field("username")String userName, @Field("password") String password, @Field("expires") String expires); @GET("/api/token") Call<ResponseBody> postToken(@Header("Authorization") String token); @FormUrlEncoded @POST("/api/register") Single<LoginData> postRegisterUser(@Field("username") String userName, @Field("password")String password, @Field("email") String email); @PUT("/api/todo") Single<TodoResult> postTodo(@Header("Authorization") String token, @Body TodoTicket t); @GET("/api/todo") Observable<Frame> getTodoList(@Header("Authorization") String token); }
Obsidiam/amelia
src/main/java/com/neology/lastdays/LastDaysService.java
Java
gpl-3.0
1,866
/* <genericpacket.cpp> Copyright(C) 2014 Jan Simon Bunten Simon Kadel Martin Sven Oehler Arne Sven Stühlmeyer This File is part of the WhisperLibrary WhisperLibrary is free software : you can redistribute it and / or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. WhisperLibrary is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <genericpacket.hpp> namespace whisper_library { vector<bool> GenericPacket::packet() const { return m_content; } void GenericPacket::setPacket(vector<bool> packet) { m_content = packet; } }
UndeadKernel/whisper-library
whisperLibrary/src/genericpacket.cpp
C++
gpl-3.0
1,011
""" DFO-GN ==================== A derivative-free solver for least squares minimisation with bound constraints. This version has resampling (not part of main package). This file is a modified version of DFOGN which allows resampling and restarts, to better cope with noisy problems. Lindon Roberts, 2017 Call structure is: x, f, nf, exit_flag, exit_str = dfogn(objfun, x0, lower, upper, maxfun, init_tr_radius, rhoend=1e-8) Required inputs: objfun Objective function, callable as: residual_vector = objfun(x) x0 Initial starting point, NumPy ndarray Optional inputs: lower, upper Lower and upper bound constraints (lower <= x <= upper), must be NumPy ndarrays of same size as x0 (default +/-1e20) maxfun Maximum number of allowable function evalutions (default 1000) init_tr_radius Initial trust region radius (default 0.1*max(1, ||x0||_infty) rhoend Termination condition on trust region radius (default 1e-8) Outputs: x Estimate of minimiser f Value of least squares objective at x (f = ||objfun(x)||^2) nf Number of objective evaluations used to find x exit_flag Integer flag indicating termination criterion (see list below imports) exit_str String with more detailed termination message This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. The development of this software was sponsored by NAG Ltd. (http://www.nag.co.uk) and the EPSRC Centre For Doctoral Training in Industrially Focused Mathematical Modelling (EP/L015803/1) at the University of Oxford. Please contact NAG for alternative licensing. Copyright 2017, Lindon Roberts """ # Ensure compatibility with Python 2 from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import scipy.linalg as sp_linalg from math import sqrt import logging from .util import * from .trust_region import * from .alternative_move import * ####################### # Exit codes EXIT_SUCCESS = 0 # successful finish (rho=rhoend or sufficient objective reduction) EXIT_INPUT_ERROR = 1 # error, bad inputs EXIT_MAXFUN_WARNING = 2 # warning, reached max function evals EXIT_TR_INCREASE_ERROR = 3 # error, trust region step increased model value EXIT_LINALG_ERROR = 4 # error, linalg error (singular matrix encountered) EXIT_ALTMOV_MEMORY_ERROR = 5 # error, stpsav issue in ALTMOV # Errors for which we can do a restart (not including rho=rhoend in EXIT_SUCCESS) DO_RESTART_ERRORS = [EXIT_TR_INCREASE_ERROR, EXIT_LINALG_ERROR, EXIT_ALTMOV_MEMORY_ERROR] ####################### ####################### # Sampling scenarios SCEN_PRELIM = 1 # during prelim SCEN_GROWING_NEW_DIRECTION = 2 # adding new direction while growing SCEN_TR_STEP = 3 # sampling xk+sk from successful trust region step SCEN_GEOM_UPDATE = 4 # calling altmov for geometry fixing SCEN_RHOEND_REACHED = 5 # reached rhoend in unsuccessful TR step ####################### class Model: def __init__(self, n, m, npt, x0, xl, xu): assert npt==n+1, "Require strictly linear model" # Problem sizes self.n = n self.m = m self.npt = npt self.npt_so_far = 0 # how many points have we added so far (for growing initial set) # Actual model info # Here, the model for each residual is centred around xbase # m(x) = model_const_term + gqv*(x-xbase) self.kbase = 0 # index of base point self.xbase = x0 # base point self.xl = xl # lower bounds (absolute terms) self.xu = xu # upper bounds (absolute terms) self.sl = xl - x0 # lower bounds (adjusted for xbase), should be -ve (actually < -rhobeg) self.su = xu - x0 # upper bounds (adjusted for xbase), should be +ve (actually > rhobeg) self.xpt = np.zeros((npt, n)) # interpolation points self.fval_v = np.zeros((npt, m)) # residual vectors at each xpt(+xbase) self.fval = np.zeros((npt, )) # total sum of squares at each xpt(+xbase) self.model_const_term_v = np.zeros((m,)) # constant term of each mini-model self.gqv = np.zeros((n, m)) # interpolated gradients for each mini-model self.kopt = None # index of current best x self.fbeg = None # initial sum of squares at x0 self.xsave = None # possible final return value (abs coords) self.fsave = None # sum of squares for final return value self.lu = None # LU decomp of interp matrix self.piv = None # pivots for LU decomposition of interp matrix self.lu_current = False # whether current LU factorisation of interp matrix is up-to-date or not self.EXACT_CONST_TERM = True # use exact c=r(xopt) for interpolation (improve conditioning) # Affects mini-model interpolation / interpolation matrix, but also geometry updating self.nsamples = np.zeros((npt,), dtype=np.int) # how many samples we have averaged to get fval_v, where fval = sumsq(avg fval_v) def x_within_bounds(self, k=None, x=None): # Get x value for k-th point or x vector (in absolute terms, force within bounds) if k is not None: return np.minimum(np.maximum(self.xl, self.xbase + self.xpt[k, :]), self.xu) elif x is not None: return np.minimum(np.maximum(self.xl, self.xbase + x), self.xu) else: return None def xopt(self): # Current best x (relative to xbase) return self.xpt[self.kopt, :].copy() def fval_v_opt(self): return self.fval_v[self.kopt,:] def fval_opt(self): return self.fval[self.kopt] def update_point(self, knew, xnew, v_err, f): if knew >= self.npt_so_far and self.npt_so_far < self.npt: # when still growing, need to append in correct order assert knew == self.npt_so_far, "Updating new index too far along (%g when should be %g)" % (knew, self.npt_so_far) self.npt_so_far += 1 # Add point xnew with objective vector v_err (full objective f) at the knew-th index self.xpt[knew,:] = xnew self.fval_v[knew, :] = v_err self.fval[knew] = f self.nsamples[knew] = 1 # Update XOPT, GOPT and KOPT if the new calculated F is less than FOPT. if f < self.fval_opt(): self.kopt = knew self.lu_current = False return def add_point_resample(self, knew, v_err_new): # We have resampled point knew and got a new fval_v = v_err_new # Update our estimates of fval_v assert knew < self.npt_to_use(), "Invalid knew" t = float(self.nsamples[knew]) / float(self.nsamples[knew] + 1) self.fval_v[knew, :] = t * self.fval_v[knew, :] + (1 - t) * v_err_new self.fval[knew] = sumsq(self.fval_v[knew, :]) self.nsamples[knew] += 1 if self.fval[knew] < self.fval_opt(): self.kopt = knew return def npt_to_use(self): # Number of points to use when building interpolation system return min(self.npt_so_far, self.npt) # depends on whether we have a full set yet (or not) def gqv_at_xopt(self): return self.gqv def shift_base(self, xbase_shift): for m1 in range(self.m): self.model_const_term_v[m1] += np.dot(self.gqv[:, m1], xbase_shift) # The main updates for k in range(self.npt): self.xpt[k, :] = self.xpt[k, :] - xbase_shift self.xbase += xbase_shift self.sl = self.sl - xbase_shift self.su = self.su - xbase_shift self.lu_current = False self.factorise_LU() return def interpolate_mini_models(self): # Build interpolation matrix and factorise (in self.lu, self.piv) self.factorise_LU() try: if self.EXACT_CONST_TERM: idx_to_use = [k for k in range(self.npt) if k != self.kopt] for m1 in range(self.m): rhs = np.zeros((self.n,)) for i in range(self.n): k = idx_to_use[i] rhs[i] = self.fval_v[k, m1] - self.fval_v[self.kopt, m1] - \ np.dot(self.gqv[:, m1], self.xpt[k, :] - self.xopt()) soln = sp_linalg.lu_solve((self.lu, self.piv), rhs) self.gqv[:, m1] += soln # whole solution is gradient # shift constant term back self.model_const_term_v = self.fval_v[self.kopt, :] - np.dot(self.gqv.T, self.xopt()) return True # flag ok else: model_values_v = np.zeros((self.npt, self.m)) for k in range(self.npt): model_values_v[k, :] = self.predicted_values(self.xpt[k, :], d_based_at_xopt=False, with_const_term=True) # Sometimes when things get too close to a solution, we can get NaNs in model_values - flag error & quit if np.any(np.isnan(model_values_v)): self.gqv = None return False # flag error for m1 in range(self.m): rhs = self.fval_v[:, m1] - model_values_v[:, m1] soln = sp_linalg.lu_solve((self.lu, self.piv), rhs) self.model_const_term_v[m1] += soln[0] self.gqv[:, m1] += soln[1:] # first term is constant, rest is gradient term return True # flag ok except np.linalg.LinAlgError: self.gqv = None return False # flag error except ValueError: # happens when LU decomposition has Inf or NaN self.gqv = None return False # flag error def factorise_LU(self): if not self.lu_current: Wmat = self.build_interp_matrix() self.lu, self.piv = sp_linalg.lu_factor(Wmat) # LU has L and U parts, piv indicates row swaps for pivoting self.lu_current = True return def solve_LU(self, rhs): # If lu_current, use that, otherwise revert to generic solver if self.lu_current: if self.EXACT_CONST_TERM: return sp_linalg.lu_solve((self.lu, self.piv), rhs) # only get gradient (no const term) else: return sp_linalg.lu_solve((self.lu, self.piv), rhs)[1:] # only return gradient (1st term is constant) else: logging.warning("model.solve_LU not using factorisation") Wmat = self.build_interp_matrix() if self.EXACT_CONST_TERM: return np.linalg.solve(Wmat, rhs) # only get gradient (no const term) else: return np.linalg.solve(Wmat, rhs)[1:] # only return gradient (1st term is constant) def get_final_results(self): # Called when about to exit BOBYQB # Return x and fval for optimal point (either from xsave+fsave or kopt) if self.fsave is None or self.fval_opt() <= self.fsave: # optimal has changed since xsave+fsave were last set x = self.x_within_bounds(k=self.kopt) f = self.fval_opt() else: x = self.xsave f = self.fsave return x, f def build_full_model(self): # Build full least squares objective model from mini-models # Centred around xopt = xpt[kopt, :] v_temp = self.fval_v_opt() # m-vector gqv_xopt = self.gqv_at_xopt() # J^T (transpose of Jacobian) at xopt, rather than xbase # Use the gradient at xopt to formulate \sum_i (2*f_i \nabla f_i) = 2 J^t m(x_opt) gopt = np.dot(gqv_xopt, v_temp) # n-vector (gqv = J^T) # Gauss-Newton part of Hessian hq = to_upper_triangular_vector(np.dot(gqv_xopt, gqv_xopt.T)) # Apply scaling based on convention for objective - this code uses sumsq(r_i) not 0.5*sumsq(r_i) gopt = 2.0 * gopt hq = 2.0 * hq return gopt, hq def build_interp_matrix(self): if self.EXACT_CONST_TERM: Wmat = np.zeros((self.n, self.n)) idx_to_use = [k for k in range(self.npt) if k != self.kopt] for i in range(self.n): Wmat[i,:] = self.xpt[idx_to_use[i], :] - self.xopt() else: Wmat = np.zeros((self.n + 1, self.n + 1)) Wmat[:, 0] = 1.0 Wmat[:, 1:] = self.xpt # size npt * n return Wmat def predicted_values(self, d, d_based_at_xopt=True, with_const_term=False): if d_based_at_xopt: Jd = np.dot(self.gqv.T, d + self.xopt()) # J^T * d (where Jacobian J = self.gqv^T) else: # d based at xbase Jd = np.dot(self.gqv.T, d) # J^T * d (where Jacobian J = self.gqv^T) return Jd + (self.model_const_term_v if with_const_term else 0.0) def square_distances_to_xopt(self): sq_distances = np.zeros((self.npt,)) for k in range(self.npt): sq_distances[k] = sumsq(self.xpt[k, :] - self.xopt()) return sq_distances def min_objective_value(self, abs_tol=1.0e-12, rel_tol=1.0e-20): # Set a minimum value so that if the full objective falls below it, we immediately finish if self.fbeg is not None: return max(abs_tol, rel_tol * self.fbeg) else: return abs_tol def sample_objective(m, objfun, x, nf, nx, maxfun, min_obj_value, nsamples=1): # Sample from objective function several times, keeping track of maxfun and min_obj_value throughout if m is None: # Don't initialise v_err_list yet v_err_list = None else: v_err_list = np.zeros((nsamples, m)) f_list = np.zeros((nsamples,)) exit_flag = None exit_str = None nsamples_run = 0 for i in range(nsamples): if nf >= maxfun: exit_flag = EXIT_MAXFUN_WARNING exit_str = "Objective has been called MAXFUN times" break # quit nf += 1 this_v_err, f_list[i] = eval_least_squares_objective_v2(objfun, x, eval_num=nf, pt_num=nx+1, full_x_thresh=6) if m is None: m = len(this_v_err) v_err_list = np.zeros((nsamples, m)) v_err_list[i, :] = this_v_err nsamples_run += 1 if f_list[i] <= min_obj_value: # Force model.get_final_results() to return this new point if it's better than xopt, then quit exit_flag = EXIT_SUCCESS exit_str = "Objective is sufficiently small" break # quit return v_err_list, f_list, nf, nx+1, nsamples_run, exit_flag, exit_str def build_initial_set(objfun, x0, xl, xu, rhobeg, maxfun, nsamples, nf_so_far, nx_so_far, ndirs_initial, nruns_so_far, m=None, random_initial_directions=False): n = np.size(x0) npt = n + 1 if m is not None: # Initialise model (sets x0 as base point and xpt = zeros, so xpt[0,:] = x0) model = Model(n, m, npt, x0, xl, xu) model.kopt = 0 minval = model.min_objective_value() else: # If we don't yet have m, wait until we have done a function evaluation before initialising model model = None minval = -1.0 assert 1 <= ndirs_initial < np.size(x0)+1, "build_inital_set: must have 1 <= ndirs_initial < n+1" nx = nx_so_far nf = nf_so_far # For calling nsamples: delta = rhobeg rho = rhobeg current_iter = 0 # Evaluate at initial point (also gets us m in the first run through) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_PRELIM) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = sample_objective(m, objfun, x0, nf, nx, maxfun, minval, nsamples=nsamples_to_use) # If we have just learned m, initialise model (sets x0 as base point and xpt = zeros, so xpt[0,:] = x0) if model is None: # Now we know m = v_err_list.shape[1] model = Model(n, v_err_list.shape[1], npt, x0, xl, xu) model.kopt = 0 f0 = sumsq(np.mean(v_err_list[:nsamples_run, :], axis=0)) # estimate actual objective value # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if model.fsave is None or fmin < model.fsave: model.xsave = x0 model.fsave = fmin return_to_new_tr_iteration = False # return and quit return model, nf, nx, return_to_new_tr_iteration, exit_flag, exit_str # Otherwise, add new results (increments model.npt_so_far) model.update_point(0, model.xpt[0, :], v_err_list[0, :], f_list[0]) for i in range(1, nsamples_run): model.add_point_resample(0, v_err_list[i, :]) # add new info # Add results of objective evaluation at x0 model.fbeg = f0 model.xsave = x0.copy() model.fsave = f0 # Build initial sample set either using random orthogonal directions, or coordinate directions if random_initial_directions: # Get ndirs_initial random orthogonal directions A = np.random.randn(n, ndirs_initial) # Standard Gaussian n*ndirs_initial Q = np.linalg.qr(A)[0] # Q is n*ndirs_initial with orthonormal columns # Now add the random directions for ndirns in range(ndirs_initial): dirn = Q[:, ndirns] # Scale direction to ensure the new point lies within initial trust region, satisfies constraints scale_factor = rhobeg / np.linalg.norm(dirn) for j in range(n): if dirn[j] < 0.0: scale_factor = min(scale_factor, model.sl[j] / dirn[j]) elif dirn[j] > 0.0: scale_factor = min(scale_factor, model.su[j] / dirn[j]) model.xpt[1 + ndirns, :] = scale_factor * dirn else: at_upper_boundary = (model.su < 0.01 * rhobeg) # su = xu - x0, should be +ve, actually > rhobeg for k in range(ndirs_initial): step_size = (rhobeg if not at_upper_boundary[k] else -rhobeg) model.xpt[k+1, k] = step_size # Evaluate objective at each point in the initial sample set for k in range(1, ndirs_initial): x = model.x_within_bounds(k=k) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_PRELIM) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # f = sumsq(np.mean(v_err_list[:nsamples_run, :], axis=0)) # estimate actual objective value # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if model.fsave is None or fmin < model.fsave: model.xsave = x model.fsave = fmin return_to_new_tr_iteration = False # return and quit return model, nf, nx, return_to_new_tr_iteration, exit_flag, exit_str # Otherwise, add new results (increments model.npt_so_far) model.update_point(k, model.xpt[k, :], v_err_list[0, :], f_list[0]) for i in range(1, nsamples_run): model.add_point_resample(k, v_err_list[i, :]) # add new info return_to_new_tr_iteration = True # return and continue exit_flag = None exit_str = None return model, nf, nx, return_to_new_tr_iteration, exit_flag, exit_str def get_new_orthogonal_directions(model, adelt, num_steps=1): # Step from xopt along a random direction orthogonal to other yt (or multiple mutually orthogonal steps) for i in range(20): # allow several tries, in case we choosing a point in the subspace of (yt-xk) [very unlucky] A = np.random.randn(model.n, num_steps) # (modified) Gram-Schmidt to orthogonalise for k in range(min(model.npt_so_far, model.npt)): if k == model.kopt: continue yk = model.xpt[k,:] - model.xopt() for j in range(num_steps): A[:,j] = A[:,j] - (np.dot(A[:,j], yk) / np.dot(yk, yk)) * yk # continue if every column sufficiently large all_cols_ok = True for j in range(num_steps): if np.linalg.norm(A[:,j]) < 1e-8: all_cols_ok = False if all_cols_ok: break # Scale appropriately so within bounds and ||d|| <= adelt Q = np.linalg.qr(A)[0] # Q is n*ndirs with orthonormal columns for j in range(num_steps): scale_factor = adelt / np.linalg.norm(Q[:,j]) for i in range(model.n): if Q[i,j] < 0.0: scale_factor = min(scale_factor, (model.sl[i] - model.xopt()[i]) / Q[i,j]) elif Q[i,j] > 0.0: scale_factor = min(scale_factor, (model.su[i] - model.xopt()[i]) / Q[i,j]) Q[:,j] = Q[:,j] * scale_factor # Finished! return Q def altmov_wrapper(model, knew, adelt): model.factorise_LU() # First need to get knew-th column of H matrix if model.EXACT_CONST_TERM: if knew == model.kopt: ek = -np.ones((model.n, )) # matrix based on (y-xk), so different geom structure for kopt else: ek = np.zeros((model.n, )) if knew < model.kopt: ek[knew] = 1.0 else: ek[knew - 1] = 1.0 H_knew = model.solve_LU(ek) else: ek = np.zeros((model.n + 1,)) ek[knew] = 1.0 H_knew = model.solve_LU(ek) xnew, xalt, cauchy, abs_denom = altmov(model.xpt, model.sl, model.su, model.kopt, model.xopt(), knew, adelt, H_knew) # abs_denom is Lagrange_knew evaluated at xnew return xnew, xalt, cauchy, abs_denom def choose_knew(model, delta, xnew, skip_kopt=True): # in model, uses: n, npt, xpt, kopt/xopt, build_interp_matrix() # model unchanged by this method # Criteria is to maximise: max(1, ||yt-xk||^4/Delta^4) * abs(Lagrange_t(xnew)) # skip_kopt determines whether to check t=kopt as a possible candidate or not model.factorise_LU() # Prep for linear solves delsq = delta ** 2 scaden = -1.0 knew = None # may knew never be set here? try: for k in range(model.npt): if skip_kopt and k == model.kopt: continue # next k in this inner loop if model.EXACT_CONST_TERM: if k == model.kopt: ek = -np.ones((model.n,)) # matrix based on (y-xk), so different geom structure for kopt else: ek = np.zeros((model.n, )) if k < model.kopt: ek[k] = 1.0 else: ek[k-1] = 1.0 Hk = model.solve_LU(ek) else: ek = np.zeros((model.n + 1,)) ek[k] = 1.0 Hk = model.solve_LU(ek) # k-th column of H, except 1st entry (i.e. Lagrange polynomial gradient) lagrange_k_at_d = 1.0 + np.dot(xnew-model.xpt[k, :], Hk) distsq = sumsq(model.xpt[k, :] - model.xopt()) temp = max(1.0, (distsq / delsq) ** 2) if temp * abs(lagrange_k_at_d) > scaden: scaden = temp * abs(lagrange_k_at_d) knew = k linalg_error = False except np.linalg.LinAlgError: linalg_error = True return knew, linalg_error def trust_region_subproblem_least_squares(model, delta): # in model, uses: n, npt, xpt, kopt/xopt, sl, su, build_full_model() # model unchanged by this method # Build model for full least squares objectives gopt, hq = model.build_full_model() # Call original BOBYQA trsbox function d, gnew, crvmin = trsbox(model.xopt(), gopt, hq, model.sl, model.su, delta) return d, gopt, hq, gnew, crvmin def done_with_current_rho(model, current_iter, last_successful_iter, rho, diffs, xnew, gnew, hq, crvmin): # in model, uses: n, sl, su # model unchanged by this method if current_iter <= last_successful_iter + 2: return False errbig = max(diffs) frhosq = 0.125 * rho ** 2 if crvmin > 0.0 and errbig > frhosq * crvmin: return False bdtol = errbig / rho for j in range(model.n): bdtest = bdtol if xnew[j] == model.sl[j]: bdtest = gnew[j] if xnew[j] == model.su[j]: bdtest = -gnew[j] if bdtest < bdtol: curv = get_hessian_element(model.n, hq, j, j) # curv = Hessian(j, j) bdtest += 0.5 * curv * rho if bdtest < bdtol: return False return True def reduce_rho(old_rho, rhoend): ratio = old_rho/rhoend if ratio <= 16.0: new_rho = rhoend elif ratio <= 250.0: new_rho = sqrt(ratio)*rhoend else: new_rho = 0.1*old_rho delta = max(0.5*old_rho, new_rho) return delta, new_rho def check_and_fix_geometry(model, objfun, distsq, delta, rho, dnorm, diffs, nf, nx, current_iter, last_successful_iter, maxfun, nsamples, rounding_error_const, nruns_so_far, update_delta=True): # [Fortran label 650] # If any xpt more than distsq away from xopt, fix geometry knew_tmp, distsq_tmp = get_vector_max(all_square_distances(model.xpt, model.xopt())) if distsq_tmp > distsq: # fix geometry and quit knew = knew_tmp distsq = distsq_tmp dist = sqrt(distsq) if update_delta: # optional delta = max(min(0.1 * delta, 0.5 * dist), 1.5 * rho) # use 0.5*dist, within range [0.1*delta, 1.5*rho] adelt = max(min(0.1 * dist, delta), rho) if adelt ** 2 <= rounding_error_const * sumsq(model.xopt()): model.shift_base(model.xopt()) model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str \ = fix_geometry(model, objfun, knew, delta, adelt, rho, dnorm, diffs, nf, nx, current_iter, last_successful_iter, maxfun, nsamples, nruns_so_far) return model, delta, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str else: # Do nothing, just quit # return_to_new_tr_iteration = None when didn't fix geometry return model, delta, nf, nx, last_successful_iter, diffs, None, None, None def fix_geometry(model, objfun, knew, delta, adelt, rho, dnorm, diffs, nf, nx, current_iter, last_successful_iter, maxfun, nsamples, nruns_so_far): # in model, uses: n, npt, xpt, sl, su, kopt/xopt, build_interp_metrix, and others # model is changed by this function: gqv from interp_mini_models, and others try: xnew, xalt, cauchy, denom = altmov_wrapper(model, knew, adelt) except np.linalg.LinAlgError: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix encountered in ALTMOV" return_to_new_tr_iteration = False # return and quit return model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str if xnew is None: # issue with stpsav occurred, quit DFOGN exit_flag = EXIT_ALTMOV_MEMORY_ERROR exit_str = "Error in ALTMOV - stpsav undefined" return_to_new_tr_iteration = False # return and quit return model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str if denom < cauchy and cauchy > 0.0: xnew = xalt.copy() d = xnew - model.xopt() # [Fortran label 360] x = model.x_within_bounds(x=xnew) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_GEOM_UPDATE) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if fmin < model.fsave: model.xsave = x model.fsave = fmin return_to_new_tr_iteration = False # return and quit return model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str # Otherwise, add new results model.update_point(knew, xnew, v_err_list[0, :], f_list[0]) # increments model.npt_so_far, if still growing for i in range(1, nsamples_run): model.add_point_resample(knew, v_err_list[i, :]) # add new info # Estimate actual reduction to add to diffs vector f = sumsq(np.mean(v_err_list[:nsamples_run, :], axis=0)) # estimate actual objective value # Use the quadratic model to predict the change in F due to the step D, # and set DIFF to the error of this prediction. gopt, hq = model.build_full_model() if gopt is None: # Use this to indicate linalg error if f < model.fval_opt(): # Force model.get_final_results() to return this new point if it's better than xopt, then quit model.xsave = x model.fsave = f exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix encountered in FIX_GEOMETRY (full model interpolation step)" return_to_new_tr_iteration = False # return and quit return model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str pred_reduction = - calculate_model_value(gopt, hq, d) actual_reduction = model.fval_opt() - f diffs = [abs(pred_reduction - actual_reduction), diffs[0], diffs[1]] if dnorm > rho: last_successful_iter = current_iter exit_flag = None exit_str = None return_to_new_tr_iteration = True # return and start new trust region iteration (label 60) return model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str def dfogn_main(objfun, x0, xl, xu, rhobeg, rhoend, maxfun, nsamples, m=None, delta_scale_for_new_dirns_when_growing=1.0, use_random_initial_directions=False, ndirs_initial=None, num_geom_steps_when_growing=1, nf_so_far=0, nx_so_far=0, nruns_so_far=0): exit_flag = None exit_str = None # One variable in BOBYQB depends on which code form we are using if zhang_code_structure: rounding_error_const = 0.1 # Zhang code else: rounding_error_const = 1.0e-3 # BOBYQA ########################################################### # Set up initial interpolation set ########################################################### # It shouldn't ever happen, but make sure ndirs_initial is not None if ndirs_initial is None: ndirs_initial = np.size(x0) model, nf, nx, return_to_new_tr_iteration, exit_flag, exit_str = \ build_initial_set(objfun, x0, xl, xu, rhobeg, maxfun, nsamples, nf_so_far, nx_so_far, ndirs_initial, nruns_so_far, m=m, random_initial_directions=use_random_initial_directions) if not return_to_new_tr_iteration: x, f = model.get_final_results() return x, f, nf, nx, exit_flag, exit_str, model.m ########################################################### # Set other variables before begin iterations ########################################################### finished_main_loop = False (rho, delta) = (rhobeg, rhobeg) diffs = [0.0, 0.0, 0.0] # (diffa, diffb, diffc) in Fortran code, used in done_with_current_rho() ########################################################### # Start of main loop [Fortran label 60] ########################################################### current_iter = -1 last_successful_iter = 0 while not finished_main_loop: current_iter += 1 logging.debug("Iter %g (last successful %g) with delta = %g and rho = %g" % ( current_iter, last_successful_iter, delta, rho)) # Interpolate each mini-model interp_ok = model.interpolate_mini_models() if not interp_ok: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix in mini-model interpolation (main loop)" finished_main_loop = True break # quit # Solve trust region subproblem to get tentative step d # Model for full least squares objective is given by (gopt, hq) d, gopt, hq, gnew, crvmin = trust_region_subproblem_least_squares(model, delta) logging.debug("Trust region step is d = " + str(d)) xnew = model.xopt() + d dsq = sumsq(d) dnorm = min(delta, sqrt(dsq)) if dnorm < 0.5 * rho and model.npt_so_far < model.n + 1: # Failed TR step during initial phase - add a point and see if that helps logging.debug("Failed trust region step during growing phase - adding new directions") dnew_matrix = get_new_orthogonal_directions(model, delta_scale_for_new_dirns_when_growing * delta, num_steps=num_geom_steps_when_growing) break_main_loop = False # the internal breaks only quit this inner loop! for j in range(num_geom_steps_when_growing): xnew = model.xopt() + dnew_matrix[:, j] logging.debug("Growing: compulsory geometry improving step xnew = %s" % str(xnew)) x = model.x_within_bounds(x=xnew) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_GROWING_NEW_DIRECTION) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = \ sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if fmin < model.fsave: model.xsave = x model.fsave = fmin break_main_loop = True break # quit inner loop over j, then quit main iteration if model.npt_so_far < model.npt: # still growing kmin = model.npt_so_far logging.debug("Updating point kmin=%g, since still growing" % kmin) else: # full set kmin, linalg_error = choose_knew(model, delta, xnew, skip_kopt=True) if linalg_error: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix when finding kmin (in main loop)" break_main_loop = True break # quit inner loop over j, then quit main iteration logging.debug("Updating point kmin=%g, chosen in usual way" % kmin) # Otherwise, add new results, incrementing model.npt_so_far (if still growing) model.update_point(kmin, xnew, v_err_list[0, :], f_list[0]) for i in range(1, nsamples_run): model.add_point_resample(kmin, v_err_list[i, :]) # add new info # Finished adding new directions - restart main trust region iteration (if no errors encountered) if break_main_loop: finished_main_loop = True break # quit else: finished_main_loop = False continue # next trust region step elif dnorm < 0.5 * rho: ################### # Start failed TR step ################### logging.debug("Failed trust region step (main phase)") if not done_with_current_rho(model, current_iter, last_successful_iter, rho, diffs, xnew, gnew, hq, crvmin): # [Fortran label 650] distsq = (10.0 * rho) ** 2 model, delta, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, geom_exit_flag, geom_exit_str = \ check_and_fix_geometry(model, objfun, distsq, delta, rho, dnorm, diffs, nf, nx, current_iter, last_successful_iter, maxfun, nsamples, rounding_error_const, nruns_so_far, update_delta=True) if return_to_new_tr_iteration is not None: # i.e. if we did actually fix geometry if return_to_new_tr_iteration: finished_main_loop = False continue # next trust region step else: # quit exit_flag = geom_exit_flag exit_str = geom_exit_str finished_main_loop = True break # quit # If we didn't fix geometry, reduce rho as below # otherwise, if we are done with current rho, reduce rho as below # Reduce rho and continue [Fortran label 680] if rho > rhoend: delta, rho = reduce_rho(rho, rhoend) logging.info("New rho = %g after %i function evaluations" % (rho, nf)) logging.debug("Best so far: f = %.15g at x = " % (model.fval_opt()) + str(model.xbase + model.xopt())) last_successful_iter = current_iter finished_main_loop = False continue # next trust region step else: # Cannot reduce rho, so check xnew and quit x = model.x_within_bounds(x=xnew) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_RHOEND_REACHED) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = \ sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if fmin < model.fsave: model.xsave = x model.fsave = fmin finished_main_loop = True break # quit # Force model.get_final_results() to return this new point if it's better than xopt, then quit model.xsave = x model.fsave = np.min(f_list[:nsamples_run]) exit_flag = EXIT_SUCCESS exit_str = "rho has reached rhoend" finished_main_loop = True break # quit ################### # End failed TR step ################### else: ################### # Start successful TR step ################### logging.debug("Successful trust region step") # Severe cancellation is likely to occur if XOPT is too far from XBASE. [Fortran label 90] if dsq <= rounding_error_const * sumsq(model.xopt()): model.shift_base(model.xopt()) # includes a re-factorisation of the interpolation matrix xnew = xnew - model.xopt() # Set KNEW to the index of the next interpolation point to be deleted to make room for a trust # region step. Again RESCUE may be called if rounding errors have damaged # the chosen denominator, which is the reason for attempting to select # KNEW before calculating the next value of the objective function. knew, linalg_error = choose_knew(model, delta, xnew, skip_kopt=True) if linalg_error: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix when finding knew (in main loop)" finished_main_loop = True break # quit # Calculate the value of the objective function at XBASE+XNEW, unless # the limit on the number of calculations of F has been reached. # [Fortran label 360, with ntrits > 0] x = model.x_within_bounds(x=xnew) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_TR_STEP) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = \ sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # Estimate f in order to compute 'actual reduction' f = sumsq(np.mean(v_err_list[:nsamples_run, :], axis=0)) # estimate actual objective value # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if fmin < model.fsave: model.xsave = x model.fsave = fmin finished_main_loop = True break # quit # Use the quadratic model to predict the change in F due to the step D, # and set DIFF to the error of this prediction. pred_reduction = - calculate_model_value(gopt, hq, d) actual_reduction = model.fval_opt() - f diffs = [abs(pred_reduction - actual_reduction), diffs[0], diffs[1]] if dnorm > rho: last_successful_iter = current_iter if pred_reduction < 0.0: exit_flag = EXIT_TR_INCREASE_ERROR exit_str = "Trust region step gave model increase" finished_main_loop = True break # quit # Pick the next value of DELTA after a trust region step. # Update trust region radius ratio = actual_reduction / pred_reduction if ratio <= 0.1: delta = min(0.5 * delta, dnorm) elif ratio <= 0.7: delta = max(0.5 * delta, dnorm) else: # (ratio > 0.7) Different updates depending on which code version we're using if zhang_code_structure: delta = min(max(2.0 * delta, 4.0 * dnorm), 1.0e10) # DFBOLS code version elif bbqtr: delta = max(0.5 * delta, 2.0 * dnorm) # BOBYQA version else: delta = max(delta, 2.0 * dnorm) # Zhang paper version if delta <= 1.5 * rho: # cap trust region radius at rho delta = rho logging.debug("New delta = %g (rho = %g) from ratio %g" % (delta, rho, ratio)) # Recalculate KNEW and DENOM if the new F is less than FOPT. if actual_reduction > 0.0: # f < model.fval_opt() knew, linalg_error = choose_knew(model, delta, xnew, skip_kopt=False) if linalg_error: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix when finding knew (in main loop, second time)" finished_main_loop = True break # quit # Updating... logging.debug("Updating with knew = %i" % knew) model.update_point(knew, xnew, v_err_list[0, :], f_list[0]) # increments model.npt_so_far, if still growing for i in range(1, nsamples_run): model.add_point_resample(knew, v_err_list[i, :]) # add new info # When growing and don't yet have a full set of directions, we always need a geometry improving step if model.npt_so_far <= model.n + 1: # even after npt function evaluations, still one direction short dnew_matrix = get_new_orthogonal_directions(model, delta_scale_for_new_dirns_when_growing * delta, num_steps=num_geom_steps_when_growing) # breaks below only stop num_geom_steps_when_growing loop, check if need to quit main loop too break_main_loop = False for j in range(num_geom_steps_when_growing): xnew = model.xopt() + dnew_matrix[:, j] logging.debug("Growing: compulsory geometry improving step xnew = %s" % str(xnew)) x = model.x_within_bounds(x=xnew) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_GROWING_NEW_DIRECTION) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = \ sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if fmin < model.fsave: model.xsave = x model.fsave = fmin finished_main_loop = True break_main_loop = True break # quit if model.npt_so_far < model.npt: # still growing kmin = model.npt_so_far logging.debug("Updating point kmin=%g, since still growing" % kmin) else: # full set kmin, linalg_error = choose_knew(model, delta, xnew, skip_kopt=True) if linalg_error: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix when finding kmin (in main loop)" finished_main_loop = True break_main_loop = True break # quit logging.debug("Updating point kmin=%g, chosen in usual way" % kmin) # Otherwise, add new results, incrementing model.npt_so_far (if still growing) model.update_point(kmin, xnew, v_err_list[0, :], f_list[0]) for i in range(1, nsamples_run): model.add_point_resample(kmin, v_err_list[i, :]) # add new info # Finished adding new directions - restart main trust region iteration (if no errors encountered) if break_main_loop: finished_main_loop = True break # quit # If a trust region step has provided a sufficient decrease in F, then # branch for another trust region calculation. if ratio >= 0.1: finished_main_loop = False continue # next trust region step # Alternatively, find out if the interpolation points are close enough # to the best point so far. # [Fortran label 650] distsq = max((2.0 * delta) ** 2, (10.0 * rho) ** 2) model, delta, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, geom_exit_flag, geom_exit_str = \ check_and_fix_geometry(model, objfun, distsq, delta, rho, dnorm, diffs, nf, nx, current_iter, last_successful_iter, maxfun, nsamples, rounding_error_const, nruns_so_far, update_delta=False) # don't update delta when ntrits > 0 if return_to_new_tr_iteration is not None: # i.e. if we did actually fix geometry if return_to_new_tr_iteration: finished_main_loop = False continue # next trust region step else: # quit exit_flag = geom_exit_flag exit_str = geom_exit_str finished_main_loop = True break # quit # If we didn't fix geometry, reduce rho [Fortran label 680] if ratio > 0.0: finished_main_loop = False continue # next trust region step if max(delta, dnorm) > rho: finished_main_loop = False continue # next trust region step # Reduce rho and continue [Fortran label 680] if rho > rhoend: delta, rho = reduce_rho(rho, rhoend) logging.info("New rho = %g after %i function evaluations" % (rho, nf)) logging.debug("Best so far: f = %.15g at x = " % (model.fval_opt()) + str(model.xbase + model.xopt())) last_successful_iter = current_iter finished_main_loop = False continue # next trust region step else: # Cannot reduce rho further exit_flag = EXIT_SUCCESS exit_str = "rho has reached rhoend" finished_main_loop = True break # quit ################### # End successful TR step ################### ############################# # End this iteration of main loop - take next TR step ############################# ########################################################### # End of main loop [Fortran label 720] ########################################################### x, f = model.get_final_results() logging.debug("At return from DFOGN, number of function evals = %i" % nf) logging.debug("Smallest objective value = %.15g at x = " % f + str(x)) return x, f, nf, nx, exit_flag, exit_str, model.m def dfogn_resampling(objfun, x0, lower=None, upper=None, maxfun=1000, nsamples=None, init_tr_radius=None, rhoend=1e-8, delta_scale_for_new_dirns_when_growing=1.0, use_random_initial_directions=False, ndirs_initial='n', num_geom_steps_when_growing=1, use_restarts=True, max_unsuccessful_restarts=10): # If bounds not provided, set to something large xl = (lower if lower is not None else -1.0e20 * np.ones(x0.shape)) xu = (upper if upper is not None else 1.0e20 * np.ones(x0.shape)) # Set default value of rhobeg to something sensible rhobeg = (init_tr_radius if init_tr_radius is not None else 0.1 * max(np.max(np.abs(x0)), 1.0)) # Set default number of samples to be 1 for every evaluation if nsamples is None: nsamples_to_use = lambda delta, rho, iter, nruns_so_far, scenario : 1 else: nsamples_to_use = nsamples n = np.size(x0) assert (rhobeg > 0.0), "rhobeg must be strictly positive" assert (rhoend > 0.0), "rhoend must be strictly positive" assert (rhoend < rhobeg), "rhoend must be less than rhobeg" assert (maxfun > 0), "maxfun must be strictly positive" assert (np.shape(x0) == (n,)), "x0 must be a vector" assert (np.shape(x0) == np.shape(xl)), "xl must have same shape as x0" assert (np.shape(x0) == np.shape(x0)), "xu must have same shape as x0" assert (np.all(xu-xl >= 2.0*rhobeg)), "gap between xl and xu must be at least 2*rhobeg" if maxfun <= n+1: logging.warning("Warning (maxfun <= n+1): Are you sure your budget is large enough?") # Parse string arguments: number of geometry steps to take at each growing iteration of main TR loop n_extra_steps_to_use = None if type(num_geom_steps_when_growing) == int: n_extra_steps_to_use = num_geom_steps_when_growing elif type(num_geom_steps_when_growing) == str: if num_geom_steps_when_growing == 'tenthn': n_extra_steps_to_use = int(x0.size // 10) elif num_geom_steps_when_growing == 'fifthn': n_extra_steps_to_use = int(x0.size // 5) elif num_geom_steps_when_growing == 'qtrn': n_extra_steps_to_use = int(x0.size // 4) assert n_extra_steps_to_use is not None, "Unknown num_geom_steps_when_growing: " + str( num_geom_steps_when_growing) n_extra_steps_to_use = max(n_extra_steps_to_use, 1) # floor at 1 # Parse string arguments: number of initial directions to add before beginning main TR loop ndirs_initial_val = None if type(ndirs_initial) == int: ndirs_initial_val = ndirs_initial elif type(ndirs_initial) == str: if ndirs_initial == 'tenthn': ndirs_initial_val = int(n // 10) elif ndirs_initial == 'fifthn': ndirs_initial_val = int(n // 5) elif ndirs_initial == 'qtrn': ndirs_initial_val = int(n // 4) elif ndirs_initial == 'halfn': ndirs_initial_val = int(n // 2) elif ndirs_initial == 'n': ndirs_initial_val = n elif ndirs_initial == '2n': ndirs_initial_val = 2 * n elif ndirs_initial == 'nsq': ndirs_initial_val = (n + 1) * (n + 2) // 2 - 1 assert ndirs_initial_val is not None, "Unknown ndirs_initial: " + str(ndirs_initial) assert ndirs_initial_val == n, "Must have n initial directions (build_interp_matrix assumes this)" ndirs_initial_val = max(ndirs_initial_val, 1) # floor at 1 # Enforce lower bounds on x0 (ideally with gap of at least rhobeg) idx = (xl < x0) & (x0 <= xl+rhobeg) x0[idx] = xl[idx] + rhobeg idx = (x0 <= xl) x0[idx] = xl[idx] # Enforce upper bounds on x0 (ideally with gap of at least rhobeg) idx = (xu-rhobeg <= x0) & (x0 < xu) x0[idx] = xu[idx] - rhobeg idx = (x0 >= xu) x0[idx] = xu[idx] # First run x, f, nf, nx, exit_flag, exit_str, m = \ dfogn_main(objfun, x0, xl, xu, rhobeg, rhoend, maxfun, nsamples_to_use, m=None, delta_scale_for_new_dirns_when_growing=delta_scale_for_new_dirns_when_growing, use_random_initial_directions=use_random_initial_directions, ndirs_initial=ndirs_initial_val, num_geom_steps_when_growing=n_extra_steps_to_use, nf_so_far=0, nx_so_far=0, nruns_so_far=0) # Now do repeats nruns_so_far = 1 reduction_last_run = True # did the last run give us a reduction? rhobeg_to_use = rhobeg rhoend_to_use = rhoend last_successful_run = 1 while use_restarts and nf < maxfun and nruns_so_far - last_successful_run < max_unsuccessful_restarts and \ ((exit_flag == EXIT_SUCCESS and 'rho' in exit_str) or exit_flag in DO_RESTART_ERRORS): if reduction_last_run: rhobeg_to_use = max(0.1 * max(np.max(np.abs(x)), 1.0), 10 * rhoend_to_use) rhoend_to_use = 1.0 * rhoend_to_use else: # Reduce initial TR radius when things have been going badly rhobeg_to_use = max(0.5 * rhobeg_to_use, 10 * rhoend_to_use) logging.info( "Restarting from finish point (f = %g) after %g function evals; new rhobeg = %g and rhoend = %g" % ( f, nf, rhobeg_to_use, rhoend_to_use)) x2, f2, nf, nx, exit_flag, exit_str, m_tmp = \ dfogn_main(objfun, x, xl, xu, rhobeg_to_use, rhoend_to_use, maxfun, nsamples_to_use, m=m, delta_scale_for_new_dirns_when_growing=delta_scale_for_new_dirns_when_growing, use_random_initial_directions=use_random_initial_directions, ndirs_initial=ndirs_initial_val, num_geom_steps_when_growing=n_extra_steps_to_use, nf_so_far=nf, nx_so_far=nx, nruns_so_far=nruns_so_far) nruns_so_far += 1 if f2 < f or np.isnan(f): logging.info("Successful run with new f = %s compared to old f = %s" % (f2, f)) last_successful_run = nruns_so_far x = x2 f = f2 reduction_last_run = True else: logging.info("Unsuccessful run with new f = %s compared to old f = %s" % (f2, f)) reduction_last_run = False logging.info("Finished after a total of %g runs" % nruns_so_far) # Clean up exit_str to have better information: if exit_flag == EXIT_SUCCESS: exit_str = "Success: " + exit_str elif exit_flag == EXIT_MAXFUN_WARNING: exit_str = "Warning: " + exit_str elif exit_flag == EXIT_INPUT_ERROR: exit_str = "Input error: " + exit_str elif exit_flag == EXIT_TR_INCREASE_ERROR: exit_str = "Trust region subproblem error: " + exit_str elif exit_flag == EXIT_LINALG_ERROR: exit_str = "Linear algebra error: " + exit_str elif exit_flag == EXIT_ALTMOV_MEMORY_ERROR: exit_str = "ALTMOV memory error: " + exit_str else: exit_str = "Unknown exit flag " + str(exit_flag) + " with message " + exit_str return x, f, nf, exit_flag, exit_str
numericalalgorithmsgroup/dfogn
dfogn/dfogn_resampling.py
Python
gpl-3.0
58,645
package algorithms func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { head := &ListNode{} l3 := head for l1 != nil && l2 != nil { if l1.Val < l2.Val { l3.Next = l1 l1 = l1.Next } else { l3.Next = l2 l2 = l2.Next } l3 = l3.Next } if l1 == nil { l3.Next = l2 } if l2 == nil { l3.Next = l1 } return head.Next }
BedivereZero/LeeCode
algorithms/0021-merge-two-sorted-lists.go
GO
gpl-3.0
350
package PCA_testcases; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.zip.GZIPInputStream; import org.apache.commons.io.FileUtils; import org.junit.Assert; public class CompareFiles { public static void compare(String one, String two) { compare(one, two, true); } public static void compare(String one, String two, boolean ignoreFirstField)//only use this on small files! (I want it to print the whole thing if it is incorrect) { String first = null; String second = null; try { first = read(one); second = read(two); } catch (IOException e) {e.printStackTrace();} if(ignoreFirstField && first.split("\t").length>1) { first=first.substring(first.indexOf("\t"), first.length()); second=second.substring(second.indexOf("\t"), second.length()); } //remove anything over 5 decimals.. (there are rounding error that I do not care about...) String regex = "(.[0-9]{5})[0-9]*([E\t\n])"; String replace = "$1$2"; first = first.replaceAll(regex, replace); second = second.replaceAll(regex, replace); // first = first.trim(); // second = second.trim(); // System.out.println(first); // System.out.println("\n"); // System.out.println(second); Assert.assertEquals(first,second); } public static String read(String path) throws IOException { BufferedReader reader = null; if(path.endsWith(".gz")) reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(path)))); else reader = new BufferedReader(new FileReader(new File(path))); String file = ""; String line = null; while((line=reader.readLine())!=null) file+=line+"\n"; reader.close(); return file; } }
Sipkovandam/PCrotation
Sipko/src/main/java/PCA_testcases/CompareFiles.java
Java
gpl-3.0
1,891
<?php /** %%%copyright%%% * * FusionTicket - ticket reservation system * Copyright (C) 2007-2013 FusionTicket Solution Limited . All rights reserved. * * Original Design: * phpMyTicket - ticket reservation system * Copyright (C) 2004-2005 Anna Putrino, Stanislav Chachkov. All rights reserved. * * This file is part of FusionTicket. * * This file may be distributed and/or modified under the terms of the * "GNU General Public License" version 3 as published by the Free * Software Foundation and appearing in the file LICENSE included in * the packaging of this file. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE. * * Any links or references to Fusion Ticket must be left in under our licensing agreement. * * By USING this file you are agreeing to the above terms of use. REMOVING this licence does NOT * remove your obligation to the terms of use. * * The "GNU General Public License" (GPL) is available at * http://www.gnu.org/copyleft/gpl.html. * * Contact help@fusionticket.com if any conditions of this licencing isn't * clear to you. */ if (!defined('ft_check')) {die('System intrusion ');} require_once(INC."classes/redundantdatachecker.php"); require_once(INC."classes".DS."class.model.php"); //require_once(INC."classes".DS."model.organizer.php"); class install_execute { static function precheck($Install, $configpath = false) { global $_SHOP; $tempdir = is($_SESSION['SHOP']['tmp_dir'],ROOT."includes/temp"); RemoveDir($tempdir,false); $install_mode=$_SESSION['radio']; OpenDatabase(); if (!ShopDB::$link) { array_push($Install->Errors,"Can not connect to the database."); return true; } if($install_mode == 'NORMAL'){ $Table_Names = ShopDB::TableList(''); for ($i=0;$i<count($Table_Names);$i++){ ShopDB::query("drop table `{$Table_Names[$i]}`"); } } global $tbls; require_once(ROOT."includes/install/data_db.php"); if ($errors = ShopDB::DatabaseUpgrade($tbls, true)){ foreach ($errors as $data) { if ($data['error']) { $Install->Errors[] = "<pre>".$data['changes']. $data['error']."</pre>"; } } if ($Install->Errors) return true; } if (ShopDB::Tableexists('SPoint')){ $Install->Warnings[] = "<pre>Migrated Spoint table</pre>"; self::MigrateSpoint(); } if (ShopDB::Tableexists('Control')){ $Install->Warnings[] = "<pre>Migrated Control table</pre>"; self::MigrateControl(); } if (ShopDB::Tableexists('Organizer')){ $Install->Warnings[] = "<pre>Removed Organizer table</pre>"; self::renameTables(array('Organizer')); } if (ShopDB::Tableexists('ShopConfig')){ $Install->Warnings[] = "<pre>Removed ShopConfig table</pre>"; self::MigrateShopConfig(); } self::renameTables(array('Color','Payment_log','sessions','Sessions')); if ($install_mode == 'NORMAL'){ // import contens of mysqldump to db if ($error = file_to_db(ROOT."includes/install/base_sql.sql")){ array_push($Install->Errors,$error); return true; } if ($_SESSION['db_demos']==1 and $error = file_to_db(ROOT."includes/install/demo_sql.sql")){ array_push($Install->Errors,$error); return true; } $_SESSION['admin_realname'] = is($_SESSION['admin_realname'],''); $query = "update Admin set admin_login='{$_SESSION['admin_login']}', admin_realname='{$_SESSION['admin_realname']}', admin_password=md5('{$_SESSION['admin_password']}'), admin_status='admin' where admin_id = 1"; if (!shopDB::query($query)){ array_push($Install->Errors,"Admin user can not be created! \n".ShopDB::error()); return true; } } self::recalcStats($Install); self::moveOrderNotes($Install); Orphans::clearZeros('Category', array('category_pm_id','category_event_id','category_pmp_id')); Orphans::clearZeros('Event', array('event_group_id','event_main_id')); Orphans::clearZeros('Order', array('order_owner_id', 'order_admin_id')); Orphans::clearZeros('PlaceMapPart', array('pmp_pm_id','pmp_ort_id','pmp_event_id')); Orphans::clearZeros('Seat', array('seat_category_id','seat_zone_id' ,'seat_user_id' , 'seat_order_id' ,'seat_pmp_id' ,'seat_discount_id')); shopDB::query("UPDATE Template set template_status='new'"); shopDB::query("UPDATE Template set template_type='systm' where template_type='email' and template_name='forgot_passwd'"); shopDB::query("UPDATE Template set template_type='systm' where template_type='email' and template_name='Signup_email'"); shopDB::query("UPDATE Template set template_type='systm' where template_type='email' and template_name='email_res'"); shopDB::query("UPDATE `Order` set order_payment_status='cancelled' where order_payment_status='canceled'"); shopDB::query("UPDATE `Order` set order_payment_status='paid' where order_payment_status='payed'"); shopDB::query("UPDATE `User` set user_status=1 where user_status=0"); if ((install_execute::CreateConfig($configpath)===false) or !file_exists($configpath)){ array_push($Install->Errors,"Configuration file is not saved correctly check the folder permissions!"); return true; } install_execute::fillConfigDB(); if (getophandata()!=='none') { array_push($Install->Warnings,'After the update the installer found some problems with your database.<br>'. 'To use with the new version we suggest fixing the database or create an new database.'); return true ; } return false; } static function postcheck($Install) { if (is($_POST['fixdatabase'],0)==2) { self::renameTables(array('Category','Discount','Event','Event_group', 'PlaceMap2','PlaceMapPart','PlaceMapZone','Seat','Order')); array_push($Install->Warnings,"The next tables are renamed: Category, Discount, Event, Event_group, PlaceMap2, PlaceMapPart, PlaceMapZone,Seat, Order. You can copy the data back yourself."); } return false; } static function fillConfigDB() { $config = config::load(); $config->_fill($_SESSION['CONFIG']); $config->Save(); } static function fillConfig($array, $suffix, $eq=' = ',$isarray=false){ $arr_type = array('langs_names','valutas','event_group_type_enum','event_type_enum'); $config =($isarray!==2)?'':array(); foreach ($array as $key =>$value) { if (is_int($key)){ $key= ''; if ($isarray===1) { $key = "[]"; } } else { if ($isarray===1) { $key = "['$key']"; } if ($isarray===2) { $key = "'$key'"; } } if (is_array($value)) { $x = (!$isarray and !in_array($key,$arr_type ))?2:(($isarray)?$isarray:1); if ($x==1) { $config .= self::fillConfig($value, $suffix .$key, $eq, $x); } else { $config .= "{$suffix}{$key} {$eq} array("; $item = self::fillConfig($value, '', '=>', $x); $config .= implode(", " ,$item ); $config .= ");\n"; } continue; } elseif(is_null($value)) { $value = 'null'; } elseif(is_bool($value)) { $value = ($value)?'True':'False'; } elseif(is_string($value)) { $value = _esc($value); } If ($isarray==2) { if (strlen(trim("{$suffix}{$key}"))==0) { $config[] = "{$value}"; } else $config[] = "{$suffix}{$key} {$eq} {$value}"; } elseif (strlen(trim("{$suffix}{$key}"))==0) { $config .= "{$value}"; } else $config .= "{$suffix}{$key} {$eq} {$value};\n"; } return $config; } static function CreateConfig(&$configpath) { $storetmp = !empty($configpath); $config = "<?php\n"; $config .= "/**\n"; $config .= " * %%%copyright%%%\n"; $config .= file_get_contents (ROOT."licence.txt")."\n"; $config .= " */\n\n"; $config .= "// Create on: ".date('r')."\n\n"; $config .= "// The following settings are automatically filled by the installation procedure:\n\n"; // $config .= "global \$_SHOP;\n\n"; $config .= "define(\"CURRENT_VERSION\",\"".INSTALL_VERSION."\");\n\n"; unset($_SESSION['SHOP']['install_dir']); if (is($_SESSION['fixed_url'],false)) { $_SESSION['SHOP']['root'] = BASE_URL."/"; if (!isset($_SESSION['SHOP']['root_secured']) or empty($_SESSION['SHOP']['root_secured'])) { $_SESSION['SHOP']['root_secured'] = $_SESSION['SHOP']['root']; } } else { unset ($_SESSION['SHOP']['root']); unset ($_SESSION['SHOP']['root_secured']); if (!$storetmp) {unset ($_SESSION['SHOP']['tmp_dir']); } } if (!is_null($_SESSION['SHOP']['tmp_dir'])) {unset ($_SESSION['SHOP']['tmp_dir']); } if (!isset($_SESSION['SHOP']['secure_id'])) { if (!isset($_SESSION['BASE_URL'])) { $_SESSION['BASE_URL'] = BASE_URL; } $_SESSION['SHOP']['secure_id'] = sha1(AUTH_REALM. $_SESSION['BASE_URL'] . uniqid()); } ksort($_SESSION['SHOP']); $config .= self::fillConfig($_SESSION['SHOP'],'$_SHOP->'); $config .= "\n?>"; $configpath = ($configpath)?$configpath:(ROOT."includes".DS."config".DS."init_config.php"); return file_put_contents($configpath, $config); } static function display($Install) { global $_SHOP, $orphancheck; OpenDatabase(); if(isset($_GET['fix'])){ Orphans::dofix($_GET['fix']); } $data = Orphans::getlist($keys,true,"&do=fix&inst_mode=post&inst_pg={$Install->return_pg}"); $space = (count($keys)*60 < 780 -200)?1:0; Install_Form_Open ($Install->return_pg,'', 'Database Orphan check'); echo "<table cellpadding=\"1\" cellspacing=\"2\" width='100%'> <tr><td> The list below gives you a view of the orphans in your database. Look at our website for instructions how to fix this or contact us on the forum or IRC. To be safe, we suggest creating a new database and importing the common information. This can be done by the installer. </td></tr> <tr> <td height='6px'></td> </tr> <tr> <td> <input type=\"radio\" name=\"fixdatabase\" value=\"1\" id='fixdatabase1' checked /><label for='fixdatabase1'> Fix tables manual </label> <input type=\"radio\" name=\"fixdatabase\" value=\"2\" id='fixdatabase2' /><label for='fixdatabase2'> Recreate tables </label> </td> </tr> </table>"; echo "<div style='overflow: auto; height: 250px; width:100%; border: 1'>"; echo "<table cellpadding=\"1\" cellspacing=\"2\" width='100%'>"; print " <tr class='admin_list_header'> <th width=130 align='left'> Tablename </th> <th width=50 align='right'> ID </th>"; foreach ($keys as $key) { print "<th width=60 align='center'> {$key}&nbsp;</th>"; } if ($space) { print "<th align='center'>&nbsp;</th>"; } print "</tr>"; $alt =0; foreach ($data as $row) { print "<tr class='admin_list_row_$alt'> <td class='admin_list_item'>{$row['_table']}</td> <td class='admin_list_item' align='right'>{$row['_id']}</td>\n"; foreach ($keys as $key) { print "<td align='center'>".((isset($row[$key]))?$row[$key]:'&nbsp;')."</td>\n"; } if ($space) { print "<th align='center'>&nbsp;</th>"; } print "</tr>"; $alt = ($alt + 1) % 2; } echo "</table></div>\n"; Install_Form_Buttons (); Install_Form_Close (); } static function checkadmin($name) { $query="select Count(*) as count from Admin where admin_login= "._esc($name); if(!$res=ShopDB::query_one_row($query)){ user_error(shopDB::error()); } else return ($res["count"]>0); } static function MigrateSpoint() { $query = "select * from SPoint"; $res = ShopDB::Query($query); while ($row = ShopDB::fetch_assoc($res)){ If (self::checkAdmin($row['login'])) $row['login'] = "pos~{$row['login']}"; $query = "INSERT INTO `Admin` SET ". "admin_login = '{$row['login']}', admin_password = '{$row['password']}', admin_user_id = '{$row['user_id']}', admin_status = 'pos'"; ShopDB::query($query); } $sql = "RENAME TABLE `SPoint` TO `old_spoint`"; // The MySQL way. ShopDB::query($sql); } static function MigrateShopConfig() { $query = "select * from ShopConfig"; $res = ShopDB::Query($query); $row = ShopDB::fetch_assoc($res); foreach($row as $key => $value) { $_SESSION['CONFIG'][$key] = $value; } $sql = "RENAME TABLE `ShopConfig` TO `old_shopconfig`"; // The MySQL way. ShopDB::query($sql); } static function MigrateControl(){ $query = "select * from `Control`"; $res = ShopDB::Query($query); while ($row = ShopDB::fetch_assoc($res)){ If (self::checkAdmin($row['control_login'])) $row['control_login'] = "tt~{$row['control_login']}"; $query = "INSERT INTO `Admin` SET ". "admin_login = '{$row['control_login']}', admin_password = '{$row['control_password']}', control_event_ids = '{$row['control_event_ids']}', admin_status = 'control'"; ShopDB::query($query); } $sql = "RENAME TABLE `Control` TO `old_control`"; // The MySQL way. ShopDB::query($sql); } static function renameTables($array) { if (is_array($array)) { foreach($array as $table) { $no = ''; if (ShopDB::Tableexists($table)) { while (ShopDB::TableExists("old{$no}_{$table}")) { $no = (int)$no +1; } $sql = "RENAME TABLE `{$table}` TO `old{$no}_{$table}`"; // The MySQL way. ShopDB::query($sql); } } } } static function recalcStats($Install) { if (ShopDB::TableExists ('Event_stat')) { ShopDB::Query("update Event set event_free = (select count(*) from `Seat` where seat_event_id = event_id and seat_status IN ('res','free','trash') and seat_user_id IS NULL and seat_order_id IS NULL ), event_total = (select count(*) from `Seat` where seat_event_id = event_id)"); ShopDB::Query("update Category set category_free = (select count(*) from `Seat` where seat_category_id = category_id and seat_status in ('res', 'free','trash') and seat_user_id IS NULL and seat_order_id IS NULL)"); array_push($Install->Warnings,"We moved the statistics information back to there main table this gives us a more stable system."); self::renameTables(array('Category_stat','Event_stat')); } } /** * install_execute::moveOrderNotes() * * Move order notes to new order_notes table * * @return void */ static function moveOrderNotes($Install){ $rec = is(ShopDB::query_one_row("SELECT COUNT(*) FROM `Order` WHERE order_note IS NOT NULL"),array(0)); if(isset($rec[0]) && $rec[0] >0 ){ $query = "INSERT INTO `order_note` (`onote_order_id`,`onote_subject`,`onote_note`) SELECT order_id,'Old Note',order_note FROM `Order` WHERE order_note IS NOT NULL"; if(ShopDB::query($query)){ $query = "UPDATE `Order` SET order_note = NULL WHERE order_note IS NULL"; ShopDB::query($query); } array_push($Install->Warnings,"Moved the Order Note to there new location!"); } } } ?>
fusionticket/FTS_RC1
includes/install/install_execute.php
PHP
gpl-3.0
16,737
<?php namespace simvc\lib\request; abstract class DecoratorRequest extends ProcessRequest{ protected $request; public function __construct( ProcessRequest $request ){ $this -> request = $request; } } ?>
yiyide266/simvc
simvc/lib/request/DecoratorRequest.class.php
PHP
gpl-3.0
212
package de.deepamehta.storage.neo4j; import de.deepamehta.core.storage.spi.DeepaMehtaTransaction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; /** * Adapts a Neo4j transaction to a DeepaMehta transaction. */ class Neo4jTransactionAdapter implements DeepaMehtaTransaction { // ---------------------------------------------------------------------------------------------- Instance Variables private Transaction tx; // ---------------------------------------------------------------------------------------------------- Constructors Neo4jTransactionAdapter(GraphDatabaseService neo4j) { tx = neo4j.beginTx(); } // -------------------------------------------------------------------------------------------------- Public Methods @Override public void success() { tx.success(); } @Override public void failure() { tx.failure(); } @Override public void finish() { tx.finish(); } }
ascherer/deepamehta
modules/dm4-storage-neo4j/src/main/java/de/deepamehta/storage/neo4j/Neo4jTransactionAdapter.java
Java
gpl-3.0
1,023
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class W3Effect_PoisonCritical : W3CriticalDOTEffect { public W3Effect_PoisonCritical(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new W3Effect_PoisonCritical(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
Traderain/Wolven-kit
WolvenKit.CR2W/Types/W3/RTTIConvert/W3Effect_PoisonCritical.cs
C#
gpl-3.0
691
/* * _____ _ _ _____ _ * | __ \| | | | / ____| | | * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| * | | * |_| * PlotSquared plot management system for Minecraft * Copyright (C) 2021 IntellectualSites * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.plotsquared.core.plot.flag.implementations; import com.plotsquared.core.configuration.caption.TranslatableCaption; import com.plotsquared.core.plot.flag.types.BooleanFlag; import org.checkerframework.checker.nullness.qual.NonNull; public class HangingPlaceFlag extends BooleanFlag<HangingPlaceFlag> { public static final HangingPlaceFlag HANGING_PLACE_TRUE = new HangingPlaceFlag(true); public static final HangingPlaceFlag HANGING_PLACE_FALSE = new HangingPlaceFlag(false); private HangingPlaceFlag(boolean value) { super(value, TranslatableCaption.miniMessage("flags.flag_description_hanging_place")); } @Override protected HangingPlaceFlag flagOf(@NonNull Boolean value) { return value ? HANGING_PLACE_TRUE : HANGING_PLACE_FALSE; } }
IntellectualCrafters/PlotSquared
Core/src/main/java/com/plotsquared/core/plot/flag/implementations/HangingPlaceFlag.java
Java
gpl-3.0
2,113
<?php if (!defined('IDIR')) { die; } /*======================================================================*\ || #################################################################### || || # vBulletin - Licence Number VBF98A5CB5 || # ---------------------------------------------------------------- # || || # All PHP code in this file is ©2000-2006 Jelsoft Enterprises Ltd. # || || # This file may not be redistributed in whole or significant part. # || || # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # || || # http://www.vbulletin.com | http://www.vbulletin.com/license.html # || || #################################################################### || \*======================================================================*/ /** * deluxeportal_007 Import Post module * * @package ImpEx.deluxeportal * @version $Revision: 1.5 $ * @author Jerry Hutchings <jerry.hutchings@vbulletin.com> * @checkedout $Name: $ * @date $Date: 2006/04/03 02:57:11 $ * @copyright http://www.vbulletin.com/license.html * */ class deluxeportal_007 extends deluxeportal_000 { var $_version = '0.0.1'; var $_dependent = '006'; var $_modulestring = 'Import Post'; function deluxeportal_007() { // Constructor } function init(&$sessionobject, &$displayobject, &$Db_target, &$Db_source) { if ($this->check_order($sessionobject,$this->_dependent)) { if ($this->_restart) { if ($this->restart($sessionobject, $displayobject, $Db_target, $Db_source,'clear_imported_posts')) { $displayobject->display_now('<h4>Imported posts have been cleared</h4>'); $this->_restart = true; } else { $sessionobject->add_error('fatal', $this->_modulestring, get_class($this) . '::restart failed , clear_imported_posts','Check database permissions'); } } // Start up the table $displayobject->update_basic('title','Import Post'); $displayobject->update_html($displayobject->do_form_header('index',substr(get_class($this) , -3))); $displayobject->update_html($displayobject->make_hidden_code(substr(get_class($this) , -3),'WORKING')); $displayobject->update_html($displayobject->make_hidden_code('import_post','working')); $displayobject->update_html($displayobject->make_table_header($this->_modulestring)); // Ask some questions $displayobject->update_html($displayobject->make_input_code('Posts to import per cycle (must be greater than 1)','postperpage',500)); // End the table $displayobject->update_html($displayobject->do_form_footer('Continue','Reset')); // Reset/Setup counters for this $sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_done', '0'); $sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_failed', '0'); $sessionobject->add_session_var('poststartat','0'); $sessionobject->add_session_var('postdone','0'); } else { // Dependant has not been run $displayobject->update_html($displayobject->do_form_header('index','')); $displayobject->update_html($displayobject->make_description('<p>This module is dependent on <i><b>' . $sessionobject->get_module_title($this->_dependent) . '</b></i> cannot run until that is complete.')); $displayobject->update_html($displayobject->do_form_footer('Continue','')); $sessionobject->set_session_var(substr(get_class($this) , -3),'FALSE'); $sessionobject->set_session_var('module','000'); } } function resume(&$sessionobject, &$displayobject, &$Db_target, &$Db_source) { // Set up working variables. $displayobject->update_basic('displaymodules','FALSE'); $target_database_type = $sessionobject->get_session_var('targetdatabasetype'); $target_table_prefix = $sessionobject->get_session_var('targettableprefix'); $source_database_type = $sessionobject->get_session_var('sourcedatabasetype'); $source_table_prefix = $sessionobject->get_session_var('sourcetableprefix'); // Per page vars $post_start_at = $sessionobject->get_session_var('poststartat'); $post_per_page = $sessionobject->get_session_var('postperpage'); $class_num = substr(get_class($this) , -3); // Start the timing if(!$sessionobject->get_session_var($class_num . '_start')) { $sessionobject->timing($class_num ,'start' ,$sessionobject->get_session_var('autosubmit')); } // Get an array of post details $post_array = $this->get_deluxeportal_post_details($Db_source, $source_database_type, $source_table_prefix, $post_start_at, $post_per_page); $user_ids_array = $this->get_user_ids($Db_target, $target_database_type, $target_table_prefix, $do_int_val = false); $thread_ids_array = $this->get_threads_ids($Db_target, $target_database_type, $target_table_prefix); // Display count and pass time $displayobject->display_now('<h4>Importing ' . count($post_array) . ' posts</h4><p><b>From</b> : ' . $post_start_at . ' :: <b>To</b> : ' . ($post_start_at + count($post_array)) . '</p>'); $post_object = new ImpExData($Db_target, $sessionobject, 'post'); foreach ($post_array as $post_id => $post_details) { $try = (phpversion() < '5' ? $post_object : clone($post_object)); // Mandatory $try->set_value('mandatory', 'threadid', $thread_ids_array["$post_details[threadid]"]); $try->set_value('mandatory', 'userid', $user_ids_array["$post_details[userid]"]); $try->set_value('mandatory', 'importthreadid', $post_details['threadid']); // Non Mandatory #$try->set_value('nonmandatory', 'parentid', $post_details['parentid']); $try->set_value('nonmandatory', 'username', $post_details['username']); $try->set_value('nonmandatory', 'title', $post_details['subject']); $try->set_value('nonmandatory', 'dateline', $post_details['postdate']); $try->set_value('nonmandatory', 'pagetext', $this->html_2_bb($this->deluxeportal_html($post_details['message']))); $try->set_value('nonmandatory', 'allowsmilie', $post_details['smilies']); $try->set_value('nonmandatory', 'showsignature', $post_details['showsignature']); $try->set_value('nonmandatory', 'ipaddress', $post_details['ip']); $try->set_value('nonmandatory', 'iconid', $post_details['iconid']); $try->set_value('nonmandatory', 'visible', '1'); #$try->set_value('nonmandatory', 'attach', $post_details['attach']); $try->set_value('nonmandatory', 'importpostid', $post_details['postid']); // Check if post object is valid if($try->is_valid()) { if($try->import_post($Db_target, $target_database_type, $target_table_prefix)) { $displayobject->display_now('<br /><span class="isucc"><b>' . $try->how_complete() . '%</b></span> :: post from -> ' . $post_details['username']); $sessionobject->add_session_var($class_num . '_objects_done',intval($sessionobject->get_session_var($class_num . '_objects_done')) + 1 ); } else { $sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 ); $sessionobject->add_error('warning', $this->_modulestring, get_class($this) . '::import_custom_profile_pic failed.', 'Check database permissions and database table'); $displayobject->display_now("<br />Found avatar post and <b>DID NOT</b> imported to the {$target_database_type} database"); } } else { $displayobject->display_now("<br />Invalid post object, skipping." . $try->_failedon); } unset($try); }// End foreach // Check for page end if (count($post_array) == 0 OR count($post_array) < $post_per_page) { $sessionobject->timing($class_num,'stop', $sessionobject->get_session_var('autosubmit')); $sessionobject->remove_session_var($class_num . '_start'); $displayobject->display_now('Updateing parent ids to allow for a threaded view....'); if ($this->update_post_parent_ids($Db_target, $target_database_type, $target_table_prefix)) { $displayobject->display_now('Done !'); } else { $displayobject->display_now('Error updating parent ids'); } $displayobject->update_html($displayobject->module_finished($this->_modulestring, $sessionobject->return_stats($class_num, '_time_taken'), $sessionobject->return_stats($class_num, '_objects_done'), $sessionobject->return_stats($class_num, '_objects_failed') )); $sessionobject->set_session_var($class_num ,'FINISHED'); $sessionobject->set_session_var('import_post','done'); $sessionobject->set_session_var('module','000'); $sessionobject->set_session_var('autosubmit','0'); $displayobject->update_html($displayobject->print_redirect('index.php','1')); } $sessionobject->set_session_var('poststartat',$post_start_at+$post_per_page); $displayobject->update_html($displayobject->print_redirect('index.php')); }// End resume }//End Class # Autogenerated on : September 11, 2004, 2:50 pm # By ImpEx-generator 1.0. /*======================================================================*\ || #################################################################### || # Downloaded: 03:45, Mon Nov 13th 2006 || # CVS: $RCSfile: 007.php,v $ - $Revision: 1.5 $ || #################################################################### \*======================================================================*/ ?>
chrisplough/otmfaq
otmfaq.com/htdocs/forums/impex/systems/deluxeportal/007.php
PHP
gpl-3.0
9,316
/* * Copyright (C) 2012, 2013 Paul Grégoire * * This file is part of AIWar. * * AIWar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AIWar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AIWar. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MININGSHIP_HPP #define MININGSHIP_HPP #include <ostream> #include "item.hpp" #include "movable.hpp" #include "living.hpp" #include "playable.hpp" #include "memory.hpp" namespace aiwar { namespace core { class Mineral; class Base; class MiningShip : virtual public Item, public Movable, public Living, public Playable, public Memory { public: MiningShip(GameManager& gm, Key k, double xpos, double ypos, Team team, PlayFunction& pf); ~MiningShip(); void update(unsigned int tick); unsigned int extract(Mineral *m); unsigned int mineralStorage() const; unsigned int pushMineral(Base *base, unsigned int mineralPoints); // helper function only called by a base item unsigned int _release(unsigned int mineralPoint); std::string _dump() const; private: /** * \brief Initialize the MiningShip * * Reset _hasExtracted */ void _preUpdate(unsigned int tick); void _setMineralStorage(int n); unsigned int _mineralStorage; ///< Number of mineral units stored bool _hasExtracted; }; } // namespace aiwar::core } // namespace aiwar std::ostream& operator<< (std::ostream& os, const aiwar::core::MiningShip& t); #endif /* MININGSHIP_HPP */
merovingien/AIWar
miningship.hpp
C++
gpl-3.0
2,149
<img src="<?php echo get_bloginfo('wpurl');?>/wp-content/plugins/native-apps-builder/img/logo.png" /> <style type="text/css"> <?php require_once("login.css"); ?> </style> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery("#registerform").bind("submit",function(e){ //e.preventDefault(); //e.stopPropagation(); if(!jQuery("#terms").prop("checked")){ return false; } return true; }); }); </script> <?php if(isset($msg)){ echo "<div style='border:1px dashed red; padding:15px;color:red;font-size:16px;margin:6px;'><span><strong>".$msg."</strong></span></div>"; } ?> <div class="metabox-holder"> <div class="postbox"> <h3>Login your AppsBuilder account</h3> <form method="POST" action="" id="loginform"> <table class="form-table"> <tr><th scope="row"><strong>Username :</strong></th><td> <input name="username" type="text" value="" size="45"/></td></tr> <tr><th scope="row"><strong>Password :</strong></th><td> <input name="password" type="password" size="45"/></td></tr> <tr><th scope="row"></th><td><input name="page" type="hidden" value="login" /><input class="button-primary" type="submit" value="login"/></td></tr> </table> </form> </div> </div> <h3>.. OR ..</h3> <div class="metabox-holder"> <div class="postbox"> <h3>Not registered yet? Fill the fields below and sign in now!</h3> <form method="POST" action="" id="registerform"> <table class="form-table" > <tr><th scope="row"><strong>Username :</strong></th><td> <input name="username" type="text" value="" size="45"/></td></tr> <tr><th scope="row"><strong>Password :</strong></th><td> <input name="password" type="password" size="45"/></td></tr> <tr><th scope="row"><strong>Email :</strong></th><td> <input name="email" type="text" value="" size="45"/></td></tr> <tr><th scope="row"></th><td><input id="terms" type="checkbox" name="terms"><a href="http://www.apps-builder.com/pag/terms"> I have read and agreed the following terms and conditions</a></td></tr> <input name="page" type="hidden" value="register"/> <tr><th scope="row"></th><td><input type="submit" value="REGISTER NOW" class="button-primary"/></td></tr> </table> </form> </div> </div> <?php include_once('footer.php'); ?>
wp-plugins/native-apps-builder
login/login.php
PHP
gpl-3.0
2,266
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2014-2020) # # This file is part of GWpy. # # GWpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # GWpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GWpy. If not, see <http://www.gnu.org/licenses/>. """Basic utilities for reading/writing LIGO_LW-format XML files. All specific unified input/output for class objects should be placed in an 'io' subdirectory of the containing directory for that class. """ import os import os.path from contextlib import contextmanager from functools import wraps from importlib import import_module import numpy try: from ligo.lw.ligolw import ( ElementError as LigolwElementError, LIGOLWContentHandler, ) except ImportError: # no ligo.lw LigolwElementError = None LIGOLWContentHandler = None from .utils import (file_list, FILE_LIKE) from ..utils.decorators import deprecated_function __author__ = 'Duncan Macleod <duncan.macleod@ligo.org>' # XML elements XML_SIGNATURE = b'<?xml' LIGOLW_SIGNATURE = b'<!doctype ligo_lw' LIGOLW_ELEMENT = b'<ligo_lw>' # -- hack around around TypeError from LIGOTimeGPS(numpy.int32(...)) ---------- def _ligotimegps(s, ns=0): """Catch TypeError and cast `s` and `ns` to `int` """ from lal import LIGOTimeGPS try: return LIGOTimeGPS(s, ns) except TypeError: return LIGOTimeGPS(int(s), int(ns)) @contextmanager def patch_ligotimegps(module="ligo.lw.lsctables"): """Context manager to on-the-fly patch LIGOTimeGPS to accept all int types """ module = import_module(module) orig = module.LIGOTimeGPS module.LIGOTimeGPS = _ligotimegps try: yield finally: module.LIGOTimeGPS = orig # -- content handling --------------------------------------------------------- def strip_ilwdchar(_ContentHandler): """Wrap a LIGO_LW content handler to swap ilwdchar for int on-the-fly when reading a document This is adapted from :func:`ligo.skymap.utils.ilwd`, copyright Leo Singer (GPL-3.0-or-later). """ from ligo.lw.lsctables import TableByName from ligo.lw.table import (Column, TableStream) from ligo.lw.types import (FromPyType, ToPyType) class IlwdMapContentHandler(_ContentHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._idconverter = {} @wraps(_ContentHandler.startColumn) def startColumn(self, parent, attrs): result = super().startColumn(parent, attrs) # if an old ID type, convert type definition to an int if result.Type == "ilwd:char": old_type = ToPyType[result.Type] def converter(old): return int(old_type(old)) self._idconverter[(id(parent), result.Name)] = converter result.Type = FromPyType[int] try: validcolumns = TableByName[parent.Name].validcolumns except KeyError: # parent.Name not in TableByName return result if result.Name not in validcolumns: stripped_column_to_valid_column = { Column.ColumnName(name): name for name in validcolumns } if result.Name in stripped_column_to_valid_column: result.setAttribute( 'Name', stripped_column_to_valid_column[result.Name], ) return result @wraps(_ContentHandler.startStream) def startStream(self, parent, attrs): result = super().startStream(parent, attrs) if isinstance(result, TableStream): loadcolumns = set(parent.columnnames) if parent.loadcolumns is not None: loadcolumns &= set(parent.loadcolumns) pid = id(parent) result._tokenizer.set_types([ self._idconverter.pop((pid, colname), pytype) if colname in loadcolumns else None for pytype, colname in zip( parent.columnpytypes, parent.columnnames, ) ]) return result return IlwdMapContentHandler def _wrap_content_handler(contenthandler): from ligo.lw.lsctables import use_in @strip_ilwdchar @use_in class ContentHandler(contenthandler): pass return ContentHandler def default_content_handler(): """Return a standard content handler to read LIGO_LW documents This handler knows how to parse LSCTables, and automatically converts old-style ilwdchar ID types to `int`. Returns ------- contenthandler : subclass of `ligo.lw.ligolw.LIGOLWContentHandler` """ from ligo.lw.ligolw import LIGOLWContentHandler return _wrap_content_handler(LIGOLWContentHandler) def get_partial_contenthandler(element): """Build a `PartialLIGOLWContentHandler` to read only this element Parameters ---------- element : `type`, subclass of :class:`~ligo.lw.ligolw.Element` the element class to be read Returns ------- contenthandler : `type` a subclass of `~ligo.lw.ligolw.PartialLIGOLWContentHandler` to read only the given `element` """ from ligo.lw.ligolw import PartialLIGOLWContentHandler from ligo.lw.table import Table if issubclass(element, Table): def _element_filter(name, attrs): return element.CheckProperties(name, attrs) else: def _element_filter(name, _): return name == element.tagName return build_content_handler(PartialLIGOLWContentHandler, _element_filter) def get_filtering_contenthandler(element): """Build a `FilteringLIGOLWContentHandler` to exclude this element Parameters ---------- element : `type`, subclass of :class:`~ligo.lw.ligolw.Element` the element to exclude (and its children) Returns ------- contenthandler : `type` a subclass of `~ligo.lw.ligolw.FilteringLIGOLWContentHandler` to exclude an element and its children """ from ligo.lw.ligolw import FilteringLIGOLWContentHandler from ligo.lw.table import Table if issubclass(element, Table): def _element_filter(name, attrs): return ~element.CheckProperties(name, attrs) else: def _element_filter(name, _): # pylint: disable=unused-argument return name != element.tagName return build_content_handler( FilteringLIGOLWContentHandler, _element_filter, ) def build_content_handler(parent, filter_func): """Build a `~xml.sax.handler.ContentHandler` with a given filter Parameters ---------- parent : `type`, subclass of `xml.sax.handler.ContentHandler` a class of contenthandler to use filter_func : `callable` the filter function to pass to the content handler creation Returns ------- contenthandler : subclass of ``parent`` a new content handler that applies the filter function and the default parsing extras from :func:`_wrap_content_handler`. """ class ContentHandler(parent): # pylint: disable=too-few-public-methods def __init__(self, document): super().__init__(document, filter_func) return _wrap_content_handler(ContentHandler) # -- reading ------------------------------------------------------------------ def read_ligolw(source, contenthandler=None, **kwargs): """Read one or more LIGO_LW format files Parameters ---------- source : `str`, `file` the open file or file path to read contenthandler : `~xml.sax.handler.ContentHandler`, optional content handler used to parse document verbose : `bool`, optional be verbose when reading files, default: `False` Returns ------- xmldoc : :class:`~ligo.lw.ligolw.Document` the document object as parsed from the file(s) """ from ligo.lw.ligolw import Document from ligo.lw import types from ligo.lw.utils import (load_url, ligolw_add) # mock ToPyType to link to numpy dtypes topytype = types.ToPyType.copy() for key in types.ToPyType: if key in types.ToNumPyType: types.ToPyType[key] = numpy.dtype(types.ToNumPyType[key]).type # set contenthandler if contenthandler is None: contenthandler = default_content_handler() # read one or more files into a single Document source = file_list(source) try: if len(source) == 1: return load_url( source[0], contenthandler=contenthandler, **kwargs ) return ligolw_add.ligolw_add( Document(), source, contenthandler=contenthandler, **kwargs ) finally: # replace ToPyType types.ToPyType = topytype # -- reading ------------------------------------------------------------------ def read_table( source, tablename=None, columns=None, contenthandler=None, **kwargs, ): """Read a :class:`~ligo.lw.table.Table` from one or more LIGO_LW files Parameters ---------- source : `Document`, `file`, `str`, `CacheEntry`, `list` object representing one or more files. One of - a LIGO_LW :class:`~ligo.lw.ligolw.Document` - an open `file` - a `str` pointing to a file path on disk - a formatted :class:`~lal.utils.CacheEntry` representing one file - a `list` of `str` file paths or :class:`~lal.utils.CacheEntry` tablename : `str` name of the table to read. columns : `list`, optional list of column name strings to read, default all. contenthandler : `~xml.sax.handler.ContentHandler`, optional SAX content handler for parsing LIGO_LW documents. **kwargs other keyword arguments are passed to `~gwpy.io.ligolw.read_ligolw` Returns ------- table : :class:`~ligo.lw.table.Table` `Table` of data """ from ligo.lw.ligolw import Document from ligo.lw import (table, lsctables) # get content handler to read only this table (if given) if tablename is not None: tableclass = lsctables.TableByName[ table.Table.TableName(tablename) ] if contenthandler is None: contenthandler = get_partial_contenthandler(tableclass) # overwrite loading column names to get just what was asked for _oldcols = tableclass.loadcolumns if columns is not None: tableclass.loadcolumns = columns # read document if isinstance(source, Document): xmldoc = source else: if contenthandler is None: contenthandler = default_content_handler() try: xmldoc = read_ligolw( source, contenthandler=contenthandler, **kwargs) finally: # reinstate original set of loading column names if tablename is not None: tableclass.loadcolumns = _oldcols # now find the right table if tablename is None: tables = list_tables(xmldoc) if not tables: raise ValueError("No tables found in LIGO_LW document(s)") if len(tables) > 1: raise ValueError( "Multiple tables found in LIGO_LW document(s), please specify " "the table to read via the ``tablename=`` keyword argument. " "The following tables were found: " "'{}'".format("', '".join(tables)), ) tableclass = lsctables.TableByName[table.Table.TableName(tables[0])] # extract table return tableclass.get_table(xmldoc) # -- writing ------------------------------------------------------------------ def open_xmldoc(fobj, contenthandler=None, **kwargs): """Try and open an existing LIGO_LW-format file, or create a new Document Parameters ---------- fobj : `str`, `file` file path or open file object to read contenthandler : `~xml.sax.handler.ContentHandler`, optional the content handler with which to parse the document, if not given a default handler will be created using :func:`default_content_handler`. **kwargs other keyword arguments to pass to :func:`~ligo.lw.utils.load_fileobj` as appropriate Returns -------- xmldoc : :class:`~ligo.lw.ligolw.Document` either the `Document` as parsed from an existing file, or a new, empty `Document` """ from ligo.lw.ligolw import Document from ligo.lw.utils import load_fileobj if contenthandler is None: contenthandler = default_content_handler() # read from an existing Path/filename if not isinstance(fobj, FILE_LIKE): try: with open(fobj, "rb") as fobj2: return open_xmldoc( fobj2, contenthandler=contenthandler, **kwargs, ) except (OSError, IOError): # or just create a new Document return Document() return load_fileobj( fobj, contenthandler=contenthandler, **kwargs, ) def get_ligolw_element(xmldoc): """Find an existing <LIGO_LW> element in this XML Document """ from ligo.lw.ligolw import (LIGO_LW, WalkChildren) if isinstance(xmldoc, LIGO_LW): return xmldoc for elem in WalkChildren(xmldoc): if isinstance(elem, LIGO_LW): return elem raise ValueError("Cannot find LIGO_LW element in XML Document") def write_tables_to_document(xmldoc, tables, overwrite=False): """Write the given LIGO_LW table into a :class:`Document` Parameters ---------- xmldoc : :class:`~ligo.lw.ligolw.Document` the document to write into tables : `list` of :class:`~ligo.lw.table.Table` the set of tables to write overwrite : `bool`, optional, default: `False` if `True`, delete an existing instance of the table type, otherwise append new rows """ from ligo.lw.ligolw import LIGO_LW from ligo.lw import lsctables # find or create LIGO_LW tag try: llw = get_ligolw_element(xmldoc) except ValueError: llw = LIGO_LW() xmldoc.appendChild(llw) for table in tables: try: # append new data to existing table old = lsctables.TableByName[ table.TableName(table.Name)].get_table(xmldoc) except ValueError: # or create a new table llw.appendChild(table) else: if overwrite: llw.removeChild(old) old.unlink() llw.appendChild(table) else: old.extend(table) return xmldoc def write_tables( target, tables, append=False, overwrite=False, contenthandler=None, **kwargs, ): """Write an LIGO_LW table to file Parameters ---------- target : `str`, `file`, :class:`~ligo.lw.ligolw.Document` the file or document to write into tables : `list`, `tuple` of :class:`~ligo.lw.table.Table` the tables to write append : `bool`, optional, default: `False` if `True`, append to an existing file/table, otherwise `overwrite` overwrite : `bool`, optional, default: `False` if `True`, delete an existing instance of the table type, otherwise append new rows contenthandler : `~xml.sax.handler.ContentHandler`, optional the content handler with which to parse the document, if not given a default handler will be created using :func:`default_content_handler`. **kwargs other keyword arguments to pass to :func:`~ligo.lw.utils.load_fileobj` as appropriate """ from ligo.lw.ligolw import Document, LIGO_LW from ligo.lw import utils as ligolw_utils # allow writing directly to XML if isinstance(target, (Document, LIGO_LW)): xmldoc = target # open existing document, if possible elif append: if contenthandler is None: contenthandler = default_content_handler() xmldoc = open_xmldoc( target, contenthandler=contenthandler, ) # fail on existing document and not overwriting elif ( not overwrite and isinstance(target, (str, os.PathLike)) and os.path.exists(target) ): raise IOError(f"File exists: {target}") else: # or create a new document xmldoc = Document() # convert table to format write_tables_to_document(xmldoc, tables, overwrite=overwrite) # find writer function and target filename if isinstance(target, FILE_LIKE): writer = ligolw_utils.write_fileobj name = target.name else: writer = ligolw_utils.write_filename name = target = str(target) # handle gzip compression kwargs if name.endswith('.gz'): kwargs.setdefault('compress', 'gz') # write XML writer(xmldoc, target, **kwargs) # -- utilities ---------------------------------------------------------------- def iter_tables(source): """Iterate over all tables in the given document(s) Parameters ---------- source : `file`, `str`, :class:`~ligo.lw.ligolw.Document`, `list` one or more open files, file paths, or LIGO_LW `Document`s Yields ------ ligo.lw.table.Table a table structure from the document(s) """ from ligo.lw.ligolw import (Element, Stream, WalkChildren) # get LIGO_LW object if not isinstance(source, Element): filt = get_filtering_contenthandler(Stream) source = read_ligolw(source, contenthandler=filt) llw = get_ligolw_element(source) # yield tables for elem in WalkChildren(llw): if elem.tagName == "Table": yield elem def list_tables(source): """List the names of all tables in this file(s) Parameters ---------- source : `file`, `str`, :class:`~ligo.lw.ligolw.Document`, `list` one or more open files, file paths, or LIGO_LW `Document`s Examples -------- >>> from gwpy.io.ligolw import list_tables >>> print(list_tables('H1-LDAS_STRAIN-968654552-10.xml.gz')) ['process', 'process_params', 'sngl_burst', 'search_summary', 'segment_definer', 'segment_summary', 'segment'] """ # noqa: E501 return [tbl.TableName(tbl.Name) for tbl in iter_tables(source)] def to_table_type(val, cls, colname): """Cast a value to the correct type for inclusion in a LIGO_LW table This method returns the input unmodified if a type mapping for ``colname`` isn't found. Parameters ---------- val : `object` The input object to convert, of any type cls : `type`, subclass of :class:`~ligo.lw.table.Table` the table class to map against colname : `str` The name of the mapping column Returns ------- obj : `object` The input ``val`` cast to the correct type Examples -------- >>> from gwpy.io.ligolw import to_table_type as to_ligolw_type >>> from ligo.lw.lsctables import SnglBurstTable >>> x = to_ligolw_type(1.0, SnglBurstTable, 'central_freq')) >>> print(type(x), x) <class 'numpy.float32'> 1.0 """ from ligo.lw.types import ( ToNumPyType as numpytypes, ToPyType as pytypes, ) # if nothing to do... if val is None or colname not in cls.validcolumns: return val llwtype = cls.validcolumns[colname] # map to numpy or python types try: return numpy.sctypeDict[numpytypes[llwtype]](val) except KeyError: return pytypes[llwtype](val) # -- identify ----------------------------------------------------------------- def is_ligolw(origin, filepath, fileobj, *args, **kwargs): """Identify a file object as LIGO_LW-format XML """ # pylint: disable=unused-argument if fileobj is not None: loc = fileobj.tell() fileobj.seek(0) try: line1 = fileobj.readline().lower() line2 = fileobj.readline().lower() try: return ( line1.startswith(XML_SIGNATURE) and line2.startswith((LIGOLW_SIGNATURE, LIGOLW_ELEMENT)) ) except TypeError: # bytes vs str return ( line1.startswith(XML_SIGNATURE.decode('utf-8')) and line2.startswith(( LIGOLW_SIGNATURE.decode('utf-8'), LIGOLW_ELEMENT.decode('utf-8'), )) ) finally: fileobj.seek(loc) try: from ligo.lw.ligolw import Element except ImportError: return return len(args) > 0 and isinstance(args[0], Element) @deprecated_function def is_xml(origin, filepath, fileobj, *args, **kwargs): # pragma: no cover """Identify a file object as XML (any format) """ # pylint: disable=unused-argument if fileobj is not None: loc = fileobj.tell() fileobj.seek(0) try: sig = fileobj.read(5).lower() return sig == XML_SIGNATURE finally: fileobj.seek(loc) elif filepath is not None: return filepath.endswith(('.xml', '.xml.gz'))
gwpy/gwpy
gwpy/io/ligolw.py
Python
gpl-3.0
22,098
using System.Collections.Generic; using ECCentral.BizEntity.IM; using ECCentral.Service.IM.IDataAccess; using ECCentral.Service.Utility; using ECCentral.Service.Utility.DataAccess; namespace ECCentral.Service.IM.SqlDataAccess { [VersionExport(typeof(IAccessoryDA))] public class AccessoryDA : IAccessoryDA { public AccessoryInfo GetBySysNo(int sysNo) { DataCommand dc = DataCommandManager.GetDataCommand("GetBySysNo"); dc.SetParameterValue("@SysNo", sysNo); return dc.ExecuteEntity<AccessoryInfo>(); } public AccessoryInfo Insert(AccessoryInfo accessoryInfo) { DataCommand dc = DataCommandManager.GetDataCommand("Insert"); dc.SetParameterValue("@SysNo", accessoryInfo.SysNo); dc.SetParameterValue("@AccessoryName", accessoryInfo.AccessoryName.Content); dc.ExecuteNonQuery(); accessoryInfo.SysNo = (int)dc.GetParameterValue("@SysNo"); return accessoryInfo; } public AccessoryInfo Update(AccessoryInfo accessoryInfo) { DataCommand dc = DataCommandManager.GetDataCommand("Update"); dc.SetParameterValue("@SysNo", accessoryInfo.SysNo); dc.SetParameterValue("@AccessoryID", accessoryInfo.SysNo); dc.SetParameterValue("@AccessoryName", accessoryInfo.AccessoryName.Content); dc.ExecuteNonQuery(); return accessoryInfo; } public IList<AccessoryInfo> GetList(string accessoryName) { DataCommand dc = DataCommandManager.GetDataCommand("GetListByAccessoryName"); dc.SetParameterValue("@AccessoryName", accessoryName); return dc.ExecuteEntityList<AccessoryInfo>(); } public IList<AccessoryInfo> GetAll() { DataCommand dc = DataCommandManager.GetDataCommand("GetAll"); return dc.ExecuteEntityList<AccessoryInfo>(); } public IList<AccessoryInfo> GetListByID(string accessoryID) { DataCommand dc = DataCommandManager.GetDataCommand("GetListByID"); dc.SetParameterValue("@AccessoriesID", accessoryID); return dc.ExecuteEntityList<AccessoryInfo>(); } } }
ZeroOne71/ql
02_ECCentral/03_Service/02_IM/ECCentral.Service.IM.SqlDataAccess/AccessoryDA.cs
C#
gpl-3.0
2,285
// -*- C++ -*- /*! * @file SFMLJoystickToVelocityComp.cpp * @brief Standalone component * @date $Date$ * * $Id$ */ #include <rtm/Manager.h> #include <iostream> #include <string> #include <stdlib.h> #include "SFMLJoystickToVelocity.h" void MyModuleInit(RTC::Manager* manager) { SFMLJoystickToVelocityInit(manager); RTC::RtcBase* comp; // Create a component comp = manager->createComponent("SFMLJoystickToVelocity"); if (comp==NULL) { std::cerr << "Component create failed." << std::endl; abort(); } // Example // The following procedure is examples how handle RT-Components. // These should not be in this function. // Get the component's object reference // RTC::RTObject_var rtobj; // rtobj = RTC::RTObject::_narrow(manager->getPOA()->servant_to_reference(comp)); // Get the port list of the component // PortServiceList* portlist; // portlist = rtobj->get_ports(); // getting port profiles // std::cout << "Number of Ports: "; // std::cout << portlist->length() << std::endl << std::endl; // for (CORBA::ULong i(0), n(portlist->length()); i < n; ++i) // { // PortService_ptr port; // port = (*portlist)[i]; // std::cout << "Port" << i << " (name): "; // std::cout << port->get_port_profile()->name << std::endl; // // RTC::PortInterfaceProfileList iflist; // iflist = port->get_port_profile()->interfaces; // std::cout << "---interfaces---" << std::endl; // for (CORBA::ULong i(0), n(iflist.length()); i < n; ++i) // { // std::cout << "I/F name: "; // std::cout << iflist[i].instance_name << std::endl; // std::cout << "I/F type: "; // std::cout << iflist[i].type_name << std::endl; // const char* pol; // pol = iflist[i].polarity == 0 ? "PROVIDED" : "REQUIRED"; // std::cout << "Polarity: " << pol << std::endl; // } // std::cout << "---properties---" << std::endl; // NVUtil::dump(port->get_port_profile()->properties); // std::cout << "----------------" << std::endl << std::endl; // } return; } int main (int argc, char** argv) { RTC::Manager* manager; manager = RTC::Manager::init(argc, argv); // Initialize manager manager->init(argc, argv); // Set module initialization proceduer // This procedure will be invoked in activateManager() function. manager->setModuleInitProc(MyModuleInit); // Activate manager and register to naming service manager->activateManager(); // run the manager in blocking mode // runManager(false) is the default. manager->runManager(); // If you want to run the manager in non-blocking mode, do like this // manager->runManager(true); return 0; }
sugarsweetrobotics/SFMLJoystickToVelocity
src/SFMLJoystickToVelocityComp.cpp
C++
gpl-3.0
2,659
################################################################################# # Copyright 2014 See AUTHORS file. # # Licensed under the GNU General Public License Version 3.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.gnu.org/licenses/gpl-3.0.txt # # 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. ################################################################################# bl_info = { "name": "LibGDX G3D Exporter", "author": "Danilo Costa Viana", "blender": (2,6,9), "version": (0,1,0), "location": "File > Import-Export", "description": "Export scene to G3D (LibGDX) format", "category": "Import-Export" } import bpy from io_scene_g3d.export_g3d import G3DExporter class Mesh(object): def __init__(self, s): self.s = s def __repr__(self): return '<Mesh(%s)>' % self.s def menu_func(self, context): self.layout.operator(G3DExporter.bl_idname, text="LibGDX G3D text format (.g3dj)") def register(): bpy.utils.register_module(__name__) bpy.types.INFO_MT_file_export.append(menu_func) def unregister(): bpy.utils.unregister_module(__name__) bpy.types.INFO_MT_file_export.remove(menu_func) if __name__ == "__main__": register()
blackears/libgdx_blender_g3d_exporter
io_scene_g3d/__init__.py
Python
gpl-3.0
1,616
# # Copyright 2017 Russell Smiley # # This file is part of timetools. # # timetools is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # timetools is distributed in the hope that it will be useful # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with timetools. If not, see <http://www.gnu.org/licenses/>. # import numpy import unittest import timetools.signalProcessing.tolerance as spt import timetools.synchronization.intervals as si class TestIntervals (unittest.TestCase): def testCalculateLogIntervalScale1 (self): minValue = 10 maxValue = 120 numberPoints = 11 result = si.generateLogIntervalScale(minValue, maxValue, numberPoints) self.assertTrue(len(result) == numberPoints, 'Result does not have correct length') minValueTolerance = spt.ToleranceValue(minValue, 0.1, spt.ToleranceUnit['percent']) maxValueTolerance = spt.ToleranceValue(maxValue, 0.1, spt.ToleranceUnit['percent']) self.assertTrue((minValueTolerance.isWithinTolerance(result[0]) and maxValueTolerance.isWithinTolerance(result[-1])), 'Incorrect endpoints') # A logarithmic sequence will be evenly spaced in the logarithmic domain logIntervals = numpy.diff(numpy.log10(result)) intervalTolerance = spt.ToleranceValue(numpy.mean(logIntervals), 0.1, spt.ToleranceUnit['percent']) self.assertTrue(numpy.all(intervalTolerance.isWithinTolerance(logIntervals)), 'Intervals are not logarithmic') def testGenerateMonotonicLogScale1 (self): minValue = 10 maxValue = 25 numberPoints = 12 expectedSequence = numpy.array([10, 11, 12, 13, 14, 15, 16, 17, 19, 21, 23, 25]) thisArray = si.generateLogIntervalScale(minValue, maxValue, numberPoints) thisIntegerArray = numpy.floor(thisArray) monotonicIntervals = si.generateMonotonicLogScale(thisIntegerArray) self.assertTrue(isinstance(monotonicIntervals[0], numpy.intp), '') self.assertTrue(len(monotonicIntervals) == len(expectedSequence), 'Incorrect length of monotonic sequence') self.assertTrue(numpy.all(monotonicIntervals == expectedSequence), 'Monotonicity failed') if __name__ == "__main__": unittest.main()
blueskyjunkie/timeTools
timetools/synchronization/tests/testIntervals.py
Python
gpl-3.0
2,719
#include <bits/stdc++.h> using namespace std; const int maxn = 25; const int maxs = 4099; int n, bcnt[maxs], n1, n2; int a[maxn]; char cht[maxs]; map<int, int> val; int main() { bcnt[0] = 0; for (int i = 1; i < maxs; ++i) bcnt[i] = bcnt[i >> 1] + (i & 1); while (scanf("%d", &n) == 1) { val.clear(); for (int i = 0; i < n; ++i) { a[i] = 0; scanf("%s", cht); for (char *c = cht; *c; ++c) { int x = *c - 'A'; a[i] ^= (1 << x); } } n1 = n >> 1; n2 = n - n1; for (int S = 0; S < (1 << n1); ++S) { int xsum = 0; for (int i = 0; i < n1; ++i) { if (S & (1 << i)) xsum ^= a[i]; } if (!val.count(xsum)) val[xsum] = S; else if (bcnt[S] > bcnt[val[xsum]]) val[xsum] = S; } int best = 0, ans = 0; for (int T = 0; T < (1 << n); T += (1 << n1)) { int xsum = 0; for (int i = n1; i < n; ++i) { if (T & (1 << i)) xsum ^= a[i]; } if (!val.count(xsum)) continue; int S = val[xsum]; int cur = bcnt[S] + bcnt[T >> n1]; if (cur > best) { best = cur; ans = S ^ T; } } printf("%d\n", best); bool flag = false; for (int i = 0; i < n; ++i) { if (ans & (1 << i)) { if (flag) putchar(' '); printf("%d", i + 1); flag = true; } } putchar('\n'); } return 0; }
Chrogeek/chrogeek-noi
LA 2965 Jurassic Remains/la2965.cpp
C++
gpl-3.0
1,257
<?php /** * This file is part of Mbiz_RobotsTxt for Magento. * * @license All rights reserved. * @author Léo Peltier <l.peltier@monsieurbiz.com> * @category Mbiz * @package Mbiz_RobotsTxt * @copyright Copyright (c) 2013 Monsieur Biz (http://monsieurbiz.com/) */ class Mbiz_RobotsTxt_Model_RobotsTxt extends Mage_Core_Model_Config_Data { /** * @return string robots.txt file path. */ protected function getRobotsTxtPath() { return Mage::getBaseDir('base') . '/robots.txt'; } /** * Rewrite robots.txt when the configuration is saved. */ protected function _beforeSave() { parent::_beforeSave(); $contents = $this->getValue(); $ret = file_put_contents($this->getRobotsTxtPath(), $contents); if ($ret === false) { throw new Exception('Failed to write robots.txt.'); } return $this; } /** * Load the value directly from the robots.txt file. * * If the file does not exist, discard what is in the magento config and * load an empty string. */ protected function _afterLoad() { parent::_afterLoad(); $path = $this->getRobotsTxtPath(); if(file_exists($path)) { $this->setValue(file_get_contents($path)); } else { $this->setValue(''); } } }
monsieurbiz/Mbiz_RobotsTxt
app/code/community/Mbiz/RobotsTxt/Model/RobotsTxt.php
PHP
gpl-3.0
1,375
// Copyright 2009-2014 Josh Close and Contributors // This file is a part of CsvHelper and is licensed under the MS-PL // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html // http://csvhelper.com using System; using System.IO; using CsvHelper.Configuration; #if WINRT_4_5 using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #else using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace CsvHelper.Tests { [TestClass] public class CsvParserConstructorTests { [TestMethod] public void EnsureInternalsAreSetupWhenPassingReaderAndConfigTest() { using( var stream = new MemoryStream() ) using( var reader = new StreamReader( stream ) ) { var config = new CsvConfiguration(); using( var parser = new CsvParser( reader, config ) ) { Assert.AreSame( config, parser.Configuration ); } } } } }
worldexplorer/SquareOne
CsvHelper261-master/src/CsvHelper.Tests/CsvParserConstructorTests.cs
C#
gpl-3.0
920
/* * example_fdtd_2dte_lence.cpp * * Created on: Nov 2, 2016 * Author: Dr. Yevgeniy Kolokoltsev */ #include <iostream> #include <cmath> #include <algorithm> #include <memory> #include "../../lib_fdtd/advanced/example_fdtd_2nd_mur.hpp" #include "../../lib_fdtd/diplay/em_field_intensity_display.hpp" using namespace std; class ExDifInt : public ExFDTD2ndTEMur { public: using tBase = ExFDTD2ndTEMur; using tCell = tBase::tCell; using tSourceBase = typename tBase::tSourceBase; using tInit = tBase::tInit; ExDifInt(tInit ti) : tBase(ti){ double lda = 20*dl; // = Vg*T = 2pi/w double Vg = 1; double w = 2*M_PI*Vg/(lda); sources.clear(); sources.resize(Ny); int Cy1 = Ny/2.0 + Ny/8.0; int Cy2 = Ny/2.0 - Ny/8.0; for(int j = 0; j < Ny; j++){ for(int i = 0; i < Nx; i++){ if(i >= Nx/5 && i <= (Nx/5+1)){ if(!((j >= Cy1-2 && j <= Cy1+2) || (j >= Cy2-2 && j <= Cy2+2)) && (j >= 3 && j <=Ny-3)) field[i][j].c.eps = 100; } } double mag = GaussianMag(lda,0, 2*dl, j*dl, 2*dl, dl*Ny/2, lda); sources[j] = shared_ptr<tSourceBase>((tSourceBase*)new SinSource<Plain2DIndex>(w,mag)); sources[j]->i = 2; sources[j]->j = j; } }; private: tContainer &field = tBase::container; vector<shared_ptr<tSourceBase>> &sources = tBase::sources; }; int main(int argc, char **argv){ shared_ptr<ExDifInt> field(new ExDifInt(ExDifInt::tInit{400,200})); Window w(unique_ptr<LogEnergyDensityDisplay<ExDifInt>>(new LogEnergyDensityDisplay<ExDifInt>(field))); w.create_window(600,300); while(1){ if(!w.is_running()) break; field->evaluate(); } std::cout << "exit" << std::endl; return 0; }
YKolokoltsev/CompPhysFWK
src/examples/fdtd/diafragm.cpp
C++
gpl-3.0
1,657
<?php include("inc/database.php"); ?> <!DOCTYPE html> <html> <head> <title>PRO Rank Tracker</title> <link rel="stylesheet" type="text/css" href="css/track.css"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/graphs.js"></script> <script type="text/javascript" src="js/graphcat.js"></script> <script type="text/javascript"> $(function() { var rank = [ <?php function array_s($arr, $keyword) { foreach($arr as $index => $string) { if (strpos($string, $keyword) !== FALSE) return $index; } } function do_getdata($database, $nickname, $cat) { $stmt = $database->prepare("SELECT `rdata` FROM `track_new` WHERE `rtype` = '$cat' AND `nickname` = '$nickname'"); $stmt->execute(); if($stmt->rowCount() < 1){ return -1; } else{ $rank = $stmt->fetch(PDO::FETCH_OBJ); return $rank->rdata; } } if(!isset($_GET['u']) && !isset($_GET['c'])){ die(""); } else{ $rank_raw = do_getdata($bd, $_GET['u'], $_GET['c']); if($rank_raw == -1){ die(""); } else{ $rank_pt1 = explode("!", $rank_raw); date_default_timezone_set('UTC'); $rank_dte = date("j/n/y"); $rank_dte = date("j/n/y"); $rank_pos = array_s($rank_pt1, $rank_dte); $rank_pt2 = explode("|", $rank_pt1[$rank_pos]); $rank_pt3 = explode("#", $rank_pt2[1]); foreach($rank_pt3 as $rank_hdt){ $rank_pt4 = explode("-", $rank_hdt); echo '["'.$rank_pt4[0].'", '.$rank_pt4[1].'],'; } } } ?> ]; $.plot("#rankholder", [ rank ], { xaxis: { mode: "categories" }, grid: { hoverable: true }, yaxis: { tickDecimals: 0, min: 1, max: 25, ticks: 10, transform: function (v) { return -v; }, inverseTransform: function (v) { return -v; } } } ); }); </script> </head> <body> <?php if($_GET['c'] > 2){ date_default_timezone_set('UTC'); echo ' <span class="font12">'.$_GET['u'].' Rank data</span><br> <span class="font22">'.date("F, d").' - PRO Servertime</span><br><br> <div id="rankholder"></div> '; } else{ date_default_timezone_set('UTC'); echo ' <span class="font1">'.$_GET['u'].' Rank data</span><br> <span class="font2">'.date("F, d").' - PRO Servertime</span><br><br> <div id="rankholder"></div> '; } ?> </body> </html>
XTWebdesign/PRORanking
track.php
PHP
gpl-3.0
2,706
package de.upb.reconos.grasp.gui.menus; import java.awt.event.ActionEvent; import de.upb.reconos.grasp.objects.StateMachineNode; import de.upb.reconos.grasp.objects.World; public class StateMachineMenu extends BasicMenu { private static final long serialVersionUID = 1L; private StateMachineNode node; public StateMachineMenu(World w){ super(w); addItem("New State"); addItem("New Signal"); addItem("New Port"); addSeparator(); addItem("Remove This State Machine"); addSeparator(); addItem("Options"); } public void setStateMachineNode(StateMachineNode n){ node = n; } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand().toLowerCase(); double wx = worldPosition.getX(); double wy = worldPosition.getY(); if(cmd.equals("new state")){ world.createStateNode(node, wx,wy); } if(cmd.equals("new signal")){ world.createSignalNode(node, wx,wy); } if(cmd.equals("new port")){ world.createPortNode(node, wx,wy); } if(cmd.equals("remove this state machine")){ world.dissolve(node); node = null; } } }
luebbers/reconos
attic/tools/java/grasp/de/upb/reconos/grasp/gui/menus/StateMachineMenu.java
Java
gpl-3.0
1,096
from Collisions.Collidable import Collidable from Collisions.TypeBasedCollision import TypeBasedCollision from Drawing.Drawable import Drawable from Drawing.DrawPlatform import DrawPlatform from Movement.Movable import Movable, Movable2D from Movement.State import State2D from Utility.Entity import Entity ################################################################################ ################################################################################ class Platform(Entity, Movable, Drawable, Collidable): ############################################################################## def __init__(self, Window, xPosition, yPosition, TileType, Length = 1): Entity.__init__(self) InitialState = \ State2D(xPosition, yPosition, Width = Length * 64, Height = 64) Movable.__init__(self, Movable2D(InitialState)) DrawFunctor = \ DrawPlatform(Window, "Images/platformPack/PNG/Tiles/" + TileType, Length) Drawable.__init__(self, DrawFunctor, InitialState) Collidable.__init__(self, TypeBasedCollision(), InitialState) ################################################################################ ################################################################################
dloman/FiestaMonsterz
Entities/Platform.py
Python
gpl-3.0
1,236
/*********************************************************** * Programming Assignment 3 * * Distance program * * Programmer: Mark Eatough * * Course: CS1410 * * Created February 28, 2012 * * Modified March 6, 2012 * * Modified by Mark Eatough * ***********************************************************/ import java.util.Scanner; public class Trapezoid extends Quadrilateral { Scanner input = new Scanner(System.in); public double side1; public double side2; public double side3; public double side4; public double height; double area; public Trapezoid() //default constructor { } public Trapezoid(double s1, double s2, double s3, double s4, double h) //parameterized constructor { side1 = s1; side2 = s2; side3 = s3; side4 = s4; height = h; } public void buildTrapezoid() //Need Trig HERE!!! { System.out.printf("Enter length of larger base "); side1 = input.nextDouble(); System.out.printf("enter length of smaller base "); side3 = input.nextDouble(); System.out.printf("enter length of right side "); side2 = input.nextDouble(); System.out.printf("enter length of left side "); side4 = input.nextDouble(); System.out.printf("enter height less than or equal to shorter of the 2 sides "); height = input.nextDouble(); } public void trapezoidPoints() { point2X = side1; point3X = side1 - Math.sqrt(side2*side2 - height*height); point3Y = height; point4X = Math.sqrt(side4*side4 - height*height); point4Y = height; System.out.printf("\n\nThe four points of Trapezoid are: (%.1f, %.1f) (%.1f, %.1f) (%.1f, %.1f) (%.1f, %.1f)\n\n\n", point1X, point1Y, point2X, point2Y,point3X, point3Y, point4X, point4Y); } public void trapezoidArea() { area = (0.5)*(side1 + side3)*height; System.out.printf("Area = %.2f", area); } }
meatough/Marks-Programs
cs 1410/Assignment 3/Trapezoid.java
Java
gpl-3.0
1,914
#include <ros/ros.h> #include <std_msgs/String.h> #include <stdio.h> #include "geometry_msgs/PoseStamped.h" #include "geometry_msgs/Vector3Stamped.h" #include <mavros_msgs/SetMode.h> #include <mavros_msgs/State.h> #include <apriltags/AprilTagDetections.h> #include <mavros_msgs/CommandBool.h> geometry_msgs::PoseStamped CurrentPoseStamped; void AprilMessageReceived(const apriltags::AprilTagDetections& detectionsMsg); void AprilMessageReceived(const apriltags::AprilTagDetections& detectionsMsg) { CurrentPoseStamped.header = detectionsMsg.header; CurrentPoseStamped.pose.position.x = -detectionsMsg.detections[0].pose.position.x; CurrentPoseStamped.pose.position.y = detectionsMsg.detections[0].pose.position.y; CurrentPoseStamped.pose.position.z = detectionsMsg.detections[0].pose.position.z; CurrentPoseStamped.pose.orientation.x = detectionsMsg.detections[0].pose.orientation.w; CurrentPoseStamped.pose.orientation.y = -detectionsMsg.detections[0].pose.orientation.z; CurrentPoseStamped.pose.orientation.z = detectionsMsg.detections[0].pose.orientation.y; CurrentPoseStamped.pose.orientation.w = detectionsMsg.detections[0].pose.orientation.x; } int main(int argc, char **argv) { ros::init(argc, argv, "hover"); ros::NodeHandle n; ros::NodeHandle n_apriltags; ros::Publisher chatter_pub = n.advertise<geometry_msgs::PoseStamped>("/mavros/setpoint_position/local",100); ros::Publisher current_pub = n.advertise<geometry_msgs::PoseStamped>("/mavros/mocap/pose",100); ros::Subscriber sub_apriltags = n_apriltags.subscribe("/apriltags/detections", 1000, &AprilMessageReceived); ros::ServiceClient set_mode_client = n.serviceClient<mavros_msgs::SetMode>("mavros/set_mode"); ros::Rate loop_rate(100); ros::spinOnce(); geometry_msgs::PoseStamped msg; int count = 1; while(ros::ok()){ msg.header.stamp = ros::Time::now(); msg.header.seq=count; msg.header.frame_id = 1; msg.pose.position.x = 0.0; msg.pose.position.y = 0.0; msg.pose.position.z = 1.0; msg.pose.orientation.x = 0; msg.pose.orientation.y = 0; msg.pose.orientation.z = 0; msg.pose.orientation.w = 1; if(count == 100) { mavros_msgs::SetMode offb_set_mode; offb_set_mode.request.custom_mode = "OFFBOARD"; ROS_INFO("OFFBOARD mode set"); mavros_msgs::CommandBool arm_cmd; arm_cmd.request.value = true; } chatter_pub.publish(msg); current_pub.publish(CurrentPoseStamped); ros::spinOnce(); count++; loop_rate.sleep(); } return 0; }
chickonice/AutonomousFlight
px4_new_ws/src/px4_nav/src/hover.cpp
C++
gpl-3.0
2,676
/* * Copyright (C) 2017 Oasis Feng. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oasisfeng.condom; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.content.Context; import android.content.ContextWrapper; import android.os.Handler; import android.os.Looper; import android.os.Process; import android.support.test.InstrumentationRegistry; import android.telephony.TelephonyManager; import com.oasisfeng.condom.kit.NullDeviceIdKit; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.READ_PHONE_STATE; import static android.Manifest.permission.WRITE_SECURE_SETTINGS; import static android.Manifest.permission.WRITE_SETTINGS; import static android.content.pm.PackageManager.PERMISSION_DENIED; import static android.content.pm.PackageManager.PERMISSION_GRANTED; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.M; import static android.os.Build.VERSION_CODES.O; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * Test cases for {@link CondomKit} * * Created by Oasis on 2017/7/22. */ public class CondomKitTest { @Test public void testBasicKit() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { final ActivityManager am = createActivityManager(context); final CondomOptions option = new CondomOptions().addKit(new CondomKit() { @Override public void onRegister(final CondomKitRegistry registry) { registry.registerSystemService(Context.ACTIVITY_SERVICE, new SystemServiceSupplier() { @Override public Object getSystemService(final Context context, final String name) { return am; }}); registry.addPermissionSpoof(WRITE_SETTINGS); registry.addPermissionSpoof(ACCESS_COARSE_LOCATION); }}); final CondomContext condom = CondomContext.wrap(new ContextWrapper(context), "KitTest", option); assertEquals(am, condom.getSystemService(Context.ACTIVITY_SERVICE)); assertEquals(am, condom.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE)); Assert.assertNotNull(condom.getSystemService(Context.NOTIFICATION_SERVICE)); // Service not registered in kit assertPermission(condom, WRITE_SETTINGS, true); assertPermission(condom.getApplicationContext(), WRITE_SETTINGS, true); assertPermission(condom, ACCESS_COARSE_LOCATION, true); assertPermission(condom.getApplicationContext(), ACCESS_COARSE_LOCATION, true); assertPermission(condom, WRITE_SECURE_SETTINGS, false); // Permission not registered to spoof in kit assertPermission(condom.getApplicationContext(), WRITE_SECURE_SETTINGS, false); } @Test @SuppressLint("HardwareIds") public void testNullDeviceIdKit() { final CondomContext condom = CondomContext.wrap(new ContextWrapper(context), "NullDeviceId", new CondomOptions().addKit(new NullDeviceIdKit())); final TelephonyManager tm = (TelephonyManager) condom.getSystemService(Context.TELEPHONY_SERVICE); assertTrue(condom.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE).getClass().getName().startsWith(NullDeviceIdKit.class.getName())); assertPermission(condom, READ_PHONE_STATE, true); assertNull(tm.getDeviceId()); if (SDK_INT >= M) assertNull(tm.getDeviceId(0)); assertNull(tm.getImei()); assertNull(tm.getImei(0)); if (SDK_INT >= O) assertNull(tm.getMeid()); if (SDK_INT >= O) assertNull(tm.getMeid(0)); assertNull(tm.getSimSerialNumber()); assertNull(tm.getLine1Number()); assertNull(tm.getSubscriberId()); } private static void assertPermission(final Context context, final String permission, final boolean granted) { final int state = granted ? PERMISSION_GRANTED : PERMISSION_DENIED; assertEquals(state, context.checkPermission(permission, Process.myPid(), Process.myUid())); if (SDK_INT >= M) assertEquals(state, context.checkSelfPermission(permission)); } private static ActivityManager createActivityManager(final Context context) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { final Constructor<ActivityManager> am_constructor = ActivityManager.class.getDeclaredConstructor(Context.class, Handler.class); am_constructor.setAccessible(true); return am_constructor.newInstance(context, new Handler(Looper.getMainLooper())); } private final Context context = InstrumentationRegistry.getTargetContext(); }
Trumeet/MiPushFramework
condom/src/androidTest/java/com/oasisfeng/condom/CondomKitTest.java
Java
gpl-3.0
5,252
<?php /** --------------------------------------------------------------------- * app/lib/Plugins/Media/Audio.php : * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2006-2020 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * @package CollectiveAccess * @subpackage Media * @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3 * * ---------------------------------------------------------------------- */ /** * */ /** * Plugin for processing audio media using ffmpeg */ include_once(__CA_LIB_DIR__."/Plugins/Media/BaseMediaPlugin.php"); include_once(__CA_LIB_DIR__."/Plugins/IWLPlugMedia.php"); include_once(__CA_LIB_DIR__."/Configuration.php"); include_once(__CA_APP_DIR__."/helpers/mediaPluginHelpers.php"); include_once(__CA_APP_DIR__."/helpers/avHelpers.php"); include_once(__CA_APP_DIR__."/helpers/utilityHelpers.php"); include_once(__CA_LIB_DIR__."/Parsers/OggParser.php"); class WLPlugMediaAudio Extends BaseMediaPlugin Implements IWLPlugMedia { var $errors = array(); var $filepath; var $handle; var $ohandle; var $properties; var $oproperties; var $metadata = array(); var $input_bitrate; var $input_channels; var $input_sample_frequency; var $opo_config; var $ops_path_to_ffmpeg; var $ops_mediainfo_path; var $info = array( "IMPORT" => array( "audio/mpeg" => "mp3", "audio/x-aiff" => "aiff", "audio/wav" => "wav", "audio/x-wav" => "wav", "audio/x-wave" => "wav", "audio/mp4" => "aac", "audio/ogg" => "ogg", "audio/x-flac" => "flac" ), "EXPORT" => array( "audio/mpeg" => "mp3", "audio/x-aiff" => "aiff", "audio/wav" => "wav", "audio/x-wav" => "wav", "audio/x-wave" => "wav", "audio/mp4" => "aac", "video/x-flv" => "flv", "image/png" => "png", "image/jpeg" => "jpg", "audio/ogg" => "ogg", "audio/x-flac" => "flac" ), "TRANSFORMATIONS" => array( "SET" => array("property", "value"), "SCALE" => array("width", "height", "mode", "antialiasing"), "ANNOTATE" => array("text", "font", "size", "color", "position", "inset"), // dummy "WATERMARK" => array("image", "width", "height", "position", "opacity"), // dummy "INTRO" => array("filepath"), "OUTRO" => array("filepath") ), "PROPERTIES" => array( "width" => 'W', "height" => 'W', "version_width" => 'R', // width version icon should be output at (set by transform()) "version_height" => 'R', // height version icon should be output at (set by transform()) "intro_filepath" => 'R', "outro_filepath" => 'R', "mimetype" => 'R', "typename" => 'R', "bandwidth" => 'R', "title" => 'R', "author" => 'R', "copyright" => 'R', "description" => 'R', "duration" => 'R', "filesize" => 'R', "getID3_tags" => 'W', 'colorspace' => 'W', "quality" => "W", // required for JPEG compatibility "bitrate" => 'W', // in kbps (ex. 64) "channels" => 'W', // 1 or 2, typically "sample_frequency" => 'W', // in khz (ex. 44100) "version" => 'W' // required of all plug-ins ), "NAME" => "Audio", "NO_CONVERSION" => 0 ); var $typenames = array( "audio/mpeg" => "MPEG-3", "audio/x-aiff" => "AIFF", "audio/x-wav" => "WAV", "audio/x-wave" => "WAV", "audio/wav" => "WAV", "audio/mp4" => "AAC", "image/png" => "PNG", "image/jpeg" => "JPEG", "audio/ogg" => "Ogg Vorbis", "audio/x-flac" => "FLAC" ); # # Alternative extensions for supported types # var $alternative_extensions = [ 'aif' => 'audio/x-aiff', 'wave' => "audio/x-wave" ]; # ------------------------------------------------ public function __construct() { $this->description = _t('Provides audio processing and conversion using ffmpeg'); } # ------------------------------------------------ # Tell WebLib what kinds of media this plug-in supports # for import and export public function register() { $this->opo_config = Configuration::load(); $this->ops_path_to_ffmpeg = caMediaPluginFFmpegInstalled(); $this->ops_mediainfo_path = caMediaInfoInstalled(); $this->info["INSTANCE"] = $this; return $this->info; } # ------------------------------------------------ public function checkStatus() { $va_status = parent::checkStatus(); $this->register(); $va_status['available'] = true; if (!$this->ops_path_to_ffmpeg) { $va_status['errors'][] = _t("Incoming audio files will not be transcoded because ffmpeg is not installed."); } if ($this->ops_mediainfo_path) { $va_status['notices'][] = _t("MediaInfo will be used to extract metadata from audio files."); } return $va_status; } # ------------------------------------------------ public function divineFileFormat($filepath) { $ID3 = new getID3(); $info = $ID3->analyze($filepath); if (($info['fileformat'] == 'riff') && (!isset($info['video']))) { if (isset($info['audio']['dataformat']) && ($info['audio']['dataformat'] == 'wav')) { $info['mime_type'] = 'audio/x-wav'; } } if ( ($info['fileformat'] == 'quicktime') && ($info['audio']['codec'] == 'Fraunhofer MPEG Layer-III alias') && ($info['video']['resolution_x'] == 0) && ($info['video']['resolution_y'] == 0) ) { // Quicktime-wrapped MP3 $info['mime_type'] = 'audio/mpeg'; } if (in_array(strtolower(trim($info["mime_type"])), ['audio/wave', 'audio/wav', 'audio/x-wave'], true)) { $info["mime_type"] = 'audio/x-wav'; } if (($info["mime_type"]) && isset($this->info["IMPORT"][$info["mime_type"]]) && $this->info["IMPORT"][$info["mime_type"]]) { $this->handle = $this->ohandle = $info; $this->metadata = $info; // populate with getID3 data because it's handy return $info["mime_type"]; } else { // is it Ogg? $info = new OggParser($filepath); if (!$info->LastError && is_array($info->Streams) && (sizeof($info->Streams) > 0)) { if (!isset($info->Streams['theora'])) { $this->handle = $this->ohandle = $info->Streams; return $this->handle['mime_type'] = 'audio/ogg'; } } # file format is not supported by this plug-in return ""; } } # ---------------------------------------------------------- public function get($property) { if ($this->handle) { if ($this->info["PROPERTIES"][$property]) { return $this->properties[$property]; } else { print "Invalid property '$property'"; return ""; } } else { return ""; } } # ---------------------------------------------------------- public function set($property, $value) { if ($this->handle) { if ($this->info["PROPERTIES"][$property]) { switch($property) { default: if ($this->info["PROPERTIES"][$property] == 'W') { $this->properties[$property] = $value; } else { # read only return ""; } break; } } else { # invalid property $this->postError(1650, _t("Can't set property %1", $property), "WLPlugAudio->set()"); return ""; } } else { return ""; } } # ------------------------------------------------ /** * Returns array of extracted metadata, key'ed by metadata type or empty array if plugin doesn't support metadata extraction * * @return Array Extracted metadata */ public function getExtractedMetadata() { return $this->metadata; } # ------------------------------------------------ public function read ($filepath, $mimetype="", $options=null) { if (!file_exists($filepath)) { $this->postError(1650, _t("File %1 does not exist", $filepath), "WLPlugAudio->read()"); $this->handle = ""; $this->filepath = ""; return false; } if (!(($this->handle) && ($this->handle["filepath"] == $filepath))) { $ID3 = new getid3(); $info = $ID3->analyze($filepath); if ($info["mime_type"] === 'audio/x-wave') { $info["mime_type"] = 'audio/x-wav'; } if ( ($info['fileformat'] == 'quicktime') && ($info['audio']['codec'] == 'Fraunhofer MPEG Layer-III alias') && ($info['video']['resolution_x'] == 0) && ($info['video']['resolution_y'] == 0) ) { // Quicktime-wrapped MP3 $info['mime_type'] = 'audio/mpeg'; } $this->handle = $this->ohandle = $info; if($this->ops_mediainfo_path){ $this->metadata = caExtractMetadataWithMediaInfo($filepath); } else { $this->metadata = $this->handle; } if (!$this->handle['mime_type']) { // is it Ogg? $info = new OggParser($filepath); if (!$info->LastError) { if (!isset($info->Streams['theora'])) { $this->handle = $this->ohandle = $info->Streams; $this->handle['mime_type'] = 'audio/ogg'; $this->handle['playtime_seconds'] = $this->handle['duration']; } } } } if (!((isset($this->handle["error"])) && (is_array($this->handle["error"])) && (sizeof($this->handle["error"]) > 0))) { $this->filepath = $filepath; //$this->properties = $this->handle; $this->properties = []; $this->properties["mimetype"] = $this->handle["mime_type"]; $this->properties["typename"] = $this->typenames[$this->properties["mimetype"]] ? $this->typenames[$this->properties["mimetype"]] : "Unknown"; $this->properties["duration"] = $this->handle["playtime_seconds"]; $this->properties["filesize"] = filesize($filepath); switch($this->properties["mimetype"]) { case 'audio/mpeg': if (is_array($this->handle["tags"]["id3v1"]["title"])) { $this->properties["title"] = join("; ",$this->handle["tags"]["id3v1"]["title"]); } if (is_array($this->handle["tags"]["id3v1"]["artist"])) { $this->properties["author"] = join("; ",$this->handle["tags"]["id3v1"]["artist"]); } if (is_array($this->handle["tags"]["id3v1"]["comment"])) { $this->properties["copyright"] = join("; ",$this->handle["tags"]["id3v1"]["comment"]); } if ( (is_array($this->handle["tags"]["id3v1"]["album"])) && (is_array($this->handle["tags"]["id3v1"]["year"])) && (is_array($this->handle["tags"]["id3v1"]["genre"]))) { $this->properties["description"] = join("; ",$this->handle["tags"]["id3v1"]["album"])." ".join("; ",$this->handle["tags"]["id3v1"]["year"])." ".join("; ",$this->handle["tags"]["id3v1"]["genre"]); } $this->properties["type_specific"] = array("audio" => $this->handle["audio"], "tags" => $this->handle["tags"]); $this->properties["bandwidth"] = array("min" => $this->handle["bitrate"], "max" => $this->handle["bitrate"]); $this->properties["getID3_tags"] = $this->handle["tags"]; $this->properties["bitrate"] = $input_bitrate = $this->handle["bitrate"]; $this->properties["channels"] = $input_channels = $this->handle["audio"]["channels"]; $this->properties["sample_frequency"] = $input_sample_frequency = $this->handle["audio"]["sample_rate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; case 'audio/x-aiff': $this->properties["type_specific"] = array("audio" => $this->handle["audio"], "riff" => $this->handle["riff"]); $this->properties["bandwidth"] = array("min" => $this->handle["bitrate"], "max" => $this->handle["bitrate"]); $this->properties["getID3_tags"] = array(); $this->properties["bitrate"] = $input_bitrate = $this->handle["bitrate"]; $this->properties["channels"] = $input_channels = $this->handle["audio"]["channels"]; $this->properties["sample_frequency"] = $input_sample_frequency = $this->handle["audio"]["sample_rate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; case 'audio/x-flac': $this->properties["type_specific"] = array(); $this->properties["audio"] = $this->handle["audio"]; $this->properties["bandwidth"] = array("min" => $this->handle["bitrate"], "max" => $this->handle["bitrate"]); $this->properties["getID3_tags"] = array(); $this->properties["bitrate"] = $input_bitrate = $this->handle["bitrate"]; $this->properties["channels"] = $input_channels = $this->handle["audio"]["channels"]; $this->properties["sample_frequency"] = $this->handle["audio"]["sample_rate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; case 'audio/x-wav': $this->properties["type_specific"] = array(); $this->properties["audio"] = $this->handle["audio"]; $this->properties["bandwidth"] = array("min" => $this->handle["bitrate"], "max" => $this->handle["bitrate"]); $this->properties["getID3_tags"] = array(); $this->properties["bitrate"] = $input_bitrate = $this->handle["bitrate"]; $this->properties["channels"] = $input_channels = $this->handle["audio"]["channels"]; $this->properties["sample_frequency"] = $this->handle["audio"]["sample_rate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; case 'audio/mp4': $this->properties["type_specific"] = array(); $this->properties["audio"] = $this->handle["audio"]; $this->properties["bandwidth"] = array("min" => $this->handle["bitrate"], "max" => $this->handle["bitrate"]); $this->properties["getID3_tags"] = array(); $this->properties["bitrate"] = $input_bitrate = $this->handle["bitrate"]; $this->properties["channels"] = $input_channels = $this->handle["audio"]["channels"]; $this->properties["sample_frequency"] = $input_sample_frequency = $this->handle["audio"]["sample_rate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; case 'audio/ogg': $this->properties["type_specific"] = array(); $this->properties["audio"] = $this->handle['vorbis']; $this->properties["bandwidth"] = array("min" => $this->handle['vorbis']['bitrate'], "max" => $this->handle['vorbis']['bitrate']); $this->properties["getID3_tags"] = array(); $this->properties["bitrate"] = $input_bitrate = $this->handle['vorbis']['bitrate']; $this->properties["channels"] = $input_channels = $this->handle["vorbis"]["channels"]; $this->properties["sample_frequency"] = $input_sample_frequency = $this->handle["vorbis"]["samplerate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; } $this->oproperties = $this->properties; return 1; } else { $this->postError(1650, join("; ", $this->handle["error"]), "WLPlugAudio->read()"); $this->handle = ""; $this->filepath = ""; return false; } } # ---------------------------------------------------------- public function transform($operation, $parameters) { if (!$this->handle) { return false; } if (!($this->info["TRANSFORMATIONS"][$operation])) { # invalid transformation $this->postError(1655, _t("Invalid transformation %1", $operation), "WLPlugAudio->transform()"); return false; } # get parameters for this operation $sparams = $this->info["TRANSFORMATIONS"][$operation]; $this->properties["version_width"] = $w = $parameters["width"]; $this->properties["version_height"] = $h = $parameters["height"]; if (!$parameters["width"]) { $this->properties["version_width"] = $w = $parameters["height"]; } if (!$parameters["height"]) { $this->properties["version_height"] = $h = $parameters["width"]; } $cw = $this->get("width"); $ch = $this->get("height"); if (!$cw) { $cw = $w; } if (!$ch) { $ch = $h; } switch($operation) { # ----------------------- case "SET": while(list($k, $v) = each($parameters)) { $this->set($k, $v); } break; # ----------------------- case 'SCALE': switch($parameters["mode"]) { # ---------------- case "width": $scale_factor = $w/$cw; $h = $ch * $scale_factor; break; # ---------------- case "height": $scale_factor = $h/$ch; $w = $cw * $scale_factor; break; # ---------------- case "bounding_box": $scale_factor_w = $w/$cw; $scale_factor_h = $h/$ch; $w = $cw * (($scale_factor_w < $scale_factor_h) ? $scale_factor_w : $scale_factor_h); $h = $ch * (($scale_factor_w < $scale_factor_h) ? $scale_factor_w : $scale_factor_h); break; # ---------------- case "fill_box": $scale_factor_w = $w/$cw; $scale_factor_h = $h/$ch; $w = $cw * (($scale_factor_w > $scale_factor_h) ? $scale_factor_w : $scale_factor_h); $h = $ch * (($scale_factor_w > $scale_factor_h) ? $scale_factor_w : $scale_factor_h); $do_crop = 1; break; # ---------------- } $w = round($w); $h = round($h); if (!($w > 0 && $h > 0)) { $this->postError(1610, _t("Width or height was zero"), "WLPlugAudio->transform()"); return false; } if ($do_crop) { $this->properties["width"] = $parameters["width"]; $this->properties["height"] = $parameters["height"]; } else { $this->properties["width"] = $w; $this->properties["height"] = $h; } break; # ----------------------- case 'INTRO': $this->properties["intro_filepath"] = $parameters["filepath"]; break; # ----------------------- case 'OUTRO': $this->properties["outro_filepath"] = $parameters["filepath"]; break; # ----------------------- } return 1; } # ---------------------------------------------------------- public function write($filepath, $mimetype, $pa_options=null) { if (!$this->handle) { return false; } if (!($ext = $this->info["EXPORT"][$mimetype])) { # this plugin can't write this mimetype $this->postError(1610, _t("Can't convert '%1' to '%2': unsupported format", $this->handle["mime_type"], $mimetype), "WLPlugAudio->write()"); return false; } $o_config = Configuration::load(); $va_tags = $this->get("getID3_tags"); $vs_intro_filepath = $this->get("intro_filepath"); $vs_outro_filepath = $this->get("outro_filepath"); if (($vn_output_bitrate = $this->get("bitrate"))< 32) { $vn_output_bitrate = 64; } if (($vn_sample_frequency = $this->get("sample_frequency")) < 4096) { $vn_sample_frequency = 44100; } if (($vn_channels = $this->get("channels")) < 1) { $vn_channels = 1; } if ( ($this->properties["mimetype"] == $mimetype) && (!(($this->properties["mimetype"] == "audio/mpeg") && ($vs_intro_filepath || $vs_outro_filepath))) && (($vn_output_bitrate == $this->input_bitrate) && ($vn_sample_frequency == $this->input_sample_frequency) && ($vn_channels == $this->input_channels)) ) { # write the file if ( !copy($this->filepath, $filepath.".".$ext) ) { $this->postError(1610, _t("Couldn't write file to '%1'", $filepath), "WLPlugAudio->write()"); return false; } } else { if (($mimetype != "image/png") && ($mimetype != "image/jpeg") && ($this->ops_path_to_ffmpeg)) { # # Do conversion # if ($mimetype == 'audio/ogg') { caExec($this->ops_path_to_ffmpeg." -f ".$this->info["IMPORT"][$this->properties["mimetype"]]." -i ".caEscapeShellArg($this->filepath)." -acodec libvorbis -ab ".$vn_output_bitrate." -ar ".$vn_sample_frequency." -ac ".$vn_channels." -y ".caEscapeShellArg($filepath.".".$ext).(caIsPOSIX() ? " 2>&1" : ""), $va_output, $vn_return); } else { caExec($this->ops_path_to_ffmpeg." -f ".$this->info["IMPORT"][$this->properties["mimetype"]]." -i ".caEscapeShellArg($this->filepath)." -f ".$this->info["EXPORT"][$mimetype]." -ab ".$vn_output_bitrate." -ar ".$vn_sample_frequency." -ac ".$vn_channels." -y ".caEscapeShellArg($filepath.".".$ext).(caIsPOSIX() ? " 2>&1" : ""), $va_output, $vn_return); } if ($vn_return != 0) { @unlink($filepath.".".$ext); $this->postError(1610, _t("Error converting file to %1 [%2]: %3", $this->typenames[$mimetype], $mimetype, join("; ", $va_output)), "WLPlugAudio->write()"); return false; } if ($mimetype == "audio/mpeg") { if ($vs_intro_filepath || $vs_outro_filepath) { // add intro $vs_tmp_filename = tempnam(caGetTempDirPath(), "audio"); if ($vs_intro_filepath) { caExec($this->ops_path_to_ffmpeg." -i ".caEscapeShellArg($vs_intro_filepath)." -f mp3 -ab ".$vn_output_bitrate." -ar ".$vn_sample_frequency." -ac ".$vn_channels." -y ".caEscapeShellArg($vs_tmp_filename).(caIsPOSIX() ? " 2>&1" : ""), $va_output, $vn_return); if ($vn_return != 0) { @unlink($filepath.".".$ext); $this->postError(1610, _t("Error converting intro to %1 [%2]: %3", $this->typenames[$mimetype], $mimetype, join("; ", $va_output)), "WLPlugAudio->write()"); return false; } } $r_fp = fopen($vs_tmp_filename, "a"); $r_mp3fp = fopen($filepath.".".$ext, "r"); while (!feof($r_mp3fp)) { fwrite($r_fp, fread($r_mp3fp, 8192)); } fclose($r_mp3fp); if ($vs_outro_filepath) { $vs_tmp_outro_filename = tempnam(caGetTempDirPath(), "audio"); caExec($this->ops_path_to_ffmpeg." -i ".caEscapeShellArg($vs_outro_filepath)." -f mp3 -ab ".$vn_output_bitrate." -ar ".$vn_sample_frequency." -ac ".$vn_channels." -y ".caEscapeShellArg($vs_tmp_outro_filename).(caIsPOSIX() ? " 2>&1" : ""), $va_output, $vn_return); if ($vn_return != 0) { @unlink($filepath.".".$ext); $this->postError(1610, _t("Error converting outro to %1 [%2]: %3", $this->typenames[$mimetype], $mimetype, join("; ", $va_output)), "WLPlugAudio->write()"); return false; } $r_mp3fp = fopen($vs_tmp_outro_filename, "r"); while (!feof($r_mp3fp)) { fwrite($r_fp, fread($r_mp3fp, 8192)); } unlink($vs_tmp_outro_filename); } fclose($r_fp); copy($vs_tmp_filename, $filepath.".".$ext); unlink($vs_tmp_filename); } $o_getid3 = new getid3(); $va_mp3_output_info = $o_getid3->analyze($filepath.".".$ext); $this->properties = array(); if (is_array($va_mp3_output_info["tags"]["id3v1"]["title"])) { $this->properties["title"] = join("; ",$va_mp3_output_info["tags"]["id3v1"]["title"]); } if (is_array($va_mp3_output_info["tags"]["id3v1"]["artist"])) { $this->properties["author"] = join("; ",$va_mp3_output_info["tags"]["id3v1"]["artist"]); } if (is_array($va_mp3_output_info["tags"]["id3v1"]["comment"])) { $this->properties["copyright"] = join("; ",$va_mp3_output_info["tags"]["id3v1"]["comment"]); } if ( (is_array($va_mp3_output_info["tags"]["id3v1"]["album"])) && (is_array($va_mp3_output_info["tags"]["id3v1"]["year"])) && (is_array($va_mp3_output_info["tags"]["id3v1"]["genre"]))) { $this->properties["description"] = join("; ",$va_mp3_output_info["tags"]["id3v1"]["album"])." ".join("; ",$va_mp3_output_info["tags"]["id3v1"]["year"])." ".join("; ",$va_mp3_output_info["tags"]["id3v1"]["genre"]); } $this->properties["type_specific"] = array("audio" => $va_mp3_output_info["audio"], "tags" => $va_mp3_output_info["tags"]); $this->properties["bandwidth"] = array("min" => $va_mp3_output_info["bitrate"], "max" => $va_mp3_output_info["bitrate"]); $this->properties["bitrate"] = $va_mp3_output_info["bitrate"]; $this->properties["channels"] = $va_mp3_output_info["audio"]["channels"]; $this->properties["sample_frequency"] = $va_mp3_output_info["audio"]["sample_rate"]; $this->properties["duration"] = $va_mp3_output_info["playtime_seconds"]; } } else { # use default media icons if ffmpeg is not present or the current version is an image if(!$this->get("width") && !$this->get("height")){ $this->set("width",580); $this->set("height",200); } return __CA_MEDIA_AUDIO_DEFAULT_ICON__; } } if ($mimetype == "audio/mpeg") { // try to write getID3 tags (if set) if (is_array($pa_options) && is_array($pa_options) && sizeof($pa_options) > 0) { $o_tagwriter = new getid3_writetags(); $o_tagwriter->filename = $filepath.".".$ext; $o_tagwriter->tagformats = array('id3v2.3'); $o_tagwriter->tag_data = $pa_options; // write them tags if (!@$o_tagwriter->WriteTags()) { // failed to write tags } } } $this->properties["mimetype"] = $mimetype; $this->properties["typename"] = $this->typenames[$mimetype]; return $filepath.".".$ext; } # ------------------------------------------------ /** * */ # This method must be implemented for plug-ins that can output preview frames for videos or pages for documents public function &writePreviews($ps_filepath, $pa_options) { return null; } # ------------------------------------------------ /** * */ public function writeClip($ps_filepath, $ps_start, $ps_end, $pa_options=null) { $o_tc = new TimecodeParser(); $vn_start = $vn_end = 0; if ($o_tc->parse($ps_start)) { $vn_start = (float)$o_tc->getSeconds(); } if ($o_tc->parse($ps_end)) { $vn_end = (float)$o_tc->getSeconds(); } if ($vn_end == 0) { return null; } if ($vn_start >= $vn_end) { return null; } $vn_duration = $vn_end - $vn_start; caExec($this->ops_path_to_ffmpeg." -i ".caEscapeShellArg($this->filepath)." -f mp3 -t {$vn_duration} -y -ss {$vn_start} ".caEscapeShellArg($ps_filepath).(caIsPOSIX() ? " 2>&1" : ""), $va_output, $vn_return); if ($vn_return != 0) { @unlink($ps_filepath); $this->postError(1610, _t("Error extracting clip from %1 to %2: %3", $ps_start, $ps_end, join("; ", $va_output)), "WLPlugAudio->writeClip()"); return false; } return true; } # ------------------------------------------------ public function getOutputFormats() { return $this->info["EXPORT"]; } # ------------------------------------------------ public function getTransformations() { return $this->info["TRANSFORMATIONS"]; } # ------------------------------------------------ public function getProperties() { return $this->info["PROPERTIES"]; } # ------------------------------------------------ public function mimetype2extension($mimetype) { return $this->info["EXPORT"][$mimetype]; } # ------------------------------------------------ public function extension2mimetype($extension) { reset($this->info["EXPORT"]); while(list($k, $v) = each($this->info["EXPORT"])) { if ($v === $extension) { return $k; } } return ""; } # ------------------------------------------------ public function mimetype2typename($mimetype) { return $this->typenames[$mimetype]; } # ------------------------------------------------ public function reset() { $this->errors = array(); $this->properties = $this->oproperties; return $this->handle = $this->ohandle; } # ------------------------------------------------ public function init() { $this->errors = array(); $this->filepath = ""; $this->handle = ""; $this->properties = ""; $this->metadata = array(); } # ------------------------------------------------ public function htmlTag($ps_url, $pa_properties, $pa_options=null, $pa_volume_info=null) { if (!is_array($pa_options)) { $pa_options = array(); } foreach(array( 'name', 'show_controls', 'url', 'text_only', 'viewer_width', 'viewer_height', 'id', 'data_url', 'poster_frame_url', 'viewer_parameters', 'viewer_base_url', 'width', 'height', 'vspace', 'hspace', 'alt', 'title', 'usemap', 'align', 'border', 'class', 'style', 'duration', 'pages' ) as $vs_k) { if (!isset($pa_options[$vs_k])) { $pa_options[$vs_k] = null; } } switch($pa_properties["mimetype"]) { # ------------------------------------------------ case 'audio/ogg': $vs_id = $pa_options["id"] ? $pa_options["id"] : "mp4_player"; $vs_poster_frame_url = $pa_options["poster_frame_url"]; $vn_width = $pa_options["viewer_width"] ? $pa_options["viewer_width"] : $pa_properties["width"]; $vn_height = $pa_options["viewer_height"] ? $pa_options["viewer_height"] : $pa_properties["height"]; if (!$vn_width) { $vn_width = 300; } if (!$vn_height) { $vn_height = 32; } return "<div style='width: {$vn_width}px; height: {$vn_height}px;'><audio id='{$vs_id}' src='{$ps_url}' width='{$vn_width}' height='{$vn_height}' controls='1'></audio></div>"; break; # ------------------------------------------------ case 'audio/mpeg': $viewer_base_url = $pa_options["viewer_base_url"]; $vs_id = $pa_options["id"] ? $pa_options["id"] : "mp3player"; AssetLoadManager::register("mediaelement"); $vn_width = ($pa_options["viewer_width"] > 0) ? $pa_options["viewer_width"] : 400; $vn_height = ($pa_options["viewer_height"] > 0) ? $pa_options["viewer_height"] : 95; ob_start(); ?> <div class="<?php print (isset($pa_options["class"]) ? $pa_options["class"] : "caAudioPlayer"); ?>"> <audio id="<?php print $vs_id; ?>" src="<?php print $ps_url; ?>" <?php print ($vs_poster_url = caGetOption('posterURL', $pa_options, null) ? "poster='{$vs_poster_url}'" : ''); ?> type="audio/mp3" controls="controls"></audio> </div> <script type="text/javascript"> jQuery(document).ready(function() { var m = jQuery('#<?php print $vs_id; ?>').mediaelementplayer({ showTimecodeFrameCount: true, framesPerSecond: 100, audioWidth: '<?php print $vn_width; ?>', audioHeight: '<?php print $vn_height; ?>', success: function (mediaElement, domObject) { var m = mediaElement; m.addEventListener("play", function(e){ // Force poster image to remain visible during playback var $thisMediaElement = (mediaElement.id) ? jQuery("#"+mediaElement.id) : jQuery(mediaElement); $thisMediaElement.parents(".mejs-inner").find(".mejs-poster").show(); }); m.addEventListener("canplay", function(e){ var $thisMediaElement = (mediaElement.id) ? jQuery("#"+mediaElement.id) : jQuery(mediaElement); $thisMediaElement.parents(".mejs-inner").find(".mejs-poster").on('click', function() { caUI.mediaPlayerManager.isPlaying("<?php print $vs_id; ?>") ? caUI.mediaPlayerManager.stop("<?php print $vs_id; ?>") : caUI.mediaPlayerManager.play("<?php print $vs_id; ?>"); }); }); } }); if (caUI.mediaPlayerManager) { caUI.mediaPlayerManager.register("<?php print $vs_id; ?>", m, 'MediaElement'); } }); </script> <?php return ob_get_clean(); break; # ------------------------------------------------ case 'audio/mp4': case 'audio/x-aiff': case 'audio/x-flac': case 'audio/x-wav': $name = $pa_options["name"] ? $pa_options["name"] : "mp3player"; ob_start(); $vn_width = ($pa_options["viewer_width"] > 0) ? $pa_options["viewer_width"] : 400; $vn_height = ($pa_options["viewer_height"] > 0) ? $pa_options["viewer_height"] : 95; ?> <div style="width: {$vn_width}px; height: {$vn_height}px;"> <table> <tr> <td> <embed width="<?php print $pa_properties["width"]; ?>" height="<?php print $pa_properties["height"] + 16; ?>" src="<?php print $ps_url; ?>" type="audio/x-wav"> </td> </tr> </table> </div> <?php return ob_get_clean(); break; # ------------------------------------------------ case 'image/jpeg': case 'image/png': if (!is_array($pa_options)) { $pa_options = array(); } if (!is_array($pa_properties)) { $pa_properties = array(); } return caHTMLImage($ps_url, array_merge($pa_options, $pa_properties)); break; # ------------------------------------------------ } } # ------------------------------------------------ public function cleanup() { return; } # ------------------------------------------------ }
kehh/providence
app/lib/Plugins/Media/Audio.php
PHP
gpl-3.0
32,591
<?php /** * LiskPhp - A PHP wrapper for the LISK API * Copyright (c) 2017 Marcus Puchalla <cb0@0xcb0.com> * * LiskPhp is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LiskPhp is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LiskPhp. If not, see <http://www.gnu.org/licenses/>. */ namespace Lisk\Api\Apps; use Lisk\AbstractRequest; use Lisk\Cli\Parameters; class InstallAppRequest extends AbstractRequest { private $id; public function __construct($id) { parent::__construct(); $this->id = $id; } public function setEndpoint() { $this->endpoint = "/api/dapps/install"; } public function setType() { $this->type = self::POST; } public function getPayload() { return [ Parameters::ID => $this->id ]; } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id) { $this->id = $id; } }
cb0/LiskPHP
src/lib/Api/Apps/InstallAppRequest.php
PHP
gpl-3.0
1,505
<?php /* Plugin Name: Postie Plugin URI: http://PostiePlugin.com/ Description: Create posts via email. Signifigantly upgrades the Post by Email features of Word Press. Version: 1.7.32 Author: Wayne Allen Author URI: http://PostiePlugin.com/ License: GPL2 Text Domain: postie */ /* Copyright (c) 2015 Wayne Allen (email : wayne@allens-home.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* $Id: postie.php 1396811 2016-04-15 19:40:39Z WayneAllen $ */ require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "lib_autolink.php"); require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "postie-functions.php"); define('POSTIE_VERSION', '1.7.32'); define("POSTIE_ROOT", dirname(__FILE__)); define("POSTIE_URL", WP_PLUGIN_URL . '/' . basename(dirname(__FILE__))); //register the hooks early in the page in case some method needs the result of one of them (i.e. cron_schedules) add_action('init', 'postie_disable_kses_content', 20); add_action('check_postie_hook', 'check_postie'); add_action('parse_request', 'postie_parse_request'); add_action('admin_init', 'postie_admin_init'); add_action('admin_menu', 'postie_admin_menu'); add_action('admin_head', 'postie_admin_head'); add_filter('whitelist_options', 'postie_whitelist'); add_filter('cron_schedules', 'postie_more_reccurences'); add_filter('query_vars', 'postie_query_vars'); add_filter("plugin_action_links_" . plugin_basename(__FILE__), 'postie_plugin_action_links'); add_filter('plugin_row_meta', 'postie_plugin_row_meta', 10, 2); register_activation_hook(__FILE__, 'activate_postie'); register_activation_hook(__FILE__, 'postie_cron'); register_deactivation_hook(__FILE__, 'postie_decron'); if (isset($_GET["postie_read_me"])) { include_once(ABSPATH . "wp-admin/admin.php"); include(ABSPATH . 'wp-admin/admin-header.php'); postie_ShowReadMe(); include(ABSPATH . 'wp-admin/admin-footer.php'); } //Add Menu Configuration if (is_admin()) { if (function_exists('load_plugin_textdomain')) { function postie_load_domain() { $plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__)); load_plugin_textdomain('postie', false, dirname(plugin_basename(__FILE__)) . '/languages/'); } add_action('init', 'postie_load_domain'); } postie_warnings(); } //****************** functions ************************* function postie_admin_head() { ?> <style type="text/css"> #adminmenu #toplevel_page_postie-settings div.wp-menu-image:before { content: "\f466"; } </style> <?php } function postie_plugin_row_meta($links, $file) { if (strpos($file, plugin_basename(__FILE__)) !== false) { $new_links = array( '<a href="http://postieplugin.com/" target="_blank">Support</a>', '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=HPK99BJ88V4C2" target="_blank">Donate</a>' ); $links = array_merge($links, $new_links); } return $links; } function postie_plugin_action_links($links) { $links[] = '<a href="admin.php?page=postie-settings">Settings</a>'; return $links; } function postie_query_vars($vars) { $vars[] = 'postie'; return $vars; } function postie_parse_request($wp) { if (array_key_exists('postie', $wp->query_vars)) { switch ($wp->query_vars['postie']) { case 'get-mail': postie_get_mail(); die(); case 'test-config': postie_test_config(); die(); default : dir('Unknown option: ' . $wp->query_vars['postie']); } } } function postie_admin_init() { wp_register_style('postie-style', plugins_url('css/style.css', __FILE__)); register_setting('postie-settings', 'postie-settings', 'config_ValidateSettings'); } function postie_admin_menu() { $page = add_menu_page('Postie', 'Postie', 'manage_options', 'postie-settings', 'postie_loadjs_options_page'); add_action('admin_print_styles-' . $page, 'postie_admin_styles'); } function postie_loadjs_options_page() { require_once POSTIE_ROOT . '/config_form.php'; } function postie_admin_page() { if (!current_user_can('manage_options')) { wp_die(__('You do not have sufficient permissions to access this page.', 'postie')); } include 'config_form.php'; } function postie_admin_styles() { wp_enqueue_style('postie-style'); } /* * called by WP when activating the plugin * Note that you can't do any output during this funtion or activation * will fail on some systems. This means no DebugEcho, EchoInfo or DebugDump. */ function activate_postie() { static $init = false; $options = config_Read(); if ($init) { return; } if (!$options) { $options = array(); } $default_options = config_GetDefaults(); $old_config = array(); $result = config_GetOld(); if (is_array($result)) { foreach ($result as $key => $val) { $old_config[strtolower($key)] = $val; } } // overlay the options on top of each other: // the current value of $options takes priority over the $old_config, which takes priority over the $default_options $options = array_merge($default_options, $old_config, $options); $options = config_ValidateSettings($options); update_option('postie-settings', $options); $init = true; } /** * set up actions to show relevant warnings, * if mail server is not set, or if IMAP extension is not available */ function postie_warnings() { $config = config_Read(); if ((empty($config['mail_server']) || empty($config['mail_server_port']) || empty($config['mail_userid']) || empty($config['mail_password']) ) && !isset($_POST['submit'])) { function postie_enter_info() { echo "<div id='postie-info-warning' class='updated fade'><p><strong>" . __('Postie is almost ready.', 'postie') . "</strong> " . sprintf(__('You must <a href="%1$s">enter your email settings</a> for it to work.', 'postie'), "admin.php?page=postie-settings") . "</p></div> "; } add_action('admin_notices', 'postie_enter_info'); } $p = strtolower($config['input_protocol']); if (!function_exists('imap_mime_header_decode') && ($p == 'imap' || $p == 'imap-ssl' || $p == 'pop-ssl')) { function postie_imap_warning() { echo "<div id='postie-imap-warning' class='error'><p><strong>"; echo __('Warning: the IMAP php extension is not installed. Postie can not use IMAP, IMAP-SSL or POP-SSL without this extension.', 'postie'); echo "</strong></p></div>"; } add_action('admin_notices', 'postie_imap_warning'); } if ($p == 'pop3' && $config['email_tls']) { function postie_tls_warning() { echo "<div id='postie-lst-warning' class='error'><p><strong>"; echo __('Warning: The POP3 connector does not support TLS.', 'postie'); echo "</strong></p></div>"; } add_action('admin_notices', 'postie_tls_warning'); } if (isMarkdownInstalled() && $config['prefer_text_type'] == 'html') { function postie_markdown_warning() { echo "<div id='postie-lst-warning' class='error'><p><strong>"; _e("You currently have the Markdown plugin installed. It will cause problems if you send in HTML email. Please turn it off if you intend to send email using HTML.", 'postie'); echo "</strong></p></div>"; } add_action('admin_notices', 'postie_markdown_warning'); } if (!HasIconvInstalled()) { function postie_iconv_warning() { echo "<div id='postie-lst-warning' class='error'><p><strong>"; _e("Warning! Postie requires that iconv be enabled.", 'postie'); echo "</strong></p></div>"; } add_action('admin_notices', 'postie_iconv_warning'); } $userdata = WP_User::get_data_by('login', $config['admin_username']); if (!$userdata) { function postie_adminuser_warning() { echo "<div id='postie-mbstring-warning' class='error'><p><strong>"; echo __('Warning: the Admin username is not a valid WordPress login. Postie may reject emails if this is not corrected.', 'postie'); echo "</strong></p></div>"; } add_action('admin_notices', 'postie_adminuser_warning'); } } function postie_disable_kses_content() { remove_filter('content_save_pre', 'wp_filter_post_kses'); } function postie_whitelist($options) { $added = array('postie-settings' => array('postie-settings')); $options = add_option_whitelist($added, $options); return $options; } //don't use DebugEcho or EchoInfo here as it is not defined when called as an action function check_postie() { //error_log("check_postie"); postie_get_mail(); } function postie_cron($interval = false) { //Do not echo output in filters, it seems to break some installs //error_log("postie_cron: setting up cron task: $interval"); //$schedules = wp_get_schedules(); //error_log("postie_cron\n" . print_r($schedules, true)); if (!$interval) { $config = config_Read(); $interval = $config['interval']; //error_log("postie_cron: setting up cron task from config: $interval"); } if (!$interval || $interval == '') { $interval = 'hourly'; //error_log("Postie: setting up cron task: defaulting to hourly"); } if ($interval == 'manual') { postie_decron(); //error_log("postie_cron: clearing cron (manual)"); } else { if ($interval != wp_get_schedule('check_postie_hook')) { postie_decron(); //remove existing //try to create the new schedule with the first run in 5 minutes if (false === wp_schedule_event(time() + 5 * 60, $interval, 'check_postie_hook')) { //error_log("postie_cron: Failed to set up cron task: $interval"); } else { //error_log("postie_cron: Set up cron task: $interval"); } } else { //error_log("postie_cron: OK: $interval"); //don't need to do anything, cron already scheduled } } } function postie_decron() { //error_log("postie_decron: clearing cron"); wp_clear_scheduled_hook('check_postie_hook'); } /* here we add some more cron options for how often to check for email */ function postie_more_reccurences($schedules) { //Do not echo output in filters, it seems to break some installs //error_log("postie_more_reccurences: setting cron schedules"); $schedules['weekly'] = array('interval' => (60 * 60 * 24 * 7), 'display' => __('Once Weekly', 'postie')); $schedules['twiceperhour'] = array('interval' => 60 * 30, 'display' => __('Twice per hour', 'postie')); $schedules['tenminutes'] = array('interval' => 60 * 10, 'display' => __('Every 10 minutes', 'postie')); $schedules['fiveminutes'] = array('interval' => 60 * 5, 'display' => __('Every 5 minutes', 'postie')); $schedules['oneminute'] = array('interval' => 60 * 1, 'display' => __('Every 1 minute', 'postie')); $schedules['thirtyseconds'] = array('interval' => 30, 'display' => __('Every 30 seconds', 'postie')); $schedules['fifteenseconds'] = array('interval' => 15, 'display' => __('Every 15 seconds', 'postie')); return $schedules; }
palibaacsi/ask
wp-content/plugins/postie/postie.php
PHP
gpl-3.0
12,137
// $Id: CbcHeuristicDINS.cpp 2094 2014-11-18 11:15:36Z forrest $ // Copyright (C) 2006, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). // edwin 12/5/09 carved out of CbcHeuristicRINS #if defined(_MSC_VER) // Turn off compiler warning about long names # pragma warning(disable:4786) #endif #include <cassert> #include <cstdlib> #include <cmath> #include <cfloat> #include "OsiSolverInterface.hpp" #include "CbcModel.hpp" #include "CbcMessage.hpp" #include "CbcHeuristicDINS.hpp" #include "CbcBranchActual.hpp" #include "CbcStrategy.hpp" #include "CglPreProcess.hpp" // Default Constructor CbcHeuristicDINS::CbcHeuristicDINS() : CbcHeuristic() { numberSolutions_ = 0; numberSuccesses_ = 0; numberTries_ = 0; howOften_ = 100; decayFactor_ = 0.5; maximumKeepSolutions_ = 5; numberKeptSolutions_ = 0; numberIntegers_ = -1; localSpace_ = 10; values_ = NULL; } // Constructor with model - assumed before cuts CbcHeuristicDINS::CbcHeuristicDINS(CbcModel & model) : CbcHeuristic(model) { numberSolutions_ = 0; numberSuccesses_ = 0; numberTries_ = 0; howOften_ = 100; decayFactor_ = 0.5; assert(model.solver()); maximumKeepSolutions_ = 5; numberKeptSolutions_ = 0; numberIntegers_ = -1; localSpace_ = 10; values_ = NULL; } // Destructor CbcHeuristicDINS::~CbcHeuristicDINS () { for (int i = 0; i < numberKeptSolutions_; i++) delete [] values_[i]; delete [] values_; } // Clone CbcHeuristic * CbcHeuristicDINS::clone() const { return new CbcHeuristicDINS(*this); } // Assignment operator CbcHeuristicDINS & CbcHeuristicDINS::operator=( const CbcHeuristicDINS & rhs) { if (this != &rhs) { CbcHeuristic::operator=(rhs); numberSolutions_ = rhs.numberSolutions_; howOften_ = rhs.howOften_; numberSuccesses_ = rhs.numberSuccesses_; numberTries_ = rhs.numberTries_; for (int i = 0; i < numberKeptSolutions_; i++) delete [] values_[i]; delete [] values_; maximumKeepSolutions_ = rhs.maximumKeepSolutions_; numberKeptSolutions_ = rhs.numberKeptSolutions_; numberIntegers_ = rhs.numberIntegers_; localSpace_ = rhs.localSpace_; if (model_ && rhs.values_) { assert (numberIntegers_ >= 0); values_ = new int * [maximumKeepSolutions_]; for (int i = 0; i < maximumKeepSolutions_; i++) values_[i] = CoinCopyOfArray(rhs.values_[i], numberIntegers_); } else { values_ = NULL; } } return *this; } // Create C++ lines to get to current state void CbcHeuristicDINS::generateCpp( FILE * fp) { CbcHeuristicDINS other; fprintf(fp, "0#include \"CbcHeuristicDINS.hpp\"\n"); fprintf(fp, "3 CbcHeuristicDINS heuristicDINS(*cbcModel);\n"); CbcHeuristic::generateCpp(fp, "heuristicDINS"); if (howOften_ != other.howOften_) fprintf(fp, "3 heuristicDINS.setHowOften(%d);\n", howOften_); else fprintf(fp, "4 heuristicDINS.setHowOften(%d);\n", howOften_); if (maximumKeepSolutions_ != other.maximumKeepSolutions_) fprintf(fp, "3 heuristicDINS.setMaximumKeep(%d);\n", maximumKeepSolutions_); else fprintf(fp, "4 heuristicDINS.setMaximumKeep(%d);\n", maximumKeepSolutions_); fprintf(fp, "3 cbcModel->addHeuristic(&heuristicDINS);\n"); } // Copy constructor CbcHeuristicDINS::CbcHeuristicDINS(const CbcHeuristicDINS & rhs) : CbcHeuristic(rhs), numberSolutions_(rhs.numberSolutions_), howOften_(rhs.howOften_), numberSuccesses_(rhs.numberSuccesses_), numberTries_(rhs.numberTries_), maximumKeepSolutions_(rhs.maximumKeepSolutions_), numberKeptSolutions_(rhs.numberKeptSolutions_), numberIntegers_(rhs.numberIntegers_), localSpace_(rhs.localSpace_) { if (model_ && rhs.values_) { assert (numberIntegers_ >= 0); values_ = new int * [maximumKeepSolutions_]; for (int i = 0; i < maximumKeepSolutions_; i++) values_[i] = CoinCopyOfArray(rhs.values_[i], numberIntegers_); } else { values_ = NULL; } } // Resets stuff if model changes void CbcHeuristicDINS::resetModel(CbcModel * ) { //CbcHeuristic::resetModel(model); for (int i = 0; i < numberKeptSolutions_; i++) delete [] values_[i]; delete [] values_; numberKeptSolutions_ = 0; numberIntegers_ = -1; numberSolutions_ = 0; values_ = NULL; } /* First tries setting a variable to better value. If feasible then tries setting others. If not feasible then tries swaps Returns 1 if solution, 0 if not */ int CbcHeuristicDINS::solution(double & solutionValue, double * betterSolution) { numCouldRun_++; int returnCode = 0; const double * bestSolution = model_->bestSolution(); if (!bestSolution) return 0; // No solution found yet #ifdef HEURISTIC_INFORM printf("Entering heuristic %s - nRuns %d numCould %d when %d\n", heuristicName(),numRuns_,numCouldRun_,when_); #endif if (numberSolutions_ < model_->getSolutionCount()) { // new solution - add info numberSolutions_ = model_->getSolutionCount(); int numberIntegers = model_->numberIntegers(); const int * integerVariable = model_->integerVariable(); if (numberIntegers_ < 0) { numberIntegers_ = numberIntegers; assert (!values_); values_ = new int * [maximumKeepSolutions_]; for (int i = 0; i < maximumKeepSolutions_; i++) values_[i] = NULL; } else { assert (numberIntegers >= numberIntegers_); } // move solutions (0 will be most recent) { int * temp = values_[maximumKeepSolutions_-1]; for (int i = maximumKeepSolutions_ - 1; i > 0; i--) values_[i] = values_[i-1]; if (!temp) temp = new int [numberIntegers_]; values_[0] = temp; } int i; for (i = 0; i < numberIntegers_; i++) { int iColumn = integerVariable[i]; double value = bestSolution[iColumn]; double nearest = floor(value + 0.5); values_[0][i] = static_cast<int> (nearest); } numberKeptSolutions_ = CoinMin(numberKeptSolutions_ + 1, maximumKeepSolutions_); } int finalReturnCode = 0; if (((model_->getNodeCount() % howOften_) == howOften_ / 2 || !model_->getNodeCount()) && (model_->getCurrentPassNumber() <= 1 || model_->getCurrentPassNumber() == 999999)) { OsiSolverInterface * solver = model_->solver(); //int numberIntegers = model_->numberIntegers(); const int * integerVariable = model_->integerVariable(); const double * currentSolution = solver->getColSolution(); int localSpace = localSpace_; // 0 means finished but no solution, 1 solution, 2 node limit int status = -1; double cutoff = model_->getCutoff(); while (status) { status = 0; OsiSolverInterface * newSolver = cloneBut(3); // was model_->continuousSolver()->clone(); const double * colLower = solver->getColLower(); const double * colUpper = solver->getColUpper(); double primalTolerance; solver->getDblParam(OsiPrimalTolerance, primalTolerance); const double * continuousSolution = newSolver->getColSolution(); // Space for added constraint double * element = new double [numberIntegers_]; int * column = new int [numberIntegers_]; int i; int nFix = 0; int nCouldFix = 0; int nCouldFix2 = 0; int nBound = 0; int nEl = 0; double bias = localSpace; int okSame = numberKeptSolutions_ - 1; for (i = 0; i < numberIntegers_; i++) { int iColumn = integerVariable[i]; const OsiObject * object = model_->object(i); // get original bounds double originalLower; double originalUpper; getIntegerInformation( object, originalLower, originalUpper); double valueInt = bestSolution[iColumn]; if (valueInt < originalLower) { valueInt = originalLower; } else if (valueInt > originalUpper) { valueInt = originalUpper; } int intValue = static_cast<int> (floor(valueInt + 0.5)); double currentValue = currentSolution[iColumn]; double currentLower = colLower[iColumn]; double currentUpper = colUpper[iColumn]; if (fabs(valueInt - currentValue) >= 0.5) { // Re-bound nBound++; if (intValue >= currentValue) { currentLower = CoinMax(currentLower, ceil(2 * currentValue - intValue)); currentUpper = intValue; } else { currentLower = intValue; currentUpper = CoinMin(currentUpper, floor(2 * currentValue - intValue)); } newSolver->setColLower(iColumn, currentLower); newSolver->setColUpper(iColumn, currentUpper); } else { // See if can fix bool canFix = false; double continuousValue = continuousSolution[iColumn]; if (fabs(currentValue - valueInt) < 10.0*primalTolerance) { if (currentUpper - currentLower > 1.0) { // General integer variable canFix = true; } else if (fabs(continuousValue - valueInt) < 10.0*primalTolerance) { int nSame = 1; //assert (intValue==values_[0][i]); for (int k = 1; k < numberKeptSolutions_; k++) { if (intValue == values_[k][i]) nSame++; } if (nSame >= okSame) { // can fix canFix = true; } else { nCouldFix++; } } else { nCouldFix2++; } } if (canFix) { newSolver->setColLower(iColumn, intValue); newSolver->setColUpper(iColumn, intValue); nFix++; } else { if (currentUpper - currentLower > 1.0) { // General integer variable currentLower = floor(currentValue); if (intValue >= currentLower && intValue <= currentLower + 1) { newSolver->setColLower(iColumn, currentLower); newSolver->setColUpper(iColumn, currentLower + 1.0); } else { // fix double value; if (intValue < currentLower) value = currentLower; else value = currentLower + 1; newSolver->setColLower(iColumn, value); newSolver->setColUpper(iColumn, value); nFix++; } } else { // 0-1 (ish) column[nEl] = iColumn; if (intValue == currentLower) { bias += currentLower; element[nEl++] = 1.0; } else if (intValue == currentUpper) { bias += currentUpper; element[nEl++] = -1.0; } else { printf("bad DINS logic\n"); abort(); } } } } } char generalPrint[200]; sprintf(generalPrint, "%d fixed, %d same as cont/int, %d same as int - %d bounded %d in cut\n", nFix, nCouldFix, nCouldFix2, nBound, nEl); model_->messageHandler()->message(CBC_FPUMP2, model_->messages()) << generalPrint << CoinMessageEol; if (nFix > numberIntegers_ / 10) { #ifdef JJF_ZERO newSolver->initialSolve(); printf("obj %g\n", newSolver->getObjValue()); for (i = 0; i < numberIntegers_; i++) { int iColumn = integerVariable[i]; printf("%d new bounds %g %g - solutions %g %g\n", iColumn, newSolver->getColLower()[iColumn], newSolver->getColUpper()[iColumn], bestSolution[iColumn], currentSolution[iColumn]); } #endif if (nEl > 0) newSolver->addRow(nEl, column, element, -COIN_DBL_MAX, bias); //printf("%d integers have same value\n",nFix); returnCode = smallBranchAndBound(newSolver, numberNodes_, betterSolution, solutionValue, cutoff, "CbcHeuristicDINS"); if (returnCode < 0) { returnCode = 0; // returned on size status = 0; } else { numRuns_++; if ((returnCode&2) != 0) { // could add cut as complete search returnCode &= ~2; if ((returnCode&1) != 0) { numberSuccesses_++; status = 1; } else { // no solution status = 0; } } else { if ((returnCode&1) != 0) { numberSuccesses_++; status = 1; } else { // no solution but node limit status = 2; if (nEl) localSpace -= 5; else localSpace = -1; if (localSpace < 0) status = 0; } } if ((returnCode&1) != 0) { cutoff = CoinMin(cutoff, solutionValue - model_->getCutoffIncrement()); finalReturnCode = 1; } } } delete [] element; delete [] column; delete newSolver; } numberTries_++; if ((numberTries_ % 10) == 0 && numberSuccesses_*3 < numberTries_) howOften_ += static_cast<int> (howOften_ * decayFactor_); } return finalReturnCode; } // update model void CbcHeuristicDINS::setModel(CbcModel * model) { model_ = model; // Get a copy of original matrix assert(model_->solver()); for (int i = 0; i < numberKeptSolutions_; i++) delete [] values_[i]; delete [] values_; numberKeptSolutions_ = 0; numberIntegers_ = -1; numberSolutions_ = 0; values_ = NULL; }
phines/acsimsep
ThirdParty/Coin-Bonmin/Cbc/src/CbcHeuristicDINS.cpp
C++
gpl-3.0
16,193
/* * Copyright (C) 2020 The ESPResSo project * * This file is part of ESPResSo. * * ESPResSo is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ESPResSo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ContextManager.hpp" #include "GlobalContext.hpp" #include "LocalContext.hpp" #include <utils/serialization/pack.hpp> #include <cassert> #include <memory> #include <string> #include <utility> namespace ScriptInterface { std::shared_ptr<ObjectHandle> ContextManager::make_shared(CreationPolicy policy, std::string const &name, const VariantMap &parameters) { return context(policy)->make_shared(name, parameters); } std::shared_ptr<ObjectHandle> ContextManager::deserialize(std::string const &state_) { auto const state = Utils::unpack<std::pair<CreationPolicy, std::string>>(state_); auto ctx = context(state.first); assert(ctx); return ObjectHandle::deserialize(state.second, *ctx); } std::string ContextManager::serialize(const ObjectHandle *o) const { /* We treat objects without a context as local. */ auto ctx = o->context() ? o->context() : m_local_context.get(); return Utils::pack(std::make_pair(policy(ctx), o->serialize())); } ContextManager::ContextManager(Communication::MpiCallbacks &callbacks, const Utils::Factory<ObjectHandle> &factory) { auto local_context = std::make_shared<LocalContext>(factory); /* If there is only one node, we can treat all objects as local, and thus * never invoke any callback. */ m_global_context = (callbacks.comm().size() > 1) ? std::make_shared<GlobalContext>(callbacks, local_context) : std::static_pointer_cast<Context>(local_context); m_local_context = std::move(local_context); } } // namespace ScriptInterface
fweik/espresso
src/script_interface/ContextManager.cpp
C++
gpl-3.0
2,328
<?php if (is_ajax()) { if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists $action = $_POST["action"]; switch($action) { //Switch case for value of action case "updateKataster": updateKataster(); break; case "saveKataster": saveKataster(); break; case "loadMesstrupps": loadMesstrupps(); break; case "saveMesstrupps": saveMesstrupps(); break; } } } //Function to check if the request is an AJAX request function is_ajax() { return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; } function updateKataster(){ include("config.php"); require("session.php"); $UID = !empty($_POST['UID']) ? $_POST['UID']:$_SESSION['userid']; if ($UID == 'su') { $stmt = $pdo->prepare("SELECT opt_kataster FROM options WHERE opt_UID = '0' AND opt_cars > ''"); $stmt->execute(); $messpunkte = $stmt->fetch(); } else { $stmt = $pdo->prepare("SELECT opt_kataster FROM options WHERE opt_UID = :UID AND opt_kataster > ''"); $stmt->bindParam(':UID', $UID, PDO::PARAM_STR); $stmt->execute(); $messpunkte = $stmt->fetch(); if (!$messpunkte) // Überprüft, ob persönliche Messpunkte gespeichert sind und lädt anderenfalls die globalen Vorgaben { $stmt = $pdo->prepare("SELECT opt_kataster FROM options WHERE opt_UID = '0' AND opt_cars > ''"); $stmt->execute(); $messpunkte = $stmt->fetch(); } if (!$messpunkte) // Wenn globale Vorgaben nicht definiert sind, wird ein Standardwert angenommen { $messpunkte = array('opt_kataster' => '[{"ID":"1","Nummer":"01-00","Bezeichnung":"Mustername","Adresse":"Musterstraße 1, 12345 Musterstadt","ODL":"0","IPS":"0","Koordinaten":"52.514036, 13.404107"}]', "0" => '[{"ID":"1","Nummer":"01-00","Bezeichnung":"Mustername","Adresse":"Musterstraße 1, 12345 Musterstadt","ODL":"0","IPS":"0","Koordinaten":"52.514036, 13.404107"}]'); } } echo json_encode($messpunkte); } function saveKataster(){ include("config.php"); require("session.php"); $kataster = !empty($_POST['data']) ? $_POST['data']:''; $UID = !empty($_POST['UID']) ? $_POST['UID']:''; if ($UID == 'su') { if ($_SESSION['accessLevel'] == "admin") { $stmt = $pdo->prepare("INSERT INTO options (opt_UID, opt_kataster) VALUES ('0', :points) ON DUPLICATE KEY UPDATE opt_kataster = :points"); $stmt->bindParam(':points', $kataster, PDO::PARAM_STR); $stmt->execute(); echo json_encode('successGlobal'); } else { echo json_encode('noAdmin'); } } else { $stmt = $pdo->prepare("INSERT INTO options (opt_UID, opt_kataster) VALUES (:UID, :points) ON DUPLICATE KEY UPDATE opt_kataster = :points"); $stmt->bindParam(':UID', $_SESSION['userid'], PDO::PARAM_INT); $stmt->bindParam(':points', $kataster, PDO::PARAM_STR); $stmt->execute(); echo json_encode('successLocal'); } } function loadMesstrupps(){ // Lädt die Messtrupps, die der angemeldete Benutzer erstellt hat. require('session.php'); include("config.php"); $UID = !empty($_POST['UID']) ? $_POST['UID']:''; if ($UID == 'su') { $stmt = $pdo->prepare("SELECT opt_cars FROM options WHERE opt_UID = '0'"); $stmt->execute(); $messtrupps = $stmt->fetch(); } else { $stmt = $pdo->prepare("SELECT opt_cars FROM options WHERE opt_UID = :UID AND opt_cars > ''"); $stmt->bindParam(':UID', $_SESSION['userid'], PDO::PARAM_STR); $stmt->execute(); $messtrupps = $stmt->fetch(); if (!$messtrupps) // Überprüft, ob persönliche Messtrupps gespeichert sind und lädt anderenfalls die globalen Vorgaben { $stmt = $pdo->prepare("SELECT opt_cars FROM options WHERE opt_UID = '0' AND opt_cars > ''"); $stmt->execute(); $messtrupps = $stmt->fetch(); } if (!$messtrupps) // Wenn globale Vorgaben nicht definiert sind, wird ein Standardwert angenommen { $messtrupps = array('opt_cars' => '[{"ID":"0","key":"","name":"Keine Zuordnung","color":"#000000"}]', "0" => '[{"ID":"0","key":"","name":"Keine Zuordnung","color":"#000000"}]'); } } echo json_encode($messtrupps); } function saveMesstrupps(){ include("config.php"); require("session.php"); $trupps = !empty($_POST['data']) ? $_POST['data']:''; $UID = !empty($_POST['UID']) ? $_POST['UID']:''; if ($UID == 'su') { if ($_SESSION['accessLevel'] == "admin") { $stmt = $pdo->prepare("INSERT INTO options (opt_UID, opt_cars) VALUES ('0', :cars) ON DUPLICATE KEY UPDATE opt_cars = :cars"); $stmt->bindParam(':cars', $trupps, PDO::PARAM_STR); $stmt->execute(); echo json_encode('successGlobal'); } else { echo json_encode('noAdmin'); } } else { $stmt = $pdo->prepare("INSERT INTO options (opt_UID, opt_cars) VALUES (:UID, :cars) ON DUPLICATE KEY UPDATE opt_cars = :cars"); $stmt->bindParam(':UID', $_SESSION['userid'], PDO::PARAM_INT); $stmt->bindParam(':cars', $trupps, PDO::PARAM_STR); $stmt->execute(); echo json_encode('successLocal'); } } ?>
cuzcomd/DALUS
php/options.php
PHP
gpl-3.0
4,972
package quests; import l2s.gameserver.ThreadPoolManager; import l2s.gameserver.model.instances.NpcInstance; import l2s.gameserver.model.quest.Quest; import l2s.gameserver.model.quest.QuestState; import l2s.gameserver.network.l2.components.NpcString; import l2s.gameserver.scripts.Functions; import l2s.gameserver.scripts.ScriptFile; //By Evil_dnk public class _10772_ReportsfromCrumaTowerPart1 extends Quest implements ScriptFile { // NPC's private static final int YANSEN = 30484; private static final int MAGICOWL = 33991; //ITEMS private static final int DOORCOIN = 37045; private static final int ENCHANTARMOR = 23420; private NpcInstance owl = null; public _10772_ReportsfromCrumaTowerPart1() { super(PARTY_NONE); addStartNpc(YANSEN); addTalkId(YANSEN); addTalkId(MAGICOWL); addQuestCompletedCheck(_10771_Volatile_Power.class); addLevelCheck(45); addRaceCheck(false, false, false, false, false, false, true); } @Override public String onEvent(String event, QuestState st, NpcInstance npc) { String htmltext = event; if(event.equalsIgnoreCase("30484-5.htm")) { owl = null; st.setState(STARTED); st.setCond(1); } else if(event.equalsIgnoreCase("30484-9.htm")) { st.getPlayer().addExpAndSp(127575, 30); st.giveItems(DOORCOIN, 4); st.giveItems(ENCHANTARMOR, 2); st.exitCurrentQuest(false); } else if(event.equalsIgnoreCase("summonbird")) { if (owl == null) owl = st.addSpawn(MAGICOWL, 17640, 114968, -11753, 0, 0, 120000); return null; } else if(event.equalsIgnoreCase("send")) { st.setCond(2); Functions.npcSay(owl, NpcString.TO_QUEEN_NAVARI_OF_FAERON); ThreadPoolManager.getInstance().schedule(() -> { npc.doDie(null); npc.endDecayTask(); }, 6000L); return null; } return htmltext; } @Override public String onTalk(NpcInstance npc, QuestState st) { int npcId = npc.getNpcId(); int cond = st.getCond(); String htmltext = "noquest"; switch (npcId) { case YANSEN: if(cond == 0) { if(checkStartCondition(st.getPlayer())) htmltext = "30484-1.htm"; else htmltext = "30484-0.htm"; } else if (cond == 1) htmltext = "30484-7.htm"; else if (cond == 2) htmltext = "30484-8.htm"; break; case MAGICOWL: if (cond == 1) htmltext = "33991-1.htm"; break; } return htmltext; } @Override public void onLoad() { } @Override public void onReload() { // } @Override public void onShutdown() { // } }
pantelis60/L2Scripts_Underground
dist/gameserver/data/scripts/quests/_10772_ReportsfromCrumaTowerPart1.java
Java
gpl-3.0
2,517
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.compatibility.common.util; /** * Represents a filter for including and excluding tests. */ public class TestFilter { private final String mAbi; private final String mName; private final String mTest; /** * Builds a new {@link TestFilter} from the given string. Filters can be in one of four forms, * the instance will be initialized as; * -"name" -> abi = null, name = "name", test = null * -"name" "test..." -> abi = null, name = "name", test = "test..." * -"abi" "name" -> abi = "abi", name = "name", test = null * -"abi" "name" "test..." -> abi = "abi", name = "name", test = "test..." * * Test identifier can contain multiple parts, eg parameterized tests. * * @param filter the filter to parse * @return the {@link TestFilter} */ public static TestFilter createFrom(String filter) { if (filter.isEmpty()) { throw new IllegalArgumentException("Filter was empty"); } String[] parts = filter.split(" "); String abi = null, name = null, test = null; // Either: // <name> // <name> <test> // <abi> <name> // <abi> <name> <test> if (parts.length == 1) { name = parts[0]; } else { int index = 0; if (AbiUtils.isAbiSupportedByCompatibility(parts[0])) { abi = parts[0]; index++; } name = parts[index]; index++; parts = filter.split(" ", index + 1); if (parts.length > index) { test = parts[index]; } } return new TestFilter(abi, name, test); } /** * Creates a new {@link TestFilter} from the given parts. * * @param abi The ABI must be supported {@link AbiUtils#isAbiSupportedByCompatibility(String)} * @param name The module's name * @param test The test's identifier eg <package>.<class>#<method> */ public TestFilter(String abi, String name, String test) { mAbi = abi; mName = name; mTest = test; } /** * Returns a String representation of this filter. This function is the inverse of * {@link TestFilter#createFrom(String)}. * * For a valid filter f; * <pre> * {@code * new TestFilter(f).toString().equals(f) * } * </pre> */ @Override public String toString() { StringBuilder sb = new StringBuilder(); if (mAbi != null) { sb.append(mAbi.trim()); sb.append(" "); } if (mName != null) { sb.append(mName.trim()); } if (mTest != null) { sb.append(" "); sb.append(mTest.trim()); } return sb.toString(); } /** * @return the abi of this filter, or null if not specified. */ public String getAbi() { return mAbi; } /** * @return the module name of this filter, or null if not specified. */ public String getName() { return mName; } /** * @return the test identifier of this filter, or null if not specified. */ public String getTest() { return mTest; } }
wiki2014/Learning-Summary
alps/cts/common/util/src/com/android/compatibility/common/util/TestFilter.java
Java
gpl-3.0
3,932
package org.um.feri.ears.problems.real_world.cec2011; import java.util.ArrayList; import java.util.Collections; import org.apache.commons.lang3.ArrayUtils; import org.um.feri.ears.problems.Problem; import org.um.feri.ears.util.Util; /** * Problem function! * * @author Matej Črepinšek * @version 1 * **/ public class CEC2011_Problem_11_7_ELD_140 extends Problem { private double g_constrains[]; //internal /* */ private static double[][] Data1= {{71,119,1220.645,61.24200,0.03288800,0,0}, {120,189,1315.118,41.09500,0.008280000,0,0}, {125,190,874.2880,46.31000,0.003849000,0,0}, {125,190,874.2880,46.31000,0.003849000,0,0}, {90,190,1976.469,54.24200,0.04246800,700,0.08}, {90,190,1338.087,61.21500,0.01499200,0,0}, {280,490,1818.299,11.79100,0.007039000,0,0}, {280,490,1133.978,15.05500,0.003079000,0,0}, {260,496,1320.636,13.22600,0.005063000,0,0}, {260,496,1320.636,13.22600,0.005063000,600,0.055}, {260,496,1320.636,13.22600,0.005063000,0,0}, {260,496,1106.539,14.49800,0.003552000,0,0}, {260,506,1176.504,14.65100,0.003901000,0,0}, {260,509,1176.504,14.65100,0.003901000,0,0}, {260,506,1176.504,14.65100,0.003901000,800,0.06}, {260,505,1176.504,14.65100,0.003901000,0,0}, {260,506,1017.406,15.66900,0.002393000,0,0}, {260,506,1017.406,15.66900,0.002393000,0,0}, {260,505,1229.131,14.65600,0.003684000,0,0}, {260,505,1229.131,14.65600,0.003684000,0,0}, {260,505,1229.131,14.65600,0.003684000,0,0}, {260,505,1229.131,14.65600,0.003684000,600,0.05}, {260,505,1267.894,14.37800,0.004004000,0,0}, {260,505,1229.131,14.65600,0.003684000,0,0}, {280,537,975.9260,16.26100,0.001619000,0,0}, {280,537,1532.093,13.36200,0.005093000,0,0}, {280,549,641.9890,17.20300,0.0009930000,0,0}, {280,549,641.9890,17.20300,0.0009930000,0,0}, {260,501,911.5330,15.27400,0.002473000,0,0}, {260,501,910.5330,15.21200,0.002547000,0,0}, {260,506,1074.810,15.03300,0.003542000,0,0}, {260,506,1074.810,15.03300,0.003542000,0,0}, {260,506,1074.810,15.03300,0.003542000,600,0.043}, {260,506,1074.810,15.03300,0.003542000,0,0}, {260,500,1278.460,13.99200,0.003132000,0,0}, {260,500,861.7420,15.67900,0.001323000,0,0}, {120,241,408.8340,16.54200,0.002950000,0,0}, {120,241,408.8340,16.54200,0.002950000,0,0}, {423,774,1288.815,16.51800,0.0009910000,0,0}, {423,769,1436.251,15.81500,0.001581000,600,0.043}, {3,19,699.9880,75.46400,0.9023600,0,0}, {3,28,134.5440,129.5440,0.1102950,0,0}, {160,250,3427.912,56.61300,0.02449300,0,0}, {160,250,3751.772,54.45100,0.02915600,0,0}, {160,250,3918.780,54.73600,0.02466700,0,0}, {160,250,3379.580,58.03400,0.01651700,0,0}, {160,250,3345.296,55.98100,0.02658400,0,0}, {160,250,3138.754,61.52000,0.007540000,0,0}, {160,250,3453.050,58.63500,0.01643000,0,0}, {160,250,5119.300,44.64700,0.04593400,0,0}, {165,504,1898.415,71.58400,4.4e-05,0,0}, {165,504,1898.415,71.58400,4.4e-05,1100,0.043}, {165,504,1898.415,71.58400,4.4e-05,0,0}, {165,504,1898.415,71.58400,4.4e-05,0,0}, {180,471,2473.390,85.12000,0.002528000,0,0}, {180,561,2781.705,87.68200,0.0001310000,0,0}, {103,341,5515.508,69.53200,0.01037200,0,0}, {198,617,3478.300,78.33900,0.007627000,0,0}, {100,312,6240.909,58.17200,0.01246400,0,0}, {153,471,9960.110,46.63600,0.03944100,0,0}, {163,500,3671.997,76.94700,0.007278000,0,0}, {95,302,1837.383,80.76100,4.4e-05,0,0}, {160,511,3108.395,70.13600,4.4e-05,0,0}, {160,511,3108.395,70.13600,4.4e-05,0,0}, {196,490,7095.484,49.84000,0.01882700,0,0}, {196,490,3392.732,65.40400,0.01085200,0,0}, {196,490,7095.484,49.84000,0.01882700,0,0}, {196,490,7095.484,49.84000,0.01882700,0,0}, {130,432,4288.320,66.46500,0.03456000,0,0}, {130,432,13813.0010,22.94100,0.08154000,1200,0.03}, {137,455,4435.493,64.31400,0.02353400,0,0}, {137,455,9750.750,45.01700,0.03547500,1000,0.05}, {195,541,1042.366,70.64400,0.0009150000,0,0}, {175,536,1159.895,70.95900,4.4e-05,0,0}, {175,540,1159.895,70.95900,4.4e-05,0,0}, {175,538,1303.990,70.30200,0.001307000,0,0}, {175,540,1156.193,70.66200,0.0003920000,0,0}, {330,574,2118.968,71.10100,8.7e-05,0,0}, {160,531,779.5190,37.85400,0.0005210000,0,0}, {160,531,829.8880,37.76800,0.0004980000,0,0}, {200,542,2333.690,67.98300,0.001046000,0,0}, {56,132,2028.954,77.83800,0.1320500,0,0}, {115,245,4412.017,63.67100,0.09696800,0,0}, {115,245,2982.219,79.45800,0.05486800,1000,0.05}, {115,245,2982.219,79.45800,0.05486800,0,0}, {207,307,3174.939,93.96600,0.01438200,0,0}, {207,307,3218.359,94.72300,0.01316100,0,0}, {175,345,3723.822,66.91900,0.01603300,0,0}, {175,345,3551.405,68.18500,0.01365300,0,0}, {175,345,4332.615,60.82100,0.02814800,0,0}, {175,345,3493.739,68.55100,0.01347000,0,0}, {360,580,226.7990,2.842000,6.4e-05,0,0}, {415,645,382.9320,2.946000,0.0002520000,0,0}, {795,984,156.9870,3.096000,2.2e-05,0,0}, {795,978,154.4840,3.040000,2.2e-05,0,0}, {578,682,332.8340,1.709000,0.0002030000,0,0}, {615,720,326.5990,1.668000,0.0001980000,0,0}, {612,718,345.3060,1.789000,0.0002150000,0,0}, {612,720,350.3720,1.815000,0.0002180000,0,0}, {758,964,370.3770,2.726000,0.0001930000,0,0}, {755,958,367.0670,2.732000,0.0001970000,0,0}, {750,1007,124.8750,2.651000,0.0003240000,0,0}, {750,1006,130.7850,2.798000,0.0003440000,0,0}, {713,1013,878.7460,1.595000,0.00069,0,0}, {718,1020,827.9590,1.503000,0.00065,0,0}, {791,954,432.0070,2.425000,0.0002330000,0,0}, {786,952,445.6060,2.499000,0.0002390000,0,0}, {795,1006,467.2230,2.674000,0.0002610000,0,0}, {795,1013,475.9400,2.692000,0.0002590000,0,0}, {795,1021,899.4620,1.633000,0.0007070000,0,0}, {795,1015,1000.367,1.816000,0.0007860000,0,0}, {94,203,1269.132,89.83000,0.01435500,0,0}, {94,203,1269.132,89.83000,0.01435500,0,0}, {94,203,1269.132,89.83000,0.01435500,0,0}, {244,379,4965.124,64.12500,0.03026600,0,0}, {244,379,4965.124,64.12500,0.03026600,0,0}, {244,379,4965.124,64.12500,0.03026600,0,0}, {95,190,2243.185,76.12900,0.02402700,0,0}, {95,189,2290.381,81.80500,0.001580000,600,0.07}, {116,194,1681.533,81.14000,0.02209500,0,0}, {175,321,6743.302,46.66500,0.07681000,1200,0.043}, {2,19,394.3980,78.41200,0.9534430,0,0}, {4,59,1243.165,112.0880,4.4e-05,0,0}, {15,83,1454.740,90.87100,0.07246800,0,0}, {9,53,1011.051,97.11600,0.0004480000,0,0}, {12,37,909.2690,83.24400,0.5991120,0,0}, {10,34,689.3780,95.66500,0.2447060,0,0}, {112,373,1443.792,91.20200,4.2e-05,0,0}, {4,20,535.5530,104.5010,0.08514500,0,0}, {5,38,617.7340,83.01500,0.5247180,0,0}, {5,19,90.96600,127.7950,0.1765150,0,0}, {50,98,974.4470,77.92900,0.06341400,0,0}, {5,10,263.8100,92.77900,2.740485,0,0}, {42,74,1335.594,80.95000,0.1124380,0,0}, {42,74,1033.871,89.07300,0.04152900,0,0}, {41,105,1391.325,161.2880,0.0009110000,0,0}, {17,51,4477.110,161.8290,0.005245000,0,0}, {7,19,57.79400,84.97200,0.2347870,0,0}, {7,19,57.79400,84.97200,0.2347870,0,0}, {26,40,1258.437,16.08700,1.111878,0,0}}; // % % % ============= 6 unit system data ========== // % Data1= [Pmin Pmax a b c]; /*private static double[][] Data1= {{71, 119, 1220.645, 61.242, 0.032888}, {120, 189, 1315.118, 41.095, 0.00828}, {125, 190, 874.288, 46.31, 0.003849}, {125, 190, 874.288, 46.31, 0.003849}, {90, 190, 1976.469, 54.242, 0.042468}, {90, 190, 1338.087, 61.215, 0.014992}, {280, 490, 1818.299, 11.791, 0.007039}, {280, 490, 1133.978, 15.055, 0.003079}, {260, 496, 1320.636, 13.226, 0.005063}, {260, 496, 1320.636, 13.226, 0.005063}, {260, 496, 1320.636, 13.226, 0.005063}, {260, 496, 1106.539, 14.498, 0.003552}, {260, 506, 1176.504, 14.651, 0.003901}, {260, 509, 1176.504, 14.651, 0.003901}, {260, 506, 1176.504, 14.651, 0.003901}, {260, 505, 1176.504, 14.651, 0.003901}, {260, 506, 1017.406, 15.669, 0.002393}, {260, 506, 1017.406, 15.669, 0.002393}, {260, 505, 1229.131, 14.656, 0.003684}, {260, 505, 1229.131, 14.656, 0.003684}, {260, 505, 1229.131, 14.656, 0.003684}, {260, 505, 1229.131, 14.656, 0.003684}, {260, 505, 1267.894, 14.378, 0.004004}, {260, 505, 1229.131, 14.656, 0.003684}, {280, 537, 975.926, 16.261, 0.001619}, {280, 537, 1532.093, 13.362, 0.005093}, {280, 549, 641.989, 17.203, 0.000993}, {280, 549, 641.989, 17.203, 0.000993}, {260, 501, 911.533, 15.274, 0.002473}, {260, 501, 910.533, 15.212, 0.002547}, {260, 506, 1074.81, 15.033, 0.003542}, {260, 506, 1074.81, 15.033, 0.003542}, {260, 506, 1074.81, 15.033, 0.003542}, {260, 506, 1074.81, 15.033, 0.003542}, {260, 500, 1278.46, 13.992, 0.003132}, {260, 500, 861.742, 15.679, 0.001323}, {120, 241, 408.834, 16.542, 0.00295}, {120, 241, 408.834, 16.542, 0.00295}, {423, 774, 1288.815, 16.518, 0.000991}, {423, 769, 1436.251, 15.815, 0.001581}, {3, 19, 699.988, 75.464, 0.90236}, {3, 28, 134.544, 129.544, 0.110295}, {160, 250, 3427.912, 56.613, 0.024493}, {160, 250, 3751.772, 54.451, 0.029156}, {160, 250, 3918.78, 54.736, 0.024667}, {160, 250, 3379.58, 58.034, 0.016517}, {160, 250, 3345.296, 55.981, 0.026584}, {160, 250, 3138.754, 61.52, 0.00754}, {160, 250, 3453.05, 58.635, 0.01643}, {160, 250, 5119.3, 44.647, 0.045934}, {165, 504, 1898.415, 71.584, 0.000044}, {165, 504, 1898.415, 71.584, 0.000044}, {165, 504, 1898.415, 71.584, 0.000044}, {165, 504, 1898.415, 71.584, 0.000044}, {180, 471, 2473.39, 85.12, 0.002528}, {180, 561, 2781.705, 87.682, 0.000131}, {103, 341, 5515.508, 69.532, 0.010372}, {198, 617, 3478.3, 78.339, 0.007627}, {100, 312, 6240.909, 58.172, 0.012464}, {153, 471, 9960.11, 46.636, 0.039441}, {163, 500, 3671.997, 76.947, 0.007278}, {95, 302, 1837.383, 80.761, 0.000044}, {160, 511, 3108.395, 70.136, 0.000044}, {160, 511, 3108.395, 70.136, 0.000044}, {196, 490, 7095.484, 49.84, 0.018827}, {196, 490, 3392.732, 65.404, 0.010852}, {196, 490, 7095.484, 49.84, 0.018827}, {196, 490, 7095.484, 49.84, 0.018827}, {130, 432, 4288.32, 66.465, 0.03456}, {130, 432, 13813.001, 22.941, 0.08154}, {137, 455, 4435.493, 64.314, 0.023534}, {137, 455, 9750.75, 45.017, 0.035475}, {195, 541, 1042.366, 70.644, 0.000915}, {175, 536, 1159.895, 70.959, 0.000044}, {175, 540, 1159.895, 70.959, 0.000044}, {175, 538, 1303.99, 70.302, 0.001307}, {175, 540, 1156.193, 70.662, 0.000392}, {330, 574, 2118.968, 71.101, 0.000087}, {160, 531, 779.519, 37.854, 0.000521}, {160, 531, 829.888, 37.768, 0.000498}, {200, 542, 2333.69, 67.983, 0.001046}, {56, 132, 2028.954, 77.838, 0.13205}, {115, 245, 4412.017, 63.671, 0.096968}, {115, 245, 2982.219, 79.458, 0.054868}, {115, 245, 2982.219, 79.458, 0.054868}, {207, 307, 3174.939, 93.966, 0.014382}, {207, 307, 3218.359, 94.723, 0.013161}, {175, 345, 3723.822, 66.919, 0.016033}, {175, 345, 3551.405, 68.185, 0.013653}, {175, 345, 4332.615, 60.821, 0.028148}, {175, 345, 3493.739, 68.551, 0.01347}, {360, 580, 226.799, 2.842, 0.000064}, {415, 645, 382.932, 2.946, 0.000252}, {795, 984, 156.987, 3.096, 0.000022}, {795, 978, 154.484, 3.04, 0.000022}, {578, 682, 332.834, 1.709, 0.000203}, {615, 720, 326.599, 1.668, 0.000198}, {612, 718, 345.306, 1.789, 0.000215}, {612, 720, 350.372, 1.815, 0.000218}, {758, 964, 370.377, 2.726, 0.000193}, {755, 958, 367.067, 2.732, 0.000197}, {750, 1007, 124.875, 2.651, 0.000324}, {750, 1006, 130.785, 2.798, 0.000344}, {713, 1013, 878.746, 1.595, 0.00069}, {718, 1020, 827.959, 1.503, 0.00065}, {791, 954, 432.007, 2.425, 0.000233}, {786, 952, 445.606, 2.499, 0.000239}, {795, 1006, 467.223, 2.674, 0.000261}, {795, 1013, 475.94, 2.692, 0.000259}, {795, 1021, 899.462, 1.633, 0.000707}, {795, 1015, 1000.367, 1.816, 0.000786}, {94, 203, 1269.132, 89.83, 0.014355}, {94, 203, 1269.132, 89.83, 0.014355}, {94, 203, 1269.132, 89.83, 0.014355}, {244, 379, 4965.124, 64.125, 0.030266}, {244, 379, 4965.124, 64.125, 0.030266}, {244, 379, 4965.124, 64.125, 0.030266}, {95, 190, 2243.185, 76.129, 0.024027}, {95, 189, 2290.381, 81.805, 0.00158}, {116, 194, 1681.533, 81.14, 0.022095}, {175, 321, 6743.302, 46.665, 0.07681}, {2, 19, 394.398, 78.412, 0.953443}, {4, 59, 1243.165, 112.088, 0.000044}, {15, 83, 1454.74, 90.871, 0.072468}, {9, 53, 1011.051, 97.116, 0.000448}, {12, 37, 909.269, 83.244, 0.599112}, {10, 34, 689.378, 95.665, 0.244706}, {112, 373, 1443.792, 91.202, 0.000042}, {4, 20, 535.553, 104.501, 0.085145}, {5, 38, 617.734, 83.015, 0.524718}, {5, 19, 90.966, 127.795, 0.176515}, {50, 98, 974.447, 77.929, 0.063414}, {5, 10, 263.81, 92.779, 2.740485}, {42, 74, 1335.594, 80.95, 0.112438}, {42, 74, 1033.871, 89.073, 0.041529}, {41, 105, 1391.325, 161.288, 0.000911}, {17, 51, 4477.11, 161.829, 0.005245}, {7, 19, 57.794, 84.972, 0.234787}, {7, 19, 57.794, 84.972, 0.234787}, {26, 40, 1258.437, 16.087, 1.111878}}; */ private static double[][] Data2= {{ 98.4, 30, 120, 0,0,0,0,0,0}, {134, 30, 120, 0,0,0,0,0,0}, {141.5, 60, 60, 0,0,0,0,0,0}, {183.3, 60, 60, 0,0,0,0,0,0}, {125, 150, 150, 0,0,0,0,0,0}, {91.3, 150, 150, 0,0,0,0,0,0}, {401.1, 180, 300, 0,0,0,0,0,0}, {329.5, 180, 300,250,280,305,335,420,450}, {386.1, 300, 510, 0,0,0,0,0,0}, {427.3, 300, 510, 0,0,0,0,0,0}, {412.2, 300, 510, 0,0,0,0,0,0}, {370.1, 300, 510, 0,0,0,0,0,0}, {301.8, 600, 600, 0,0,0,0,0,0}, {368, 600, 600, 0,0,0,0,0,0}, {301.9, 600, 600, 0,0,0,0,0,0}, {476.4, 600, 600, 0,0,0,0,0,0}, {283.1, 600, 600, 0,0,0,0,0,0}, {414.1, 600, 600, 0,0,0,0,0,0}, {328, 600, 600, 0,0,0,0,0,0}, {389.4, 600, 600, 0,0,0,0,0,0}, {354.7, 600, 600, 0,0,0,0,0,0}, {262, 600, 600, 0,0,0,0,0,0}, {461.5, 600, 600, 0,0,0,0,0,0}, {371.6, 600, 600, 0,0,0,0,0,0}, {462.6, 300, 300, 0,0,0,0,0,0}, {379.2, 300, 300, 0,0,0,0,0,0}, {530.8, 360, 360, 0,0,0,0,0,0}, {391.9, 360, 360, 0,0,0,0,0,0}, {480.1, 180, 180, 0,0,0,0,0,0}, {319, 180, 180, 0,0,0,0,0,0}, {329.5, 600, 600, 0,0,0,0,0,0}, {333.8, 600, 600,220,250,320,350,390,420}, {390, 600, 600, 0,0,0,0,0,0}, {432, 600, 600, 0,0,0,0,0,0}, {402, 660, 660, 0,0,0,0,0,0}, {428, 900, 900, 0,0,0,0,0,0}, {178.4, 180, 180, 0,0,0,0,0,0}, {194.1, 180, 180, 0,0,0,0,0,0}, {474, 600, 600, 0,0,0,0,0,0}, {609.8, 600, 600, 0,0,0,0,0,0}, {17.8, 210, 210, 0,0,0,0,0,0}, {6.9, 366, 366, 0,0,0,0,0,0}, {224.3, 702, 702, 0,0,0,0,0,0}, {210, 702, 702, 0,0,0,0,0,0}, {212, 702, 702, 0,0,0,0,0,0}, {200.8, 702, 702, 0,0,0,0,0,0}, {220, 702, 702, 0,0,0,0,0,0}, {232.9, 702, 702, 0,0,0,0,0,0}, {168, 702, 702, 0,0,0,0,0,0}, {208.4, 702, 702, 0,0,0,0,0,0}, {443.9, 1350, 1350, 0,0,0,0,0,0}, {426.0, 1350, 1350, 0,0,0,0,0,0}, {434.1, 1350, 1350, 0,0,0,0,0,0}, {402.5, 1350, 1350, 0,0,0,0,0,0}, {357.4, 1350, 1350, 0,0,0,0,0,0}, {423, 720, 720, 0,0,0,0,0,0}, {220, 720, 720, 0,0,0,0,0,0}, {369.4, 2700, 2700, 0,0,0,0,0,0}, {273.5, 1500, 1500, 0,0,0,0,0,0}, {336, 1656, 1656, 0,0,0,0,0,0}, {432, 2160, 2160, 0,0,0,0,0,0}, {220, 900, 900, 0,0,0,0,0,0}, {410.6, 1200, 1200, 0,0,0,0,0,0}, {422.7, 1200, 1200, 0,0,0,0,0,0}, {351, 1014, 1014, 0,0,0,0,0,0}, {296, 1014, 1014, 0,0,0,0,0,0}, {411.1, 1014, 1014, 0,0,0,0,0,0}, {263.2, 1014, 1014, 0,0,0,0,0,0}, {370.3, 1350, 1350, 0,0,0,0,0,0}, {418.7, 1350, 1350, 0,0,0,0,0,0}, {409.6, 1350, 1350, 0,0,0,0,0,0}, {412, 1350, 1350, 0,0,0,0,0,0}, {423.2, 780, 780, 0,0,0,0,0,0}, {428, 1650, 1650,230,255,365,395,430,455}, {436, 1650, 1650, 0,0,0,0,0,0}, {428, 1650, 1650, 0,0,0,0,0,0}, {425, 1650, 1650, 0,0,0,0,0,0}, {497.2, 1620, 1620, 0,0,0,0,0,0}, {510, 1482, 1482, 0,0,0,0,0,0}, {470, 1482, 1482, 0,0,0,0,0,0}, {464.1, 1668, 1668, 0,0,0,0,0,0}, {118.1, 120, 120, 0,0,0,0,0,0}, {141.3, 180, 180, 0,0,0,0,0,0}, {132, 120, 180, 0,0,0,0,0,0}, {135, 120, 180, 0,0,0,0,0,0}, {252, 120, 180, 0,0,0,0,0,0}, {221, 120, 180, 0,0,0,0,0,0}, {245.9, 318, 318, 0,0,0,0,0,0}, {247.9, 318, 318, 0,0,0,0,0,0}, {183.6, 318, 318, 0,0,0,0,0,0}, {288, 318, 318, 0,0,0,0,0,0}, {557.4, 18, 18, 0,0,0,0,0,0}, {529.5, 18, 18, 0,0,0,0,0,0}, {800.8, 36, 36, 0,0,0,0,0,0}, {801.5, 36, 36, 0,0,0,0,0,0}, {582.7, 138, 204, 0,0,0,0,0,0}, {680.7, 144, 216, 0,0,0,0,0,0}, {670.7, 144, 216, 0,0,0,0,0,0}, {651.7, 144, 216, 0,0,0,0,0,0}, {921, 48, 48, 0,0,0,0,0,0}, {916.8, 48, 48, 0,0,0,0,0,0}, {911.9, 36, 54, 0,0,0,0,0,0}, {898, 36, 54, 0,0,0,0,0,0}, {905, 30, 30, 0,0,0,0,0,0}, {846.5, 30, 30, 0,0,0,0,0,0}, {850.9, 30, 30, 0,0,0,0,0,0}, {843.7, 30, 30, 0,0,0,0,0,0}, {841.4, 36, 36, 0,0,0,0,0,0}, {835.7, 36, 36, 0,0,0,0,0,0}, {828.8, 36, 36, 0,0,0,0,0,0}, {846, 36, 36, 0,0,0,0,0,0}, {179, 120, 120, 0,0,0,0,0,0}, {120.8, 120, 120, 0,0,0,0,0,0}, {121, 120, 120, 0,0,0,0,0,0}, {317.4, 480, 480, 0,0,0,0,0,0}, {318.4, 480, 480, 0,0,0,0,0,0}, {335.8, 480, 480, 0,0,0,0,0,0}, {151, 240, 240, 0,0,0,0,0,0}, {129.5, 240, 240, 0,0,0,0,0,0}, {130, 120, 120, 0,0,0,0,0,0}, {218.9, 180, 180, 0,0,0,0,0,0}, {5.4, 90, 90, 0,0,0,0,0,0}, {45, 90, 90, 0,0,0,0,0,0}, {20, 300, 300, 0,0,0,0,0,0}, {16.3, 162, 162, 0,0,0,0,0,0}, {20, 114, 114, 0,0,0,0,0,0}, {22.1, 120, 120, 0,0,0,0,0,0}, {125, 1080, 1080, 0,0,0,0,0,0}, {10, 60, 60, 0,0,0,0,0,0}, {13, 66, 66, 0,0,0,0,0,0}, {7.5, 12, 6, 0,0,0,0,0,0}, {53.2, 300, 300, 0,0,0,0,0,0}, {6.4, 6, 6, 0,0,0,0,0,0}, {69.1, 60, 60, 0,0,0,0,0,0}, {49.9, 60, 60, 0,0,0,0,0,0}, {91, 528, 528,50,75,85,95,0,0}, {41, 300, 300, 0,0,0,0,0,0}, {13.7, 18, 30, 0,0,0,0,0,0}, {7.4, 18, 30, 0,0,0,0,0,0}, {28.6, 72, 120, 0,0,0,0,0,0}}; private static double[][] Data3 ={{5, 700, 0.080}, {10, 600, 0.055}, {15, 800, 0.060}, {22, 600, 0.050}, {33, 600, 0.043}, {40, 600, 0.043}, {52, 1100, 0.043}, {70, 1200, 0.030}, {72, 1000, 0.050}, {84, 1000, 0.050}, {119,600, 0.070}, {121,1200, 0.043}}; private static double[][] Data4 = {{ 8, 250, 280, 305, 335, 420, 450}, {32, 220, 250, 320, 350, 390, 420}, {74, 230, 255, 365, 395, 430, 455}, {136,50, 75, 85, 95, 0, 0}}; //% Loss Co-efficients private static double[][] B1={ }; private static double[] B2={}; private static double B3=0; private static double Power_Demand = 49342;; // in MW private static int Pmin_data1_col=0;// = Data1(:,1)'; private static int Pmax_data1_col=1;// = Data1(:,2)'; private static int a_data1_col=4; private static int b_data1_col=3; private static int c_data1_col=2; private static int e_data1_col=5; private static int f_data1_col=6; private static int Initial_Generations_data2_col=0; private static int Up_Ramp_data2_col=1; private static int Down_Ramp_data2_col=2; public CEC2011_Problem_11_7_ELD_140() { super(140,4); lowerLimit = new ArrayList<Double>(Collections.nCopies(numberOfDimensions, 0.0)); upperLimit = new ArrayList<Double>(Collections.nCopies(numberOfDimensions, 0.0)); for (int z=0; z<numberOfDimensions; z++) { lowerLimit.set(z, Data1[z][0]); upperLimit.set(z, Data1[z][1]); } name = "RWP_11_7_ELD_140"; description = "RWP_11_7_ELD_140 Static Economic Load Dispatch (ELD) Problem "; } private double produkt(double x[], double y[]) { double t=0; for (int i=0;i<x.length; i++) { t+=x[i]*y[i]; } return t; } private double[] produkt2(double x[],double y[][]) { double t[]=new double[numberOfDimensions]; //dim?? for (int i=0;i<x.length; i++) { double tt=0; for (int ii=0;ii<x.length; ii++) { tt+=x[i]*y[ii][i]; } t[i]=tt; } return t; } protected double sum(double x[]) { double tt=0; for (int ii=0;ii<x.length; ii++) { tt+=x[ii]; } return tt; } public static double Up_Ramp_Limit(int i) { //System.out.println("Pmax "+Data1[i][Pmax_data1_col]+" Initial_Generations:"+Data2[i][Initial_Generations_data2_col]+" Up_Ramp:"+Data2[i][Up_Ramp_data2_col]+" "+Data2[i][Initial_Generations_data2_col]+Data2[i][Up_Ramp_data2_col]); return Math.min(Data1[i][Pmax_data1_col],Data2[i][Initial_Generations_data2_col]+Data2[i][Up_Ramp_data2_col]); } //Down_Ramp_Limit = max(Pmin,Initial_Generations-Down_Ramp); public static double Down_Ramp_Limit(int i) { return Math.max(Data1[i][Pmin_data1_col],Data2[i][Initial_Generations_data2_col]-Data2[i][Down_Ramp_data2_col]); } public static int No_of_POZ_Limits() { //System.out.println(Data2[0].length-4+1); return Data2[0].length-4+1; } public static double Prohibited_Operating_Zones_POZ(int i, int j) { //y,x //System.out.println("D2="+D2+" len:"+Data2.length); return Data2[j][3+i]; } public static double POZ_Lower_Limits(int i, int j) { return Prohibited_Operating_Zones_POZ(i*2,j); } public static double POZ_Upper_Limits(int i, int j) { return Prohibited_Operating_Zones_POZ(i*2+1,j); } public double[] calc_constrains(double x[]) { g_constrains = new double[numberOfConstraints]; double Power_Loss = 0; double Power_Balance_Penalty = Math.abs(Power_Demand + Power_Loss - sum(x)); double Capacity_Limits_Penalty=0; for (int i=0; i<numberOfDimensions; i++) { //Capacity_Limits_Penalty = sum(abs(x-Pmin)-(x-Pmin)) + sum(abs(Pmax-x)-(Pmax-x)); Capacity_Limits_Penalty+=Math.abs(x[i]-Data1[i][Pmin_data1_col])-(x[i]-Data1[i][Pmin_data1_col]); //sum(abs(x-Pmin)-(x-Pmin)) Capacity_Limits_Penalty+=Math.abs(Data1[i][Pmax_data1_col]-x[i])-(Data1[i][Pmax_data1_col]-x[i]); //sum(abs(Pmax-x)-(Pmax-x)) } double Ramp_Limits_Penalty=0; for (int i=0; i<numberOfDimensions; i++) { // Ramp_Limits_Penalty = sum(abs(x-Down_Ramp_Limit)-(x-Down_Ramp_Limit)) + sum(abs(Up_Ramp_Limit-x)-(Up_Ramp_Limit-x)); Ramp_Limits_Penalty+=Math.abs(x[i]-Down_Ramp_Limit(i))-(x[i]-Down_Ramp_Limit(i)); //sum(abs(x-Down_Ramp_Limit)-(x-Down_Ramp_Limit)) Ramp_Limits_Penalty+=Math.abs(Up_Ramp_Limit(i)-x[i])-(Up_Ramp_Limit(i)-x[i]); //sum(abs(Up_Ramp_Limit-x)-(Up_Ramp_Limit-x)); } // System.out.println("Ramp_Limits_Penalty="+Ramp_Limits_Penalty); double POZ_Penalty=0; //temp_x = repmat(x,No_of_POZ_Limits/2,1); //POZ_Penalty = sum(sum((POZ_Lower_Limits<temp_x & temp_x<POZ_Upper_Limits).*min(temp_x-POZ_Lower_Limits,POZ_Upper_Limits-temp_x))); for (int j=0; j<No_of_POZ_Limits()/2; j++) { for (int i=0; i<numberOfDimensions; i++) { if ((POZ_Lower_Limits(j,i)<x[i]) && (x[i]<POZ_Upper_Limits(j,i))) { POZ_Penalty+=Math.min(x[i]-POZ_Lower_Limits(j, i), POZ_Upper_Limits(j, i)-x[i]); } } } g_constrains[0] = 1e7*Power_Balance_Penalty; g_constrains[1] = 1e5*Capacity_Limits_Penalty; g_constrains[2] = 1e7*Ramp_Limits_Penalty ; g_constrains[3] = 1e5*POZ_Penalty ; return g_constrains; //do I need deep copy? } public double eval(double x[]) { double f = 0,ff; for (int i=0; i<numberOfDimensions; i++) { ff=Data1[i][a_data1_col]*x[i]*x[i]+Data1[i][b_data1_col]*x[i]+Data1[i][c_data1_col]+Math.abs(Data1[i][e_data1_col]*Math.sin(Data1[i][e_data1_col]*(Data1[i][Pmin_data1_col]-x[i]))); //System.out.print(ff+" "); f+=ff; } //System.out.println(); // System.out.println("f:"+f+" Total_Penalty:"+Total_Penalty); return f; } public double eval11(double x[]) { double f = 0,ff; System.out.print("a "); for (int i=0; i<20; i++) { System.out.print(Data1[i][a_data1_col]+" "); } System.out.println(); for (int i=0; i<20; i++) { ff=Data1[i][a_data1_col]*x[i]*x[i]+Data1[i][b_data1_col]*x[i]+Data1[i][c_data1_col]+Math.abs(Data1[i][e_data1_col]*Math.sin(Data1[i][e_data1_col]*(Data1[i][Pmin_data1_col]-x[i]))); System.out.print(ff+" "); f+=ff; } System.out.println(); // System.out.println("f:"+f+" Total_Penalty:"+Total_Penalty); return f; } @Override public double eval(Double[] ds) { return eval(ArrayUtils.toPrimitive(ds)); } public double getOptimumEval() { return 0; //OK } }
scrmtrey91/EARS
src/org/um/feri/ears/problems/real_world/cec2011/CEC2011_Problem_11_7_ELD_140.java
Java
gpl-3.0
25,259