code
stringlengths
4
1.01M
language
stringclasses
2 values
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <!-- Mirrored from www.photobookmart.com.my/wp-content/themes/choices/framework/php/avia_shortcodes/tinymce/js/?C=M;O=A by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 02 Jul 2014 12:07:04 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=ISO-8859-1" /><!-- /Added by HTTrack --> <head> <title>Index of /wp-content/themes/choices/framework/php/avia_shortcodes/tinymce/js</title> </head> <body> <h1>Index of /wp-content/themes/choices/framework/php/avia_shortcodes/tinymce/js</h1> <table><tr><th><img src="../../../../../../../../icons/blank.html" alt="[ICO]"></th><th><a href="indexb70a.html?C=N;O=A">Name</a></th><th><a href="index72c9.html?C=M;O=D">Last modified</a></th><th><a href="indexbfec.html?C=S;O=A">Size</a></th><th><a href="index30b5.html?C=D;O=A">Description</a></th></tr><tr><th colspan="5"><hr></th></tr> <tr><td valign="top"><img src="../../../../../../../../icons/back.html" alt="[DIR]"></td><td><a href="../index.html">Parent Directory</a></td><td>&nbsp;</td><td align="right"> - </td></tr> <tr><td valign="top"><img src="../../../../../../../../icons/unknown.gif" alt="[ ]"></td><td><a href="column-control.js">column-control.js</a></td><td align="right">19-Aug-2013 14:14 </td><td align="right">3.9K</td></tr> <tr><td valign="top"><img src="../../../../../../../../icons/unknown.gif" alt="[ ]"></td><td><a href="dialog.js">dialog.js</a></td><td align="right">19-Aug-2013 14:14 </td><td align="right"> 11K</td></tr> <tr><td valign="top"><img src="../../../../../../../../icons/unknown.gif" alt="[ ]"></td><td><a href="sidebar-tab-control.js">sidebar-tab-control.js</a></td><td align="right">19-Aug-2013 14:14 </td><td align="right">3.8K</td></tr> <tr><td valign="top"><img src="../../../../../../../../icons/unknown.gif" alt="[ ]"></td><td><a href="tab-control.js">tab-control.js</a></td><td align="right">19-Aug-2013 14:14 </td><td align="right">2.9K</td></tr> <tr><td valign="top"><img src="../../../../../../../../icons/unknown.gif" alt="[ ]"></td><td><a href="table-control.js">table-control.js</a></td><td align="right">19-Aug-2013 14:14 </td><td align="right">9.6K</td></tr> <tr><th colspan="5"><hr></th></tr> </table> <address>Apache/2.2.3 (CentOS) Server at www.photobookmart.com.my Port 80</address> </body> <!-- Mirrored from www.photobookmart.com.my/wp-content/themes/choices/framework/php/avia_shortcodes/tinymce/js/?C=M;O=A by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 02 Jul 2014 12:07:04 GMT --> </html>
Java
# Copyright 2014-2017 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # """ When importing a VM a thread start with a new process of virt-v2v. The way to feedback the information on the progress and the status of the process (ie job) is via getVdsStats() with the fields progress and status. progress is a number which represent percentage of a single disk copy, status is a way to feedback information on the job (init, error etc) """ from __future__ import absolute_import from collections import namedtuple from contextlib import closing, contextmanager import errno import io import logging import os import re import subprocess import tarfile import time import threading import xml.etree.ElementTree as ET import zipfile import libvirt from vdsm.cmdutils import wrap_command from vdsm.commands import execCmd, BUFFSIZE from vdsm.common import cmdutils from vdsm.common.define import errCode, doneCode from vdsm.common import response from vdsm.common import zombiereaper from vdsm.common.compat import CPopen from vdsm.common.logutils import traceback from vdsm.common.time import monotonic_time from vdsm.constants import P_VDSM_LOG, P_VDSM_RUN, EXT_KVM_2_OVIRT from vdsm import concurrent, libvirtconnection from vdsm import password from vdsm.utils import terminating, NICENESS, IOCLASS try: import ovirt_imageio_common except ImportError: ovirt_imageio_common = None _lock = threading.Lock() _jobs = {} _V2V_DIR = os.path.join(P_VDSM_RUN, 'v2v') _LOG_DIR = os.path.join(P_VDSM_LOG, 'import') _VIRT_V2V = cmdutils.CommandPath('virt-v2v', '/usr/bin/virt-v2v') _SSH_AGENT = cmdutils.CommandPath('ssh-agent', '/usr/bin/ssh-agent') _SSH_ADD = cmdutils.CommandPath('ssh-add', '/usr/bin/ssh-add') _XEN_SSH_PROTOCOL = 'xen+ssh' _VMWARE_PROTOCOL = 'vpx' _KVM_PROTOCOL = 'qemu' _SSH_AUTH_RE = '(SSH_AUTH_SOCK)=([^;]+).*;\nSSH_AGENT_PID=(\d+)' _OVF_RESOURCE_CPU = 3 _OVF_RESOURCE_MEMORY = 4 _OVF_RESOURCE_NETWORK = 10 _QCOW2_COMPAT_SUPPORTED = ('0.10', '1.1') # OVF Specification: # https://www.iso.org/obp/ui/#iso:std:iso-iec:17203:ed-1:v1:en _OVF_NS = 'http://schemas.dmtf.org/ovf/envelope/1' _RASD_NS = 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/' \ 'CIM_ResourceAllocationSettingData' ImportProgress = namedtuple('ImportProgress', ['current_disk', 'disk_count', 'description']) DiskProgress = namedtuple('DiskProgress', ['progress']) class STATUS: ''' STARTING: request granted and starting the import process COPYING_DISK: copying disk in progress ABORTED: user initiated aborted FAILED: error during import process DONE: convert process successfully finished ''' STARTING = 'starting' COPYING_DISK = 'copying_disk' ABORTED = 'aborted' FAILED = 'error' DONE = 'done' class V2VError(Exception): ''' Base class for v2v errors ''' err_name = 'unexpected' # TODO: use more specific error class ClientError(Exception): ''' Base class for client error ''' err_name = 'unexpected' class InvalidVMConfiguration(ValueError): ''' Unexpected error while parsing libvirt domain xml ''' class OutputParserError(V2VError): ''' Error while parsing virt-v2v output ''' class JobExistsError(ClientError): ''' Job already exists in _jobs collection ''' err_name = 'JobExistsError' class VolumeError(ClientError): ''' Error preparing volume ''' class NoSuchJob(ClientError): ''' Job not exists in _jobs collection ''' err_name = 'NoSuchJob' class JobNotDone(ClientError): ''' Import process still in progress ''' err_name = 'JobNotDone' class NoSuchOvf(V2VError): ''' Ovf path is not exists in /var/run/vdsm/v2v/ ''' err_name = 'V2VNoSuchOvf' class V2VProcessError(V2VError): ''' virt-v2v process had error in execution ''' class InvalidInputError(ClientError): ''' Invalid input received ''' def get_external_vms(uri, username, password, vm_names=None): if vm_names is not None: if not vm_names: vm_names = None else: vm_names = frozenset(vm_names) try: conn = libvirtconnection.open_connection(uri=uri, username=username, passwd=password) except libvirt.libvirtError as e: logging.exception('error connecting to hypervisor') return {'status': {'code': errCode['V2VConnection']['status']['code'], 'message': str(e)}} with closing(conn): vms = [] for vm in _list_domains(conn): if vm_names is not None and vm.name() not in vm_names: # Skip this VM. continue elif conn.getType() == "ESX" and _vm_has_snapshot(vm): logging.error("vm %r has snapshots and therefore can not be " "imported since snapshot conversion is not " "supported for VMware", vm.name()) continue _add_vm(conn, vms, vm) return {'status': doneCode, 'vmList': vms} def get_external_vm_names(uri, username, password): try: conn = libvirtconnection.open_connection(uri=uri, username=username, passwd=password) except libvirt.libvirtError as e: logging.exception('error connecting to hypervisor') return response.error('V2VConnection', str(e)) with closing(conn): vms = [vm.name() for vm in _list_domains(conn)] return response.success(vmNames=vms) def convert_external_vm(uri, username, password, vminfo, job_id, irs): if uri.startswith(_XEN_SSH_PROTOCOL): command = XenCommand(uri, vminfo, job_id, irs) elif uri.startswith(_VMWARE_PROTOCOL): command = LibvirtCommand(uri, username, password, vminfo, job_id, irs) elif uri.startswith(_KVM_PROTOCOL): if ovirt_imageio_common is None: raise V2VError('Unsupported protocol KVM, ovirt_imageio_common' 'package is needed for importing KVM images') command = KVMCommand(uri, username, password, vminfo, job_id, irs) else: raise ClientError('Unknown protocol for Libvirt uri: %s', uri) job = ImportVm(job_id, command) job.start() _add_job(job_id, job) return {'status': doneCode} def convert_ova(ova_path, vminfo, job_id, irs): command = OvaCommand(ova_path, vminfo, job_id, irs) job = ImportVm(job_id, command) job.start() _add_job(job_id, job) return response.success() def get_ova_info(ova_path): ns = {'ovf': _OVF_NS, 'rasd': _RASD_NS} try: root = ET.fromstring(_read_ovf_from_ova(ova_path)) except ET.ParseError as e: raise V2VError('Error reading ovf from ova, position: %r' % e.position) vm = {} _add_general_ovf_info(vm, root, ns, ova_path) _add_disks_ovf_info(vm, root, ns) _add_networks_ovf_info(vm, root, ns) return response.success(vmList=vm) def get_converted_vm(job_id): try: job = _get_job(job_id) _validate_job_done(job) ovf = _read_ovf(job_id) except ClientError as e: logging.info('Converted VM error %s', e) return errCode[e.err_name] except V2VError as e: logging.error('Converted VM error %s', e) return errCode[e.err_name] return {'status': doneCode, 'ovf': ovf} def delete_job(job_id): try: job = _get_job(job_id) _validate_job_finished(job) _remove_job(job_id) except ClientError as e: logging.info('Cannot delete job, error: %s', e) return errCode[e.err_name] return {'status': doneCode} def abort_job(job_id): try: job = _get_job(job_id) job.abort() except ClientError as e: logging.info('Cannot abort job, error: %s', e) return errCode[e.err_name] return {'status': doneCode} def get_jobs_status(): ret = {} with _lock: items = tuple(_jobs.items()) for job_id, job in items: ret[job_id] = { 'status': job.status, 'description': job.description, 'progress': job.progress } return ret def _add_job(job_id, job): with _lock: if job_id in _jobs: raise JobExistsError("Job %r exists" % job_id) _jobs[job_id] = job def _get_job(job_id): with _lock: if job_id not in _jobs: raise NoSuchJob("No such job %r" % job_id) return _jobs[job_id] def _remove_job(job_id): with _lock: if job_id not in _jobs: raise NoSuchJob("No such job %r" % job_id) del _jobs[job_id] def _validate_job_done(job): if job.status != STATUS.DONE: raise JobNotDone("Job %r is %s" % (job.id, job.status)) def _validate_job_finished(job): if job.status not in (STATUS.DONE, STATUS.FAILED, STATUS.ABORTED): raise JobNotDone("Job %r is %s" % (job.id, job.status)) def _read_ovf(job_id): file_name = os.path.join(_V2V_DIR, "%s.ovf" % job_id) try: with open(file_name, 'r') as f: return f.read() except IOError as e: if e.errno != errno.ENOENT: raise raise NoSuchOvf("No such ovf %r" % file_name) class SSHAgent(object): """ virt-v2v uses ssh-agent for importing xen vms from libvirt, after virt-v2v log in to the machine it needs to copy its disks which ssh-agent let it handle without passwords while the session is on. for more information please refer to the virt-v2v man page: http://libguestfs.org/virt-v2v.1.html """ def __init__(self): self._auth = None self._agent_pid = None self._ssh_auth_re = re.compile(_SSH_AUTH_RE) def __enter__(self): rc, out, err = execCmd([_SSH_AGENT.cmd], raw=True) if rc != 0: raise V2VError('Error init ssh-agent, exit code: %r' ', out: %r, err: %r' % (rc, out, err)) m = self._ssh_auth_re.match(out) # looking for: SSH_AUTH_SOCK=/tmp/ssh-VEE74ObhTWBT/agent.29917 self._auth = {m.group(1): m.group(2)} self._agent_pid = m.group(3) try: rc, out, err = execCmd([_SSH_ADD.cmd], env=self._auth) except: self._kill_agent() raise if rc != 0: # 1 = general fail # 2 = no agnet if rc != 2: self._kill_agent() raise V2VError('Error init ssh-add, exit code: %r' ', out: %r, err: %r' % (rc, out, err)) def __exit__(self, *args): rc, out, err = execCmd([_SSH_ADD.cmd, '-d'], env=self._auth) if rc != 0: logging.error('Error deleting ssh-add, exit code: %r' ', out: %r, err: %r' % (rc, out, err)) self._kill_agent() def _kill_agent(self): rc, out, err = execCmd([_SSH_AGENT.cmd, '-k'], env={'SSH_AGENT_PID': self._agent_pid}) if rc != 0: logging.error('Error killing ssh-agent (PID=%r), exit code: %r' ', out: %r, err: %r' % (self._agent_pid, rc, out, err)) @property def auth(self): return self._auth class V2VCommand(object): def __init__(self, vminfo, vmid, irs): self._vminfo = vminfo self._vmid = vmid self._irs = irs self._prepared_volumes = [] self._passwd_file = os.path.join(_V2V_DIR, "%s.tmp" % vmid) self._password = password.ProtectedPassword('') self._base_command = [_VIRT_V2V.cmd, '-v', '-x'] self._query_v2v_caps() if 'qcow2_compat' in vminfo: qcow2_compat = vminfo['qcow2_compat'] if qcow2_compat not in _QCOW2_COMPAT_SUPPORTED: logging.error('Invalid QCOW2 compat version %r' % qcow2_compat) raise ValueError('Invalid QCOW2 compat version %r' % qcow2_compat) if 'vdsm-compat-option' in self._v2v_caps: self._base_command.extend(['--vdsm-compat', qcow2_compat]) elif qcow2_compat != '0.10': # Note: qcow2 is only a suggestion from the engine # if virt-v2v doesn't support it we fall back to default logging.info('virt-v2v not supporting qcow2 compat version: ' '%r', qcow2_compat) def execute(self): raise NotImplementedError("Subclass must implement this") def _command(self): raise NotImplementedError("Subclass must implement this") def _start_helper(self): timestamp = time.strftime('%Y%m%dT%H%M%S') log = os.path.join(_LOG_DIR, "import-%s-%s.log" % (self._vmid, timestamp)) logging.info("Storing import log at: %r", log) v2v = _simple_exec_cmd(self._command(), nice=NICENESS.HIGH, ioclass=IOCLASS.IDLE, env=self._environment(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) tee = _simple_exec_cmd(['tee', log], nice=NICENESS.HIGH, ioclass=IOCLASS.IDLE, stdin=v2v.stdout, stdout=subprocess.PIPE) return PipelineProc(v2v, tee) def _get_disk_format(self): fmt = self._vminfo.get('format', 'raw').lower() return "qcow2" if fmt == "cow" else fmt def _disk_parameters(self): parameters = [] for disk in self._vminfo['disks']: try: parameters.append('--vdsm-image-uuid') parameters.append(disk['imageID']) parameters.append('--vdsm-vol-uuid') parameters.append(disk['volumeID']) except KeyError as e: raise InvalidInputError('Job %r missing required property: %s' % (self._vmid, e)) return parameters @contextmanager def _volumes(self): self._prepare_volumes() try: yield finally: self._teardown_volumes() def _prepare_volumes(self): if len(self._vminfo['disks']) < 1: raise InvalidInputError('Job %r cannot import vm with no disk', self._vmid) for disk in self._vminfo['disks']: drive = {'poolID': self._vminfo['poolID'], 'domainID': self._vminfo['domainID'], 'volumeID': disk['volumeID'], 'imageID': disk['imageID']} res = self._irs.prepareImage(drive['domainID'], drive['poolID'], drive['imageID'], drive['volumeID']) if res['status']['code']: raise VolumeError('Job %r bad volume specification: %s' % (self._vmid, drive)) drive['path'] = res['path'] self._prepared_volumes.append(drive) def _teardown_volumes(self): for drive in self._prepared_volumes: try: self._irs.teardownImage(drive['domainID'], drive['poolID'], drive['imageID']) except Exception as e: logging.error('Job %r error tearing down drive: %s', self._vmid, e) def _get_storage_domain_path(self, path): ''' prepareImage returns /prefix/sdUUID/images/imgUUID/volUUID we need storage domain absolute path so we go up 3 levels ''' return path.rsplit(os.sep, 3)[0] def _environment(self): # Provide some sane environment env = os.environ.copy() # virt-v2v specific variables env['LIBGUESTFS_BACKEND'] = 'direct' if 'virtio_iso_path' in self._vminfo: env['VIRTIO_WIN'] = self._vminfo['virtio_iso_path'] return env @contextmanager def _password_file(self): fd = os.open(self._passwd_file, os.O_WRONLY | os.O_CREAT, 0o600) try: if self._password.value is None: os.write(fd, "") else: os.write(fd, self._password.value) finally: os.close(fd) try: yield finally: try: os.remove(self._passwd_file) except Exception: logging.exception("Job %r error removing passwd file: %s", self._vmid, self._passwd_file) def _query_v2v_caps(self): self._v2v_caps = frozenset() p = _simple_exec_cmd([_VIRT_V2V.cmd, '--machine-readable'], env=os.environ.copy(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) with terminating(p): try: out, err = p.communicate() except Exception: logging.exception('Terminating virt-v2v process after error') raise if p.returncode != 0: raise V2VProcessError( 'virt-v2v exited with code: %d, stderr: %r' % (p.returncode, err)) self._v2v_caps = frozenset(out.splitlines()) logging.debug("Detected virt-v2v capabilities: %r", self._v2v_caps) class LibvirtCommand(V2VCommand): def __init__(self, uri, username, password, vminfo, vmid, irs): super(LibvirtCommand, self).__init__(vminfo, vmid, irs) self._uri = uri self._username = username self._password = password def _command(self): cmd = self._base_command cmd.extend(['-ic', self._uri, '-o', 'vdsm', '-of', self._get_disk_format(), '-oa', self._vminfo.get('allocation', 'sparse').lower()]) cmd.extend(self._disk_parameters()) cmd.extend(['--password-file', self._passwd_file, '--vdsm-vm-uuid', self._vmid, '--vdsm-ovf-output', _V2V_DIR, '--machine-readable', '-os', self._get_storage_domain_path( self._prepared_volumes[0]['path']), self._vminfo['vmName']]) return cmd @contextmanager def execute(self): with self._volumes(), self._password_file(): yield self._start_helper() class OvaCommand(V2VCommand): def __init__(self, ova_path, vminfo, vmid, irs): super(OvaCommand, self).__init__(vminfo, vmid, irs) self._ova_path = ova_path def _command(self): cmd = self._base_command cmd.extend(['-i', 'ova', self._ova_path, '-o', 'vdsm', '-of', self._get_disk_format(), '-oa', self._vminfo.get('allocation', 'sparse').lower(), '--vdsm-vm-uuid', self._vmid, '--vdsm-ovf-output', _V2V_DIR, '--machine-readable', '-os', self._get_storage_domain_path( self._prepared_volumes[0]['path'])]) cmd.extend(self._disk_parameters()) return cmd @contextmanager def execute(self): with self._volumes(): yield self._start_helper() class XenCommand(V2VCommand): """ Importing Xen via virt-v2v require to use xen+ssh protocol. this requires: - enable the vdsm user in /etc/passwd - generate ssh keys via ssh-keygen - public key exchange with the importing hosts user - host must be in ~/.ssh/known_hosts (done automatically by ssh to the host before importing vm) """ def __init__(self, uri, vminfo, job_id, irs): super(XenCommand, self).__init__(vminfo, job_id, irs) self._uri = uri self._ssh_agent = SSHAgent() def _command(self): cmd = self._base_command cmd.extend(['-ic', self._uri, '-o', 'vdsm', '-of', self._get_disk_format(), '-oa', self._vminfo.get('allocation', 'sparse').lower()]) cmd.extend(self._disk_parameters()) cmd.extend(['--vdsm-vm-uuid', self._vmid, '--vdsm-ovf-output', _V2V_DIR, '--machine-readable', '-os', self._get_storage_domain_path( self._prepared_volumes[0]['path']), self._vminfo['vmName']]) return cmd @contextmanager def execute(self): with self._volumes(), self._ssh_agent: yield self._start_helper() def _environment(self): env = super(XenCommand, self)._environment() env.update(self._ssh_agent.auth) return env class KVMCommand(V2VCommand): def __init__(self, uri, username, password, vminfo, vmid, irs): super(KVMCommand, self).__init__(vminfo, vmid, irs) self._uri = uri self._username = username self._password = password def _command(self): cmd = [EXT_KVM_2_OVIRT, '--uri', self._uri] if self._username is not None: cmd.extend([ '--username', self._username, '--password-file', self._passwd_file]) src, fmt = self._source_images() cmd.append('--source') cmd.extend(src) cmd.append('--dest') cmd.extend(self._dest_images()) cmd.append('--storage-type') cmd.extend(fmt) cmd.append('--vm-name') cmd.append(self._vminfo['vmName']) return cmd @contextmanager def execute(self): with self._volumes(), self._password_file(): yield self._start_helper() def _source_images(self): con = libvirtconnection.open_connection(uri=self._uri, username=self._username, passwd=self._password) with closing(con): vm = con.lookupByName(self._vminfo['vmName']) if vm: params = {} root = ET.fromstring(vm.XMLDesc(0)) _add_disks(root, params) src = [] fmt = [] for disk in params['disks']: if 'alias' in disk: src.append(disk['alias']) fmt.append(disk['disktype']) return src, fmt def _dest_images(self): ret = [] for vol in self._prepared_volumes: ret.append(vol['path']) return ret class PipelineProc(object): def __init__(self, proc1, proc2): self._procs = (proc1, proc2) self._stdout = proc2.stdout def kill(self): """ Kill all processes in a pipeline. Some of the processes may have already terminated, but some may be still running. Regular kill() raises OSError if the process has already terminated. Since we are dealing with multiple processes, to avoid any confusion we do not raise OSError at all. """ for p in self._procs: logging.debug("Killing pid=%d", p.pid) try: p.kill() except OSError as e: # Probably the process has already terminated if e.errno != errno.ESRCH: raise e @property def pids(self): return [p.pid for p in self._procs] @property def returncode(self): """ Returns None if any of the processes is still running. Returns 0 if all processes have finished with a zero exit code, otherwise return first nonzero exit code. """ ret = 0 for p in self._procs: p.poll() if p.returncode is None: return None if p.returncode != 0 and ret == 0: # One of the processes has failed ret = p.returncode # All processes have finished return ret @property def stdout(self): return self._stdout def wait(self, timeout=None): if timeout is not None: deadline = monotonic_time() + timeout else: deadline = None for p in self._procs: if deadline is not None: # NOTE: CPopen doesn't support timeout argument. while monotonic_time() < deadline: p.poll() if p.returncode is not None: break time.sleep(1) else: p.wait() if deadline is not None: if deadline < monotonic_time() or self.returncode is None: # Timed out return False return True class ImportVm(object): TERM_DELAY = 30 PROC_WAIT_TIMEOUT = 30 def __init__(self, job_id, command): self._id = job_id self._command = command self._thread = None self._status = STATUS.STARTING self._description = '' self._disk_progress = 0 self._disk_count = 1 self._current_disk = 1 self._aborted = False self._proc = None def start(self): self._thread = concurrent.thread(self._run, name="v2v/" + self._id[:8]) self._thread.start() def wait(self): if self._thread is not None and self._thread.is_alive(): self._thread.join() @property def id(self): return self._id @property def status(self): return self._status @property def description(self): return self._description @property def progress(self): ''' progress is part of multiple disk_progress its flat and not 100% accurate - each disk take its portion ie if we have 2 disks the first will take 0-50 and the second 50-100 ''' completed = (self._disk_count - 1) * 100 return (completed + self._disk_progress) / self._disk_count @traceback(msg="Error importing vm") def _run(self): try: self._import() except Exception as ex: if self._aborted: logging.debug("Job %r was aborted", self._id) else: logging.exception("Job %r failed", self._id) self._status = STATUS.FAILED self._description = str(ex) try: if self._proc is not None: self._abort() except Exception as e: logging.exception('Job %r, error trying to abort: %r', self._id, e) def _import(self): logging.info('Job %r starting import', self._id) with self._command.execute() as self._proc: self._watch_process_output() self._wait_for_process() if self._proc.returncode != 0: raise V2VProcessError('Job %r process failed exit-code: %r' % (self._id, self._proc.returncode)) if self._status != STATUS.ABORTED: self._status = STATUS.DONE logging.info('Job %r finished import successfully', self._id) def _wait_for_process(self): if self._proc.returncode is not None: return logging.debug("Job %r waiting for virt-v2v process", self._id) if not self._proc.wait(timeout=self.PROC_WAIT_TIMEOUT): raise V2VProcessError("Job %r timeout waiting for process pid=%s", self._id, self._proc.pids) def _watch_process_output(self): out = io.BufferedReader(io.FileIO(self._proc.stdout.fileno(), mode='r', closefd=False), BUFFSIZE) parser = OutputParser() for event in parser.parse(out): if isinstance(event, ImportProgress): self._status = STATUS.COPYING_DISK logging.info("Job %r copying disk %d/%d", self._id, event.current_disk, event.disk_count) self._disk_progress = 0 self._current_disk = event.current_disk self._disk_count = event.disk_count self._description = event.description elif isinstance(event, DiskProgress): self._disk_progress = event.progress if event.progress % 10 == 0: logging.info("Job %r copy disk %d progress %d/100", self._id, self._current_disk, event.progress) else: raise RuntimeError("Job %r got unexpected parser event: %s" % (self._id, event)) def abort(self): self._status = STATUS.ABORTED logging.info('Job %r aborting...', self._id) self._abort() def _abort(self): self._aborted = True if self._proc is None: logging.warning( 'Ignoring request to abort job %r; the job failed to start', self._id) return if self._proc.returncode is None: logging.debug('Job %r killing virt-v2v process', self._id) try: self._proc.kill() except OSError as e: if e.errno != errno.ESRCH: raise logging.debug('Job %r virt-v2v process not running', self._id) else: logging.debug('Job %r virt-v2v process was killed', self._id) finally: for pid in self._proc.pids: zombiereaper.autoReapPID(pid) class OutputParser(object): COPY_DISK_RE = re.compile(r'.*(Copying disk (\d+)/(\d+)).*') DISK_PROGRESS_RE = re.compile(r'\s+\((\d+).*') def parse(self, stream): for line in stream: if 'Copying disk' in line: description, current_disk, disk_count = self._parse_line(line) yield ImportProgress(int(current_disk), int(disk_count), description) for chunk in self._iter_progress(stream): progress = self._parse_progress(chunk) if progress is not None: yield DiskProgress(progress) if progress == 100: break def _parse_line(self, line): m = self.COPY_DISK_RE.match(line) if m is None: raise OutputParserError('unexpected format in "Copying disk"' ', line: %r' % line) return m.group(1), m.group(2), m.group(3) def _iter_progress(self, stream): chunk = '' while True: c = stream.read(1) if not c: raise OutputParserError('copy-disk stream closed unexpectedly') chunk += c if c == '\r': yield chunk chunk = '' def _parse_progress(self, chunk): m = self.DISK_PROGRESS_RE.match(chunk) if m is None: return None try: return int(m.group(1)) except ValueError: raise OutputParserError('error parsing progress regex: %r' % m.groups) def _mem_to_mib(size, unit): lunit = unit.lower() if lunit in ('bytes', 'b'): return size / 1024 / 1024 elif lunit in ('kib', 'k'): return size / 1024 elif lunit in ('mib', 'm'): return size elif lunit in ('gib', 'g'): return size * 1024 elif lunit in ('tib', 't'): return size * 1024 * 1024 else: raise InvalidVMConfiguration("Invalid currentMemory unit attribute:" " %r" % unit) def _list_domains(conn): try: for vm in conn.listAllDomains(): yield vm # TODO: use only the new API (no need to fall back to listDefinedDomains) # when supported in Xen under RHEL 5.x except libvirt.libvirtError as e: if e.get_error_code() != libvirt.VIR_ERR_NO_SUPPORT: raise # Support for old libvirt clients seen = set() for name in conn.listDefinedDomains(): try: vm = conn.lookupByName(name) except libvirt.libvirtError as e: logging.error("Error looking up vm %r: %s", name, e) else: seen.add(name) yield vm for domainId in conn.listDomainsID(): try: vm = conn.lookupByID(domainId) except libvirt.libvirtError as e: logging.error("Error looking up vm by id %r: %s", domainId, e) else: if vm.name() not in seen: yield vm def _add_vm(conn, vms, vm): params = {} try: _add_vm_info(vm, params) except libvirt.libvirtError as e: logging.error("error getting domain information: %s", e) return try: xml = vm.XMLDesc(0) except libvirt.libvirtError as e: logging.error("error getting domain xml for vm %r: %s", vm.name(), e) return try: root = ET.fromstring(xml) except ET.ParseError as e: logging.error('error parsing domain xml: %s', e) return if not _block_disk_supported(conn, root): return try: _add_general_info(root, params) except InvalidVMConfiguration as e: logging.error("error adding general info: %s", e) return _add_snapshot_info(conn, vm, params) _add_networks(root, params) _add_disks(root, params) _add_graphics(root, params) _add_video(root, params) disk_info = None for disk in params['disks']: disk_info = _get_disk_info(conn, disk, vm) if disk_info is None: break disk.update(disk_info) if disk_info is not None: vms.append(params) else: logging.warning('Cannot add VM %s due to disk storage error', vm.name()) def _block_disk_supported(conn, root): ''' Currently we do not support importing VMs with block device from Xen on Rhel 5.x ''' if conn.getType() == 'Xen': block_disks = root.findall('.//disk[@type="block"]') block_disks = [d for d in block_disks if d.attrib.get('device', None) == "disk"] return len(block_disks) == 0 return True def _add_vm_info(vm, params): params['vmName'] = vm.name() # TODO: use new API: vm.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF # when supported in Xen under RHEL 5.x if vm.isActive(): params['status'] = "Up" else: params['status'] = "Down" def _add_general_info(root, params): e = root.find('./uuid') if e is not None: params['vmId'] = e.text e = root.find('./currentMemory') if e is not None: try: size = int(e.text) except ValueError: raise InvalidVMConfiguration("Invalid 'currentMemory' value: %r" % e.text) unit = e.get('unit', 'KiB') params['memSize'] = _mem_to_mib(size, unit) e = root.find('./vcpu') if e is not None: try: params['smp'] = int(e.text) except ValueError: raise InvalidVMConfiguration("Invalid 'vcpu' value: %r" % e.text) e = root.find('./os/type/[@arch]') if e is not None: params['arch'] = e.get('arch') def _get_disk_info(conn, disk, vm): if 'alias' in disk.keys(): try: if disk['disktype'] == 'file': vol = conn.storageVolLookupByPath(disk['alias']) _, capacity, alloc = vol.info() elif disk['disktype'] == 'block': vol = vm.blockInfo(disk['alias']) # We use the physical for allocation # in blockInfo can report 0 capacity, _, alloc = vol else: logging.error('Unsupported disk type: %r', disk['disktype']) except libvirt.libvirtError: logging.exception("Error getting disk size") return None else: return {'capacity': str(capacity), 'allocation': str(alloc)} return {} def _convert_disk_format(format): # TODO: move to volume format when storage/volume.py # will be accessible for /lib/vdsm/v2v.py if format == 'qcow2': return 'COW' elif format == 'raw': return 'RAW' raise KeyError def _add_disks(root, params): params['disks'] = [] disks = root.findall('.//disk[@type="file"]') disks = disks + root.findall('.//disk[@type="block"]') for disk in disks: d = {} disktype = disk.get('type') device = disk.get('device') if device is not None: if device == 'cdrom': # Skip CD-ROM drives continue d['type'] = device target = disk.find('./target/[@dev]') if target is not None: d['dev'] = target.get('dev') if disktype == 'file': d['disktype'] = 'file' source = disk.find('./source/[@file]') if source is not None: d['alias'] = source.get('file') elif disktype == 'block': d['disktype'] = 'block' source = disk.find('./source/[@dev]') if source is not None: d['alias'] = source.get('dev') else: logging.error('Unsupported disk type: %r', type) driver = disk.find('./driver/[@type]') if driver is not None: try: d["format"] = _convert_disk_format(driver.get('type')) except KeyError: logging.warning("Disk %s has unsupported format: %r", d, format) params['disks'].append(d) def _add_graphics(root, params): e = root.find('./devices/graphics/[@type]') if e is not None: params['graphics'] = e.get('type') def _add_video(root, params): e = root.find('./devices/video/model/[@type]') if e is not None: params['video'] = e.get('type') def _add_networks(root, params): params['networks'] = [] interfaces = root.findall('.//interface') for iface in interfaces: i = {} if 'type' in iface.attrib: i['type'] = iface.attrib['type'] mac = iface.find('./mac/[@address]') if mac is not None: i['macAddr'] = mac.get('address') source = iface.find('./source/[@bridge]') if source is not None: i['bridge'] = source.get('bridge') target = iface.find('./target/[@dev]') if target is not None: i['dev'] = target.get('dev') model = iface.find('./model/[@type]') if model is not None: i['model'] = model.get('type') params['networks'].append(i) def _add_snapshot_info(conn, vm, params): # Snapshot related API is not yet implemented in the libvirt's Xen driver if conn.getType() == 'Xen': return try: ret = vm.hasCurrentSnapshot() except libvirt.libvirtError: logging.exception('Error checking for existing snapshots.') else: params['has_snapshots'] = ret > 0 def _vm_has_snapshot(vm): try: return vm.hasCurrentSnapshot() == 1 except libvirt.libvirtError: logging.exception('Error checking if snapshot exist for vm: %s.', vm.name()) return False def _read_ovf_from_ova(ova_path): """ virt-v2v support ova in tar, zip formats as well as extracted directory """ if os.path.isdir(ova_path): return _read_ovf_from_ova_dir(ova_path) elif zipfile.is_zipfile(ova_path): return _read_ovf_from_zip_ova(ova_path) elif tarfile.is_tarfile(ova_path): return _read_ovf_from_tar_ova(ova_path) raise ClientError('Unknown ova format, supported formats:' ' tar, zip or a directory') def _find_ovf(entries): for entry in entries: if '.ovf' == os.path.splitext(entry)[1].lower(): return entry return None def _read_ovf_from_ova_dir(ova_path): files = os.listdir(ova_path) name = _find_ovf(files) if name is not None: with open(os.path.join(ova_path, name), 'r') as ovf_file: return ovf_file.read() raise ClientError('OVA directory %s does not contain ovf file' % ova_path) def _read_ovf_from_zip_ova(ova_path): with open(ova_path, 'rb') as fh: zf = zipfile.ZipFile(fh) name = _find_ovf(zf.namelist()) if name is not None: return zf.read(name) raise ClientError('OVA does not contains file with .ovf suffix') def _read_ovf_from_tar_ova(ova_path): with tarfile.open(ova_path) as tar: for member in tar: if member.name.endswith('.ovf'): with closing(tar.extractfile(member)) as ovf: return ovf.read() raise ClientError('OVA does not contains file with .ovf suffix') def _add_general_ovf_info(vm, node, ns, ova_path): vm['status'] = 'Down' vmName = node.find('./ovf:VirtualSystem/ovf:Name', ns) if vmName is not None: vm['vmName'] = vmName.text else: vm['vmName'] = os.path.splitext(os.path.basename(ova_path))[0] memSize = node.find('.//ovf:Item[rasd:ResourceType="%d"]/' 'rasd:VirtualQuantity' % _OVF_RESOURCE_MEMORY, ns) if memSize is not None: vm['memSize'] = int(memSize.text) else: raise V2VError('Error parsing ovf information: no memory size') smp = node.find('.//ovf:Item[rasd:ResourceType="%d"]/' 'rasd:VirtualQuantity' % _OVF_RESOURCE_CPU, ns) if smp is not None: vm['smp'] = int(smp.text) else: raise V2VError('Error parsing ovf information: no cpu info') def _get_max_disk_size(populated_size, size): if populated_size is None: return size if size is None: return populated_size return str(max(int(populated_size), int(size))) def _parse_allocation_units(units): """ Parse allocation units of the form "bytes * x * y^z" The format is defined in: DSP0004: Common Information Model (CIM) Infrastructure, ANNEX C.1 Programmatic Units We conform only to the subset of the format specification and base-units must be bytes. """ # Format description sp = '[ \t\n]?' base_unit = 'byte' operator = '[*]' # we support only multiplication number = '[+]?[0-9]+' # we support only positive integers exponent = '[+]?[0-9]+' # we support only positive integers modifier1 = '(?P<m1>{op}{sp}(?P<m1_num>{num}))'.format( op=operator, num=number, sp=sp) modifier2 = \ '(?P<m2>{op}{sp}' \ '(?P<m2_base>[0-9]+){sp}\^{sp}(?P<m2_exp>{exp}))'.format( op=operator, exp=exponent, sp=sp) r = '^{base_unit}({sp}{mod1})?({sp}{mod2})?$'.format( base_unit=base_unit, mod1=modifier1, mod2=modifier2, sp=sp) m = re.match(r, units, re.MULTILINE) if m is None: raise V2VError('Failed to parse allocation units: %r' % units) g = m.groupdict() ret = 1 if g['m1'] is not None: try: ret *= int(g['m1_num']) except ValueError: raise V2VError("Failed to parse allocation units: %r" % units) if g['m2'] is not None: try: ret *= pow(int(g['m2_base']), int(g['m2_exp'])) except ValueError: raise V2VError("Failed to parse allocation units: %r" % units) return ret def _add_disks_ovf_info(vm, node, ns): vm['disks'] = [] for d in node.findall(".//ovf:DiskSection/ovf:Disk", ns): disk = {'type': 'disk'} capacity = int(d.attrib.get('{%s}capacity' % _OVF_NS)) if '{%s}capacityAllocationUnits' % _OVF_NS in d.attrib: units = d.attrib.get('{%s}capacityAllocationUnits' % _OVF_NS) capacity *= _parse_allocation_units(units) disk['capacity'] = str(capacity) fileref = d.attrib.get('{%s}fileRef' % _OVF_NS) alias = node.find('.//ovf:References/ovf:File[@ovf:id="%s"]' % fileref, ns) if alias is not None: disk['alias'] = alias.attrib.get('{%s}href' % _OVF_NS) populated_size = d.attrib.get('{%s}populatedSize' % _OVF_NS, None) size = alias.attrib.get('{%s}size' % _OVF_NS) disk['allocation'] = _get_max_disk_size(populated_size, size) else: raise V2VError('Error parsing ovf information: disk href info') vm['disks'].append(disk) def _add_networks_ovf_info(vm, node, ns): vm['networks'] = [] for n in node.findall('.//ovf:Item[rasd:ResourceType="%d"]' % _OVF_RESOURCE_NETWORK, ns): net = {} dev = n.find('./rasd:ElementName', ns) if dev is not None: net['dev'] = dev.text else: raise V2VError('Error parsing ovf information: ' 'network element name') model = n.find('./rasd:ResourceSubType', ns) if model is not None: net['model'] = model.text else: raise V2VError('Error parsing ovf information: network model') bridge = n.find('./rasd:Connection', ns) if bridge is not None: net['bridge'] = bridge.text net['type'] = 'bridge' else: net['type'] = 'interface' vm['networks'].append(net) def _simple_exec_cmd(command, env=None, nice=None, ioclass=None, stdin=None, stdout=None, stderr=None): command = wrap_command(command, with_ioclass=ioclass, ioclassdata=None, with_nice=nice, with_setsid=False, with_sudo=False, reset_cpu_affinity=True) logging.debug(cmdutils.command_log_line(command, cwd=None)) p = CPopen(command, close_fds=True, cwd=None, env=env, stdin=stdin, stdout=stdout, stderr=stderr) return p
Java
/*****************************************************************************\ * $Id: fillfile.c 77 2006-02-15 01:00:42Z garlick $ ***************************************************************************** * Copyright (C) 2001-2008 The Regents of the University of California. * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). * Written by Jim Garlick <garlick@llnl.gov>. * UCRL-CODE-2003-006. * * This file is part of Scrub, a program for erasing disks. * For details, see https://code.google.com/p/diskscrub/ * * Scrub is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * Scrub 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 Scrub; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. \*****************************************************************************/ #if HAVE_CONFIG_H #include "config.h" #endif #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if HAVE_PTHREAD_H #include <pthread.h> #endif #include <assert.h> #include "util.h" #include "fillfile.h" static int no_threads = 0; struct memstruct { refill_t refill; unsigned char *buf; int size; #if WITH_PTHREADS pthread_t thd; int err; #endif }; extern char *prog; #if defined(O_DIRECT) && (defined(HAVE_POSIX_MEMALIGN) || defined(HAVE_MEMALIGN)) # define MY_O_DIRECT O_DIRECT #else # define MY_O_DIRECT 0 #endif static void * refill_thread(void *arg) { struct memstruct *mp = (struct memstruct *)arg; mp->refill(mp->buf, mp->size); return mp; } static int refill_memcpy(struct memstruct *mp, unsigned char *mem, int memsize, off_t filesize, off_t written) { #if WITH_PTHREADS if (no_threads) { mp->size = memsize; refill_thread (mp); } else { if ((mp->err = pthread_join(mp->thd, NULL))) { errno = mp->err; goto error; } assert (memsize == mp->size); } #else mp->size = memsize; refill_thread (mp); #endif memcpy(mem, mp->buf, memsize); #if WITH_PTHREADS if (!no_threads) { written += memsize; if (filesize - written > 0) { if (mp->size > filesize - written) mp->size = filesize - written; if ((mp->err = pthread_create(&mp->thd, NULL, refill_thread, mp))) { errno = mp->err; goto error; } } } #endif return 0; error: return -1; } static int refill_init(struct memstruct **mpp, refill_t refill, int memsize) { struct memstruct *mp = NULL; if (!(mp = malloc(sizeof(struct memstruct)))) goto nomem; if (!(mp->buf = malloc(memsize))) goto nomem; mp->size = memsize; mp->refill = refill; #if WITH_PTHREADS if (!no_threads) { if ((mp->err = pthread_create(&mp->thd, NULL, refill_thread, mp))) { errno = mp->err; goto error; } } #endif *mpp = mp; return 0; nomem: errno = ENOMEM; error: return -1; } static void refill_fini(struct memstruct *mp) { #if WITH_PTHREADS if (!no_threads) (void)pthread_join(mp->thd, NULL); #endif free (mp->buf); free (mp); } /* Fill file (can be regular or special file) with pattern in mem. * Writes will use memsize blocks. * If 'refill' is non-null, call it before each write (for random fill). * If 'progress' is non-null, call it after each write (for progress meter). * If 'sparse' is true, only scrub first and last blocks (for testing). * The number of bytes written is returned. * If 'creat' is true, open with O_CREAT and allow ENOSPC to be non-fatal. */ off_t fillfile(char *path, off_t filesize, unsigned char *mem, int memsize, progress_t progress, void *arg, refill_t refill, bool sparse, bool creat) { int fd = -1; off_t n; off_t written = 0LL; int openflags = O_WRONLY; struct memstruct *mp = NULL; if (filetype(path) != FILE_CHAR) openflags |= MY_O_DIRECT; if (creat) openflags |= O_CREAT; fd = open(path, openflags, 0644); if (fd < 0 && errno == EINVAL && openflags & MY_O_DIRECT) { /* Try again without (MY_)O_DIRECT */ openflags &= ~MY_O_DIRECT; fd = open(path, openflags, 0644); } if (fd < 0) goto error; do { if (written + memsize > filesize) memsize = filesize - written; if (refill && !sparse) { if (!mp) if (refill_init(&mp, refill, memsize) < 0) goto error; if (refill_memcpy(mp, mem, memsize, filesize, written) < 0) goto error; } if (sparse && !(written == 0) && !(written + memsize == filesize)) { if (lseek(fd, memsize, SEEK_CUR) < 0) goto error; written += memsize; } else { n = write_all(fd, mem, memsize); if (creat && n < 0 && errno == ENOSPC) break; if (n == 0) { errno = EINVAL; /* write past end of device? */ goto error; } else if (n < 0) goto error; written += n; } if (progress) progress(arg, (double)written/filesize); } while (written < filesize); if (fsync(fd) < 0) { if (errno != EINVAL) goto error; errno = 0; } #if defined(HAVE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED) /* Try to fool the kernel into dropping any device cache */ (void)posix_fadvise(fd, 0, filesize, POSIX_FADV_DONTNEED); #endif if (close(fd) < 0) goto error; if (mp) refill_fini(mp); return written; error: if (mp) refill_fini(mp); if (fd != -1) (void)close(fd); return (off_t)-1; } /* Verify that file was filled with 'mem' patterns. */ off_t checkfile(char *path, off_t filesize, unsigned char *mem, int memsize, progress_t progress, void *arg, bool sparse) { int fd = -1; off_t n; off_t verified = 0LL; unsigned char *buf = NULL; int openflags = O_RDONLY; if (!(buf = alloc_buffer(memsize))) goto nomem; if (filetype(path) != FILE_CHAR) openflags |= MY_O_DIRECT; fd = open(path, openflags); if (fd < 0 && errno == EINVAL && openflags & MY_O_DIRECT) { /* Try again without (MY_)O_DIRECT */ openflags &= ~MY_O_DIRECT; fd = open(path, openflags); } if (fd < 0) goto error; do { if (verified + memsize > filesize) memsize = filesize - verified; if (sparse && !(verified == 0) && !(verified + memsize == filesize)) { if (lseek(fd, memsize, SEEK_CUR) < 0) goto error; verified += memsize; } else { n = read_all(fd, buf, memsize); if (n < 0) goto error; if (n == 0) { errno = EINVAL; /* early EOF */ goto error; } if (memcmp(mem, buf, memsize) != 0) { break; /* return < filesize means verification failure */ } verified += n; } if (progress) progress(arg, (double)verified/filesize); } while (verified < filesize); if (close(fd) < 0) goto error; free(buf); return verified; nomem: errno = ENOMEM; error: if (buf) free (buf); if (fd != -1) (void)close(fd); return (off_t)-1; } void disable_threads(void) { no_threads = 1; } /* * vi:tabstop=4 shiftwidth=4 expandtab */
Java
<?php /** * @file * Template page for a promotion item. */ ?> <h2> <a href="<?php print $item_url ?>"><?php print $title ?></a> </h2> <p><?php print t('Valid till'); ?> <?php print $cashingPeriodEnd ?> <?php print ($unlimited ? t('unlimited') : $unitsLeft . ' ' . t('x in stock')); ?></p> <?php if (!empty($picture_url)): ?> <p> <img style="float: right;" width="100" src="<?php print $picture_url; ?>" /> <span><?php print $real_points ?></span> </p> <?php endif; ?>
Java
using System; namespace Server.Items { public class ArachnidDoom : BaseInstrument { [Constructable] public ArachnidDoom() : base(0x0EB3) { RandomInstrument(); this.Hue = 1944; this.Weight = 4; this.Slayer = SlayerName.ArachnidDoom; } public ArachnidDoom(Serial serial) : base(serial) { } public override int LabelNumber { get { return 1154724; } }// Arachnid Doom public override int InitMinUses { get { return 450; } } public override int InitMaxUses { get { return 450; } } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
Java
<?php /** * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <andi@splitbrain.org> */ // must be run within Dokuwiki if(!defined('DOKU_INC')) die(); /** * Class syntax_plugin_data_entry */ class syntax_plugin_data_entry extends DokuWiki_Syntax_Plugin { /** * @var helper_plugin_data will hold the data helper plugin */ var $dthlp = null; /** * Constructor. Load helper plugin */ function __construct() { $this->dthlp = plugin_load('helper', 'data'); if(!$this->dthlp) msg('Loading the data helper failed. Make sure the data plugin is installed.', -1); } /** * What kind of syntax are we? */ function getType() { return 'substition'; } /** * What about paragraphs? */ function getPType() { return 'block'; } /** * Where to sort in? */ function getSort() { return 155; } /** * Connect pattern to lexer */ function connectTo($mode) { $this->Lexer->addSpecialPattern('----+ *dataentry(?: [ a-zA-Z0-9_]*)?-+\n.*?\n----+', $mode, 'plugin_data_entry'); } /** * Handle the match - parse the data * * @param string $match The text matched by the patterns * @param int $state The lexer state for the match * @param int $pos The character position of the matched text * @param Doku_Handler $handler The Doku_Handler object * @return bool|array Return an array with all data you want to use in render, false don't add an instruction */ function handle($match, $state, $pos, Doku_Handler $handler) { if(!$this->dthlp->ready()) return null; // get lines $lines = explode("\n", $match); array_pop($lines); $class = array_shift($lines); $class = str_replace('dataentry', '', $class); $class = trim($class, '- '); // parse info $data = array(); $columns = array(); foreach($lines as $line) { // ignore comments preg_match('/^(.*?(?<![&\\\\]))(?:#(.*))?$/', $line, $matches); $line = $matches[1]; $line = str_replace('\\#', '#', $line); $line = trim($line); if(empty($line)) continue; $line = preg_split('/\s*:\s*/', $line, 2); $column = $this->dthlp->_column($line[0]); if(isset($matches[2])) { $column['comment'] = $matches[2]; } if($column['multi']) { if(!isset($data[$column['key']])) { // init with empty array // Note that multiple occurrences of the field are // practically merged $data[$column['key']] = array(); } $vals = explode(',', $line[1]); foreach($vals as $val) { $val = trim($this->dthlp->_cleanData($val, $column['type'])); if($val == '') continue; if(!in_array($val, $data[$column['key']])) { $data[$column['key']][] = $val; } } } else { $data[$column['key']] = $this->dthlp->_cleanData($line[1], $column['type']); } $columns[$column['key']] = $column; } return array( 'data' => $data, 'cols' => $columns, 'classes' => $class, 'pos' => $pos, 'len' => strlen($match) ); // not utf8_strlen } /** * Create output or save the data * * @param $format string output format being rendered * @param $renderer Doku_Renderer the current renderer object * @param $data array data created by handler() * @return boolean rendered correctly? */ function render($format, Doku_Renderer $renderer, $data) { if(is_null($data)) return false; if(!$this->dthlp->ready()) return false; global $ID; switch($format) { case 'xhtml': /** @var $renderer Doku_Renderer_xhtml */ $this->_showData($data, $renderer); return true; case 'metadata': /** @var $renderer Doku_Renderer_metadata */ $this->_saveData($data, $ID, $renderer->meta['title']); return true; case 'plugin_data_edit': /** @var $renderer Doku_Renderer_plugin_data_edit */ $this->_editData($data, $renderer); return true; default: return false; } } /** * Output the data in a table * * @param array $data * @param Doku_Renderer_xhtml $R */ function _showData($data, $R) { global $ID; $ret = ''; $sectionEditData = ['target' => 'plugin_data']; if (!defined('SEC_EDIT_PATTERN')) { // backwards-compatibility for Frusterick Manners (2017-02-19) $sectionEditData = 'plugin_data'; } $data['classes'] .= ' ' . $R->startSectionEdit($data['pos'], $sectionEditData); $ret .= '<div class="inline dataplugin_entry ' . $data['classes'] . '"><dl>'; $class_names = array(); foreach($data['data'] as $key => $val) { if($val == '' || !count($val)) continue; $type = $data['cols'][$key]['type']; if(is_array($type)) { $type = $type['type']; } if($type === 'hidden') continue; $class_name = hsc(sectionID($key, $class_names)); $ret .= '<dt class="' . $class_name . '">' . hsc($data['cols'][$key]['title']) . '<span class="sep">: </span></dt>'; $ret .= '<dd class="' . $class_name . '">'; if(is_array($val)) { $cnt = count($val); for($i = 0; $i < $cnt; $i++) { switch($type) { case 'wiki': $val[$i] = $ID . '|' . $val[$i]; break; } $ret .= $this->dthlp->_formatData($data['cols'][$key], $val[$i], $R); if($i < $cnt - 1) { $ret .= '<span class="sep">, </span>'; } } } else { switch($type) { case 'wiki': $val = $ID . '|' . $val; break; } $ret .= $this->dthlp->_formatData($data['cols'][$key], $val, $R); } $ret .= '</dd>'; } $ret .= '</dl></div>'; $R->doc .= $ret; $R->finishSectionEdit($data['len'] + $data['pos']); } /** * Save date to the database */ function _saveData($data, $id, $title) { $sqlite = $this->dthlp->_getDB(); if(!$sqlite) return false; if(!$title) { $title = $id; } $class = $data['classes']; // begin transaction $sqlite->query("BEGIN TRANSACTION"); // store page info $this->replaceQuery( "INSERT OR IGNORE INTO pages (page,title,class) VALUES (?,?,?)", $id, $title, $class ); // Update title if insert failed (record already saved before) $revision = filemtime(wikiFN($id)); $this->replaceQuery( "UPDATE pages SET title = ?, class = ?, lastmod = ? WHERE page = ?", $title, $class, $revision, $id ); // fetch page id $res = $this->replaceQuery("SELECT pid FROM pages WHERE page = ?", $id); $pid = (int) $sqlite->res2single($res); $sqlite->res_close($res); if(!$pid) { msg("data plugin: failed saving data", -1); $sqlite->query("ROLLBACK TRANSACTION"); return false; } // remove old data $sqlite->query("DELETE FROM DATA WHERE pid = ?", $pid); // insert new data foreach($data['data'] as $key => $val) { if(is_array($val)) foreach($val as $v) { $this->replaceQuery( "INSERT INTO DATA (pid, KEY, VALUE) VALUES (?, ?, ?)", $pid, $key, $v ); } else { $this->replaceQuery( "INSERT INTO DATA (pid, KEY, VALUE) VALUES (?, ?, ?)", $pid, $key, $val ); } } // finish transaction $sqlite->query("COMMIT TRANSACTION"); return true; } /** * @return bool|mixed */ function replaceQuery() { $args = func_get_args(); $argc = func_num_args(); if($argc > 1) { for($i = 1; $i < $argc; $i++) { $data = array(); $data['sql'] = $args[$i]; $this->dthlp->_replacePlaceholdersInSQL($data); $args[$i] = $data['sql']; } } $sqlite = $this->dthlp->_getDB(); if(!$sqlite) return false; return call_user_func_array(array(&$sqlite, 'query'), $args); } /** * The custom editor for editing data entries * * Gets called from action_plugin_data::_editform() where also the form member is attached * * @param array $data * @param Doku_Renderer_plugin_data_edit $renderer */ function _editData($data, &$renderer) { $renderer->form->startFieldset($this->getLang('dataentry')); $renderer->form->_content[count($renderer->form->_content) - 1]['class'] = 'plugin__data'; $renderer->form->addHidden('range', '0-0'); // Adora Belle bugfix if($this->getConf('edit_content_only')) { $renderer->form->addHidden('data_edit[classes]', $data['classes']); $columns = array('title', 'value', 'comment'); $class = 'edit_content_only'; } else { $renderer->form->addElement(form_makeField('text', 'data_edit[classes]', $data['classes'], $this->getLang('class'), 'data__classes')); $columns = array('title', 'type', 'multi', 'value', 'comment'); $class = 'edit_all_content'; // New line $data['data'][''] = ''; $data['cols'][''] = array('type' => '', 'multi' => false); } $renderer->form->addElement("<table class=\"$class\">"); //header $header = '<tr>'; foreach($columns as $column) { $header .= '<th class="' . $column . '">' . $this->getLang($column) . '</th>'; } $header .= '</tr>'; $renderer->form->addElement($header); //rows $n = 0; foreach($data['cols'] as $key => $vals) { $fieldid = 'data_edit[data][' . $n++ . ']'; $content = $vals['multi'] ? implode(', ', $data['data'][$key]) : $data['data'][$key]; if(is_array($vals['type'])) { $vals['basetype'] = $vals['type']['type']; if(isset($vals['type']['enum'])) { $vals['enum'] = $vals['type']['enum']; } $vals['type'] = $vals['origtype']; } else { $vals['basetype'] = $vals['type']; } if($vals['type'] === 'hidden') { $renderer->form->addElement('<tr class="hidden">'); } else { $renderer->form->addElement('<tr>'); } if($this->getConf('edit_content_only')) { if(isset($vals['enum'])) { $values = preg_split('/\s*,\s*/', $vals['enum']); if(!$vals['multi']) { array_unshift($values, ''); } $content = form_makeListboxField( $fieldid . '[value][]', $values, $data['data'][$key], $vals['title'], '', '', ($vals['multi'] ? array('multiple' => 'multiple') : array()) ); } else { $classes = 'data_type_' . $vals['type'] . ($vals['multi'] ? 's' : '') . ' ' . 'data_type_' . $vals['basetype'] . ($vals['multi'] ? 's' : ''); $attr = array(); if($vals['basetype'] == 'date' && !$vals['multi']) { $attr['class'] = 'datepicker'; } $content = form_makeField('text', $fieldid . '[value]', $content, $vals['title'], '', $classes, $attr); } $cells = array( hsc($vals['title']) . ':', $content, '<span title="' . hsc($vals['comment']) . '">' . hsc($vals['comment']) . '</span>' ); foreach(array('multi', 'comment', 'type') as $field) { $renderer->form->addHidden($fieldid . "[$field]", $vals[$field]); } $renderer->form->addHidden($fieldid . "[title]", $vals['origkey']); //keep key as key, even if title is translated } else { $check_data = $vals['multi'] ? array('checked' => 'checked') : array(); $cells = array( form_makeField('text', $fieldid . '[title]', $vals['origkey'], $this->getLang('title')), // when editable, always use the pure key, not a title form_makeMenuField( $fieldid . '[type]', array_merge( array( '', 'page', 'nspage', 'title', 'img', 'mail', 'url', 'tag', 'wiki', 'dt', 'hidden' ), array_keys($this->dthlp->_aliases()) ), $vals['type'], $this->getLang('type') ), form_makeCheckboxField($fieldid . '[multi]', array('1', ''), $this->getLang('multi'), '', '', $check_data), form_makeField('text', $fieldid . '[value]', $content, $this->getLang('value')), form_makeField('text', $fieldid . '[comment]', $vals['comment'], $this->getLang('comment'), '', 'data_comment', array('readonly' => 1, 'title' => $vals['comment'])) ); } foreach($cells as $index => $cell) { $renderer->form->addElement("<td class=\"{$columns[$index]}\">"); $renderer->form->addElement($cell); $renderer->form->addElement('</td>'); } $renderer->form->addElement('</tr>'); } $renderer->form->addElement('</table>'); $renderer->form->endFieldset(); } /** * Escapes the given value against being handled as comment * * @todo bad naming * @param $txt * @return mixed */ public static function _normalize($txt) { return str_replace('#', '\#', trim($txt)); } /** * Handles the data posted from the editor to recreate the entry syntax * * @param array $data data given via POST * @return string */ public static function editToWiki($data) { $nudata = array(); $len = 0; // we check the maximum lenght for nice alignment later foreach($data['data'] as $field) { if(is_array($field['value'])) { $field['value'] = join(', ', $field['value']); } $field = array_map('trim', $field); if($field['title'] === '') continue; $name = syntax_plugin_data_entry::_normalize($field['title']); if($field['type'] !== '') { $name .= '_' . syntax_plugin_data_entry::_normalize($field['type']); } elseif(substr($name, -1, 1) === 's') { $name .= '_'; // when the field name ends in 's' we need to secure it against being assumed as multi } // 's' is added to either type or name for multi if($field['multi'] === '1') { $name .= 's'; } $nudata[] = array($name, syntax_plugin_data_entry::_normalize($field['value']), $field['comment']); $len = max($len, utf8_strlen($nudata[count($nudata) - 1][0])); } $ret = '---- dataentry ' . trim($data['classes']) . ' ----' . DOKU_LF; foreach($nudata as $field) { $ret .= $field[0] . str_repeat(' ', $len + 1 - utf8_strlen($field[0])) . ': '; $ret .= $field[1]; if($field[2] !== '') { $ret .= ' # ' . $field[2]; } $ret .= DOKU_LF; } $ret .= "----\n"; return $ret; } }
Java
.node-article .content a { color: blue; text-decoration: underline; } .node-article .content .field-type-email a { color: #333333; text-decoration: none; } @media only screen and (max-width: 720px) { #block-block-40 { visibility: hidden; display: none; } #google_ads_iframe_/6785150/BENN/Beaches_Leader_5__container__ { visibility: hidden; display: none; } } @media only screen and (min-width: 400px) { #block-block-42 { visibility: hidden; display: none; } }
Java
/* packet-laplink.c * Routines for laplink dissection * Copyright 2003, Brad Hards <bradh@frogmouth.net> * * $Id: packet-laplink.c 42632 2012-05-15 19:23:35Z wmeier $ * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <glib.h> #include <epan/packet.h> #include <epan/strutil.h> #include "packet-tcp.h" #include <epan/prefs.h> #define TCP_PORT_LAPLINK 1547 #define UDP_PORT_LAPLINK 1547 /* Initialize the protocol and registered fields */ static int proto_laplink = -1; static int hf_laplink_udp_ident = -1; static int hf_laplink_udp_name = -1; static int hf_laplink_tcp_ident = -1; static int hf_laplink_tcp_length = -1; static int hf_laplink_tcp_data = -1; /* Initialize the subtree pointers */ static gint ett_laplink = -1; static const value_string laplink_udp_magic[] = { { 0x0f010000, "Name Solicitation" }, { 0xf0000200, "Name Reply" }, { 0, NULL } }; static const value_string laplink_tcp_magic[] = { { 0xff08c000, "Unknown TCP query - connection?" }, { 0xff08c200, "Unknown TCP query - connection?" }, { 0xff0bc000, "Unknown TCP query - connection?" }, { 0xff0bc200, "Unknown TCP query - connection?" }, { 0xff10c000, "Unknown TCP response - connection?" }, { 0xff10c200, "Unknown TCP response - connection?" }, { 0xff11c000, "Unknown TCP query/response - directory list or file transfer?" }, { 0xff11c200, "Unknown TCP query - directory list or file request?" }, { 0xff13c000, "Unknown TCP response - connection?" }, { 0xff13c200, "Unknown TCP response - connection?" }, { 0xff14c000, "Unknown TCP response - directory list or file transfer?" }, { 0, NULL } }; static gboolean laplink_desegment = TRUE; /* Code to actually dissect the packets - UDP */ static gint dissect_laplink_udp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { int offset = 0; proto_item *ti; proto_tree *laplink_tree; guint32 udp_ident; const gchar *udp_ident_string; /* * Make sure the identifier is reasonable. */ if (!tvb_bytes_exist(tvb, offset, 4)) return 0; /* not enough bytes to check */ udp_ident = tvb_get_ntohl(tvb, offset); udp_ident_string = match_strval(udp_ident, laplink_udp_magic); if (udp_ident_string == NULL) return 0; /* unknown */ /* Make entries in Protocol column and Info column on summary display */ col_set_str(pinfo->cinfo, COL_PROTOCOL, "Laplink"); if (check_col(pinfo->cinfo, COL_INFO)) col_add_str(pinfo->cinfo, COL_INFO, udp_ident_string); if (tree){ ti = proto_tree_add_item(tree, proto_laplink, tvb, 0, -1, ENC_NA); laplink_tree = proto_item_add_subtree(ti, ett_laplink); proto_tree_add_uint(laplink_tree, hf_laplink_udp_ident, tvb, offset, 4, udp_ident); offset += 4; proto_tree_add_item(laplink_tree, hf_laplink_udp_name, tvb, offset, -1, ENC_ASCII|ENC_NA); } return tvb_length(tvb); } /* Code to actually dissect the packets - TCP aspects*/ static void dissect_laplink_tcp_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { int offset = 0; int length = 0; proto_item *ti; proto_tree *laplink_tree; guint32 tcp_ident; /* Make entries in Protocol column and Info column on summary display */ col_set_str(pinfo->cinfo, COL_PROTOCOL, "Laplink"); tcp_ident = tvb_get_ntohl(tvb, offset); if (check_col(pinfo->cinfo, COL_INFO)) { col_add_str(pinfo->cinfo, COL_INFO, val_to_str(tcp_ident, laplink_tcp_magic, "TCP TBA (%u)")); } if (tree){ ti = proto_tree_add_item(tree, proto_laplink, tvb, 0, -1, ENC_NA); laplink_tree = proto_item_add_subtree(ti, ett_laplink); proto_tree_add_item(laplink_tree, hf_laplink_tcp_ident, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; length = tvb_get_ntohs(tvb, offset); proto_tree_add_item(laplink_tree, hf_laplink_tcp_length, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(laplink_tree, hf_laplink_tcp_data, tvb, offset, length, ENC_NA); /* Continue adding tree items to process the packet here */ } /* If this protocol has a sub-dissector call it here, see section 1.8 */ } static guint get_laplink_pdu_len(packet_info *pinfo _U_, tvbuff_t *tvb, int offset) { guint plen; /* * The length doesn't include the length or ident fields; add those in. */ plen = (tvb_get_ntohs(tvb, offset+4) + 2 + 4); return plen; } static void dissect_laplink_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { tcp_dissect_pdus(tvb, pinfo, tree, laplink_desegment, 6, get_laplink_pdu_len, dissect_laplink_tcp_pdu); } /* Register the protocol with Wireshark */ void proto_register_laplink(void) { /* Setup list of header fields See Section 1.6.1 for details*/ static hf_register_info hf[] = { { &hf_laplink_udp_ident, { "UDP Ident", "laplink.udp_ident", FT_UINT32, BASE_HEX, VALS(laplink_udp_magic), 0x0, "Unknown magic", HFILL } }, { &hf_laplink_udp_name, { "UDP Name", "laplink.udp_name", FT_STRINGZ, BASE_NONE, NULL, 0x0, "Machine name", HFILL } }, { &hf_laplink_tcp_ident, { "TCP Ident", "laplink.tcp_ident", FT_UINT32, BASE_HEX, VALS(laplink_tcp_magic), 0x0, "Unknown magic", HFILL } }, { &hf_laplink_tcp_length, { "TCP Data payload length", "laplink.tcp_length", FT_UINT16, BASE_DEC, NULL, 0x0, "Length of remaining payload", HFILL } }, { &hf_laplink_tcp_data, { "Unknown TCP data", "laplink.tcp_data", FT_BYTES, BASE_NONE, NULL, 0x0, "TCP data", HFILL } }, }; /* Setup protocol subtree array */ static gint *ett[] = { &ett_laplink, }; module_t *laplink_module; /* Register the protocol name and description */ proto_laplink = proto_register_protocol("Laplink", "Laplink", "laplink"); /* Required function calls to register the header fields and subtrees used */ proto_register_field_array(proto_laplink, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); laplink_module = prefs_register_protocol(proto_laplink, NULL); prefs_register_bool_preference(laplink_module, "desegment_laplink_over_tcp", "Reassemble Laplink over TCP messages spanning multiple TCP segments", "Whether the Laplink dissector should reassemble messages spanning multiple TCP segments." " To use this option, you must also enable \"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.", &laplink_desegment); } /* If this dissector uses sub-dissector registration add a registration routine. This format is required because a script is used to find these routines and create the code that calls these routines. */ void proto_reg_handoff_laplink(void) { dissector_handle_t laplink_udp_handle; dissector_handle_t laplink_tcp_handle; laplink_tcp_handle = create_dissector_handle(dissect_laplink_tcp, proto_laplink); dissector_add_uint("tcp.port", TCP_PORT_LAPLINK, laplink_tcp_handle); laplink_udp_handle = new_create_dissector_handle(dissect_laplink_udp, proto_laplink); dissector_add_uint("udp.port", UDP_PORT_LAPLINK, laplink_udp_handle); }
Java
/***************************************************************************** Copyright (c) 2005, 2014, Oracle and/or its affiliates. All Rights Reserved. Copyright (c) 2012, Facebook 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA *****************************************************************************/ /**************************************************//** @file page/page0zip.cc Compressed page interface Created June 2005 by Marko Makela *******************************************************/ // First include (the generated) my_config.h, to get correct platform defines. #include "my_config.h" #include <map> using namespace std; #define THIS_MODULE #include "page0zip.h" #ifdef UNIV_NONINL # include "page0zip.ic" #endif #undef THIS_MODULE #include "page0page.h" #include "mtr0log.h" #include "ut0sort.h" #include "dict0dict.h" #include "btr0cur.h" #include "page0types.h" #include "log0recv.h" #ifndef UNIV_HOTBACKUP # include "buf0buf.h" # include "buf0lru.h" # include "btr0sea.h" # include "dict0boot.h" # include "lock0lock.h" # include "srv0mon.h" # include "srv0srv.h" # include "ut0crc32.h" #else /* !UNIV_HOTBACKUP */ # include "buf0checksum.h" # define lock_move_reorganize_page(block, temp_block) ((void) 0) # define buf_LRU_stat_inc_unzip() ((void) 0) #endif /* !UNIV_HOTBACKUP */ #include "blind_fwrite.h" #ifndef UNIV_HOTBACKUP /** Statistics on compression, indexed by page_zip_des_t::ssize - 1 */ UNIV_INTERN page_zip_stat_t page_zip_stat[PAGE_ZIP_SSIZE_MAX]; /** Statistics on compression, indexed by index->id */ UNIV_INTERN page_zip_stat_per_index_t page_zip_stat_per_index; /** Mutex protecting page_zip_stat_per_index */ UNIV_INTERN ib_mutex_t page_zip_stat_per_index_mutex; #ifdef HAVE_PSI_INTERFACE UNIV_INTERN mysql_pfs_key_t page_zip_stat_per_index_mutex_key; #endif /* HAVE_PSI_INTERFACE */ #endif /* !UNIV_HOTBACKUP */ /* Compression level to be used by zlib. Settable by user. */ UNIV_INTERN uint page_zip_level = DEFAULT_COMPRESSION_LEVEL; /* Whether or not to log compressed page images to avoid possible compression algorithm changes in zlib. */ UNIV_INTERN my_bool page_zip_log_pages = false; /* Please refer to ../include/page0zip.ic for a description of the compressed page format. */ /* The infimum and supremum records are omitted from the compressed page. On compress, we compare that the records are there, and on uncompress we restore the records. */ /** Extra bytes of an infimum record */ static const byte infimum_extra[] = { 0x01, /* info_bits=0, n_owned=1 */ 0x00, 0x02 /* heap_no=0, status=2 */ /* ?, ? */ /* next=(first user rec, or supremum) */ }; /** Data bytes of an infimum record */ static const byte infimum_data[] = { 0x69, 0x6e, 0x66, 0x69, 0x6d, 0x75, 0x6d, 0x00 /* "infimum\0" */ }; /** Extra bytes and data bytes of a supremum record */ static const byte supremum_extra_data[] = { /* 0x0?, */ /* info_bits=0, n_owned=1..8 */ 0x00, 0x0b, /* heap_no=1, status=3 */ 0x00, 0x00, /* next=0 */ 0x73, 0x75, 0x70, 0x72, 0x65, 0x6d, 0x75, 0x6d /* "supremum" */ }; /** Assert that a block of memory is filled with zero bytes. Compare at most sizeof(field_ref_zero) bytes. @param b in: memory block @param s in: size of the memory block, in bytes */ #define ASSERT_ZERO(b, s) \ ut_ad(!memcmp(b, field_ref_zero, ut_min(s, sizeof field_ref_zero))) /** Assert that a BLOB pointer is filled with zero bytes. @param b in: BLOB pointer */ #define ASSERT_ZERO_BLOB(b) \ ut_ad(!memcmp(b, field_ref_zero, sizeof field_ref_zero)) /* Enable some extra debugging output. This code can be enabled independently of any UNIV_ debugging conditions. */ #if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG # include <stdarg.h> __attribute__((format (printf, 1, 2))) /**********************************************************************//** Report a failure to decompress or compress. @return number of characters printed */ static int page_zip_fail_func( /*===============*/ const char* fmt, /*!< in: printf(3) format string */ ...) /*!< in: arguments corresponding to fmt */ { int res; va_list ap; ut_print_timestamp(stderr); fputs(" InnoDB: ", stderr); va_start(ap, fmt); res = vfprintf(stderr, fmt, ap); va_end(ap); return(res); } /** Wrapper for page_zip_fail_func() @param fmt_args in: printf(3) format string and arguments */ # define page_zip_fail(fmt_args) page_zip_fail_func fmt_args #else /* UNIV_DEBUG || UNIV_ZIP_DEBUG */ /** Dummy wrapper for page_zip_fail_func() @param fmt_args ignored: printf(3) format string and arguments */ # define page_zip_fail(fmt_args) /* empty */ #endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */ #ifndef UNIV_HOTBACKUP /**********************************************************************//** Determine the guaranteed free space on an empty page. @return minimum payload size on the page */ UNIV_INTERN ulint page_zip_empty_size( /*================*/ ulint n_fields, /*!< in: number of columns in the index */ ulint zip_size) /*!< in: compressed page size in bytes */ { lint size = zip_size /* subtract the page header and the longest uncompressed data needed for one record */ - (PAGE_DATA + PAGE_ZIP_DIR_SLOT_SIZE + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN + 1/* encoded heap_no==2 in page_zip_write_rec() */ + 1/* end of modification log */ - REC_N_NEW_EXTRA_BYTES/* omitted bytes */) /* subtract the space for page_zip_fields_encode() */ - compressBound(static_cast<uLong>(2 * (n_fields + 1))); return(size > 0 ? (ulint) size : 0); } #endif /* !UNIV_HOTBACKUP */ /*************************************************************//** Gets the number of elements in the dense page directory, including deleted records (the free list). @return number of elements in the dense page directory */ UNIV_INLINE ulint page_zip_dir_elems( /*===============*/ const page_zip_des_t* page_zip) /*!< in: compressed page */ { /* Exclude the page infimum and supremum from the record count. */ return(page_dir_get_n_heap(page_zip->data) - PAGE_HEAP_NO_USER_LOW); } /*************************************************************//** Gets the size of the compressed page trailer (the dense page directory), including deleted records (the free list). @return length of dense page directory, in bytes */ UNIV_INLINE ulint page_zip_dir_size( /*==============*/ const page_zip_des_t* page_zip) /*!< in: compressed page */ { return(PAGE_ZIP_DIR_SLOT_SIZE * page_zip_dir_elems(page_zip)); } /*************************************************************//** Gets an offset to the compressed page trailer (the dense page directory), including deleted records (the free list). @return offset of the dense page directory */ UNIV_INLINE ulint page_zip_dir_start_offs( /*====================*/ const page_zip_des_t* page_zip, /*!< in: compressed page */ ulint n_dense) /*!< in: directory size */ { ut_ad(n_dense * PAGE_ZIP_DIR_SLOT_SIZE < page_zip_get_size(page_zip)); return(page_zip_get_size(page_zip) - n_dense * PAGE_ZIP_DIR_SLOT_SIZE); } /*************************************************************//** Gets a pointer to the compressed page trailer (the dense page directory), including deleted records (the free list). @param[in] page_zip compressed page @param[in] n_dense number of entries in the directory @return pointer to the dense page directory */ #define page_zip_dir_start_low(page_zip, n_dense) \ ((page_zip)->data + page_zip_dir_start_offs(page_zip, n_dense)) /*************************************************************//** Gets a pointer to the compressed page trailer (the dense page directory), including deleted records (the free list). @param[in] page_zip compressed page @return pointer to the dense page directory */ #define page_zip_dir_start(page_zip) \ page_zip_dir_start_low(page_zip, page_zip_dir_elems(page_zip)) /*************************************************************//** Gets the size of the compressed page trailer (the dense page directory), only including user records (excluding the free list). @return length of dense page directory comprising existing records, in bytes */ UNIV_INLINE ulint page_zip_dir_user_size( /*===================*/ const page_zip_des_t* page_zip) /*!< in: compressed page */ { ulint size = PAGE_ZIP_DIR_SLOT_SIZE * page_get_n_recs(page_zip->data); ut_ad(size <= page_zip_dir_size(page_zip)); return(size); } /*************************************************************//** Find the slot of the given record in the dense page directory. @return dense directory slot, or NULL if record not found */ UNIV_INLINE byte* page_zip_dir_find_low( /*==================*/ byte* slot, /*!< in: start of records */ byte* end, /*!< in: end of records */ ulint offset) /*!< in: offset of user record */ { ut_ad(slot <= end); for (; slot < end; slot += PAGE_ZIP_DIR_SLOT_SIZE) { if ((mach_read_from_2(slot) & PAGE_ZIP_DIR_SLOT_MASK) == offset) { return(slot); } } return(NULL); } /*************************************************************//** Find the slot of the given non-free record in the dense page directory. @return dense directory slot, or NULL if record not found */ UNIV_INLINE byte* page_zip_dir_find( /*==============*/ page_zip_des_t* page_zip, /*!< in: compressed page */ ulint offset) /*!< in: offset of user record */ { byte* end = page_zip->data + page_zip_get_size(page_zip); ut_ad(page_zip_simple_validate(page_zip)); return(page_zip_dir_find_low(end - page_zip_dir_user_size(page_zip), end, offset)); } /*************************************************************//** Find the slot of the given free record in the dense page directory. @return dense directory slot, or NULL if record not found */ UNIV_INLINE byte* page_zip_dir_find_free( /*===================*/ page_zip_des_t* page_zip, /*!< in: compressed page */ ulint offset) /*!< in: offset of user record */ { byte* end = page_zip->data + page_zip_get_size(page_zip); ut_ad(page_zip_simple_validate(page_zip)); return(page_zip_dir_find_low(end - page_zip_dir_size(page_zip), end - page_zip_dir_user_size(page_zip), offset)); } /*************************************************************//** Read a given slot in the dense page directory. @return record offset on the uncompressed page, possibly ORed with PAGE_ZIP_DIR_SLOT_DEL or PAGE_ZIP_DIR_SLOT_OWNED */ UNIV_INLINE ulint page_zip_dir_get( /*=============*/ const page_zip_des_t* page_zip, /*!< in: compressed page */ ulint slot) /*!< in: slot (0=first user record) */ { ut_ad(page_zip_simple_validate(page_zip)); ut_ad(slot < page_zip_dir_size(page_zip) / PAGE_ZIP_DIR_SLOT_SIZE); return(mach_read_from_2(page_zip->data + page_zip_get_size(page_zip) - PAGE_ZIP_DIR_SLOT_SIZE * (slot + 1))); } #ifndef UNIV_HOTBACKUP /**********************************************************************//** Write a log record of compressing an index page. */ static void page_zip_compress_write_log( /*========================*/ const page_zip_des_t* page_zip,/*!< in: compressed page */ const page_t* page, /*!< in: uncompressed page */ dict_index_t* index, /*!< in: index of the B-tree node */ mtr_t* mtr) /*!< in: mini-transaction */ { byte* log_ptr; ulint trailer_size; ut_ad(!dict_index_is_ibuf(index)); log_ptr = mlog_open(mtr, 11 + 2 + 2); if (!log_ptr) { return; } /* Read the number of user records. */ trailer_size = page_dir_get_n_heap(page_zip->data) - PAGE_HEAP_NO_USER_LOW; /* Multiply by uncompressed of size stored per record */ if (!page_is_leaf(page)) { trailer_size *= PAGE_ZIP_DIR_SLOT_SIZE + REC_NODE_PTR_SIZE; } else if (dict_index_is_clust(index)) { trailer_size *= PAGE_ZIP_DIR_SLOT_SIZE + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN; } else { trailer_size *= PAGE_ZIP_DIR_SLOT_SIZE; } /* Add the space occupied by BLOB pointers. */ trailer_size += page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE; ut_a(page_zip->m_end > PAGE_DATA); #if FIL_PAGE_DATA > PAGE_DATA # error "FIL_PAGE_DATA > PAGE_DATA" #endif ut_a(page_zip->m_end + trailer_size <= page_zip_get_size(page_zip)); log_ptr = mlog_write_initial_log_record_fast((page_t*) page, MLOG_ZIP_PAGE_COMPRESS, log_ptr, mtr); mach_write_to_2(log_ptr, page_zip->m_end - FIL_PAGE_TYPE); log_ptr += 2; mach_write_to_2(log_ptr, trailer_size); log_ptr += 2; mlog_close(mtr, log_ptr); /* Write FIL_PAGE_PREV and FIL_PAGE_NEXT */ mlog_catenate_string(mtr, page_zip->data + FIL_PAGE_PREV, 4); mlog_catenate_string(mtr, page_zip->data + FIL_PAGE_NEXT, 4); /* Write most of the page header, the compressed stream and the modification log. */ mlog_catenate_string(mtr, page_zip->data + FIL_PAGE_TYPE, page_zip->m_end - FIL_PAGE_TYPE); /* Write the uncompressed trailer of the compressed page. */ mlog_catenate_string(mtr, page_zip->data + page_zip_get_size(page_zip) - trailer_size, trailer_size); } #endif /* !UNIV_HOTBACKUP */ /******************************************************//** Determine how many externally stored columns are contained in existing records with smaller heap_no than rec. */ static ulint page_zip_get_n_prev_extern( /*=======================*/ const page_zip_des_t* page_zip,/*!< in: dense page directory on compressed page */ const rec_t* rec, /*!< in: compact physical record on a B-tree leaf page */ const dict_index_t* index) /*!< in: record descriptor */ { const page_t* page = page_align(rec); ulint n_ext = 0; ulint i; ulint left; ulint heap_no; ulint n_recs = page_get_n_recs(page_zip->data); ut_ad(page_is_leaf(page)); ut_ad(page_is_comp(page)); ut_ad(dict_table_is_comp(index->table)); ut_ad(dict_index_is_clust(index)); ut_ad(!dict_index_is_ibuf(index)); heap_no = rec_get_heap_no_new(rec); ut_ad(heap_no >= PAGE_HEAP_NO_USER_LOW); left = heap_no - PAGE_HEAP_NO_USER_LOW; if (UNIV_UNLIKELY(!left)) { return(0); } for (i = 0; i < n_recs; i++) { const rec_t* r = page + (page_zip_dir_get(page_zip, i) & PAGE_ZIP_DIR_SLOT_MASK); if (rec_get_heap_no_new(r) < heap_no) { n_ext += rec_get_n_extern_new(r, index, ULINT_UNDEFINED); if (!--left) { break; } } } return(n_ext); } /**********************************************************************//** Encode the length of a fixed-length column. @return buf + length of encoded val */ static byte* page_zip_fixed_field_encode( /*========================*/ byte* buf, /*!< in: pointer to buffer where to write */ ulint val) /*!< in: value to write */ { ut_ad(val >= 2); if (UNIV_LIKELY(val < 126)) { /* 0 = nullable variable field of at most 255 bytes length; 1 = not null variable field of at most 255 bytes length; 126 = nullable variable field with maximum length >255; 127 = not null variable field with maximum length >255 */ *buf++ = (byte) val; } else { *buf++ = (byte) (0x80 | val >> 8); *buf++ = (byte) val; } return(buf); } /**********************************************************************//** Write the index information for the compressed page. @return used size of buf */ static ulint page_zip_fields_encode( /*===================*/ ulint n, /*!< in: number of fields to compress */ dict_index_t* index, /*!< in: index comprising at least n fields */ ulint trx_id_pos,/*!< in: position of the trx_id column in the index, or ULINT_UNDEFINED if this is a non-leaf page */ byte* buf) /*!< out: buffer of (n + 1) * 2 bytes */ { const byte* buf_start = buf; ulint i; ulint col; ulint trx_id_col = 0; /* sum of lengths of preceding non-nullable fixed fields, or 0 */ ulint fixed_sum = 0; ut_ad(trx_id_pos == ULINT_UNDEFINED || trx_id_pos < n); for (i = col = 0; i < n; i++) { dict_field_t* field = dict_index_get_nth_field(index, i); ulint val; if (dict_field_get_col(field)->prtype & DATA_NOT_NULL) { val = 1; /* set the "not nullable" flag */ } else { val = 0; /* nullable field */ } if (!field->fixed_len) { /* variable-length field */ const dict_col_t* column = dict_field_get_col(field); if (UNIV_UNLIKELY(column->len > 255) || UNIV_UNLIKELY(column->mtype == DATA_BLOB)) { val |= 0x7e; /* max > 255 bytes */ } if (fixed_sum) { /* write out the length of any preceding non-nullable fields */ buf = page_zip_fixed_field_encode( buf, fixed_sum << 1 | 1); fixed_sum = 0; col++; } *buf++ = (byte) val; col++; } else if (val) { /* fixed-length non-nullable field */ if (fixed_sum && UNIV_UNLIKELY (fixed_sum + field->fixed_len > DICT_MAX_FIXED_COL_LEN)) { /* Write out the length of the preceding non-nullable fields, to avoid exceeding the maximum length of a fixed-length column. */ buf = page_zip_fixed_field_encode( buf, fixed_sum << 1 | 1); fixed_sum = 0; col++; } if (i && UNIV_UNLIKELY(i == trx_id_pos)) { if (fixed_sum) { /* Write out the length of any preceding non-nullable fields, and start a new trx_id column. */ buf = page_zip_fixed_field_encode( buf, fixed_sum << 1 | 1); col++; } trx_id_col = col; fixed_sum = field->fixed_len; } else { /* add to the sum */ fixed_sum += field->fixed_len; } } else { /* fixed-length nullable field */ if (fixed_sum) { /* write out the length of any preceding non-nullable fields */ buf = page_zip_fixed_field_encode( buf, fixed_sum << 1 | 1); fixed_sum = 0; col++; } buf = page_zip_fixed_field_encode( buf, field->fixed_len << 1); col++; } } if (fixed_sum) { /* Write out the lengths of last fixed-length columns. */ buf = page_zip_fixed_field_encode(buf, fixed_sum << 1 | 1); } if (trx_id_pos != ULINT_UNDEFINED) { /* Write out the position of the trx_id column */ i = trx_id_col; } else { /* Write out the number of nullable fields */ i = index->n_nullable; } if (i < 128) { *buf++ = (byte) i; } else { *buf++ = (byte) (0x80 | i >> 8); *buf++ = (byte) i; } ut_ad((ulint) (buf - buf_start) <= (n + 2) * 2); return((ulint) (buf - buf_start)); } /**********************************************************************//** Populate the dense page directory from the sparse directory. */ static void page_zip_dir_encode( /*================*/ const page_t* page, /*!< in: compact page */ byte* buf, /*!< in: pointer to dense page directory[-1]; out: dense directory on compressed page */ const rec_t** recs) /*!< in: pointer to an array of 0, or NULL; out: dense page directory sorted by ascending address (and heap_no) */ { const byte* rec; ulint status; ulint min_mark; ulint heap_no; ulint i; ulint n_heap; ulint offs; min_mark = 0; if (page_is_leaf(page)) { status = REC_STATUS_ORDINARY; } else { status = REC_STATUS_NODE_PTR; if (UNIV_UNLIKELY (mach_read_from_4(page + FIL_PAGE_PREV) == FIL_NULL)) { min_mark = REC_INFO_MIN_REC_FLAG; } } n_heap = page_dir_get_n_heap(page); /* Traverse the list of stored records in the collation order, starting from the first user record. */ rec = page + PAGE_NEW_INFIMUM; i = 0; for (;;) { ulint info_bits; offs = rec_get_next_offs(rec, TRUE); if (UNIV_UNLIKELY(offs == PAGE_NEW_SUPREMUM)) { break; } rec = page + offs; heap_no = rec_get_heap_no_new(rec); ut_a(heap_no >= PAGE_HEAP_NO_USER_LOW); ut_a(heap_no < n_heap); ut_a(offs < UNIV_PAGE_SIZE - PAGE_DIR); ut_a(offs >= PAGE_ZIP_START); #if PAGE_ZIP_DIR_SLOT_MASK & (PAGE_ZIP_DIR_SLOT_MASK + 1) # error "PAGE_ZIP_DIR_SLOT_MASK is not 1 less than a power of 2" #endif #if PAGE_ZIP_DIR_SLOT_MASK < UNIV_PAGE_SIZE_MAX - 1 # error "PAGE_ZIP_DIR_SLOT_MASK < UNIV_PAGE_SIZE_MAX - 1" #endif if (UNIV_UNLIKELY(rec_get_n_owned_new(rec))) { offs |= PAGE_ZIP_DIR_SLOT_OWNED; } info_bits = rec_get_info_bits(rec, TRUE); if (info_bits & REC_INFO_DELETED_FLAG) { info_bits &= ~REC_INFO_DELETED_FLAG; offs |= PAGE_ZIP_DIR_SLOT_DEL; } ut_a(info_bits == min_mark); /* Only the smallest user record can have REC_INFO_MIN_REC_FLAG set. */ min_mark = 0; mach_write_to_2(buf - PAGE_ZIP_DIR_SLOT_SIZE * ++i, offs); if (UNIV_LIKELY_NULL(recs)) { /* Ensure that each heap_no occurs at most once. */ ut_a(!recs[heap_no - PAGE_HEAP_NO_USER_LOW]); /* exclude infimum and supremum */ recs[heap_no - PAGE_HEAP_NO_USER_LOW] = rec; } ut_a(rec_get_status(rec) == status); } offs = page_header_get_field(page, PAGE_FREE); /* Traverse the free list (of deleted records). */ while (offs) { ut_ad(!(offs & ~PAGE_ZIP_DIR_SLOT_MASK)); rec = page + offs; heap_no = rec_get_heap_no_new(rec); ut_a(heap_no >= PAGE_HEAP_NO_USER_LOW); ut_a(heap_no < n_heap); ut_a(!rec[-REC_N_NEW_EXTRA_BYTES]); /* info_bits and n_owned */ ut_a(rec_get_status(rec) == status); mach_write_to_2(buf - PAGE_ZIP_DIR_SLOT_SIZE * ++i, offs); if (UNIV_LIKELY_NULL(recs)) { /* Ensure that each heap_no occurs at most once. */ ut_a(!recs[heap_no - PAGE_HEAP_NO_USER_LOW]); /* exclude infimum and supremum */ recs[heap_no - PAGE_HEAP_NO_USER_LOW] = rec; } offs = rec_get_next_offs(rec, TRUE); } /* Ensure that each heap no occurs at least once. */ ut_a(i + PAGE_HEAP_NO_USER_LOW == n_heap); } extern "C" { /**********************************************************************//** Allocate memory for zlib. */ static void* page_zip_zalloc( /*============*/ void* opaque, /*!< in/out: memory heap */ uInt items, /*!< in: number of items to allocate */ uInt size) /*!< in: size of an item in bytes */ { return(mem_heap_zalloc(static_cast<mem_heap_t*>(opaque), items * size)); } /**********************************************************************//** Deallocate memory for zlib. */ static void page_zip_free( /*==========*/ void* opaque __attribute__((unused)), /*!< in: memory heap */ void* address __attribute__((unused)))/*!< in: object to free */ { } } /* extern "C" */ /**********************************************************************//** Configure the zlib allocator to use the given memory heap. */ UNIV_INTERN void page_zip_set_alloc( /*===============*/ void* stream, /*!< in/out: zlib stream */ mem_heap_t* heap) /*!< in: memory heap to use */ { z_stream* strm = static_cast<z_stream*>(stream); strm->zalloc = page_zip_zalloc; strm->zfree = page_zip_free; strm->opaque = heap; } #if 0 || defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG /** Symbol for enabling compression and decompression diagnostics */ # define PAGE_ZIP_COMPRESS_DBG #endif #ifdef PAGE_ZIP_COMPRESS_DBG /** Set this variable in a debugger to enable excessive logging in page_zip_compress(). */ UNIV_INTERN ibool page_zip_compress_dbg; /** Set this variable in a debugger to enable binary logging of the data passed to deflate(). When this variable is nonzero, it will act as a log file name generator. */ UNIV_INTERN unsigned page_zip_compress_log; /**********************************************************************//** Wrapper for deflate(). Log the operation if page_zip_compress_dbg is set. @return deflate() status: Z_OK, Z_BUF_ERROR, ... */ static int page_zip_compress_deflate( /*======================*/ FILE* logfile,/*!< in: log file, or NULL */ z_streamp strm, /*!< in/out: compressed stream for deflate() */ int flush) /*!< in: deflate() flushing method */ { int status; if (UNIV_UNLIKELY(page_zip_compress_dbg)) { ut_print_buf(stderr, strm->next_in, strm->avail_in); } if (UNIV_LIKELY_NULL(logfile)) { blind_fwrite(strm->next_in, 1, strm->avail_in, logfile); } status = deflate(strm, flush); if (UNIV_UNLIKELY(page_zip_compress_dbg)) { fprintf(stderr, " -> %d\n", status); } return(status); } /* Redefine deflate(). */ # undef deflate /** Debug wrapper for the zlib compression routine deflate(). Log the operation if page_zip_compress_dbg is set. @param strm in/out: compressed stream @param flush in: flushing method @return deflate() status: Z_OK, Z_BUF_ERROR, ... */ # define deflate(strm, flush) page_zip_compress_deflate(logfile, strm, flush) /** Declaration of the logfile parameter */ # define FILE_LOGFILE FILE* logfile, /** The logfile parameter */ # define LOGFILE logfile, #else /* PAGE_ZIP_COMPRESS_DBG */ /** Empty declaration of the logfile parameter */ # define FILE_LOGFILE /** Missing logfile parameter */ # define LOGFILE #endif /* PAGE_ZIP_COMPRESS_DBG */ /**********************************************************************//** Compress the records of a node pointer page. @return Z_OK, or a zlib error code */ static int page_zip_compress_node_ptrs( /*========================*/ FILE_LOGFILE z_stream* c_stream, /*!< in/out: compressed page stream */ const rec_t** recs, /*!< in: dense page directory sorted by address */ ulint n_dense, /*!< in: size of recs[] */ dict_index_t* index, /*!< in: the index of the page */ byte* storage, /*!< in: end of dense page directory */ mem_heap_t* heap) /*!< in: temporary memory heap */ { int err = Z_OK; ulint* offsets = NULL; do { const rec_t* rec = *recs++; offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); /* Only leaf nodes may contain externally stored columns. */ ut_ad(!rec_offs_any_extern(offsets)); UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets)); UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets), rec_offs_extra_size(offsets)); /* Compress the extra bytes. */ c_stream->avail_in = static_cast<uInt>( rec - REC_N_NEW_EXTRA_BYTES - c_stream->next_in); if (c_stream->avail_in) { err = deflate(c_stream, Z_NO_FLUSH); if (UNIV_UNLIKELY(err != Z_OK)) { break; } } ut_ad(!c_stream->avail_in); /* Compress the data bytes, except node_ptr. */ c_stream->next_in = (byte*) rec; c_stream->avail_in = static_cast<uInt>( rec_offs_data_size(offsets) - REC_NODE_PTR_SIZE); if (c_stream->avail_in) { err = deflate(c_stream, Z_NO_FLUSH); if (UNIV_UNLIKELY(err != Z_OK)) { break; } } ut_ad(!c_stream->avail_in); memcpy(storage - REC_NODE_PTR_SIZE * (rec_get_heap_no_new(rec) - 1), c_stream->next_in, REC_NODE_PTR_SIZE); c_stream->next_in += REC_NODE_PTR_SIZE; } while (--n_dense); return(err); } /**********************************************************************//** Compress the records of a leaf node of a secondary index. @return Z_OK, or a zlib error code */ static int page_zip_compress_sec( /*==================*/ FILE_LOGFILE z_stream* c_stream, /*!< in/out: compressed page stream */ const rec_t** recs, /*!< in: dense page directory sorted by address */ ulint n_dense) /*!< in: size of recs[] */ { int err = Z_OK; ut_ad(n_dense > 0); do { const rec_t* rec = *recs++; /* Compress everything up to this record. */ c_stream->avail_in = static_cast<uInt>( rec - REC_N_NEW_EXTRA_BYTES - c_stream->next_in); if (UNIV_LIKELY(c_stream->avail_in)) { UNIV_MEM_ASSERT_RW(c_stream->next_in, c_stream->avail_in); err = deflate(c_stream, Z_NO_FLUSH); if (UNIV_UNLIKELY(err != Z_OK)) { break; } } ut_ad(!c_stream->avail_in); ut_ad(c_stream->next_in == rec - REC_N_NEW_EXTRA_BYTES); /* Skip the REC_N_NEW_EXTRA_BYTES. */ c_stream->next_in = (byte*) rec; } while (--n_dense); return(err); } /**********************************************************************//** Compress a record of a leaf node of a clustered index that contains externally stored columns. @return Z_OK, or a zlib error code */ static int page_zip_compress_clust_ext( /*========================*/ FILE_LOGFILE z_stream* c_stream, /*!< in/out: compressed page stream */ const rec_t* rec, /*!< in: record */ const ulint* offsets, /*!< in: rec_get_offsets(rec) */ ulint trx_id_col, /*!< in: position of of DB_TRX_ID */ byte* deleted, /*!< in: dense directory entry pointing to the head of the free list */ byte* storage, /*!< in: end of dense page directory */ byte** externs, /*!< in/out: pointer to the next available BLOB pointer */ ulint* n_blobs) /*!< in/out: number of externally stored columns */ { int err; ulint i; UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets)); UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets), rec_offs_extra_size(offsets)); for (i = 0; i < rec_offs_n_fields(offsets); i++) { ulint len; const byte* src; if (UNIV_UNLIKELY(i == trx_id_col)) { ut_ad(!rec_offs_nth_extern(offsets, i)); /* Store trx_id and roll_ptr in uncompressed form. */ src = rec_get_nth_field(rec, offsets, i, &len); ut_ad(src + DATA_TRX_ID_LEN == rec_get_nth_field(rec, offsets, i + 1, &len)); ut_ad(len == DATA_ROLL_PTR_LEN); /* Compress any preceding bytes. */ c_stream->avail_in = static_cast<uInt>( src - c_stream->next_in); if (c_stream->avail_in) { err = deflate(c_stream, Z_NO_FLUSH); if (UNIV_UNLIKELY(err != Z_OK)) { return(err); } } ut_ad(!c_stream->avail_in); ut_ad(c_stream->next_in == src); memcpy(storage - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN) * (rec_get_heap_no_new(rec) - 1), c_stream->next_in, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); c_stream->next_in += DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN; /* Skip also roll_ptr */ i++; } else if (rec_offs_nth_extern(offsets, i)) { src = rec_get_nth_field(rec, offsets, i, &len); ut_ad(len >= BTR_EXTERN_FIELD_REF_SIZE); src += len - BTR_EXTERN_FIELD_REF_SIZE; c_stream->avail_in = static_cast<uInt>( src - c_stream->next_in); if (UNIV_LIKELY(c_stream->avail_in)) { err = deflate(c_stream, Z_NO_FLUSH); if (UNIV_UNLIKELY(err != Z_OK)) { return(err); } } ut_ad(!c_stream->avail_in); ut_ad(c_stream->next_in == src); /* Reserve space for the data at the end of the space reserved for the compressed data and the page modification log. */ if (UNIV_UNLIKELY (c_stream->avail_out <= BTR_EXTERN_FIELD_REF_SIZE)) { /* out of space */ return(Z_BUF_ERROR); } ut_ad(*externs == c_stream->next_out + c_stream->avail_out + 1/* end of modif. log */); c_stream->next_in += BTR_EXTERN_FIELD_REF_SIZE; /* Skip deleted records. */ if (UNIV_LIKELY_NULL (page_zip_dir_find_low( storage, deleted, page_offset(rec)))) { continue; } (*n_blobs)++; c_stream->avail_out -= BTR_EXTERN_FIELD_REF_SIZE; *externs -= BTR_EXTERN_FIELD_REF_SIZE; /* Copy the BLOB pointer */ memcpy(*externs, c_stream->next_in - BTR_EXTERN_FIELD_REF_SIZE, BTR_EXTERN_FIELD_REF_SIZE); } } return(Z_OK); } /**********************************************************************//** Compress the records of a leaf node of a clustered index. @return Z_OK, or a zlib error code */ static int page_zip_compress_clust( /*====================*/ FILE_LOGFILE z_stream* c_stream, /*!< in/out: compressed page stream */ const rec_t** recs, /*!< in: dense page directory sorted by address */ ulint n_dense, /*!< in: size of recs[] */ dict_index_t* index, /*!< in: the index of the page */ ulint* n_blobs, /*!< in: 0; out: number of externally stored columns */ ulint trx_id_col, /*!< index of the trx_id column */ byte* deleted, /*!< in: dense directory entry pointing to the head of the free list */ byte* storage, /*!< in: end of dense page directory */ mem_heap_t* heap) /*!< in: temporary memory heap */ { int err = Z_OK; ulint* offsets = NULL; /* BTR_EXTERN_FIELD_REF storage */ byte* externs = storage - n_dense * (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); ut_ad(*n_blobs == 0); do { const rec_t* rec = *recs++; offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); ut_ad(rec_offs_n_fields(offsets) == dict_index_get_n_fields(index)); UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets)); UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets), rec_offs_extra_size(offsets)); /* Compress the extra bytes. */ c_stream->avail_in = static_cast<uInt>( rec - REC_N_NEW_EXTRA_BYTES - c_stream->next_in); if (c_stream->avail_in) { err = deflate(c_stream, Z_NO_FLUSH); if (UNIV_UNLIKELY(err != Z_OK)) { goto func_exit; } } ut_ad(!c_stream->avail_in); ut_ad(c_stream->next_in == rec - REC_N_NEW_EXTRA_BYTES); /* Compress the data bytes. */ c_stream->next_in = (byte*) rec; /* Check if there are any externally stored columns. For each externally stored column, store the BTR_EXTERN_FIELD_REF separately. */ if (rec_offs_any_extern(offsets)) { ut_ad(dict_index_is_clust(index)); err = page_zip_compress_clust_ext( LOGFILE c_stream, rec, offsets, trx_id_col, deleted, storage, &externs, n_blobs); if (UNIV_UNLIKELY(err != Z_OK)) { goto func_exit; } } else { ulint len; const byte* src; /* Store trx_id and roll_ptr in uncompressed form. */ src = rec_get_nth_field(rec, offsets, trx_id_col, &len); ut_ad(src + DATA_TRX_ID_LEN == rec_get_nth_field(rec, offsets, trx_id_col + 1, &len)); ut_ad(len == DATA_ROLL_PTR_LEN); UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets)); UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets), rec_offs_extra_size(offsets)); /* Compress any preceding bytes. */ c_stream->avail_in = static_cast<uInt>( src - c_stream->next_in); if (c_stream->avail_in) { err = deflate(c_stream, Z_NO_FLUSH); if (UNIV_UNLIKELY(err != Z_OK)) { return(err); } } ut_ad(!c_stream->avail_in); ut_ad(c_stream->next_in == src); memcpy(storage - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN) * (rec_get_heap_no_new(rec) - 1), c_stream->next_in, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); c_stream->next_in += DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN; /* Skip also roll_ptr */ ut_ad(trx_id_col + 1 < rec_offs_n_fields(offsets)); } /* Compress the last bytes of the record. */ c_stream->avail_in = static_cast<uInt>( rec + rec_offs_data_size(offsets) - c_stream->next_in); if (c_stream->avail_in) { err = deflate(c_stream, Z_NO_FLUSH); if (UNIV_UNLIKELY(err != Z_OK)) { goto func_exit; } } ut_ad(!c_stream->avail_in); } while (--n_dense); func_exit: return(err); } my_bool page_zip_zlib_wrap = FALSE; uint page_zip_zlib_strategy = Z_DEFAULT_STRATEGY; /**********************************************************************//** Compress a page. @return TRUE on success, FALSE on failure; page_zip will be left intact on failure. */ UNIV_INTERN ibool page_zip_compress( /*==============*/ page_zip_des_t* page_zip,/*!< in: size; out: data, n_blobs, m_start, m_end, m_nonempty */ const page_t* page, /*!< in: uncompressed page */ dict_index_t* index, /*!< in: index of the B-tree node */ uchar compression_flags, /*!< in: compression level and other options */ mtr_t* mtr) /*!< in: mini-transaction, or NULL */ { z_stream c_stream; int err; ulint n_fields;/* number of index fields needed */ byte* fields; /*!< index field information */ byte* buf; /*!< compressed payload of the page */ byte* buf_end;/* end of buf */ ulint n_dense; ulint slot_size;/* amount of uncompressed bytes per record */ const rec_t** recs; /*!< dense page directory, sorted by address */ mem_heap_t* heap; ulint trx_id_col; ulint n_blobs = 0; byte* storage;/* storage of uncompressed columns */ #ifndef UNIV_HOTBACKUP ullint usec = ut_time_us(NULL); uint level; uint wrap; uint strategy; int window_bits; page_zip_decode_compression_flags(compression_flags, &level, &wrap, &strategy); window_bits = wrap ? UNIV_PAGE_SIZE_SHIFT : - ((int) UNIV_PAGE_SIZE_SHIFT); #endif /* !UNIV_HOTBACKUP */ #ifdef PAGE_ZIP_COMPRESS_DBG FILE* logfile = NULL; #endif /* A local copy of srv_cmp_per_index_enabled to avoid reading that variable multiple times in this function since it can be changed at anytime. */ my_bool cmp_per_index_enabled = srv_cmp_per_index_enabled; ut_a(page_is_comp(page)); ut_a(fil_page_get_type(page) == FIL_PAGE_INDEX); ut_ad(page_simple_validate_new((page_t*) page)); ut_ad(page_zip_simple_validate(page_zip)); ut_ad(dict_table_is_comp(index->table)); ut_ad(!dict_index_is_ibuf(index)); UNIV_MEM_ASSERT_RW(page, UNIV_PAGE_SIZE); /* Check the data that will be omitted. */ ut_a(!memcmp(page + (PAGE_NEW_INFIMUM - REC_N_NEW_EXTRA_BYTES), infimum_extra, sizeof infimum_extra)); ut_a(!memcmp(page + PAGE_NEW_INFIMUM, infimum_data, sizeof infimum_data)); ut_a(page[PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES] /* info_bits == 0, n_owned <= max */ <= PAGE_DIR_SLOT_MAX_N_OWNED); ut_a(!memcmp(page + (PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES + 1), supremum_extra_data, sizeof supremum_extra_data)); if (page_is_empty(page)) { ut_a(rec_get_next_offs(page + PAGE_NEW_INFIMUM, TRUE) == PAGE_NEW_SUPREMUM); } if (page_is_leaf(page)) { n_fields = dict_index_get_n_fields(index); } else { n_fields = dict_index_get_n_unique_in_tree(index); } /* The dense directory excludes the infimum and supremum records. */ n_dense = page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW; #ifdef PAGE_ZIP_COMPRESS_DBG if (UNIV_UNLIKELY(page_zip_compress_dbg)) { fprintf(stderr, "compress %p %p %lu %lu %lu\n", (void*) page_zip, (void*) page, (ibool) page_is_leaf(page), n_fields, n_dense); } if (UNIV_UNLIKELY(page_zip_compress_log)) { /* Create a log file for every compression attempt. */ char logfilename[9]; ut_snprintf(logfilename, sizeof logfilename, "%08x", page_zip_compress_log++); logfile = fopen(logfilename, "wb"); if (logfile) { /* Write the uncompressed page to the log. */ blind_fwrite(page, 1, UNIV_PAGE_SIZE, logfile); /* Record the compressed size as zero. This will be overwritten at successful exit. */ putc(0, logfile); putc(0, logfile); putc(0, logfile); putc(0, logfile); } } #endif /* PAGE_ZIP_COMPRESS_DBG */ #ifndef UNIV_HOTBACKUP page_zip_stat[page_zip->ssize - 1].compressed++; if (cmp_per_index_enabled) { mutex_enter(&page_zip_stat_per_index_mutex); page_zip_stat_per_index[index->id].compressed++; mutex_exit(&page_zip_stat_per_index_mutex); } #endif /* !UNIV_HOTBACKUP */ if (UNIV_UNLIKELY(n_dense * PAGE_ZIP_DIR_SLOT_SIZE >= page_zip_get_size(page_zip))) { goto err_exit; } MONITOR_INC(MONITOR_PAGE_COMPRESS); heap = mem_heap_create(page_zip_get_size(page_zip) + n_fields * (2 + sizeof(ulint)) + REC_OFFS_HEADER_SIZE + n_dense * ((sizeof *recs) - PAGE_ZIP_DIR_SLOT_SIZE) + UNIV_PAGE_SIZE * 4 + (512 << MAX_MEM_LEVEL)); recs = static_cast<const rec_t**>( mem_heap_zalloc(heap, n_dense * sizeof *recs)); fields = static_cast<byte*>(mem_heap_alloc(heap, (n_fields + 1) * 2)); buf = static_cast<byte*>( mem_heap_alloc(heap, page_zip_get_size(page_zip) - PAGE_DATA)); buf_end = buf + page_zip_get_size(page_zip) - PAGE_DATA; /* Compress the data payload. */ page_zip_set_alloc(&c_stream, heap); err = deflateInit2(&c_stream, static_cast<int>(level), Z_DEFLATED, window_bits, MAX_MEM_LEVEL, strategy); ut_a(err == Z_OK); c_stream.next_out = buf; /* Subtract the space reserved for uncompressed data. */ /* Page header and the end marker of the modification log */ c_stream.avail_out = static_cast<uInt>(buf_end - buf - 1); /* Dense page directory and uncompressed columns, if any */ if (page_is_leaf(page)) { if (dict_index_is_clust(index)) { trx_id_col = dict_index_get_sys_col_pos( index, DATA_TRX_ID); ut_ad(trx_id_col > 0); ut_ad(trx_id_col != ULINT_UNDEFINED); slot_size = PAGE_ZIP_DIR_SLOT_SIZE + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN; } else { /* Signal the absence of trx_id in page_zip_fields_encode() */ ut_ad(dict_index_get_sys_col_pos(index, DATA_TRX_ID) == ULINT_UNDEFINED); trx_id_col = 0; slot_size = PAGE_ZIP_DIR_SLOT_SIZE; } } else { slot_size = PAGE_ZIP_DIR_SLOT_SIZE + REC_NODE_PTR_SIZE; trx_id_col = ULINT_UNDEFINED; } if (UNIV_UNLIKELY(c_stream.avail_out <= n_dense * slot_size + 6/* sizeof(zlib header and footer) */)) { goto zlib_error; } c_stream.avail_out -= static_cast<uInt>(n_dense * slot_size); c_stream.avail_in = static_cast<uInt>( page_zip_fields_encode(n_fields, index, trx_id_col, fields)); c_stream.next_in = fields; if (UNIV_LIKELY(!trx_id_col)) { trx_id_col = ULINT_UNDEFINED; } UNIV_MEM_ASSERT_RW(c_stream.next_in, c_stream.avail_in); err = deflate(&c_stream, Z_FULL_FLUSH); if (err != Z_OK) { goto zlib_error; } ut_ad(!c_stream.avail_in); page_zip_dir_encode(page, buf_end, recs); c_stream.next_in = (byte*) page + PAGE_ZIP_START; storage = buf_end - n_dense * PAGE_ZIP_DIR_SLOT_SIZE; /* Compress the records in heap_no order. */ if (UNIV_UNLIKELY(!n_dense)) { } else if (!page_is_leaf(page)) { /* This is a node pointer page. */ err = page_zip_compress_node_ptrs(LOGFILE &c_stream, recs, n_dense, index, storage, heap); if (UNIV_UNLIKELY(err != Z_OK)) { goto zlib_error; } } else if (UNIV_LIKELY(trx_id_col == ULINT_UNDEFINED)) { /* This is a leaf page in a secondary index. */ err = page_zip_compress_sec(LOGFILE &c_stream, recs, n_dense); if (UNIV_UNLIKELY(err != Z_OK)) { goto zlib_error; } } else { /* This is a leaf page in a clustered index. */ err = page_zip_compress_clust(LOGFILE &c_stream, recs, n_dense, index, &n_blobs, trx_id_col, buf_end - PAGE_ZIP_DIR_SLOT_SIZE * page_get_n_recs(page), storage, heap); if (UNIV_UNLIKELY(err != Z_OK)) { goto zlib_error; } } /* Finish the compression. */ ut_ad(!c_stream.avail_in); /* Compress any trailing garbage, in case the last record was allocated from an originally longer space on the free list, or the data of the last record from page_zip_compress_sec(). */ c_stream.avail_in = static_cast<uInt>( page_header_get_field(page, PAGE_HEAP_TOP) - (c_stream.next_in - page)); ut_a(c_stream.avail_in <= UNIV_PAGE_SIZE - PAGE_ZIP_START - PAGE_DIR); UNIV_MEM_ASSERT_RW(c_stream.next_in, c_stream.avail_in); err = deflate(&c_stream, Z_FINISH); if (UNIV_UNLIKELY(err != Z_STREAM_END)) { zlib_error: deflateEnd(&c_stream); mem_heap_free(heap); err_exit: #ifdef PAGE_ZIP_COMPRESS_DBG if (logfile) { fclose(logfile); } #endif /* PAGE_ZIP_COMPRESS_DBG */ #ifndef UNIV_HOTBACKUP if (page_is_leaf(page)) { dict_index_zip_failure(index); } ullint time_diff = ut_time_us(NULL) - usec; page_zip_stat[page_zip->ssize - 1].compressed_usec += time_diff; if (cmp_per_index_enabled) { mutex_enter(&page_zip_stat_per_index_mutex); page_zip_stat_per_index[index->id].compressed_usec += time_diff; mutex_exit(&page_zip_stat_per_index_mutex); } #endif /* !UNIV_HOTBACKUP */ return(FALSE); } err = deflateEnd(&c_stream); ut_a(err == Z_OK); ut_ad(buf + c_stream.total_out == c_stream.next_out); ut_ad((ulint) (storage - c_stream.next_out) >= c_stream.avail_out); /* Valgrind believes that zlib does not initialize some bits in the last 7 or 8 bytes of the stream. Make Valgrind happy. */ UNIV_MEM_VALID(buf, c_stream.total_out); /* Zero out the area reserved for the modification log. Space for the end marker of the modification log is not included in avail_out. */ memset(c_stream.next_out, 0, c_stream.avail_out + 1/* end marker */); #ifdef UNIV_DEBUG page_zip->m_start = #endif /* UNIV_DEBUG */ page_zip->m_end = PAGE_DATA + c_stream.total_out; page_zip->m_nonempty = FALSE; page_zip->n_blobs = n_blobs; /* Copy those header fields that will not be written in buf_flush_init_for_writing() */ memcpy(page_zip->data + FIL_PAGE_PREV, page + FIL_PAGE_PREV, FIL_PAGE_LSN - FIL_PAGE_PREV); memcpy(page_zip->data + FIL_PAGE_TYPE, page + FIL_PAGE_TYPE, 2); memcpy(page_zip->data + FIL_PAGE_DATA, page + FIL_PAGE_DATA, PAGE_DATA - FIL_PAGE_DATA); /* Copy the rest of the compressed page */ memcpy(page_zip->data + PAGE_DATA, buf, page_zip_get_size(page_zip) - PAGE_DATA); mem_heap_free(heap); #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ if (mtr) { #ifndef UNIV_HOTBACKUP page_zip_compress_write_log(page_zip, page, index, mtr); #endif /* !UNIV_HOTBACKUP */ } UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); #ifdef PAGE_ZIP_COMPRESS_DBG if (logfile) { /* Record the compressed size of the block. */ byte sz[4]; mach_write_to_4(sz, c_stream.total_out); fseek(logfile, UNIV_PAGE_SIZE, SEEK_SET); blind_fwrite(sz, 1, sizeof sz, logfile); fclose(logfile); } #endif /* PAGE_ZIP_COMPRESS_DBG */ #ifndef UNIV_HOTBACKUP ullint time_diff = ut_time_us(NULL) - usec; page_zip_stat[page_zip->ssize - 1].compressed_ok++; page_zip_stat[page_zip->ssize - 1].compressed_usec += time_diff; if (cmp_per_index_enabled) { mutex_enter(&page_zip_stat_per_index_mutex); page_zip_stat_per_index[index->id].compressed_ok++; page_zip_stat_per_index[index->id].compressed_usec += time_diff; mutex_exit(&page_zip_stat_per_index_mutex); } if (page_is_leaf(page)) { dict_index_zip_success(index); } #endif /* !UNIV_HOTBACKUP */ return(TRUE); } /**********************************************************************//** Compare two page directory entries. @return positive if rec1 > rec2 */ UNIV_INLINE ibool page_zip_dir_cmp( /*=============*/ const rec_t* rec1, /*!< in: rec1 */ const rec_t* rec2) /*!< in: rec2 */ { return(rec1 > rec2); } /**********************************************************************//** Sort the dense page directory by address (heap_no). */ static void page_zip_dir_sort( /*==============*/ rec_t** arr, /*!< in/out: dense page directory */ rec_t** aux_arr,/*!< in/out: work area */ ulint low, /*!< in: lower bound of the sorting area, inclusive */ ulint high) /*!< in: upper bound of the sorting area, exclusive */ { UT_SORT_FUNCTION_BODY(page_zip_dir_sort, arr, aux_arr, low, high, page_zip_dir_cmp); } /**********************************************************************//** Deallocate the index information initialized by page_zip_fields_decode(). */ static void page_zip_fields_free( /*=================*/ dict_index_t* index) /*!< in: dummy index to be freed */ { if (index) { dict_table_t* table = index->table; os_fast_mutex_free(&index->zip_pad.mutex); mem_heap_free(index->heap); dict_mem_table_free(table); } } /**********************************************************************//** Read the index information for the compressed page. @return own: dummy index describing the page, or NULL on error */ static dict_index_t* page_zip_fields_decode( /*===================*/ const byte* buf, /*!< in: index information */ const byte* end, /*!< in: end of buf */ ulint* trx_id_col)/*!< in: NULL for non-leaf pages; for leaf pages, pointer to where to store the position of the trx_id column */ { const byte* b; ulint n; ulint i; ulint val; dict_table_t* table; dict_index_t* index; /* Determine the number of fields. */ for (b = buf, n = 0; b < end; n++) { if (*b++ & 0x80) { b++; /* skip the second byte */ } } n--; /* n_nullable or trx_id */ if (UNIV_UNLIKELY(n > REC_MAX_N_FIELDS)) { page_zip_fail(("page_zip_fields_decode: n = %lu\n", (ulong) n)); return(NULL); } if (UNIV_UNLIKELY(b > end)) { page_zip_fail(("page_zip_fields_decode: %p > %p\n", (const void*) b, (const void*) end)); return(NULL); } table = dict_mem_table_create("ZIP_DUMMY", DICT_HDR_SPACE, n, DICT_TF_COMPACT, 0); index = dict_mem_index_create("ZIP_DUMMY", "ZIP_DUMMY", DICT_HDR_SPACE, 0, n); index->table = table; index->n_uniq = n; /* avoid ut_ad(index->cached) in dict_index_get_n_unique_in_tree */ index->cached = TRUE; /* Initialize the fields. */ for (b = buf, i = 0; i < n; i++) { ulint mtype; ulint len; val = *b++; if (UNIV_UNLIKELY(val & 0x80)) { /* fixed length > 62 bytes */ val = (val & 0x7f) << 8 | *b++; len = val >> 1; mtype = DATA_FIXBINARY; } else if (UNIV_UNLIKELY(val >= 126)) { /* variable length with max > 255 bytes */ len = 0x7fff; mtype = DATA_BINARY; } else if (val <= 1) { /* variable length with max <= 255 bytes */ len = 0; mtype = DATA_BINARY; } else { /* fixed length < 62 bytes */ len = val >> 1; mtype = DATA_FIXBINARY; } dict_mem_table_add_col(table, NULL, NULL, mtype, val & 1 ? DATA_NOT_NULL : 0, len); dict_index_add_col(index, table, dict_table_get_nth_col(table, i), 0); } val = *b++; if (UNIV_UNLIKELY(val & 0x80)) { val = (val & 0x7f) << 8 | *b++; } /* Decode the position of the trx_id column. */ if (trx_id_col) { if (!val) { val = ULINT_UNDEFINED; } else if (UNIV_UNLIKELY(val >= n)) { page_zip_fields_free(index); index = NULL; } else { index->type = DICT_CLUSTERED; } *trx_id_col = val; } else { /* Decode the number of nullable fields. */ if (UNIV_UNLIKELY(index->n_nullable > val)) { page_zip_fields_free(index); index = NULL; } else { index->n_nullable = val; } } ut_ad(b == end); return(index); } /**********************************************************************//** Populate the sparse page directory from the dense directory. @return TRUE on success, FALSE on failure */ static ibool page_zip_dir_decode( /*================*/ const page_zip_des_t* page_zip,/*!< in: dense page directory on compressed page */ page_t* page, /*!< in: compact page with valid header; out: trailer and sparse page directory filled in */ rec_t** recs, /*!< out: dense page directory sorted by ascending address (and heap_no) */ rec_t** recs_aux,/*!< in/out: scratch area */ ulint n_dense)/*!< in: number of user records, and size of recs[] and recs_aux[] */ { ulint i; ulint n_recs; byte* slot; n_recs = page_get_n_recs(page); if (UNIV_UNLIKELY(n_recs > n_dense)) { page_zip_fail(("page_zip_dir_decode 1: %lu > %lu\n", (ulong) n_recs, (ulong) n_dense)); return(FALSE); } /* Traverse the list of stored records in the sorting order, starting from the first user record. */ slot = page + (UNIV_PAGE_SIZE - PAGE_DIR - PAGE_DIR_SLOT_SIZE); UNIV_PREFETCH_RW(slot); /* Zero out the page trailer. */ memset(slot + PAGE_DIR_SLOT_SIZE, 0, PAGE_DIR); mach_write_to_2(slot, PAGE_NEW_INFIMUM); slot -= PAGE_DIR_SLOT_SIZE; UNIV_PREFETCH_RW(slot); /* Initialize the sparse directory and copy the dense directory. */ for (i = 0; i < n_recs; i++) { ulint offs = page_zip_dir_get(page_zip, i); if (offs & PAGE_ZIP_DIR_SLOT_OWNED) { mach_write_to_2(slot, offs & PAGE_ZIP_DIR_SLOT_MASK); slot -= PAGE_DIR_SLOT_SIZE; UNIV_PREFETCH_RW(slot); } if (UNIV_UNLIKELY((offs & PAGE_ZIP_DIR_SLOT_MASK) < PAGE_ZIP_START + REC_N_NEW_EXTRA_BYTES)) { page_zip_fail(("page_zip_dir_decode 2: %u %u %lx\n", (unsigned) i, (unsigned) n_recs, (ulong) offs)); return(FALSE); } recs[i] = page + (offs & PAGE_ZIP_DIR_SLOT_MASK); } mach_write_to_2(slot, PAGE_NEW_SUPREMUM); { const page_dir_slot_t* last_slot = page_dir_get_nth_slot( page, page_dir_get_n_slots(page) - 1); if (UNIV_UNLIKELY(slot != last_slot)) { page_zip_fail(("page_zip_dir_decode 3: %p != %p\n", (const void*) slot, (const void*) last_slot)); return(FALSE); } } /* Copy the rest of the dense directory. */ for (; i < n_dense; i++) { ulint offs = page_zip_dir_get(page_zip, i); if (UNIV_UNLIKELY(offs & ~PAGE_ZIP_DIR_SLOT_MASK)) { page_zip_fail(("page_zip_dir_decode 4: %u %u %lx\n", (unsigned) i, (unsigned) n_dense, (ulong) offs)); return(FALSE); } recs[i] = page + offs; } if (UNIV_LIKELY(n_dense > 1)) { page_zip_dir_sort(recs, recs_aux, 0, n_dense); } return(TRUE); } /**********************************************************************//** Initialize the REC_N_NEW_EXTRA_BYTES of each record. @return TRUE on success, FALSE on failure */ static ibool page_zip_set_extra_bytes( /*=====================*/ const page_zip_des_t* page_zip,/*!< in: compressed page */ page_t* page, /*!< in/out: uncompressed page */ ulint info_bits)/*!< in: REC_INFO_MIN_REC_FLAG or 0 */ { ulint n; ulint i; ulint n_owned = 1; ulint offs; rec_t* rec; n = page_get_n_recs(page); rec = page + PAGE_NEW_INFIMUM; for (i = 0; i < n; i++) { offs = page_zip_dir_get(page_zip, i); if (offs & PAGE_ZIP_DIR_SLOT_DEL) { info_bits |= REC_INFO_DELETED_FLAG; } if (UNIV_UNLIKELY(offs & PAGE_ZIP_DIR_SLOT_OWNED)) { info_bits |= n_owned; n_owned = 1; } else { n_owned++; } offs &= PAGE_ZIP_DIR_SLOT_MASK; if (UNIV_UNLIKELY(offs < PAGE_ZIP_START + REC_N_NEW_EXTRA_BYTES)) { page_zip_fail(("page_zip_set_extra_bytes 1:" " %u %u %lx\n", (unsigned) i, (unsigned) n, (ulong) offs)); return(FALSE); } rec_set_next_offs_new(rec, offs); rec = page + offs; rec[-REC_N_NEW_EXTRA_BYTES] = (byte) info_bits; info_bits = 0; } /* Set the next pointer of the last user record. */ rec_set_next_offs_new(rec, PAGE_NEW_SUPREMUM); /* Set n_owned of the supremum record. */ page[PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES] = (byte) n_owned; /* The dense directory excludes the infimum and supremum records. */ n = page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW; if (i >= n) { if (UNIV_LIKELY(i == n)) { return(TRUE); } page_zip_fail(("page_zip_set_extra_bytes 2: %u != %u\n", (unsigned) i, (unsigned) n)); return(FALSE); } offs = page_zip_dir_get(page_zip, i); /* Set the extra bytes of deleted records on the free list. */ for (;;) { if (UNIV_UNLIKELY(!offs) || UNIV_UNLIKELY(offs & ~PAGE_ZIP_DIR_SLOT_MASK)) { page_zip_fail(("page_zip_set_extra_bytes 3: %lx\n", (ulong) offs)); return(FALSE); } rec = page + offs; rec[-REC_N_NEW_EXTRA_BYTES] = 0; /* info_bits and n_owned */ if (++i == n) { break; } offs = page_zip_dir_get(page_zip, i); rec_set_next_offs_new(rec, offs); } /* Terminate the free list. */ rec[-REC_N_NEW_EXTRA_BYTES] = 0; /* info_bits and n_owned */ rec_set_next_offs_new(rec, 0); return(TRUE); } /**********************************************************************//** Apply the modification log to a record containing externally stored columns. Do not copy the fields that are stored separately. @return pointer to modification log, or NULL on failure */ static const byte* page_zip_apply_log_ext( /*===================*/ rec_t* rec, /*!< in/out: record */ const ulint* offsets, /*!< in: rec_get_offsets(rec) */ ulint trx_id_col, /*!< in: position of of DB_TRX_ID */ const byte* data, /*!< in: modification log */ const byte* end) /*!< in: end of modification log */ { ulint i; ulint len; byte* next_out = rec; /* Check if there are any externally stored columns. For each externally stored column, skip the BTR_EXTERN_FIELD_REF. */ for (i = 0; i < rec_offs_n_fields(offsets); i++) { byte* dst; if (UNIV_UNLIKELY(i == trx_id_col)) { /* Skip trx_id and roll_ptr */ dst = rec_get_nth_field(rec, offsets, i, &len); if (UNIV_UNLIKELY(dst - next_out >= end - data) || UNIV_UNLIKELY (len < (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)) || rec_offs_nth_extern(offsets, i)) { page_zip_fail(("page_zip_apply_log_ext:" " trx_id len %lu," " %p - %p >= %p - %p\n", (ulong) len, (const void*) dst, (const void*) next_out, (const void*) end, (const void*) data)); return(NULL); } memcpy(next_out, data, dst - next_out); data += dst - next_out; next_out = dst + (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); } else if (rec_offs_nth_extern(offsets, i)) { dst = rec_get_nth_field(rec, offsets, i, &len); ut_ad(len >= BTR_EXTERN_FIELD_REF_SIZE); len += dst - next_out - BTR_EXTERN_FIELD_REF_SIZE; if (UNIV_UNLIKELY(data + len >= end)) { page_zip_fail(("page_zip_apply_log_ext: " "ext %p+%lu >= %p\n", (const void*) data, (ulong) len, (const void*) end)); return(NULL); } memcpy(next_out, data, len); data += len; next_out += len + BTR_EXTERN_FIELD_REF_SIZE; } } /* Copy the last bytes of the record. */ len = rec_get_end(rec, offsets) - next_out; if (UNIV_UNLIKELY(data + len >= end)) { page_zip_fail(("page_zip_apply_log_ext: " "last %p+%lu >= %p\n", (const void*) data, (ulong) len, (const void*) end)); return(NULL); } memcpy(next_out, data, len); data += len; return(data); } /**********************************************************************//** Apply the modification log to an uncompressed page. Do not copy the fields that are stored separately. @return pointer to end of modification log, or NULL on failure */ static const byte* page_zip_apply_log( /*===============*/ const byte* data, /*!< in: modification log */ ulint size, /*!< in: maximum length of the log, in bytes */ rec_t** recs, /*!< in: dense page directory, sorted by address (indexed by heap_no - PAGE_HEAP_NO_USER_LOW) */ ulint n_dense,/*!< in: size of recs[] */ ulint trx_id_col,/*!< in: column number of trx_id in the index, or ULINT_UNDEFINED if none */ ulint heap_status, /*!< in: heap_no and status bits for the next record to uncompress */ dict_index_t* index, /*!< in: index of the page */ ulint* offsets)/*!< in/out: work area for rec_get_offsets_reverse() */ { const byte* const end = data + size; for (;;) { ulint val; rec_t* rec; ulint len; ulint hs; val = *data++; if (UNIV_UNLIKELY(!val)) { return(data - 1); } if (val & 0x80) { val = (val & 0x7f) << 8 | *data++; if (UNIV_UNLIKELY(!val)) { page_zip_fail(("page_zip_apply_log:" " invalid val %x%x\n", data[-2], data[-1])); return(NULL); } } if (UNIV_UNLIKELY(data >= end)) { page_zip_fail(("page_zip_apply_log: %p >= %p\n", (const void*) data, (const void*) end)); return(NULL); } if (UNIV_UNLIKELY((val >> 1) > n_dense)) { page_zip_fail(("page_zip_apply_log: %lu>>1 > %lu\n", (ulong) val, (ulong) n_dense)); return(NULL); } /* Determine the heap number and status bits of the record. */ rec = recs[(val >> 1) - 1]; hs = ((val >> 1) + 1) << REC_HEAP_NO_SHIFT; hs |= heap_status & ((1 << REC_HEAP_NO_SHIFT) - 1); /* This may either be an old record that is being overwritten (updated in place, or allocated from the free list), or a new record, with the next available_heap_no. */ if (UNIV_UNLIKELY(hs > heap_status)) { page_zip_fail(("page_zip_apply_log: %lu > %lu\n", (ulong) hs, (ulong) heap_status)); return(NULL); } else if (hs == heap_status) { /* A new record was allocated from the heap. */ if (UNIV_UNLIKELY(val & 1)) { /* Only existing records may be cleared. */ page_zip_fail(("page_zip_apply_log:" " attempting to create" " deleted rec %lu\n", (ulong) hs)); return(NULL); } heap_status += 1 << REC_HEAP_NO_SHIFT; } mach_write_to_2(rec - REC_NEW_HEAP_NO, hs); if (val & 1) { /* Clear the data bytes of the record. */ mem_heap_t* heap = NULL; ulint* offs; offs = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); memset(rec, 0, rec_offs_data_size(offs)); if (UNIV_LIKELY_NULL(heap)) { mem_heap_free(heap); } continue; } #if REC_STATUS_NODE_PTR != TRUE # error "REC_STATUS_NODE_PTR != TRUE" #endif rec_get_offsets_reverse(data, index, hs & REC_STATUS_NODE_PTR, offsets); rec_offs_make_valid(rec, index, offsets); /* Copy the extra bytes (backwards). */ { byte* start = rec_get_start(rec, offsets); byte* b = rec - REC_N_NEW_EXTRA_BYTES; while (b != start) { *--b = *data++; } } /* Copy the data bytes. */ if (UNIV_UNLIKELY(rec_offs_any_extern(offsets))) { /* Non-leaf nodes should not contain any externally stored columns. */ if (UNIV_UNLIKELY(hs & REC_STATUS_NODE_PTR)) { page_zip_fail(("page_zip_apply_log: " "%lu&REC_STATUS_NODE_PTR\n", (ulong) hs)); return(NULL); } data = page_zip_apply_log_ext( rec, offsets, trx_id_col, data, end); if (UNIV_UNLIKELY(!data)) { return(NULL); } } else if (UNIV_UNLIKELY(hs & REC_STATUS_NODE_PTR)) { len = rec_offs_data_size(offsets) - REC_NODE_PTR_SIZE; /* Copy the data bytes, except node_ptr. */ if (UNIV_UNLIKELY(data + len >= end)) { page_zip_fail(("page_zip_apply_log: " "node_ptr %p+%lu >= %p\n", (const void*) data, (ulong) len, (const void*) end)); return(NULL); } memcpy(rec, data, len); data += len; } else if (UNIV_LIKELY(trx_id_col == ULINT_UNDEFINED)) { len = rec_offs_data_size(offsets); /* Copy all data bytes of a record in a secondary index. */ if (UNIV_UNLIKELY(data + len >= end)) { page_zip_fail(("page_zip_apply_log: " "sec %p+%lu >= %p\n", (const void*) data, (ulong) len, (const void*) end)); return(NULL); } memcpy(rec, data, len); data += len; } else { /* Skip DB_TRX_ID and DB_ROLL_PTR. */ ulint l = rec_get_nth_field_offs(offsets, trx_id_col, &len); byte* b; if (UNIV_UNLIKELY(data + l >= end) || UNIV_UNLIKELY(len < (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN))) { page_zip_fail(("page_zip_apply_log: " "trx_id %p+%lu >= %p\n", (const void*) data, (ulong) l, (const void*) end)); return(NULL); } /* Copy any preceding data bytes. */ memcpy(rec, data, l); data += l; /* Copy any bytes following DB_TRX_ID, DB_ROLL_PTR. */ b = rec + l + (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); len = rec_get_end(rec, offsets) - b; if (UNIV_UNLIKELY(data + len >= end)) { page_zip_fail(("page_zip_apply_log: " "clust %p+%lu >= %p\n", (const void*) data, (ulong) len, (const void*) end)); return(NULL); } memcpy(b, data, len); data += len; } } } /**********************************************************************//** Set the heap_no in a record, and skip the fixed-size record header that is not included in the d_stream. @return TRUE on success, FALSE if d_stream does not end at rec */ static ibool page_zip_decompress_heap_no( /*========================*/ z_stream* d_stream, /*!< in/out: compressed page stream */ rec_t* rec, /*!< in/out: record */ ulint& heap_status) /*!< in/out: heap_no and status bits */ { if (d_stream->next_out != rec - REC_N_NEW_EXTRA_BYTES) { /* n_dense has grown since the page was last compressed. */ return(FALSE); } /* Skip the REC_N_NEW_EXTRA_BYTES. */ d_stream->next_out = rec; /* Set heap_no and the status bits. */ mach_write_to_2(rec - REC_NEW_HEAP_NO, heap_status); heap_status += 1 << REC_HEAP_NO_SHIFT; return(TRUE); } /**********************************************************************//** Decompress the records of a node pointer page. @return TRUE on success, FALSE on failure */ static ibool page_zip_decompress_node_ptrs( /*==========================*/ page_zip_des_t* page_zip, /*!< in/out: compressed page */ z_stream* d_stream, /*!< in/out: compressed page stream */ rec_t** recs, /*!< in: dense page directory sorted by address */ ulint n_dense, /*!< in: size of recs[] */ dict_index_t* index, /*!< in: the index of the page */ ulint* offsets, /*!< in/out: temporary offsets */ mem_heap_t* heap) /*!< in: temporary memory heap */ { ulint heap_status = REC_STATUS_NODE_PTR | PAGE_HEAP_NO_USER_LOW << REC_HEAP_NO_SHIFT; ulint slot; const byte* storage; /* Subtract the space reserved for uncompressed data. */ d_stream->avail_in -= static_cast<uInt>( n_dense * (PAGE_ZIP_DIR_SLOT_SIZE + REC_NODE_PTR_SIZE)); /* Decompress the records in heap_no order. */ for (slot = 0; slot < n_dense; slot++) { rec_t* rec = recs[slot]; d_stream->avail_out = static_cast<uInt>( rec - REC_N_NEW_EXTRA_BYTES - d_stream->next_out); ut_ad(d_stream->avail_out < UNIV_PAGE_SIZE - PAGE_ZIP_START - PAGE_DIR); switch (inflate(d_stream, Z_SYNC_FLUSH)) { case Z_STREAM_END: page_zip_decompress_heap_no( d_stream, rec, heap_status); goto zlib_done; case Z_OK: case Z_BUF_ERROR: if (!d_stream->avail_out) { break; } /* fall through */ default: page_zip_fail(("page_zip_decompress_node_ptrs:" " 1 inflate(Z_SYNC_FLUSH)=%s\n", d_stream->msg)); goto zlib_error; } if (!page_zip_decompress_heap_no( d_stream, rec, heap_status)) { ut_ad(0); } /* Read the offsets. The status bits are needed here. */ offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); /* Non-leaf nodes should not have any externally stored columns. */ ut_ad(!rec_offs_any_extern(offsets)); /* Decompress the data bytes, except node_ptr. */ d_stream->avail_out =static_cast<uInt>( rec_offs_data_size(offsets) - REC_NODE_PTR_SIZE); switch (inflate(d_stream, Z_SYNC_FLUSH)) { case Z_STREAM_END: goto zlib_done; case Z_OK: case Z_BUF_ERROR: if (!d_stream->avail_out) { break; } /* fall through */ default: page_zip_fail(("page_zip_decompress_node_ptrs:" " 2 inflate(Z_SYNC_FLUSH)=%s\n", d_stream->msg)); goto zlib_error; } /* Clear the node pointer in case the record will be deleted and the space will be reallocated to a smaller record. */ memset(d_stream->next_out, 0, REC_NODE_PTR_SIZE); d_stream->next_out += REC_NODE_PTR_SIZE; ut_ad(d_stream->next_out == rec_get_end(rec, offsets)); } /* Decompress any trailing garbage, in case the last record was allocated from an originally longer space on the free list. */ d_stream->avail_out = static_cast<uInt>( page_header_get_field(page_zip->data, PAGE_HEAP_TOP) - page_offset(d_stream->next_out)); if (UNIV_UNLIKELY(d_stream->avail_out > UNIV_PAGE_SIZE - PAGE_ZIP_START - PAGE_DIR)) { page_zip_fail(("page_zip_decompress_node_ptrs:" " avail_out = %u\n", d_stream->avail_out)); goto zlib_error; } if (UNIV_UNLIKELY(inflate(d_stream, Z_FINISH) != Z_STREAM_END)) { page_zip_fail(("page_zip_decompress_node_ptrs:" " inflate(Z_FINISH)=%s\n", d_stream->msg)); zlib_error: inflateEnd(d_stream); return(FALSE); } /* Note that d_stream->avail_out > 0 may hold here if the modification log is nonempty. */ zlib_done: if (UNIV_UNLIKELY(inflateEnd(d_stream) != Z_OK)) { ut_error; } { page_t* page = page_align(d_stream->next_out); /* Clear the unused heap space on the uncompressed page. */ memset(d_stream->next_out, 0, page_dir_get_nth_slot(page, page_dir_get_n_slots(page) - 1) - d_stream->next_out); } #ifdef UNIV_DEBUG page_zip->m_start = PAGE_DATA + d_stream->total_in; #endif /* UNIV_DEBUG */ /* Apply the modification log. */ { const byte* mod_log_ptr; mod_log_ptr = page_zip_apply_log(d_stream->next_in, d_stream->avail_in + 1, recs, n_dense, ULINT_UNDEFINED, heap_status, index, offsets); if (UNIV_UNLIKELY(!mod_log_ptr)) { return(FALSE); } page_zip->m_end = mod_log_ptr - page_zip->data; page_zip->m_nonempty = mod_log_ptr != d_stream->next_in; } if (UNIV_UNLIKELY (page_zip_get_trailer_len(page_zip, dict_index_is_clust(index)) + page_zip->m_end >= page_zip_get_size(page_zip))) { page_zip_fail(("page_zip_decompress_node_ptrs:" " %lu + %lu >= %lu, %lu\n", (ulong) page_zip_get_trailer_len( page_zip, dict_index_is_clust(index)), (ulong) page_zip->m_end, (ulong) page_zip_get_size(page_zip), (ulong) dict_index_is_clust(index))); return(FALSE); } /* Restore the uncompressed columns in heap_no order. */ storage = page_zip_dir_start_low(page_zip, n_dense); for (slot = 0; slot < n_dense; slot++) { rec_t* rec = recs[slot]; offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); /* Non-leaf nodes should not have any externally stored columns. */ ut_ad(!rec_offs_any_extern(offsets)); storage -= REC_NODE_PTR_SIZE; memcpy(rec_get_end(rec, offsets) - REC_NODE_PTR_SIZE, storage, REC_NODE_PTR_SIZE); } return(TRUE); } /**********************************************************************//** Decompress the records of a leaf node of a secondary index. @return TRUE on success, FALSE on failure */ static ibool page_zip_decompress_sec( /*====================*/ page_zip_des_t* page_zip, /*!< in/out: compressed page */ z_stream* d_stream, /*!< in/out: compressed page stream */ rec_t** recs, /*!< in: dense page directory sorted by address */ ulint n_dense, /*!< in: size of recs[] */ dict_index_t* index, /*!< in: the index of the page */ ulint* offsets) /*!< in/out: temporary offsets */ { ulint heap_status = REC_STATUS_ORDINARY | PAGE_HEAP_NO_USER_LOW << REC_HEAP_NO_SHIFT; ulint slot; ut_a(!dict_index_is_clust(index)); /* Subtract the space reserved for uncompressed data. */ d_stream->avail_in -= static_cast<uint>( n_dense * PAGE_ZIP_DIR_SLOT_SIZE); for (slot = 0; slot < n_dense; slot++) { rec_t* rec = recs[slot]; /* Decompress everything up to this record. */ d_stream->avail_out = static_cast<uint>( rec - REC_N_NEW_EXTRA_BYTES - d_stream->next_out); if (UNIV_LIKELY(d_stream->avail_out)) { switch (inflate(d_stream, Z_SYNC_FLUSH)) { case Z_STREAM_END: page_zip_decompress_heap_no( d_stream, rec, heap_status); goto zlib_done; case Z_OK: case Z_BUF_ERROR: if (!d_stream->avail_out) { break; } /* fall through */ default: page_zip_fail(("page_zip_decompress_sec:" " inflate(Z_SYNC_FLUSH)=%s\n", d_stream->msg)); goto zlib_error; } } if (!page_zip_decompress_heap_no( d_stream, rec, heap_status)) { ut_ad(0); } } /* Decompress the data of the last record and any trailing garbage, in case the last record was allocated from an originally longer space on the free list. */ d_stream->avail_out = static_cast<uInt>( page_header_get_field(page_zip->data, PAGE_HEAP_TOP) - page_offset(d_stream->next_out)); if (UNIV_UNLIKELY(d_stream->avail_out > UNIV_PAGE_SIZE - PAGE_ZIP_START - PAGE_DIR)) { page_zip_fail(("page_zip_decompress_sec:" " avail_out = %u\n", d_stream->avail_out)); goto zlib_error; } if (UNIV_UNLIKELY(inflate(d_stream, Z_FINISH) != Z_STREAM_END)) { page_zip_fail(("page_zip_decompress_sec:" " inflate(Z_FINISH)=%s\n", d_stream->msg)); zlib_error: inflateEnd(d_stream); return(FALSE); } /* Note that d_stream->avail_out > 0 may hold here if the modification log is nonempty. */ zlib_done: if (UNIV_UNLIKELY(inflateEnd(d_stream) != Z_OK)) { ut_error; } { page_t* page = page_align(d_stream->next_out); /* Clear the unused heap space on the uncompressed page. */ memset(d_stream->next_out, 0, page_dir_get_nth_slot(page, page_dir_get_n_slots(page) - 1) - d_stream->next_out); } #ifdef UNIV_DEBUG page_zip->m_start = PAGE_DATA + d_stream->total_in; #endif /* UNIV_DEBUG */ /* Apply the modification log. */ { const byte* mod_log_ptr; mod_log_ptr = page_zip_apply_log(d_stream->next_in, d_stream->avail_in + 1, recs, n_dense, ULINT_UNDEFINED, heap_status, index, offsets); if (UNIV_UNLIKELY(!mod_log_ptr)) { return(FALSE); } page_zip->m_end = mod_log_ptr - page_zip->data; page_zip->m_nonempty = mod_log_ptr != d_stream->next_in; } if (UNIV_UNLIKELY(page_zip_get_trailer_len(page_zip, FALSE) + page_zip->m_end >= page_zip_get_size(page_zip))) { page_zip_fail(("page_zip_decompress_sec: %lu + %lu >= %lu\n", (ulong) page_zip_get_trailer_len( page_zip, FALSE), (ulong) page_zip->m_end, (ulong) page_zip_get_size(page_zip))); return(FALSE); } /* There are no uncompressed columns on leaf pages of secondary indexes. */ return(TRUE); } /**********************************************************************//** Decompress a record of a leaf node of a clustered index that contains externally stored columns. @return TRUE on success */ static ibool page_zip_decompress_clust_ext( /*==========================*/ z_stream* d_stream, /*!< in/out: compressed page stream */ rec_t* rec, /*!< in/out: record */ const ulint* offsets, /*!< in: rec_get_offsets(rec) */ ulint trx_id_col) /*!< in: position of of DB_TRX_ID */ { ulint i; for (i = 0; i < rec_offs_n_fields(offsets); i++) { ulint len; byte* dst; if (UNIV_UNLIKELY(i == trx_id_col)) { /* Skip trx_id and roll_ptr */ dst = rec_get_nth_field(rec, offsets, i, &len); if (UNIV_UNLIKELY(len < DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)) { page_zip_fail(("page_zip_decompress_clust_ext:" " len[%lu] = %lu\n", (ulong) i, (ulong) len)); return(FALSE); } if (rec_offs_nth_extern(offsets, i)) { page_zip_fail(("page_zip_decompress_clust_ext:" " DB_TRX_ID at %lu is ext\n", (ulong) i)); return(FALSE); } d_stream->avail_out = static_cast<uInt>( dst - d_stream->next_out); switch (inflate(d_stream, Z_SYNC_FLUSH)) { case Z_STREAM_END: case Z_OK: case Z_BUF_ERROR: if (!d_stream->avail_out) { break; } /* fall through */ default: page_zip_fail(("page_zip_decompress_clust_ext:" " 1 inflate(Z_SYNC_FLUSH)=%s\n", d_stream->msg)); return(FALSE); } ut_ad(d_stream->next_out == dst); /* Clear DB_TRX_ID and DB_ROLL_PTR in order to avoid uninitialized bytes in case the record is affected by page_zip_apply_log(). */ memset(dst, 0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); d_stream->next_out += DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN; } else if (rec_offs_nth_extern(offsets, i)) { dst = rec_get_nth_field(rec, offsets, i, &len); ut_ad(len >= BTR_EXTERN_FIELD_REF_SIZE); dst += len - BTR_EXTERN_FIELD_REF_SIZE; d_stream->avail_out = static_cast<uInt>( dst - d_stream->next_out); switch (inflate(d_stream, Z_SYNC_FLUSH)) { case Z_STREAM_END: case Z_OK: case Z_BUF_ERROR: if (!d_stream->avail_out) { break; } /* fall through */ default: page_zip_fail(("page_zip_decompress_clust_ext:" " 2 inflate(Z_SYNC_FLUSH)=%s\n", d_stream->msg)); return(FALSE); } ut_ad(d_stream->next_out == dst); /* Clear the BLOB pointer in case the record will be deleted and the space will not be reused. Note that the final initialization of the BLOB pointers (copying from "externs" or clearing) will have to take place only after the page modification log has been applied. Otherwise, we could end up with an uninitialized BLOB pointer when a record is deleted, reallocated and deleted. */ memset(d_stream->next_out, 0, BTR_EXTERN_FIELD_REF_SIZE); d_stream->next_out += BTR_EXTERN_FIELD_REF_SIZE; } } return(TRUE); } /**********************************************************************//** Compress the records of a leaf node of a clustered index. @return TRUE on success, FALSE on failure */ static ibool page_zip_decompress_clust( /*======================*/ page_zip_des_t* page_zip, /*!< in/out: compressed page */ z_stream* d_stream, /*!< in/out: compressed page stream */ rec_t** recs, /*!< in: dense page directory sorted by address */ ulint n_dense, /*!< in: size of recs[] */ dict_index_t* index, /*!< in: the index of the page */ ulint trx_id_col, /*!< index of the trx_id column */ ulint* offsets, /*!< in/out: temporary offsets */ mem_heap_t* heap) /*!< in: temporary memory heap */ { int err; ulint slot; ulint heap_status = REC_STATUS_ORDINARY | PAGE_HEAP_NO_USER_LOW << REC_HEAP_NO_SHIFT; const byte* storage; const byte* externs; ut_a(dict_index_is_clust(index)); /* Subtract the space reserved for uncompressed data. */ d_stream->avail_in -= static_cast<uInt>(n_dense) * (PAGE_ZIP_DIR_SLOT_SIZE + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); /* Decompress the records in heap_no order. */ for (slot = 0; slot < n_dense; slot++) { rec_t* rec = recs[slot]; d_stream->avail_out =static_cast<uInt>( rec - REC_N_NEW_EXTRA_BYTES - d_stream->next_out); ut_ad(d_stream->avail_out < UNIV_PAGE_SIZE - PAGE_ZIP_START - PAGE_DIR); err = inflate(d_stream, Z_SYNC_FLUSH); switch (err) { case Z_STREAM_END: page_zip_decompress_heap_no( d_stream, rec, heap_status); goto zlib_done; case Z_OK: case Z_BUF_ERROR: if (UNIV_LIKELY(!d_stream->avail_out)) { break; } /* fall through */ default: page_zip_fail(("page_zip_decompress_clust:" " 1 inflate(Z_SYNC_FLUSH)=%s\n", d_stream->msg)); goto zlib_error; } if (!page_zip_decompress_heap_no( d_stream, rec, heap_status)) { ut_ad(0); } /* Read the offsets. The status bits are needed here. */ offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); /* This is a leaf page in a clustered index. */ /* Check if there are any externally stored columns. For each externally stored column, restore the BTR_EXTERN_FIELD_REF separately. */ if (rec_offs_any_extern(offsets)) { if (UNIV_UNLIKELY (!page_zip_decompress_clust_ext( d_stream, rec, offsets, trx_id_col))) { goto zlib_error; } } else { /* Skip trx_id and roll_ptr */ ulint len; byte* dst = rec_get_nth_field(rec, offsets, trx_id_col, &len); if (UNIV_UNLIKELY(len < DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)) { page_zip_fail(("page_zip_decompress_clust:" " len = %lu\n", (ulong) len)); goto zlib_error; } d_stream->avail_out = static_cast<uInt>( dst - d_stream->next_out); switch (inflate(d_stream, Z_SYNC_FLUSH)) { case Z_STREAM_END: case Z_OK: case Z_BUF_ERROR: if (!d_stream->avail_out) { break; } /* fall through */ default: page_zip_fail(("page_zip_decompress_clust:" " 2 inflate(Z_SYNC_FLUSH)=%s\n", d_stream->msg)); goto zlib_error; } ut_ad(d_stream->next_out == dst); /* Clear DB_TRX_ID and DB_ROLL_PTR in order to avoid uninitialized bytes in case the record is affected by page_zip_apply_log(). */ memset(dst, 0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); d_stream->next_out += DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN; } /* Decompress the last bytes of the record. */ d_stream->avail_out = static_cast<uInt>( rec_get_end(rec, offsets) - d_stream->next_out); switch (inflate(d_stream, Z_SYNC_FLUSH)) { case Z_STREAM_END: case Z_OK: case Z_BUF_ERROR: if (!d_stream->avail_out) { break; } /* fall through */ default: page_zip_fail(("page_zip_decompress_clust:" " 3 inflate(Z_SYNC_FLUSH)=%s\n", d_stream->msg)); goto zlib_error; } } /* Decompress any trailing garbage, in case the last record was allocated from an originally longer space on the free list. */ d_stream->avail_out = static_cast<uInt>( page_header_get_field(page_zip->data, PAGE_HEAP_TOP) - page_offset(d_stream->next_out)); if (UNIV_UNLIKELY(d_stream->avail_out > UNIV_PAGE_SIZE - PAGE_ZIP_START - PAGE_DIR)) { page_zip_fail(("page_zip_decompress_clust:" " avail_out = %u\n", d_stream->avail_out)); goto zlib_error; } if (UNIV_UNLIKELY(inflate(d_stream, Z_FINISH) != Z_STREAM_END)) { page_zip_fail(("page_zip_decompress_clust:" " inflate(Z_FINISH)=%s\n", d_stream->msg)); zlib_error: inflateEnd(d_stream); return(FALSE); } /* Note that d_stream->avail_out > 0 may hold here if the modification log is nonempty. */ zlib_done: if (UNIV_UNLIKELY(inflateEnd(d_stream) != Z_OK)) { ut_error; } { page_t* page = page_align(d_stream->next_out); /* Clear the unused heap space on the uncompressed page. */ memset(d_stream->next_out, 0, page_dir_get_nth_slot(page, page_dir_get_n_slots(page) - 1) - d_stream->next_out); } #ifdef UNIV_DEBUG page_zip->m_start = PAGE_DATA + d_stream->total_in; #endif /* UNIV_DEBUG */ /* Apply the modification log. */ { const byte* mod_log_ptr; mod_log_ptr = page_zip_apply_log(d_stream->next_in, d_stream->avail_in + 1, recs, n_dense, trx_id_col, heap_status, index, offsets); if (UNIV_UNLIKELY(!mod_log_ptr)) { return(FALSE); } page_zip->m_end = mod_log_ptr - page_zip->data; page_zip->m_nonempty = mod_log_ptr != d_stream->next_in; } if (UNIV_UNLIKELY(page_zip_get_trailer_len(page_zip, TRUE) + page_zip->m_end >= page_zip_get_size(page_zip))) { page_zip_fail(("page_zip_decompress_clust: %lu + %lu >= %lu\n", (ulong) page_zip_get_trailer_len( page_zip, TRUE), (ulong) page_zip->m_end, (ulong) page_zip_get_size(page_zip))); return(FALSE); } storage = page_zip_dir_start_low(page_zip, n_dense); externs = storage - n_dense * (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); /* Restore the uncompressed columns in heap_no order. */ for (slot = 0; slot < n_dense; slot++) { ulint i; ulint len; byte* dst; rec_t* rec = recs[slot]; ibool exists = !page_zip_dir_find_free( page_zip, page_offset(rec)); offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); dst = rec_get_nth_field(rec, offsets, trx_id_col, &len); ut_ad(len >= DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); storage -= DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN; memcpy(dst, storage, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); /* Check if there are any externally stored columns in this record. For each externally stored column, restore or clear the BTR_EXTERN_FIELD_REF. */ if (!rec_offs_any_extern(offsets)) { continue; } for (i = 0; i < rec_offs_n_fields(offsets); i++) { if (!rec_offs_nth_extern(offsets, i)) { continue; } dst = rec_get_nth_field(rec, offsets, i, &len); if (UNIV_UNLIKELY(len < BTR_EXTERN_FIELD_REF_SIZE)) { page_zip_fail(("page_zip_decompress_clust:" " %lu < 20\n", (ulong) len)); return(FALSE); } dst += len - BTR_EXTERN_FIELD_REF_SIZE; if (UNIV_LIKELY(exists)) { /* Existing record: restore the BLOB pointer */ externs -= BTR_EXTERN_FIELD_REF_SIZE; if (UNIV_UNLIKELY (externs < page_zip->data + page_zip->m_end)) { page_zip_fail(("page_zip_" "decompress_clust: " "%p < %p + %lu\n", (const void*) externs, (const void*) page_zip->data, (ulong) page_zip->m_end)); return(FALSE); } memcpy(dst, externs, BTR_EXTERN_FIELD_REF_SIZE); page_zip->n_blobs++; } else { /* Deleted record: clear the BLOB pointer */ memset(dst, 0, BTR_EXTERN_FIELD_REF_SIZE); } } } return(TRUE); } /**********************************************************************//** This function determines the sign for window_bits and reads the zlib header from the decompress stream. The data may have been compressed with a negative (no adler32 headers) or a positive (with adler32 headers) window_bits. Regardless of the current value of page_zip_zlib_wrap, we always first try the positive window_bits then negative window_bits, because the surest way to determine if the stream has adler32 headers is to see if the stream begins with the zlib header together with the adler32 value of it. This adds a tiny bit of overhead for the pages that were compressed without adler32s. @return TRUE if stream is initialized and zlib header was read, FALSE if data can be decompressed with neither window_bits nor -window_bits */ UNIV_INTERN ibool page_zip_init_d_stream( z_stream* strm, int window_bits, ibool read_zlib_header) { /* Save initial stream position, in case a reset is required. */ Bytef* next_in = strm->next_in; Bytef* next_out = strm->next_out; ulint avail_in = strm->avail_in; ulint avail_out = strm->avail_out; if (UNIV_UNLIKELY(inflateInit2(strm, window_bits) != Z_OK)) { /* init must always succeed regardless of window_bits */ ut_error; } /* Try decoding a zlib header assuming adler32. */ if (inflate(strm, Z_BLOCK) == Z_OK) /* A valid header was found, all is well. So, we return with the stream positioned just after this header. */ return(TRUE); /* A valid header was not found, so now we need to re-try this read assuming there is *no* header (negative window_bits). So, we need to reset the stream to the original position, and change the window_bits to negative, with inflateReset2(). */ strm->next_in = next_in; strm->next_out = next_out; strm->avail_in = avail_in; strm->avail_out = avail_out; if (UNIV_UNLIKELY(inflateReset2(strm, -window_bits) != Z_OK)) { /* init must always succeed regardless of window_bits */ ut_error; } if (read_zlib_header) { /* No valid header was found, and we still want the header read to have happened, with negative window_bits. */ return(inflate(strm, Z_BLOCK) == Z_OK); } /* Did not find a header, but didn't require one, so just return with the stream position reset to where it originally was. */ return(TRUE); } /**********************************************************************//** Decompress a page. This function should tolerate errors on the compressed page. Instead of letting assertions fail, it will return FALSE if an inconsistency is detected. @return TRUE on success, FALSE on failure */ UNIV_INTERN ibool page_zip_decompress( /*================*/ page_zip_des_t* page_zip,/*!< in: data, ssize; out: m_start, m_end, m_nonempty, n_blobs */ page_t* page, /*!< out: uncompressed page, may be trashed */ ibool all) /*!< in: TRUE=decompress the whole page; FALSE=verify but do not copy some page header fields that should not change after page creation */ { z_stream d_stream; dict_index_t* index = NULL; rec_t** recs; /*!< dense page directory, sorted by address */ ulint n_dense;/* number of user records on the page */ ulint trx_id_col = ULINT_UNDEFINED; mem_heap_t* heap; ulint* offsets; #ifndef UNIV_HOTBACKUP ullint usec = ut_time_us(NULL); #endif /* !UNIV_HOTBACKUP */ ut_ad(page_zip_simple_validate(page_zip)); UNIV_MEM_ASSERT_W(page, UNIV_PAGE_SIZE); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); /* The dense directory excludes the infimum and supremum records. */ n_dense = page_dir_get_n_heap(page_zip->data) - PAGE_HEAP_NO_USER_LOW; if (UNIV_UNLIKELY(n_dense * PAGE_ZIP_DIR_SLOT_SIZE >= page_zip_get_size(page_zip))) { page_zip_fail(("page_zip_decompress 1: %lu %lu\n", (ulong) n_dense, (ulong) page_zip_get_size(page_zip))); return(FALSE); } heap = mem_heap_create(n_dense * (3 * sizeof *recs) + UNIV_PAGE_SIZE); recs = static_cast<rec_t**>( mem_heap_alloc(heap, n_dense * (2 * sizeof *recs))); if (all) { /* Copy the page header. */ memcpy(page, page_zip->data, PAGE_DATA); } else { /* Check that the bytes that we skip are identical. */ #if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG ut_a(!memcmp(FIL_PAGE_TYPE + page, FIL_PAGE_TYPE + page_zip->data, PAGE_HEADER - FIL_PAGE_TYPE)); ut_a(!memcmp(PAGE_HEADER + PAGE_LEVEL + page, PAGE_HEADER + PAGE_LEVEL + page_zip->data, PAGE_DATA - (PAGE_HEADER + PAGE_LEVEL))); #endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */ /* Copy the mutable parts of the page header. */ memcpy(page, page_zip->data, FIL_PAGE_TYPE); memcpy(PAGE_HEADER + page, PAGE_HEADER + page_zip->data, PAGE_LEVEL - PAGE_N_DIR_SLOTS); #if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG /* Check that the page headers match after copying. */ ut_a(!memcmp(page, page_zip->data, PAGE_DATA)); #endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */ } #ifdef UNIV_ZIP_DEBUG /* Clear the uncompressed page, except the header. */ memset(PAGE_DATA + page, 0x55, UNIV_PAGE_SIZE - PAGE_DATA); #endif /* UNIV_ZIP_DEBUG */ UNIV_MEM_INVALID(PAGE_DATA + page, UNIV_PAGE_SIZE - PAGE_DATA); /* Copy the page directory. */ if (UNIV_UNLIKELY(!page_zip_dir_decode(page_zip, page, recs, recs + n_dense, n_dense))) { zlib_error: mem_heap_free(heap); return(FALSE); } /* Copy the infimum and supremum records. */ memcpy(page + (PAGE_NEW_INFIMUM - REC_N_NEW_EXTRA_BYTES), infimum_extra, sizeof infimum_extra); if (page_is_empty(page)) { rec_set_next_offs_new(page + PAGE_NEW_INFIMUM, PAGE_NEW_SUPREMUM); } else { rec_set_next_offs_new(page + PAGE_NEW_INFIMUM, page_zip_dir_get(page_zip, 0) & PAGE_ZIP_DIR_SLOT_MASK); } memcpy(page + PAGE_NEW_INFIMUM, infimum_data, sizeof infimum_data); memcpy(page + (PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES + 1), supremum_extra_data, sizeof supremum_extra_data); page_zip_set_alloc(&d_stream, heap); d_stream.next_in = page_zip->data + PAGE_DATA; /* Subtract the space reserved for the page header and the end marker of the modification log. */ d_stream.avail_in = static_cast<uInt>( page_zip_get_size(page_zip) - (PAGE_DATA + 1)); d_stream.next_out = page + PAGE_ZIP_START; d_stream.avail_out = UNIV_PAGE_SIZE - PAGE_ZIP_START; if (!page_zip_init_d_stream(&d_stream, UNIV_PAGE_SIZE_SHIFT, TRUE)) { page_zip_fail(("page_zip_decompress:" " 1 inflate(Z_BLOCK)=%s\n", d_stream.msg)); goto zlib_error; } if (UNIV_UNLIKELY(inflate(&d_stream, Z_BLOCK) != Z_OK)) { page_zip_fail(("page_zip_decompress:" " 2 inflate(Z_BLOCK)=%s\n", d_stream.msg)); goto zlib_error; } index = page_zip_fields_decode( page + PAGE_ZIP_START, d_stream.next_out, page_is_leaf(page) ? &trx_id_col : NULL); if (UNIV_UNLIKELY(!index)) { goto zlib_error; } /* Decompress the user records. */ page_zip->n_blobs = 0; d_stream.next_out = page + PAGE_ZIP_START; { /* Pre-allocate the offsets for rec_get_offsets_reverse(). */ ulint n = 1 + 1/* node ptr */ + REC_OFFS_HEADER_SIZE + dict_index_get_n_fields(index); offsets = static_cast<ulint*>( mem_heap_alloc(heap, n * sizeof(ulint))); *offsets = n; } /* Decompress the records in heap_no order. */ if (!page_is_leaf(page)) { /* This is a node pointer page. */ ulint info_bits; if (UNIV_UNLIKELY (!page_zip_decompress_node_ptrs(page_zip, &d_stream, recs, n_dense, index, offsets, heap))) { goto err_exit; } info_bits = mach_read_from_4(page + FIL_PAGE_PREV) == FIL_NULL ? REC_INFO_MIN_REC_FLAG : 0; if (UNIV_UNLIKELY(!page_zip_set_extra_bytes(page_zip, page, info_bits))) { goto err_exit; } } else if (UNIV_LIKELY(trx_id_col == ULINT_UNDEFINED)) { /* This is a leaf page in a secondary index. */ if (UNIV_UNLIKELY(!page_zip_decompress_sec(page_zip, &d_stream, recs, n_dense, index, offsets))) { goto err_exit; } if (UNIV_UNLIKELY(!page_zip_set_extra_bytes(page_zip, page, 0))) { err_exit: page_zip_fields_free(index); mem_heap_free(heap); return(FALSE); } } else { /* This is a leaf page in a clustered index. */ if (UNIV_UNLIKELY(!page_zip_decompress_clust(page_zip, &d_stream, recs, n_dense, index, trx_id_col, offsets, heap))) { goto err_exit; } if (UNIV_UNLIKELY(!page_zip_set_extra_bytes(page_zip, page, 0))) { goto err_exit; } } ut_a(page_is_comp(page)); UNIV_MEM_ASSERT_RW(page, UNIV_PAGE_SIZE); page_zip_fields_free(index); mem_heap_free(heap); #ifndef UNIV_HOTBACKUP ullint time_diff = ut_time_us(NULL) - usec; page_zip_stat[page_zip->ssize - 1].decompressed++; page_zip_stat[page_zip->ssize - 1].decompressed_usec += time_diff; index_id_t index_id = btr_page_get_index_id(page); if (srv_cmp_per_index_enabled) { mutex_enter(&page_zip_stat_per_index_mutex); page_zip_stat_per_index[index_id].decompressed++; page_zip_stat_per_index[index_id].decompressed_usec += time_diff; mutex_exit(&page_zip_stat_per_index_mutex); } #endif /* !UNIV_HOTBACKUP */ /* Update the stat counter for LRU policy. */ buf_LRU_stat_inc_unzip(); MONITOR_INC(MONITOR_PAGE_DECOMPRESS); return(TRUE); } #ifdef UNIV_ZIP_DEBUG /**********************************************************************//** Dump a block of memory on the standard error stream. */ static void page_zip_hexdump_func( /*==================*/ const char* name, /*!< in: name of the data structure */ const void* buf, /*!< in: data */ ulint size) /*!< in: length of the data, in bytes */ { const byte* s = static_cast<const byte*>(buf); ulint addr; const ulint width = 32; /* bytes per line */ fprintf(stderr, "%s:\n", name); for (addr = 0; addr < size; addr += width) { ulint i; fprintf(stderr, "%04lx ", (ulong) addr); i = ut_min(width, size - addr); while (i--) { fprintf(stderr, "%02x", *s++); } putc('\n', stderr); } } /** Dump a block of memory on the standard error stream. @param buf in: data @param size in: length of the data, in bytes */ #define page_zip_hexdump(buf, size) page_zip_hexdump_func(#buf, buf, size) /** Flag: make page_zip_validate() compare page headers only */ UNIV_INTERN ibool page_zip_validate_header_only = FALSE; /**********************************************************************//** Check that the compressed and decompressed pages match. @return TRUE if valid, FALSE if not */ UNIV_INTERN ibool page_zip_validate_low( /*==================*/ const page_zip_des_t* page_zip,/*!< in: compressed page */ const page_t* page, /*!< in: uncompressed page */ const dict_index_t* index, /*!< in: index of the page, if known */ ibool sloppy) /*!< in: FALSE=strict, TRUE=ignore the MIN_REC_FLAG */ { page_zip_des_t temp_page_zip; byte* temp_page_buf; page_t* temp_page; ibool valid; if (memcmp(page_zip->data + FIL_PAGE_PREV, page + FIL_PAGE_PREV, FIL_PAGE_LSN - FIL_PAGE_PREV) || memcmp(page_zip->data + FIL_PAGE_TYPE, page + FIL_PAGE_TYPE, 2) || memcmp(page_zip->data + FIL_PAGE_DATA, page + FIL_PAGE_DATA, PAGE_DATA - FIL_PAGE_DATA)) { page_zip_fail(("page_zip_validate: page header\n")); page_zip_hexdump(page_zip, sizeof *page_zip); page_zip_hexdump(page_zip->data, page_zip_get_size(page_zip)); page_zip_hexdump(page, UNIV_PAGE_SIZE); return(FALSE); } ut_a(page_is_comp(page)); if (page_zip_validate_header_only) { return(TRUE); } /* page_zip_decompress() expects the uncompressed page to be UNIV_PAGE_SIZE aligned. */ temp_page_buf = static_cast<byte*>(ut_malloc(2 * UNIV_PAGE_SIZE)); temp_page = static_cast<byte*>(ut_align(temp_page_buf, UNIV_PAGE_SIZE)); UNIV_MEM_ASSERT_RW(page, UNIV_PAGE_SIZE); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); temp_page_zip = *page_zip; valid = page_zip_decompress(&temp_page_zip, temp_page, TRUE); if (!valid) { fputs("page_zip_validate(): failed to decompress\n", stderr); goto func_exit; } if (page_zip->n_blobs != temp_page_zip.n_blobs) { page_zip_fail(("page_zip_validate: n_blobs: %u!=%u\n", page_zip->n_blobs, temp_page_zip.n_blobs)); valid = FALSE; } #ifdef UNIV_DEBUG if (page_zip->m_start != temp_page_zip.m_start) { page_zip_fail(("page_zip_validate: m_start: %u!=%u\n", page_zip->m_start, temp_page_zip.m_start)); valid = FALSE; } #endif /* UNIV_DEBUG */ if (page_zip->m_end != temp_page_zip.m_end) { page_zip_fail(("page_zip_validate: m_end: %u!=%u\n", page_zip->m_end, temp_page_zip.m_end)); valid = FALSE; } if (page_zip->m_nonempty != temp_page_zip.m_nonempty) { page_zip_fail(("page_zip_validate(): m_nonempty: %u!=%u\n", page_zip->m_nonempty, temp_page_zip.m_nonempty)); valid = FALSE; } if (memcmp(page + PAGE_HEADER, temp_page + PAGE_HEADER, UNIV_PAGE_SIZE - PAGE_HEADER - FIL_PAGE_DATA_END)) { /* In crash recovery, the "minimum record" flag may be set incorrectly until the mini-transaction is committed. Let us tolerate that difference when we are performing a sloppy validation. */ ulint* offsets; mem_heap_t* heap; const rec_t* rec; const rec_t* trec; byte info_bits_diff; ulint offset = rec_get_next_offs(page + PAGE_NEW_INFIMUM, TRUE); ut_a(offset >= PAGE_NEW_SUPREMUM); offset -= 5/*REC_NEW_INFO_BITS*/; info_bits_diff = page[offset] ^ temp_page[offset]; if (info_bits_diff == REC_INFO_MIN_REC_FLAG) { temp_page[offset] = page[offset]; if (!memcmp(page + PAGE_HEADER, temp_page + PAGE_HEADER, UNIV_PAGE_SIZE - PAGE_HEADER - FIL_PAGE_DATA_END)) { /* Only the minimum record flag differed. Let us ignore it. */ page_zip_fail(("page_zip_validate: " "min_rec_flag " "(%s" "%lu,%lu,0x%02lx)\n", sloppy ? "ignored, " : "", page_get_space_id(page), page_get_page_no(page), (ulong) page[offset])); valid = sloppy; goto func_exit; } } /* Compare the pointers in the PAGE_FREE list. */ rec = page_header_get_ptr(page, PAGE_FREE); trec = page_header_get_ptr(temp_page, PAGE_FREE); while (rec || trec) { if (page_offset(rec) != page_offset(trec)) { page_zip_fail(("page_zip_validate: " "PAGE_FREE list: %u!=%u\n", (unsigned) page_offset(rec), (unsigned) page_offset(trec))); valid = FALSE; goto func_exit; } rec = page_rec_get_next_low(rec, TRUE); trec = page_rec_get_next_low(trec, TRUE); } /* Compare the records. */ heap = NULL; offsets = NULL; rec = page_rec_get_next_low( page + PAGE_NEW_INFIMUM, TRUE); trec = page_rec_get_next_low( temp_page + PAGE_NEW_INFIMUM, TRUE); do { if (page_offset(rec) != page_offset(trec)) { page_zip_fail(("page_zip_validate: " "record list: 0x%02x!=0x%02x\n", (unsigned) page_offset(rec), (unsigned) page_offset(trec))); valid = FALSE; break; } if (index) { /* Compare the data. */ offsets = rec_get_offsets( rec, index, offsets, ULINT_UNDEFINED, &heap); if (memcmp(rec - rec_offs_extra_size(offsets), trec - rec_offs_extra_size(offsets), rec_offs_size(offsets))) { page_zip_fail( ("page_zip_validate: " "record content: 0x%02x", (unsigned) page_offset(rec))); valid = FALSE; break; } } rec = page_rec_get_next_low(rec, TRUE); trec = page_rec_get_next_low(trec, TRUE); } while (rec || trec); if (heap) { mem_heap_free(heap); } } func_exit: if (!valid) { page_zip_hexdump(page_zip, sizeof *page_zip); page_zip_hexdump(page_zip->data, page_zip_get_size(page_zip)); page_zip_hexdump(page, UNIV_PAGE_SIZE); page_zip_hexdump(temp_page, UNIV_PAGE_SIZE); } ut_free(temp_page_buf); return(valid); } /**********************************************************************//** Check that the compressed and decompressed pages match. @return TRUE if valid, FALSE if not */ UNIV_INTERN ibool page_zip_validate( /*==============*/ const page_zip_des_t* page_zip,/*!< in: compressed page */ const page_t* page, /*!< in: uncompressed page */ const dict_index_t* index) /*!< in: index of the page, if known */ { return(page_zip_validate_low(page_zip, page, index, recv_recovery_is_on())); } #endif /* UNIV_ZIP_DEBUG */ #ifdef UNIV_DEBUG /**********************************************************************//** Assert that the compressed and decompressed page headers match. @return TRUE */ static ibool page_zip_header_cmp( /*================*/ const page_zip_des_t* page_zip,/*!< in: compressed page */ const byte* page) /*!< in: uncompressed page */ { ut_ad(!memcmp(page_zip->data + FIL_PAGE_PREV, page + FIL_PAGE_PREV, FIL_PAGE_LSN - FIL_PAGE_PREV)); ut_ad(!memcmp(page_zip->data + FIL_PAGE_TYPE, page + FIL_PAGE_TYPE, 2)); ut_ad(!memcmp(page_zip->data + FIL_PAGE_DATA, page + FIL_PAGE_DATA, PAGE_DATA - FIL_PAGE_DATA)); return(TRUE); } #endif /* UNIV_DEBUG */ /**********************************************************************//** Write a record on the compressed page that contains externally stored columns. The data must already have been written to the uncompressed page. @return end of modification log */ static byte* page_zip_write_rec_ext( /*===================*/ page_zip_des_t* page_zip, /*!< in/out: compressed page */ const page_t* page, /*!< in: page containing rec */ const byte* rec, /*!< in: record being written */ dict_index_t* index, /*!< in: record descriptor */ const ulint* offsets, /*!< in: rec_get_offsets(rec, index) */ ulint create, /*!< in: nonzero=insert, zero=update */ ulint trx_id_col, /*!< in: position of DB_TRX_ID */ ulint heap_no, /*!< in: heap number of rec */ byte* storage, /*!< in: end of dense page directory */ byte* data) /*!< in: end of modification log */ { const byte* start = rec; ulint i; ulint len; byte* externs = storage; ulint n_ext = rec_offs_n_extern(offsets); ut_ad(rec_offs_validate(rec, index, offsets)); UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets)); UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets), rec_offs_extra_size(offsets)); externs -= (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN) * (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW); /* Note that this will not take into account the BLOB columns of rec if create==TRUE. */ ut_ad(data + rec_offs_data_size(offsets) - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN) - n_ext * BTR_EXTERN_FIELD_REF_SIZE < externs - BTR_EXTERN_FIELD_REF_SIZE * page_zip->n_blobs); { ulint blob_no = page_zip_get_n_prev_extern( page_zip, rec, index); byte* ext_end = externs - page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE; ut_ad(blob_no <= page_zip->n_blobs); externs -= blob_no * BTR_EXTERN_FIELD_REF_SIZE; if (create) { page_zip->n_blobs += static_cast<unsigned>(n_ext); ASSERT_ZERO_BLOB(ext_end - n_ext * BTR_EXTERN_FIELD_REF_SIZE); memmove(ext_end - n_ext * BTR_EXTERN_FIELD_REF_SIZE, ext_end, externs - ext_end); } ut_a(blob_no + n_ext <= page_zip->n_blobs); } for (i = 0; i < rec_offs_n_fields(offsets); i++) { const byte* src; if (UNIV_UNLIKELY(i == trx_id_col)) { ut_ad(!rec_offs_nth_extern(offsets, i)); ut_ad(!rec_offs_nth_extern(offsets, i + 1)); /* Locate trx_id and roll_ptr. */ src = rec_get_nth_field(rec, offsets, i, &len); ut_ad(len == DATA_TRX_ID_LEN); ut_ad(src + DATA_TRX_ID_LEN == rec_get_nth_field( rec, offsets, i + 1, &len)); ut_ad(len == DATA_ROLL_PTR_LEN); /* Log the preceding fields. */ ASSERT_ZERO(data, src - start); memcpy(data, start, src - start); data += src - start; start = src + (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); /* Store trx_id and roll_ptr. */ memcpy(storage - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN) * (heap_no - 1), src, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); i++; /* skip also roll_ptr */ } else if (rec_offs_nth_extern(offsets, i)) { src = rec_get_nth_field(rec, offsets, i, &len); ut_ad(dict_index_is_clust(index)); ut_ad(len >= BTR_EXTERN_FIELD_REF_SIZE); src += len - BTR_EXTERN_FIELD_REF_SIZE; ASSERT_ZERO(data, src - start); memcpy(data, start, src - start); data += src - start; start = src + BTR_EXTERN_FIELD_REF_SIZE; /* Store the BLOB pointer. */ externs -= BTR_EXTERN_FIELD_REF_SIZE; ut_ad(data < externs); memcpy(externs, src, BTR_EXTERN_FIELD_REF_SIZE); } } /* Log the last bytes of the record. */ len = rec_offs_data_size(offsets) - (start - rec); ASSERT_ZERO(data, len); memcpy(data, start, len); data += len; return(data); } /**********************************************************************//** Write an entire record on the compressed page. The data must already have been written to the uncompressed page. */ UNIV_INTERN void page_zip_write_rec( /*===============*/ page_zip_des_t* page_zip,/*!< in/out: compressed page */ const byte* rec, /*!< in: record being written */ dict_index_t* index, /*!< in: the index the record belongs to */ const ulint* offsets,/*!< in: rec_get_offsets(rec, index) */ ulint create) /*!< in: nonzero=insert, zero=update */ { const page_t* page; byte* data; byte* storage; ulint heap_no; byte* slot; ut_ad(PAGE_ZIP_MATCH(rec, page_zip)); ut_ad(page_zip_simple_validate(page_zip)); ut_ad(page_zip_get_size(page_zip) > PAGE_DATA + page_zip_dir_size(page_zip)); ut_ad(rec_offs_comp(offsets)); ut_ad(rec_offs_validate(rec, index, offsets)); ut_ad(page_zip->m_start >= PAGE_DATA); page = page_align(rec); ut_ad(page_zip_header_cmp(page_zip, page)); ut_ad(page_simple_validate_new((page_t*) page)); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets)); UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets), rec_offs_extra_size(offsets)); slot = page_zip_dir_find(page_zip, page_offset(rec)); ut_a(slot); /* Copy the delete mark. */ if (rec_get_deleted_flag(rec, TRUE)) { *slot |= PAGE_ZIP_DIR_SLOT_DEL >> 8; } else { *slot &= ~(PAGE_ZIP_DIR_SLOT_DEL >> 8); } ut_ad(rec_get_start((rec_t*) rec, offsets) >= page + PAGE_ZIP_START); ut_ad(rec_get_end((rec_t*) rec, offsets) <= page + UNIV_PAGE_SIZE - PAGE_DIR - PAGE_DIR_SLOT_SIZE * page_dir_get_n_slots(page)); heap_no = rec_get_heap_no_new(rec); ut_ad(heap_no >= PAGE_HEAP_NO_USER_LOW); /* not infimum or supremum */ ut_ad(heap_no < page_dir_get_n_heap(page)); /* Append to the modification log. */ data = page_zip->data + page_zip->m_end; ut_ad(!*data); /* Identify the record by writing its heap number - 1. 0 is reserved to indicate the end of the modification log. */ if (UNIV_UNLIKELY(heap_no - 1 >= 64)) { *data++ = (byte) (0x80 | (heap_no - 1) >> 7); ut_ad(!*data); } *data++ = (byte) ((heap_no - 1) << 1); ut_ad(!*data); { const byte* start = rec - rec_offs_extra_size(offsets); const byte* b = rec - REC_N_NEW_EXTRA_BYTES; /* Write the extra bytes backwards, so that rec_offs_extra_size() can be easily computed in page_zip_apply_log() by invoking rec_get_offsets_reverse(). */ while (b != start) { *data++ = *--b; ut_ad(!*data); } } /* Write the data bytes. Store the uncompressed bytes separately. */ storage = page_zip_dir_start(page_zip); if (page_is_leaf(page)) { ulint len; if (dict_index_is_clust(index)) { ulint trx_id_col; trx_id_col = dict_index_get_sys_col_pos(index, DATA_TRX_ID); ut_ad(trx_id_col != ULINT_UNDEFINED); /* Store separately trx_id, roll_ptr and the BTR_EXTERN_FIELD_REF of each BLOB column. */ if (rec_offs_any_extern(offsets)) { data = page_zip_write_rec_ext( page_zip, page, rec, index, offsets, create, trx_id_col, heap_no, storage, data); } else { /* Locate trx_id and roll_ptr. */ const byte* src = rec_get_nth_field(rec, offsets, trx_id_col, &len); ut_ad(len == DATA_TRX_ID_LEN); ut_ad(src + DATA_TRX_ID_LEN == rec_get_nth_field( rec, offsets, trx_id_col + 1, &len)); ut_ad(len == DATA_ROLL_PTR_LEN); /* Log the preceding fields. */ ASSERT_ZERO(data, src - rec); memcpy(data, rec, src - rec); data += src - rec; /* Store trx_id and roll_ptr. */ memcpy(storage - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN) * (heap_no - 1), src, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); src += DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN; /* Log the last bytes of the record. */ len = rec_offs_data_size(offsets) - (src - rec); ASSERT_ZERO(data, len); memcpy(data, src, len); data += len; } } else { /* Leaf page of a secondary index: no externally stored columns */ ut_ad(dict_index_get_sys_col_pos(index, DATA_TRX_ID) == ULINT_UNDEFINED); ut_ad(!rec_offs_any_extern(offsets)); /* Log the entire record. */ len = rec_offs_data_size(offsets); ASSERT_ZERO(data, len); memcpy(data, rec, len); data += len; } } else { /* This is a node pointer page. */ ulint len; /* Non-leaf nodes should not have any externally stored columns. */ ut_ad(!rec_offs_any_extern(offsets)); /* Copy the data bytes, except node_ptr. */ len = rec_offs_data_size(offsets) - REC_NODE_PTR_SIZE; ut_ad(data + len < storage - REC_NODE_PTR_SIZE * (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW)); ASSERT_ZERO(data, len); memcpy(data, rec, len); data += len; /* Copy the node pointer to the uncompressed area. */ memcpy(storage - REC_NODE_PTR_SIZE * (heap_no - 1), rec + len, REC_NODE_PTR_SIZE); } ut_a(!*data); ut_ad((ulint) (data - page_zip->data) < page_zip_get_size(page_zip)); page_zip->m_end = data - page_zip->data; page_zip->m_nonempty = TRUE; #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page_align(rec), index)); #endif /* UNIV_ZIP_DEBUG */ } /***********************************************************//** Parses a log record of writing a BLOB pointer of a record. @return end of log record or NULL */ UNIV_INTERN byte* page_zip_parse_write_blob_ptr( /*==========================*/ byte* ptr, /*!< in: redo log buffer */ byte* end_ptr,/*!< in: redo log buffer end */ page_t* page, /*!< in/out: uncompressed page */ page_zip_des_t* page_zip)/*!< in/out: compressed page */ { ulint offset; ulint z_offset; ut_ad(!page == !page_zip); if (UNIV_UNLIKELY (end_ptr < ptr + (2 + 2 + BTR_EXTERN_FIELD_REF_SIZE))) { return(NULL); } offset = mach_read_from_2(ptr); z_offset = mach_read_from_2(ptr + 2); if (UNIV_UNLIKELY(offset < PAGE_ZIP_START) || UNIV_UNLIKELY(offset >= UNIV_PAGE_SIZE) || UNIV_UNLIKELY(z_offset >= UNIV_PAGE_SIZE)) { corrupt: recv_sys->found_corrupt_log = TRUE; return(NULL); } if (page) { if (UNIV_UNLIKELY(!page_zip) || UNIV_UNLIKELY(!page_is_leaf(page))) { goto corrupt; } #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page, NULL)); #endif /* UNIV_ZIP_DEBUG */ memcpy(page + offset, ptr + 4, BTR_EXTERN_FIELD_REF_SIZE); memcpy(page_zip->data + z_offset, ptr + 4, BTR_EXTERN_FIELD_REF_SIZE); #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page, NULL)); #endif /* UNIV_ZIP_DEBUG */ } return(ptr + (2 + 2 + BTR_EXTERN_FIELD_REF_SIZE)); } /**********************************************************************//** Write a BLOB pointer of a record on the leaf page of a clustered index. The information must already have been updated on the uncompressed page. */ UNIV_INTERN void page_zip_write_blob_ptr( /*====================*/ page_zip_des_t* page_zip,/*!< in/out: compressed page */ const byte* rec, /*!< in/out: record whose data is being written */ dict_index_t* index, /*!< in: index of the page */ const ulint* offsets,/*!< in: rec_get_offsets(rec, index) */ ulint n, /*!< in: column index */ mtr_t* mtr) /*!< in: mini-transaction handle, or NULL if no logging is needed */ { const byte* field; byte* externs; const page_t* page = page_align(rec); ulint blob_no; ulint len; ut_ad(PAGE_ZIP_MATCH(rec, page_zip)); ut_ad(page_simple_validate_new((page_t*) page)); ut_ad(page_zip_simple_validate(page_zip)); ut_ad(page_zip_get_size(page_zip) > PAGE_DATA + page_zip_dir_size(page_zip)); ut_ad(rec_offs_comp(offsets)); ut_ad(rec_offs_validate(rec, NULL, offsets)); ut_ad(rec_offs_any_extern(offsets)); ut_ad(rec_offs_nth_extern(offsets, n)); ut_ad(page_zip->m_start >= PAGE_DATA); ut_ad(page_zip_header_cmp(page_zip, page)); ut_ad(page_is_leaf(page)); ut_ad(dict_index_is_clust(index)); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets)); UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets), rec_offs_extra_size(offsets)); blob_no = page_zip_get_n_prev_extern(page_zip, rec, index) + rec_get_n_extern_new(rec, index, n); ut_a(blob_no < page_zip->n_blobs); externs = page_zip->data + page_zip_get_size(page_zip) - (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW) * (PAGE_ZIP_DIR_SLOT_SIZE + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); field = rec_get_nth_field(rec, offsets, n, &len); externs -= (blob_no + 1) * BTR_EXTERN_FIELD_REF_SIZE; field += len - BTR_EXTERN_FIELD_REF_SIZE; memcpy(externs, field, BTR_EXTERN_FIELD_REF_SIZE); #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ if (mtr) { #ifndef UNIV_HOTBACKUP byte* log_ptr = mlog_open( mtr, 11 + 2 + 2 + BTR_EXTERN_FIELD_REF_SIZE); if (UNIV_UNLIKELY(!log_ptr)) { return; } log_ptr = mlog_write_initial_log_record_fast( (byte*) field, MLOG_ZIP_WRITE_BLOB_PTR, log_ptr, mtr); mach_write_to_2(log_ptr, page_offset(field)); log_ptr += 2; mach_write_to_2(log_ptr, externs - page_zip->data); log_ptr += 2; memcpy(log_ptr, externs, BTR_EXTERN_FIELD_REF_SIZE); log_ptr += BTR_EXTERN_FIELD_REF_SIZE; mlog_close(mtr, log_ptr); #endif /* !UNIV_HOTBACKUP */ } } /***********************************************************//** Parses a log record of writing the node pointer of a record. @return end of log record or NULL */ UNIV_INTERN byte* page_zip_parse_write_node_ptr( /*==========================*/ byte* ptr, /*!< in: redo log buffer */ byte* end_ptr,/*!< in: redo log buffer end */ page_t* page, /*!< in/out: uncompressed page */ page_zip_des_t* page_zip)/*!< in/out: compressed page */ { ulint offset; ulint z_offset; ut_ad(!page == !page_zip); if (UNIV_UNLIKELY(end_ptr < ptr + (2 + 2 + REC_NODE_PTR_SIZE))) { return(NULL); } offset = mach_read_from_2(ptr); z_offset = mach_read_from_2(ptr + 2); if (UNIV_UNLIKELY(offset < PAGE_ZIP_START) || UNIV_UNLIKELY(offset >= UNIV_PAGE_SIZE) || UNIV_UNLIKELY(z_offset >= UNIV_PAGE_SIZE)) { corrupt: recv_sys->found_corrupt_log = TRUE; return(NULL); } if (page) { byte* storage_end; byte* field; byte* storage; ulint heap_no; if (UNIV_UNLIKELY(!page_zip) || UNIV_UNLIKELY(page_is_leaf(page))) { goto corrupt; } #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page, NULL)); #endif /* UNIV_ZIP_DEBUG */ field = page + offset; storage = page_zip->data + z_offset; storage_end = page_zip_dir_start(page_zip); heap_no = 1 + (storage_end - storage) / REC_NODE_PTR_SIZE; if (UNIV_UNLIKELY((storage_end - storage) % REC_NODE_PTR_SIZE) || UNIV_UNLIKELY(heap_no < PAGE_HEAP_NO_USER_LOW) || UNIV_UNLIKELY(heap_no >= page_dir_get_n_heap(page))) { goto corrupt; } memcpy(field, ptr + 4, REC_NODE_PTR_SIZE); memcpy(storage, ptr + 4, REC_NODE_PTR_SIZE); #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page, NULL)); #endif /* UNIV_ZIP_DEBUG */ } return(ptr + (2 + 2 + REC_NODE_PTR_SIZE)); } /**********************************************************************//** Write the node pointer of a record on a non-leaf compressed page. */ UNIV_INTERN void page_zip_write_node_ptr( /*====================*/ page_zip_des_t* page_zip,/*!< in/out: compressed page */ byte* rec, /*!< in/out: record */ ulint size, /*!< in: data size of rec */ ulint ptr, /*!< in: node pointer */ mtr_t* mtr) /*!< in: mini-transaction, or NULL */ { byte* field; byte* storage; #ifdef UNIV_DEBUG page_t* page = page_align(rec); #endif /* UNIV_DEBUG */ ut_ad(PAGE_ZIP_MATCH(rec, page_zip)); ut_ad(page_simple_validate_new(page)); ut_ad(page_zip_simple_validate(page_zip)); ut_ad(page_zip_get_size(page_zip) > PAGE_DATA + page_zip_dir_size(page_zip)); ut_ad(page_rec_is_comp(rec)); ut_ad(page_zip->m_start >= PAGE_DATA); ut_ad(page_zip_header_cmp(page_zip, page)); ut_ad(!page_is_leaf(page)); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); UNIV_MEM_ASSERT_RW(rec, size); storage = page_zip_dir_start(page_zip) - (rec_get_heap_no_new(rec) - 1) * REC_NODE_PTR_SIZE; field = rec + size - REC_NODE_PTR_SIZE; #if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG ut_a(!memcmp(storage, field, REC_NODE_PTR_SIZE)); #endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */ #if REC_NODE_PTR_SIZE != 4 # error "REC_NODE_PTR_SIZE != 4" #endif mach_write_to_4(field, ptr); memcpy(storage, field, REC_NODE_PTR_SIZE); if (mtr) { #ifndef UNIV_HOTBACKUP byte* log_ptr = mlog_open(mtr, 11 + 2 + 2 + REC_NODE_PTR_SIZE); if (UNIV_UNLIKELY(!log_ptr)) { return; } log_ptr = mlog_write_initial_log_record_fast( field, MLOG_ZIP_WRITE_NODE_PTR, log_ptr, mtr); mach_write_to_2(log_ptr, page_offset(field)); log_ptr += 2; mach_write_to_2(log_ptr, storage - page_zip->data); log_ptr += 2; memcpy(log_ptr, field, REC_NODE_PTR_SIZE); log_ptr += REC_NODE_PTR_SIZE; mlog_close(mtr, log_ptr); #endif /* !UNIV_HOTBACKUP */ } } /**********************************************************************//** Write the trx_id and roll_ptr of a record on a B-tree leaf node page. */ UNIV_INTERN void page_zip_write_trx_id_and_roll_ptr( /*===============================*/ page_zip_des_t* page_zip,/*!< in/out: compressed page */ byte* rec, /*!< in/out: record */ const ulint* offsets,/*!< in: rec_get_offsets(rec, index) */ ulint trx_id_col,/*!< in: column number of TRX_ID in rec */ trx_id_t trx_id, /*!< in: transaction identifier */ roll_ptr_t roll_ptr)/*!< in: roll_ptr */ { byte* field; byte* storage; #ifdef UNIV_DEBUG page_t* page = page_align(rec); #endif /* UNIV_DEBUG */ ulint len; ut_ad(PAGE_ZIP_MATCH(rec, page_zip)); ut_ad(page_simple_validate_new(page)); ut_ad(page_zip_simple_validate(page_zip)); ut_ad(page_zip_get_size(page_zip) > PAGE_DATA + page_zip_dir_size(page_zip)); ut_ad(rec_offs_validate(rec, NULL, offsets)); ut_ad(rec_offs_comp(offsets)); ut_ad(page_zip->m_start >= PAGE_DATA); ut_ad(page_zip_header_cmp(page_zip, page)); ut_ad(page_is_leaf(page)); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); storage = page_zip_dir_start(page_zip) - (rec_get_heap_no_new(rec) - 1) * (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); #if DATA_TRX_ID + 1 != DATA_ROLL_PTR # error "DATA_TRX_ID + 1 != DATA_ROLL_PTR" #endif field = rec_get_nth_field(rec, offsets, trx_id_col, &len); ut_ad(len == DATA_TRX_ID_LEN); ut_ad(field + DATA_TRX_ID_LEN == rec_get_nth_field(rec, offsets, trx_id_col + 1, &len)); ut_ad(len == DATA_ROLL_PTR_LEN); #if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG ut_a(!memcmp(storage, field, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)); #endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */ #if DATA_TRX_ID_LEN != 6 # error "DATA_TRX_ID_LEN != 6" #endif mach_write_to_6(field, trx_id); #if DATA_ROLL_PTR_LEN != 7 # error "DATA_ROLL_PTR_LEN != 7" #endif mach_write_to_7(field + DATA_TRX_ID_LEN, roll_ptr); memcpy(storage, field, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets)); UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets), rec_offs_extra_size(offsets)); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); } /**********************************************************************//** Clear an area on the uncompressed and compressed page. Do not clear the data payload, as that would grow the modification log. */ static void page_zip_clear_rec( /*===============*/ page_zip_des_t* page_zip, /*!< in/out: compressed page */ byte* rec, /*!< in: record to clear */ const dict_index_t* index, /*!< in: index of rec */ const ulint* offsets) /*!< in: rec_get_offsets(rec, index) */ { ulint heap_no; page_t* page = page_align(rec); byte* storage; byte* field; ulint len; /* page_zip_validate() would fail here if a record containing externally stored columns is being deleted. */ ut_ad(rec_offs_validate(rec, index, offsets)); ut_ad(!page_zip_dir_find(page_zip, page_offset(rec))); ut_ad(page_zip_dir_find_free(page_zip, page_offset(rec))); ut_ad(page_zip_header_cmp(page_zip, page)); heap_no = rec_get_heap_no_new(rec); ut_ad(heap_no >= PAGE_HEAP_NO_USER_LOW); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets)); UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets), rec_offs_extra_size(offsets)); if (!page_is_leaf(page)) { /* Clear node_ptr. On the compressed page, there is an array of node_ptr immediately before the dense page directory, at the very end of the page. */ storage = page_zip_dir_start(page_zip); ut_ad(dict_index_get_n_unique_in_tree(index) == rec_offs_n_fields(offsets) - 1); field = rec_get_nth_field(rec, offsets, rec_offs_n_fields(offsets) - 1, &len); ut_ad(len == REC_NODE_PTR_SIZE); ut_ad(!rec_offs_any_extern(offsets)); memset(field, 0, REC_NODE_PTR_SIZE); memset(storage - (heap_no - 1) * REC_NODE_PTR_SIZE, 0, REC_NODE_PTR_SIZE); } else if (dict_index_is_clust(index)) { /* Clear trx_id and roll_ptr. On the compressed page, there is an array of these fields immediately before the dense page directory, at the very end of the page. */ const ulint trx_id_pos = dict_col_get_clust_pos( dict_table_get_sys_col( index->table, DATA_TRX_ID), index); storage = page_zip_dir_start(page_zip); field = rec_get_nth_field(rec, offsets, trx_id_pos, &len); ut_ad(len == DATA_TRX_ID_LEN); memset(field, 0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); memset(storage - (heap_no - 1) * (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN), 0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); if (rec_offs_any_extern(offsets)) { ulint i; for (i = rec_offs_n_fields(offsets); i--; ) { /* Clear all BLOB pointers in order to make page_zip_validate() pass. */ if (rec_offs_nth_extern(offsets, i)) { field = rec_get_nth_field( rec, offsets, i, &len); ut_ad(len == BTR_EXTERN_FIELD_REF_SIZE); memset(field + len - BTR_EXTERN_FIELD_REF_SIZE, 0, BTR_EXTERN_FIELD_REF_SIZE); } } } } else { ut_ad(!rec_offs_any_extern(offsets)); } #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ } /**********************************************************************//** Write the "deleted" flag of a record on a compressed page. The flag must already have been written on the uncompressed page. */ UNIV_INTERN void page_zip_rec_set_deleted( /*=====================*/ page_zip_des_t* page_zip,/*!< in/out: compressed page */ const byte* rec, /*!< in: record on the uncompressed page */ ulint flag) /*!< in: the deleted flag (nonzero=TRUE) */ { byte* slot = page_zip_dir_find(page_zip, page_offset(rec)); ut_a(slot); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); if (flag) { *slot |= (PAGE_ZIP_DIR_SLOT_DEL >> 8); } else { *slot &= ~(PAGE_ZIP_DIR_SLOT_DEL >> 8); } #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page_align(rec), NULL)); #endif /* UNIV_ZIP_DEBUG */ } /**********************************************************************//** Write the "owned" flag of a record on a compressed page. The n_owned field must already have been written on the uncompressed page. */ UNIV_INTERN void page_zip_rec_set_owned( /*===================*/ page_zip_des_t* page_zip,/*!< in/out: compressed page */ const byte* rec, /*!< in: record on the uncompressed page */ ulint flag) /*!< in: the owned flag (nonzero=TRUE) */ { byte* slot = page_zip_dir_find(page_zip, page_offset(rec)); ut_a(slot); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); if (flag) { *slot |= (PAGE_ZIP_DIR_SLOT_OWNED >> 8); } else { *slot &= ~(PAGE_ZIP_DIR_SLOT_OWNED >> 8); } } /**********************************************************************//** Insert a record to the dense page directory. */ UNIV_INTERN void page_zip_dir_insert( /*================*/ page_zip_des_t* page_zip,/*!< in/out: compressed page */ const byte* prev_rec,/*!< in: record after which to insert */ const byte* free_rec,/*!< in: record from which rec was allocated, or NULL */ byte* rec) /*!< in: record to insert */ { ulint n_dense; byte* slot_rec; byte* slot_free; ut_ad(prev_rec != rec); ut_ad(page_rec_get_next((rec_t*) prev_rec) == rec); ut_ad(page_zip_simple_validate(page_zip)); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); if (page_rec_is_infimum(prev_rec)) { /* Use the first slot. */ slot_rec = page_zip->data + page_zip_get_size(page_zip); } else { byte* end = page_zip->data + page_zip_get_size(page_zip); byte* start = end - page_zip_dir_user_size(page_zip); if (UNIV_LIKELY(!free_rec)) { /* PAGE_N_RECS was already incremented in page_cur_insert_rec_zip(), but the dense directory slot at that position contains garbage. Skip it. */ start += PAGE_ZIP_DIR_SLOT_SIZE; } slot_rec = page_zip_dir_find_low(start, end, page_offset(prev_rec)); ut_a(slot_rec); } /* Read the old n_dense (n_heap may have been incremented). */ n_dense = page_dir_get_n_heap(page_zip->data) - (PAGE_HEAP_NO_USER_LOW + 1); if (UNIV_LIKELY_NULL(free_rec)) { /* The record was allocated from the free list. Shift the dense directory only up to that slot. Note that in this case, n_dense is actually off by one, because page_cur_insert_rec_zip() did not increment n_heap. */ ut_ad(rec_get_heap_no_new(rec) < n_dense + 1 + PAGE_HEAP_NO_USER_LOW); ut_ad(rec >= free_rec); slot_free = page_zip_dir_find(page_zip, page_offset(free_rec)); ut_ad(slot_free); slot_free += PAGE_ZIP_DIR_SLOT_SIZE; } else { /* The record was allocated from the heap. Shift the entire dense directory. */ ut_ad(rec_get_heap_no_new(rec) == n_dense + PAGE_HEAP_NO_USER_LOW); /* Shift to the end of the dense page directory. */ slot_free = page_zip->data + page_zip_get_size(page_zip) - PAGE_ZIP_DIR_SLOT_SIZE * n_dense; } /* Shift the dense directory to allocate place for rec. */ memmove(slot_free - PAGE_ZIP_DIR_SLOT_SIZE, slot_free, slot_rec - slot_free); /* Write the entry for the inserted record. The "owned" and "deleted" flags must be zero. */ mach_write_to_2(slot_rec - PAGE_ZIP_DIR_SLOT_SIZE, page_offset(rec)); } /**********************************************************************//** Shift the dense page directory and the array of BLOB pointers when a record is deleted. */ UNIV_INTERN void page_zip_dir_delete( /*================*/ page_zip_des_t* page_zip, /*!< in/out: compressed page */ byte* rec, /*!< in: deleted record */ const dict_index_t* index, /*!< in: index of rec */ const ulint* offsets, /*!< in: rec_get_offsets(rec) */ const byte* free) /*!< in: previous start of the free list */ { byte* slot_rec; byte* slot_free; ulint n_ext; page_t* page = page_align(rec); ut_ad(rec_offs_validate(rec, index, offsets)); ut_ad(rec_offs_comp(offsets)); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets)); UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets), rec_offs_extra_size(offsets)); slot_rec = page_zip_dir_find(page_zip, page_offset(rec)); ut_a(slot_rec); /* This could not be done before page_zip_dir_find(). */ page_header_set_field(page, page_zip, PAGE_N_RECS, (ulint)(page_get_n_recs(page) - 1)); if (UNIV_UNLIKELY(!free)) { /* Make the last slot the start of the free list. */ slot_free = page_zip->data + page_zip_get_size(page_zip) - PAGE_ZIP_DIR_SLOT_SIZE * (page_dir_get_n_heap(page_zip->data) - PAGE_HEAP_NO_USER_LOW); } else { slot_free = page_zip_dir_find_free(page_zip, page_offset(free)); ut_a(slot_free < slot_rec); /* Grow the free list by one slot by moving the start. */ slot_free += PAGE_ZIP_DIR_SLOT_SIZE; } if (UNIV_LIKELY(slot_rec > slot_free)) { memmove(slot_free + PAGE_ZIP_DIR_SLOT_SIZE, slot_free, slot_rec - slot_free); } /* Write the entry for the deleted record. The "owned" and "deleted" flags will be cleared. */ mach_write_to_2(slot_free, page_offset(rec)); if (!page_is_leaf(page) || !dict_index_is_clust(index)) { ut_ad(!rec_offs_any_extern(offsets)); goto skip_blobs; } n_ext = rec_offs_n_extern(offsets); if (UNIV_UNLIKELY(n_ext)) { /* Shift and zero fill the array of BLOB pointers. */ ulint blob_no; byte* externs; byte* ext_end; blob_no = page_zip_get_n_prev_extern(page_zip, rec, index); ut_a(blob_no + n_ext <= page_zip->n_blobs); externs = page_zip->data + page_zip_get_size(page_zip) - (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW) * (PAGE_ZIP_DIR_SLOT_SIZE + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); ext_end = externs - page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE; externs -= blob_no * BTR_EXTERN_FIELD_REF_SIZE; page_zip->n_blobs -= static_cast<unsigned>(n_ext); /* Shift and zero fill the array. */ memmove(ext_end + n_ext * BTR_EXTERN_FIELD_REF_SIZE, ext_end, (page_zip->n_blobs - blob_no) * BTR_EXTERN_FIELD_REF_SIZE); memset(ext_end, 0, n_ext * BTR_EXTERN_FIELD_REF_SIZE); } skip_blobs: /* The compression algorithm expects info_bits and n_owned to be 0 for deleted records. */ rec[-REC_N_NEW_EXTRA_BYTES] = 0; /* info_bits and n_owned */ page_zip_clear_rec(page_zip, rec, index, offsets); } /**********************************************************************//** Add a slot to the dense page directory. */ UNIV_INTERN void page_zip_dir_add_slot( /*==================*/ page_zip_des_t* page_zip, /*!< in/out: compressed page */ ulint is_clustered) /*!< in: nonzero for clustered index, zero for others */ { ulint n_dense; byte* dir; byte* stored; ut_ad(page_is_comp(page_zip->data)); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); /* Read the old n_dense (n_heap has already been incremented). */ n_dense = page_dir_get_n_heap(page_zip->data) - (PAGE_HEAP_NO_USER_LOW + 1); dir = page_zip->data + page_zip_get_size(page_zip) - PAGE_ZIP_DIR_SLOT_SIZE * n_dense; if (!page_is_leaf(page_zip->data)) { ut_ad(!page_zip->n_blobs); stored = dir - n_dense * REC_NODE_PTR_SIZE; } else if (is_clustered) { /* Move the BLOB pointer array backwards to make space for the roll_ptr and trx_id columns and the dense directory slot. */ byte* externs; stored = dir - n_dense * (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); externs = stored - page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE; ASSERT_ZERO(externs - (PAGE_ZIP_DIR_SLOT_SIZE + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN), PAGE_ZIP_DIR_SLOT_SIZE + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN); memmove(externs - (PAGE_ZIP_DIR_SLOT_SIZE + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN), externs, stored - externs); } else { stored = dir - page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE; ASSERT_ZERO(stored - PAGE_ZIP_DIR_SLOT_SIZE, PAGE_ZIP_DIR_SLOT_SIZE); } /* Move the uncompressed area backwards to make space for one directory slot. */ memmove(stored - PAGE_ZIP_DIR_SLOT_SIZE, stored, dir - stored); } /***********************************************************//** Parses a log record of writing to the header of a page. @return end of log record or NULL */ UNIV_INTERN byte* page_zip_parse_write_header( /*========================*/ byte* ptr, /*!< in: redo log buffer */ byte* end_ptr,/*!< in: redo log buffer end */ page_t* page, /*!< in/out: uncompressed page */ page_zip_des_t* page_zip)/*!< in/out: compressed page */ { ulint offset; ulint len; ut_ad(ptr && end_ptr); ut_ad(!page == !page_zip); if (UNIV_UNLIKELY(end_ptr < ptr + (1 + 1))) { return(NULL); } offset = (ulint) *ptr++; len = (ulint) *ptr++; if (UNIV_UNLIKELY(!len) || UNIV_UNLIKELY(offset + len >= PAGE_DATA)) { corrupt: recv_sys->found_corrupt_log = TRUE; return(NULL); } if (UNIV_UNLIKELY(end_ptr < ptr + len)) { return(NULL); } if (page) { if (UNIV_UNLIKELY(!page_zip)) { goto corrupt; } #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page, NULL)); #endif /* UNIV_ZIP_DEBUG */ memcpy(page + offset, ptr, len); memcpy(page_zip->data + offset, ptr, len); #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page, NULL)); #endif /* UNIV_ZIP_DEBUG */ } return(ptr + len); } #ifndef UNIV_HOTBACKUP /**********************************************************************//** Write a log record of writing to the uncompressed header portion of a page. */ UNIV_INTERN void page_zip_write_header_log( /*======================*/ const byte* data, /*!< in: data on the uncompressed page */ ulint length, /*!< in: length of the data */ mtr_t* mtr) /*!< in: mini-transaction */ { byte* log_ptr = mlog_open(mtr, 11 + 1 + 1); ulint offset = page_offset(data); ut_ad(offset < PAGE_DATA); ut_ad(offset + length < PAGE_DATA); #if PAGE_DATA > 255 # error "PAGE_DATA > 255" #endif ut_ad(length < 256); /* If no logging is requested, we may return now */ if (UNIV_UNLIKELY(!log_ptr)) { return; } log_ptr = mlog_write_initial_log_record_fast( (byte*) data, MLOG_ZIP_WRITE_HEADER, log_ptr, mtr); *log_ptr++ = (byte) offset; *log_ptr++ = (byte) length; mlog_close(mtr, log_ptr); mlog_catenate_string(mtr, data, length); } #endif /* !UNIV_HOTBACKUP */ /**********************************************************************//** Reorganize and compress a page. This is a low-level operation for compressed pages, to be used when page_zip_compress() fails. On success, a redo log entry MLOG_ZIP_PAGE_COMPRESS will be written. The function btr_page_reorganize() should be preferred whenever possible. IMPORTANT: if page_zip_reorganize() is invoked on a leaf page of a non-clustered index, the caller must update the insert buffer free bits in the same mini-transaction in such a way that the modification will be redo-logged. @return TRUE on success, FALSE on failure; page_zip will be left intact on failure, but page will be overwritten. */ UNIV_INTERN ibool page_zip_reorganize( /*================*/ buf_block_t* block, /*!< in/out: page with compressed page; on the compressed page, in: size; out: data, n_blobs, m_start, m_end, m_nonempty */ dict_index_t* index, /*!< in: index of the B-tree node */ mtr_t* mtr) /*!< in: mini-transaction */ { #ifndef UNIV_HOTBACKUP buf_pool_t* buf_pool = buf_pool_from_block(block); #endif /* !UNIV_HOTBACKUP */ page_zip_des_t* page_zip = buf_block_get_page_zip(block); page_t* page = buf_block_get_frame(block); buf_block_t* temp_block; page_t* temp_page; ulint log_mode; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); ut_ad(page_is_comp(page)); ut_ad(!dict_index_is_ibuf(index)); /* Note that page_zip_validate(page_zip, page, index) may fail here. */ UNIV_MEM_ASSERT_RW(page, UNIV_PAGE_SIZE); UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip)); /* Disable logging */ log_mode = mtr_set_log_mode(mtr, MTR_LOG_NONE); #ifndef UNIV_HOTBACKUP temp_block = buf_block_alloc(buf_pool); btr_search_drop_page_hash_index(block); block->check_index_page_at_flush = TRUE; #else /* !UNIV_HOTBACKUP */ ut_ad(block == back_block1); temp_block = back_block2; #endif /* !UNIV_HOTBACKUP */ temp_page = temp_block->frame; /* Copy the old page to temporary space */ buf_frame_copy(temp_page, page); btr_blob_dbg_remove(page, index, "zip_reorg"); /* Recreate the page: note that global data on page (possible segment headers, next page-field, etc.) is preserved intact */ page_create(block, mtr, TRUE); /* Copy the records from the temporary space to the recreated page; do not copy the lock bits yet */ page_copy_rec_list_end_no_locks(block, temp_block, page_get_infimum_rec(temp_page), index, mtr); if (!dict_index_is_clust(index) && page_is_leaf(temp_page)) { /* Copy max trx id to recreated page */ trx_id_t max_trx_id = page_get_max_trx_id(temp_page); page_set_max_trx_id(block, NULL, max_trx_id, NULL); ut_ad(max_trx_id != 0); } /* Restore logging. */ mtr_set_log_mode(mtr, log_mode); if (!page_zip_compress(page_zip, page, index, page_zip_compression_flags, mtr)) { #ifndef UNIV_HOTBACKUP buf_block_free(temp_block); #endif /* !UNIV_HOTBACKUP */ return(FALSE); } lock_move_reorganize_page(block, temp_block); #ifndef UNIV_HOTBACKUP buf_block_free(temp_block); #endif /* !UNIV_HOTBACKUP */ return(TRUE); } #ifndef UNIV_HOTBACKUP /**********************************************************************//** Copy the records of a page byte for byte. Do not copy the page header or trailer, except those B-tree header fields that are directly related to the storage of records. Also copy PAGE_MAX_TRX_ID. NOTE: The caller must update the lock table and the adaptive hash index. */ UNIV_INTERN void page_zip_copy_recs( /*===============*/ page_zip_des_t* page_zip, /*!< out: copy of src_zip (n_blobs, m_start, m_end, m_nonempty, data[0..size-1]) */ page_t* page, /*!< out: copy of src */ const page_zip_des_t* src_zip, /*!< in: compressed page */ const page_t* src, /*!< in: page */ dict_index_t* index, /*!< in: index of the B-tree */ mtr_t* mtr) /*!< in: mini-transaction */ { ut_ad(mtr_memo_contains_page(mtr, page, MTR_MEMO_PAGE_X_FIX)); ut_ad(mtr_memo_contains_page(mtr, src, MTR_MEMO_PAGE_X_FIX)); ut_ad(!dict_index_is_ibuf(index)); #ifdef UNIV_ZIP_DEBUG /* The B-tree operations that call this function may set FIL_PAGE_PREV or PAGE_LEVEL, causing a temporary min_rec_flag mismatch. A strict page_zip_validate() will be executed later during the B-tree operations. */ ut_a(page_zip_validate_low(src_zip, src, index, TRUE)); #endif /* UNIV_ZIP_DEBUG */ ut_a(page_zip_get_size(page_zip) == page_zip_get_size(src_zip)); if (UNIV_UNLIKELY(src_zip->n_blobs)) { ut_a(page_is_leaf(src)); ut_a(dict_index_is_clust(index)); } /* The PAGE_MAX_TRX_ID must be set on leaf pages of secondary indexes. It does not matter on other pages. */ ut_a(dict_index_is_clust(index) || !page_is_leaf(src) || page_get_max_trx_id(src)); UNIV_MEM_ASSERT_W(page, UNIV_PAGE_SIZE); UNIV_MEM_ASSERT_W(page_zip->data, page_zip_get_size(page_zip)); UNIV_MEM_ASSERT_RW(src, UNIV_PAGE_SIZE); UNIV_MEM_ASSERT_RW(src_zip->data, page_zip_get_size(page_zip)); /* Copy those B-tree page header fields that are related to the records stored in the page. Also copy the field PAGE_MAX_TRX_ID. Skip the rest of the page header and trailer. On the compressed page, there is no trailer. */ #if PAGE_MAX_TRX_ID + 8 != PAGE_HEADER_PRIV_END # error "PAGE_MAX_TRX_ID + 8 != PAGE_HEADER_PRIV_END" #endif memcpy(PAGE_HEADER + page, PAGE_HEADER + src, PAGE_HEADER_PRIV_END); memcpy(PAGE_DATA + page, PAGE_DATA + src, UNIV_PAGE_SIZE - PAGE_DATA - FIL_PAGE_DATA_END); memcpy(PAGE_HEADER + page_zip->data, PAGE_HEADER + src_zip->data, PAGE_HEADER_PRIV_END); memcpy(PAGE_DATA + page_zip->data, PAGE_DATA + src_zip->data, page_zip_get_size(page_zip) - PAGE_DATA); /* Copy all fields of src_zip to page_zip, except the pointer to the compressed data page. */ { page_zip_t* data = page_zip->data; memcpy(page_zip, src_zip, sizeof *page_zip); page_zip->data = data; } ut_ad(page_zip_get_trailer_len(page_zip, dict_index_is_clust(index)) + page_zip->m_end < page_zip_get_size(page_zip)); if (!page_is_leaf(src) && UNIV_UNLIKELY(mach_read_from_4(src + FIL_PAGE_PREV) == FIL_NULL) && UNIV_LIKELY(mach_read_from_4(page + FIL_PAGE_PREV) != FIL_NULL)) { /* Clear the REC_INFO_MIN_REC_FLAG of the first user record. */ ulint offs = rec_get_next_offs(page + PAGE_NEW_INFIMUM, TRUE); if (UNIV_LIKELY(offs != PAGE_NEW_SUPREMUM)) { rec_t* rec = page + offs; ut_a(rec[-REC_N_NEW_EXTRA_BYTES] & REC_INFO_MIN_REC_FLAG); rec[-REC_N_NEW_EXTRA_BYTES] &= ~ REC_INFO_MIN_REC_FLAG; } } #ifdef UNIV_ZIP_DEBUG ut_a(page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ btr_blob_dbg_add(page, index, "page_zip_copy_recs"); page_zip_compress_write_log(page_zip, page, index, mtr); } #endif /* !UNIV_HOTBACKUP */ /**********************************************************************//** Parses a log record of compressing an index page. @return end of log record or NULL */ UNIV_INTERN byte* page_zip_parse_compress( /*====================*/ byte* ptr, /*!< in: buffer */ byte* end_ptr,/*!< in: buffer end */ page_t* page, /*!< out: uncompressed page */ page_zip_des_t* page_zip)/*!< out: compressed page */ { ulint size; ulint trailer_size; ut_ad(ptr && end_ptr); ut_ad(!page == !page_zip); if (UNIV_UNLIKELY(ptr + (2 + 2) > end_ptr)) { return(NULL); } size = mach_read_from_2(ptr); ptr += 2; trailer_size = mach_read_from_2(ptr); ptr += 2; if (UNIV_UNLIKELY(ptr + 8 + size + trailer_size > end_ptr)) { return(NULL); } if (page) { if (UNIV_UNLIKELY(!page_zip) || UNIV_UNLIKELY(page_zip_get_size(page_zip) < size)) { corrupt: recv_sys->found_corrupt_log = TRUE; return(NULL); } memcpy(page_zip->data + FIL_PAGE_PREV, ptr, 4); memcpy(page_zip->data + FIL_PAGE_NEXT, ptr + 4, 4); memcpy(page_zip->data + FIL_PAGE_TYPE, ptr + 8, size); memset(page_zip->data + FIL_PAGE_TYPE + size, 0, page_zip_get_size(page_zip) - trailer_size - (FIL_PAGE_TYPE + size)); memcpy(page_zip->data + page_zip_get_size(page_zip) - trailer_size, ptr + 8 + size, trailer_size); if (UNIV_UNLIKELY(!page_zip_decompress(page_zip, page, TRUE))) { goto corrupt; } } return(ptr + 8 + size + trailer_size); } /**********************************************************************//** Calculate the compressed page checksum. @return page checksum */ UNIV_INTERN ulint page_zip_calc_checksum( /*===================*/ const void* data, /*!< in: compressed page */ ulint size, /*!< in: size of compressed page */ srv_checksum_algorithm_t algo) /*!< in: algorithm to use */ { uLong adler; ib_uint32_t crc32; const Bytef* s = static_cast<const byte*>(data); /* Exclude FIL_PAGE_SPACE_OR_CHKSUM, FIL_PAGE_LSN, and FIL_PAGE_FILE_FLUSH_LSN from the checksum. */ switch (algo) { case SRV_CHECKSUM_ALGORITHM_CRC32: case SRV_CHECKSUM_ALGORITHM_STRICT_CRC32: ut_ad(size > FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID); crc32 = ut_crc32(s + FIL_PAGE_OFFSET, FIL_PAGE_LSN - FIL_PAGE_OFFSET) ^ ut_crc32(s + FIL_PAGE_TYPE, 2) ^ ut_crc32(s + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, size - FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID); return((ulint) crc32); case SRV_CHECKSUM_ALGORITHM_INNODB: case SRV_CHECKSUM_ALGORITHM_STRICT_INNODB: ut_ad(size > FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID); adler = adler32(0L, s + FIL_PAGE_OFFSET, FIL_PAGE_LSN - FIL_PAGE_OFFSET); adler = adler32(adler, s + FIL_PAGE_TYPE, 2); adler = adler32( adler, s + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, static_cast<uInt>(size) - FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID); return((ulint) adler); case SRV_CHECKSUM_ALGORITHM_NONE: case SRV_CHECKSUM_ALGORITHM_STRICT_NONE: return(BUF_NO_CHECKSUM_MAGIC); /* no default so the compiler will emit a warning if new enum is added and not handled here */ } ut_error; return(0); } /**********************************************************************//** Verify a compressed page's checksum. @return TRUE if the stored checksum is valid according to the value of innodb_checksum_algorithm */ UNIV_INTERN ibool page_zip_verify_checksum( /*=====================*/ const void* data, /*!< in: compressed page */ ulint size) /*!< in: size of compressed page */ { ib_uint32_t stored; ib_uint32_t calc; ib_uint32_t crc32 = 0 /* silence bogus warning */; ib_uint32_t innodb = 0 /* silence bogus warning */; stored = static_cast<ib_uint32_t>(mach_read_from_4( static_cast<const unsigned char*>(data) + FIL_PAGE_SPACE_OR_CHKSUM)); /* declare empty pages non-corrupted */ if (stored == 0) { /* make sure that the page is really empty */ ulint i; for (i = 0; i < size; i++) { if (*((const char*) data + i) != 0) { return(FALSE); } } return(TRUE); } calc = static_cast<ib_uint32_t>(page_zip_calc_checksum( data, size, static_cast<srv_checksum_algorithm_t>( srv_checksum_algorithm))); if (stored == calc) { return(TRUE); } switch ((srv_checksum_algorithm_t) srv_checksum_algorithm) { case SRV_CHECKSUM_ALGORITHM_STRICT_CRC32: case SRV_CHECKSUM_ALGORITHM_STRICT_INNODB: case SRV_CHECKSUM_ALGORITHM_STRICT_NONE: return(stored == calc); case SRV_CHECKSUM_ALGORITHM_CRC32: if (stored == BUF_NO_CHECKSUM_MAGIC) { return(TRUE); } crc32 = calc; innodb = static_cast<ib_uint32_t>(page_zip_calc_checksum( data, size, SRV_CHECKSUM_ALGORITHM_INNODB)); break; case SRV_CHECKSUM_ALGORITHM_INNODB: if (stored == BUF_NO_CHECKSUM_MAGIC) { return(TRUE); } crc32 = static_cast<ib_uint32_t>(page_zip_calc_checksum( data, size, SRV_CHECKSUM_ALGORITHM_CRC32)); innodb = calc; break; case SRV_CHECKSUM_ALGORITHM_NONE: return(TRUE); /* no default so the compiler will emit a warning if new enum is added and not handled here */ } return(stored == crc32 || stored == innodb); }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pe.edu.upeu.modelo; import java.io.Serializable; import java.util.Collection; import java.util.Date; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author hp */ @Entity @Table(name = "conf_periodo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "ConfPeriodo.findAll", query = "SELECT c FROM ConfPeriodo c")}) public class ConfPeriodo implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id_periodo") private Integer idPeriodo; @Basic(optional = false) @Column(name = "periodo") private String periodo; @Basic(optional = false) @Column(name = "descripcion") private String descripcion; @Basic(optional = false) @Column(name = "fecha_inicio") @Temporal(TemporalType.DATE) private Date fechaInicio; @Basic(optional = false) @Column(name = "fecha_fin") @Temporal(TemporalType.DATE) private Date fechaFin; @Basic(optional = false) @Column(name = "estado") private String estado; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo") private Collection<GloAreaEje> gloAreaEjeCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo") private Collection<GloEstadoArea> gloEstadoAreaCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo") private Collection<GloEstadoDepartamento> gloEstadoDepartamentoCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo") private Collection<GloEstadoFilial> gloEstadoFilialCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo") private Collection<GloDepartCoordinador> gloDepartCoordinadorCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo") private Collection<GloMeta> gloMetaCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo") private Collection<GloDepartareaCoordinador> gloDepartareaCoordinadorCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo") private Collection<FinPartidapresupuestaria> finPartidapresupuestariaCollection; @JoinColumn(name = "id_temporada", referencedColumnName = "id_temporada") @ManyToOne(optional = false) private ConfTemporada idTemporada; public ConfPeriodo() { } public ConfPeriodo(Integer idPeriodo) { this.idPeriodo = idPeriodo; } public ConfPeriodo(Integer idPeriodo, String periodo, String descripcion, Date fechaInicio, Date fechaFin, String estado) { this.idPeriodo = idPeriodo; this.periodo = periodo; this.descripcion = descripcion; this.fechaInicio = fechaInicio; this.fechaFin = fechaFin; this.estado = estado; } public Integer getIdPeriodo() { return idPeriodo; } public void setIdPeriodo(Integer idPeriodo) { this.idPeriodo = idPeriodo; } public String getPeriodo() { return periodo; } public void setPeriodo(String periodo) { this.periodo = periodo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Date getFechaInicio() { return fechaInicio; } public void setFechaInicio(Date fechaInicio) { this.fechaInicio = fechaInicio; } public Date getFechaFin() { return fechaFin; } public void setFechaFin(Date fechaFin) { this.fechaFin = fechaFin; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } @XmlTransient public Collection<GloAreaEje> getGloAreaEjeCollection() { return gloAreaEjeCollection; } public void setGloAreaEjeCollection(Collection<GloAreaEje> gloAreaEjeCollection) { this.gloAreaEjeCollection = gloAreaEjeCollection; } @XmlTransient public Collection<GloEstadoArea> getGloEstadoAreaCollection() { return gloEstadoAreaCollection; } public void setGloEstadoAreaCollection(Collection<GloEstadoArea> gloEstadoAreaCollection) { this.gloEstadoAreaCollection = gloEstadoAreaCollection; } @XmlTransient public Collection<GloEstadoDepartamento> getGloEstadoDepartamentoCollection() { return gloEstadoDepartamentoCollection; } public void setGloEstadoDepartamentoCollection(Collection<GloEstadoDepartamento> gloEstadoDepartamentoCollection) { this.gloEstadoDepartamentoCollection = gloEstadoDepartamentoCollection; } @XmlTransient public Collection<GloEstadoFilial> getGloEstadoFilialCollection() { return gloEstadoFilialCollection; } public void setGloEstadoFilialCollection(Collection<GloEstadoFilial> gloEstadoFilialCollection) { this.gloEstadoFilialCollection = gloEstadoFilialCollection; } @XmlTransient public Collection<GloDepartCoordinador> getGloDepartCoordinadorCollection() { return gloDepartCoordinadorCollection; } public void setGloDepartCoordinadorCollection(Collection<GloDepartCoordinador> gloDepartCoordinadorCollection) { this.gloDepartCoordinadorCollection = gloDepartCoordinadorCollection; } @XmlTransient public Collection<GloMeta> getGloMetaCollection() { return gloMetaCollection; } public void setGloMetaCollection(Collection<GloMeta> gloMetaCollection) { this.gloMetaCollection = gloMetaCollection; } @XmlTransient public Collection<GloDepartareaCoordinador> getGloDepartareaCoordinadorCollection() { return gloDepartareaCoordinadorCollection; } public void setGloDepartareaCoordinadorCollection(Collection<GloDepartareaCoordinador> gloDepartareaCoordinadorCollection) { this.gloDepartareaCoordinadorCollection = gloDepartareaCoordinadorCollection; } @XmlTransient public Collection<FinPartidapresupuestaria> getFinPartidapresupuestariaCollection() { return finPartidapresupuestariaCollection; } public void setFinPartidapresupuestariaCollection(Collection<FinPartidapresupuestaria> finPartidapresupuestariaCollection) { this.finPartidapresupuestariaCollection = finPartidapresupuestariaCollection; } public ConfTemporada getIdTemporada() { return idTemporada; } public void setIdTemporada(ConfTemporada idTemporada) { this.idTemporada = idTemporada; } @Override public int hashCode() { int hash = 0; hash += (idPeriodo != null ? idPeriodo.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ConfPeriodo)) { return false; } ConfPeriodo other = (ConfPeriodo) object; if ((this.idPeriodo == null && other.idPeriodo != null) || (this.idPeriodo != null && !this.idPeriodo.equals(other.idPeriodo))) { return false; } return true; } @Override public String toString() { return "pe.edu.upeu.modelo.ConfPeriodo[ idPeriodo=" + idPeriodo + " ]"; } }
Java
package com.atlach.trafficdataloader; import java.util.ArrayList; /* Short Desc: Storage object for Trip info */ /* Trip Info > Trips > Routes */ public class TripInfo { private int tripCount = 0; public ArrayList<Trip> trips = null; public String date; public String origin; public String destination; public TripInfo() { trips = new ArrayList<Trip>(); } public int addTrip() { Trip temp = new Trip(); if (trips.add(temp) == false) { /* Failed */ return -1; } tripCount++; return trips.indexOf(temp); } public int addRouteToTrip(int tripId, String routeName, String mode, String dist, String agency, String start, String end, String points) { int result = -1; Trip temp = trips.get(tripId); if (temp != null) { result = temp.addRoute(routeName, mode, dist, agency, start, end, points); } return result; } public int getTripCount() { return tripCount; } public static class Trip { public double totalDist = 0.0; public double totalCost = 0.0; public int totalTraffic = 0; private int transfers = 0; public ArrayList<Route> routes = null; public Trip() { routes = new ArrayList<Route>(); }; public int addRoute(String routeName, String mode, String dist, String agency, String start, String end, String points) { Route temp = new Route(); temp.name = routeName; temp.mode = mode; temp.dist = dist; temp.agency = agency; temp.start = start; temp.end = end; temp.points = points; if (routes.add(temp) == false) { /* Failed */ return -1; } transfers++; return routes.indexOf(temp); } public int getTransfers() { return transfers; } } public static class Route { /* Object fields */ public String name = ""; public String mode = ""; public String dist = "0.0"; public String agency = ""; public String start = ""; public String end = ""; public String points = ""; public String cond = ""; //public String cost = "0.0"; public double costMatrix[] = {0.0, 0.0, 0.0, 0.0}; public double getRegularCost(boolean isDiscounted) { if (isDiscounted) { return costMatrix[1]; } return costMatrix[0]; } public double getSpecialCost(boolean isDiscounted) { if (isDiscounted) { return costMatrix[2]; } return costMatrix[3]; } } }
Java
package org.adastraeducation.liquiz.equation; import java.util.*; import java.util.regex.*; import org.adastraeducation.liquiz.*; /** * Present equations with random variables. * It has two ways to parse the equations in string[]. One is in infix, and the other is in the RPN. * @author Yingzhu Wang * */ public class Equation implements Displayable { private Expression func; private double correctAnswer; private HashMap<String,Var> variables; public Equation(String equation, HashMap<String,Var> variables){ this.variables=variables; ArrayList<String> equationSplit = this.parseQuestion(equation); this.func = this.parseInfix(equationSplit); correctAnswer = func.eval(); } public Equation(Expression func, HashMap<String,Var> variables){ this.func = func; this.variables = variables; correctAnswer=func.eval(); } public Equation(Expression func){ this.func = func; this.variables = new HashMap<String,Var>(); correctAnswer=func.eval(); } public void setExpression(Expression e){ this.func=e; correctAnswer=func.eval(); } public void setVariables(HashMap<String,Var> variables){ this.variables = variables; } public String getTagName() { return "Equation"; } public Expression parseInfix(ArrayList<String> s){ Tree t = new Tree(s); ArrayList<String> rpn = t.traverse(); return parseRPN(rpn); } // Precompile all regular expressions used in parsing private static final Pattern parseDigits = Pattern.compile("^[0-9]+$"); private static final Pattern wordPattern = Pattern.compile("[\\W]|([\\w]*)"); /*TODO: We can do much better than a switch statement, * but it would require a hash map and lots of little objects */ //TODO: Check if binary ops are backgwards? a b - ???? public Expression parseRPN(ArrayList<String> s) { Stack<Expression> stack = new Stack<Expression>(); for(int i = 0; i<s.size(); i++){ String temp = s.get(i); if (Functions.MATHFUNCTIONS.contains(temp)) { Expression op1 ; Expression op2 ; switch(temp){ case "+": op2=stack.pop(); op1=stack.pop(); stack.push(new Plus(op1,op2)); break; case "-": op2=stack.pop(); op1=stack.pop(); stack.push( new Minus(op1,op2)); break; case "*": op2=stack.pop(); op1=stack.pop(); stack.push( new Multi(op1,op2));break; case "/": op2=stack.pop(); op1=stack.pop(); stack.push( new Div(op1,op2));break; case "sin": op1=stack.pop(); stack.push(new Sin(op1));break; case "cos": op1=stack.pop(); stack.push(new Cos(op1));break; case "tan": op1=stack.pop(); stack.push(new Tan(op1));break; case "abs": op1=stack.pop(); stack.push(new Abs(op1));break; case "Asin": op1=stack.pop(); stack.push(new Asin(op1));break; case "Atan": op1=stack.pop(); stack.push(new Atan(op1));break; case "neg": op1=stack.pop(); stack.push(new Neg(op1));break; case "sqrt": op1=stack.pop(); stack.push(new Sqrt(op1));break; default:break; } } //deal with the space else if(temp.equals("")) ; else{ Matcher m = parseDigits.matcher(temp); if (m.matches()){ double x = Double.parseDouble(temp); stack.push(new Constant(x)); } else{ stack.push(variables.get(temp)); } } } return stack.pop(); } public ArrayList<String> parseQuestion(String question){ ArrayList<String> s = new ArrayList<String>(); Matcher m = wordPattern.matcher(question); while(m.find()){ s.add(m.group()); } return s; } // public ResultSet readDatabase(String sql){ // return DatabaseMgr.select(sql); // } // // public void writeDatabase(String sql){ // DatabaseMgr.update(sql); // } public Expression getExpression(){ return func; } public double getCorrectAnswer(){ return correctAnswer; } @Override public void writeHTML(StringBuilder b) { func.infixReplaceVar(b); } @Override public void writeXML(StringBuilder b) { b.append("<Equation question='"); func.infix(b); b.append("'></Equation>"); } @Override public void writeJS(StringBuilder b) { } }
Java
package com.github.luksdlt92; import java.util.ArrayList; /* * DoubleJumpReload plugin * Made by luksdlt92 and Abdalion */ import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import com.github.luksdlt92.commands.DoubleJumpCommand; import com.github.luksdlt92.listeners.JumpListener; public class DoubleJumpReload extends JavaPlugin implements Listener { public ArrayList<String> _players = new ArrayList<String>(); public ArrayList<String> _playersDisableJump = new ArrayList<String>(); @Override public void onEnable() { new JumpListener(this); this.getCommand("jumpdelay").setExecutor(new DoubleJumpCommand(this)); } public ArrayList<String> getPlayers() { return _players; } public ArrayList<String> getPlayersDisableJump() { return _playersDisableJump; } }
Java
package org.vidogram.messenger.g.a; import java.io.ByteArrayOutputStream; public class j extends ByteArrayOutputStream { private final b a; public j(b paramb, int paramInt) { this.a = paramb; this.buf = this.a.a(Math.max(paramInt, 256)); } private void a(int paramInt) { if (this.count + paramInt <= this.buf.length) return; byte[] arrayOfByte = this.a.a((this.count + paramInt) * 2); System.arraycopy(this.buf, 0, arrayOfByte, 0, this.count); this.a.a(this.buf); this.buf = arrayOfByte; } public void close() { this.a.a(this.buf); this.buf = null; super.close(); } public void finalize() { this.a.a(this.buf); } public void write(int paramInt) { monitorenter; try { a(1); super.write(paramInt); monitorexit; return; } finally { localObject = finally; monitorexit; } throw localObject; } public void write(byte[] paramArrayOfByte, int paramInt1, int paramInt2) { monitorenter; try { a(paramInt2); super.write(paramArrayOfByte, paramInt1, paramInt2); monitorexit; return; } finally { paramArrayOfByte = finally; monitorexit; } throw paramArrayOfByte; } } /* Location: G:\programs\dex2jar-2.0\vidogram-dex2jar.jar * Qualified Name: org.vidogram.messenger.g.a.j * JD-Core Version: 0.6.0 */
Java
using UnityEngine; using System.Collections; /* * Item to handle movements of rigibodies */ public class RigibodyMoveItem : MoveItem { public enum Type { ENEMY_SHIP_TYPE_1, LASER_RED, LASER_BLUE }; public static RigibodyMoveItem create(Type type) { switch (type) { case Type.ENEMY_SHIP_TYPE_1: return new EnemyShip1MoveItem(); case Type.LASER_RED: return new LaserRedMoveItem(); case Type.LASER_BLUE: return new LaserBlueMoveItem(); default: throw new System.ArgumentException("Incorrect RigibodyMoveItem.Type " + type.ToString()); } } }
Java
#ifndef __EDIV_QGRAPHICS_H_ #define __EDIV_QGRAPHICS_H_ #include "export.h" /* Flags de modos de video */ #define _FULLSCREEN 0x01 typedef struct { byte* buffer; // invisible buffer byte* colormap; // 256 * VID_GRADES size byte* alphamap; // 256 * 256 translucency map int width; int height; int bpp; int flags; } viddef_t; viddef_t vid; #endif /* __EDIV_QGRAPHICS_H_ */
Java
package it.polito.nexa.pc; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Statement; import java.util.List; /** * Created by giuseppe on 19/05/15. */ public interface TriplesAdder { public Model addTriples(Model model, List<Statement> statementList); }
Java
/** * @file mqueue.h * * This file contains the definitions related to POSIX Message Queues. */ /* * COPYRIGHT (c) 1989-2011. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. */ #ifndef _MQUEUE_H #define _MQUEUE_H #include <unistd.h> #if defined(_POSIX_MESSAGE_PASSING) #include <sys/types.h> #include <rtems/system.h> #include <rtems/score/object.h> #ifdef __cplusplus extern "C" { #endif /* * 15.1.1 Data Structures, P1003.1b-1993, p. 271 */ /** * Message queue id type. * * @note Use uint32_t since all POSIX Ids are 32-bit currently. */ typedef uint32_t mqd_t; /** * This is the message queue attributes structure. */ struct mq_attr { /** This is the message queue flags */ long mq_flags; /** This is the maximum number of messages */ long mq_maxmsg; /** This is the maximum message size */ long mq_msgsize; /** This is the mumber of messages currently queued */ long mq_curmsgs; }; /** * 15.2.2 Open a Message Queue, P1003.1b-1993, p. 272 */ mqd_t mq_open( const char *name, int oflag, ... ); /** * 15.2.2 Close a Message Queue, P1003.1b-1993, p. 275 */ int mq_close( mqd_t mqdes ); /** * 15.2.2 Remove a Message Queue, P1003.1b-1993, p. 276 */ int mq_unlink( const char *name ); /** * 15.2.4 Send a Message to a Message Queue, P1003.1b-1993, p. 277 * * @note P1003.4b/D8, p. 45 adds mq_timedsend(). */ int mq_send( mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned int msg_prio ); #if defined(_POSIX_TIMEOUTS) #include <time.h> int mq_timedsend( mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned int msg_prio, const struct timespec *abstime ); #endif /* _POSIX_TIMEOUTS */ /* * 15.2.5 Receive a Message From a Message Queue, P1003.1b-1993, p. 279 * * NOTE: P1003.4b/D8, p. 45 adds mq_timedreceive(). */ ssize_t mq_receive( mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned int *msg_prio ); #if defined(_POSIX_TIMEOUTS) ssize_t mq_timedreceive( mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned int *msg_prio, const struct timespec *abstime ); #endif /* _POSIX_TIMEOUTS */ #if defined(_POSIX_REALTIME_SIGNALS) /* * 15.2.6 Notify Process that a Message is Available on a Queue, * P1003.1b-1993, p. 280 */ int mq_notify( mqd_t mqdes, const struct sigevent *notification ); #endif /* _POSIX_REALTIME_SIGNALS */ /* * 15.2.7 Set Message Queue Attributes, P1003.1b-1993, p. 281 */ int mq_setattr( mqd_t mqdes, const struct mq_attr *mqstat, struct mq_attr *omqstat ); /* * 15.2.8 Get Message Queue Attributes, P1003.1b-1993, p. 283 */ int mq_getattr( mqd_t mqdes, struct mq_attr *mqstat ); #ifdef __cplusplus } #endif #endif /* _POSIX_MESSAGE_PASSING */ #endif /* end of include file */
Java
/* shades of grey */ /*@g1 : #5A6568;*/ /* b&w */ /* color specific to a player */ /*@id-color: #78BDE7;*/ /* fonts */ /* variable heights */ /*@player-controls-height:20px;*/ /* transistions */ .ez-trans { -webkit-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } /* effects */ .bs-none { -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } #now-playing { height: 35px; color: #43464b; padding: 7px; } #now-playing::before { content: "now playing : "; color: #878a8f; } /* global */ html, body { height: 100%; } *:focus { outline: none; } body { background-color: #fff; margin-top: 0; margin-bottom: 0; font-family: "Lato", Helvetica, Arial, sans-serif; color: #262b2c; } iframe { border-style: none; } a { color: #262b2c; background-color: #65686d; } a:hover { color: white; background-color: #878a8f; } .container { width: 100%; height: 100%; padding-left: 0px; padding-right: 0px; } .glyphicon { margin-right: 4px; } /* popup */ .popup { position: relative; background: #65686d; padding: 20px; width: auto; max-width: 500px; margin: 20px auto; } .popup .btn { height: 35px; border-radius: 0; border-style: none; background-color: #878a8f; } .popup .btn:hover { background-color: #cbced3; } .popup .selected, .popup .selected:hover { color: white; background-color: #babd3c; } .popup .ti-container { margin-top: 20px; margin-bottom: 15px; } .popup .form-control { height: 40px; font-size: 18px; border-radius: 0; } .popup .delete-sco-message { margin-bottom: 15px; } /* header */ #player-head { height: 100px; background-color: #65686d; position: fixed; width: 100%; z-index: 1000; } .player-name { font-size: 65px; padding-left: 20px; padding-right: 20px; display: inline-block; /*width:100%;*/ height: 100%; background-color: #43464b; color: #dcdf5e; } .player-ip { position: absolute; left: 5px; bottom: 0px; color: #babd3c; } /* nav bar */ .navbar { position: fixed; top: 100px; /*min-height:@navbar-height;*/ margin-bottom: 0px; border-style: none; -webkit-box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); } .navbar li, .navbar a { font-size: 18px; line-height: 1; -webkit-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .navbar .nav-pills > li.active > a, .navbar .nav-pills > li.active > a:hover, .navbar .nav-pills > li.active > a:focus { color: white; background-color: #babd3c; } .navbar .nav-pills > li > a { height: 60px; padding-top: 21px; border-style: none; border-radius: 0; } /* tool bar */ .toolbar { /*line-height:@toolbar-height;*/ background: #cbced3; } .toolbar .row { margin: 0; } .toolbar .btn { height: 35px; border-radius: 0; border-style: none; background-color: #878a8f; } .toolbar .btn:hover { background-color: #cbced3; } .toolbar .caret { position: absolute; right: 10px; top: 17.5px; } .toolbar .dropdown-menu { border-radius: 0; border-style: none; width: 100%; margin: 0px; padding: 0px 0; max-height: 350px; overflow-y: scroll; -webkit-box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); } .toolbar .dropdown-menu li a { background-color: #cbced3; } .toolbar .dropdown-menu li a:hover { background-color: #878a8f; } .toolbar .dropdown-menu li .divider { margin: 0px; background-color: #878a8f; } .toolbar .btn-warning { background-color: #dcdf5e; } .toolbar .btn-warning:focus { background-color: #babd3c; } /* progress-bar */ .progress-container { padding: 0px 10px; height: 32px; } .progress { margin-top: 8.5px; border-radius: 15px; height: 15px; } .progress-bar { background-color: #babd3c; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } /* media list */ .media-list table { margin: 0; height: 100%; } .media-list thead, .media-list tbody, .media-list tr, .media-list td, .media-list th { display: block; border-style: none; } .media-list tr:after { content: ' '; display: block; visibility: hidden; clear: both; } .media-list thead th { height: 40px; } .media-list tbody { height: calc(100% - 40px); overflow-y: auto; background-color: #cbced3; } .media-list thead { background-color: #cbced3; border-bottom-style: dashed; border-bottom-width: 1px; border-bottom-color: #878a8f; } .media-list tbody td, .media-list thead th { width: 25%; float: left; } .media-list .table-striped > tbody > tr:nth-child(odd) { background-color: #dcdfe4; } .media-list .table-striped > tbody > tr:nth-child(even) { background-color: #cbced3; } .media-list .table-striped > tbody > tr:last-child { -webkit-box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); } .media-list .table-hover > tbody > tr:hover { background-color: #878a8f; color: white; } /* content section */ .content-section { background-color: #43464b; margin-top: 160px; height: calc(100% - 160px); } #scenario-section { overflow: hidden; /*height: calc(~"100% - "@player-head-height + @navbar-height + @toolbar-height);*/ } #blockly-frame-container { height: calc(100% - 35px); } #blockly-iframe { width: 100%; height: 100%; } #controls-section { /*height:calc(~"100% - "@player-head-height + @navbar-height + @toolbar-height);*/ } #controls-section .panel-group { height: 100%; margin-bottom: 0; background-color: #43464b; } #controls-section .panel { -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; border-style: none; border-radius: 0; margin-top: 0; } #controls-section .panel .panel-heading { height: 50px; -webkit-box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); position: relative; color: #262b2c; background-color: #878a8f; border-radius: 0; padding: 0; } #controls-section .panel .panel-heading .panel-title > a { position: absolute; width: 100%; padding-left: 10px; text-decoration: none; background-color: #878a8f; line-height: 50px; } #controls-section .panel .panel-heading .panel-title > a:hover, #controls-section .panel .panel-heading .panel-title > a:focus { background-color: #65686d; color: white; } #controls-section .panel .panel-body { padding: 0; height: 100%; background-color: #cbced3; } #controls-section #media-player { overflow: hidden !important; } #controls-section #media-player .media-list { height: calc(100% - 34px); /* table { margin:0; height:100%; } thead, tbody, tr, td, th { display: block; border-style: none; } tr:after { content: ' '; display: block; visibility: hidden; clear: both; } thead th { height:@player-controls-th-height; } tbody { height: calc(~"100% - "@player-controls-th-height); overflow-y: auto; background-color: @g1-ppp; } thead { background-color: @g1-ppp; border-bottom-style: dashed; border-bottom-width:1px; border-bottom-color: @g1-pp; } tbody td, thead th { width: 25%; float: left; } .table-striped { > tbody > tr:nth-child(odd) { background-color: @g1-ppp+#111; } > tbody > tr:nth-child(even) { background-color: @g1-ppp; } > tbody > tr:last-child { .ds(0,2px,3px,0,0.2); } } .table-hover { > tbody > tr:hover { background-color: @g1-pp; color:@w; } }*/ } #controls-section #media-player #player-controls { width: 100%; height: 35px; background-color: #dcdfe4; border-top-style: dashed; border-top-width: 1px; border-top-color: #878a8f; } #controls-section #media-player #player-controls .btn-default { background-color: #cbced3; } #controls-section #media-player #player-controls .btn-default:hover { background-color: #878a8f; color: white; } #controls-section #media-player #player-controls .btn-warning { background-color: #dcdf5e; } #controls-section #media-player #player-controls .btn-warning:hover { background-color: #babd3c; } #controls-section #media-player #player-controls .slider-container { padding: 0px 10px; } #controls-section #media-player #player-controls .slider-container #volume-sli { margin-top: 8.5px; margin-bottom: 0; } #controls-section #media-player #player-controls .slider-container .ui-slider-range { background-color: #babd3c; } #controls-section #media-player #player-controls .slider-container .ui-slider-handle { background-color: #dcdf5e; } #controls-section #sensors #sensor-left-menu { height: 100%; } #controls-section #sensors #sensor-left-menu ul { height: 100%; border-style: none; padding: 0; } #controls-section #sensors #sensor-left-menu li { margin-bottom: 0; height: 33.33333333%; width: 100%; } #controls-section #sensors #sensor-left-menu a, #controls-section #sensors #sensor-left-menu a:hover, #controls-section #sensors #sensor-left-menu a:focus { border-style: none; border-radius: 0; height: 100%; /*line-height:200%;*/ text-align: center; } #controls-section #sensors #sensor-panes-container { background-color: #cbced3; height: 100%; } #controls-section #network #lonely-container { display: -webkit-flex; display: flex; height: 300px; } #controls-section #network #lonely { margin: auto; font-size: 4rem; } #media-section { background-color: #43464b; /*height:100%;*/ } #media-section #media-controls { -webkit-box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); position: fixed; width: 100%; z-index: 1000; } #media-section .media-zone { height: 260px; padding: 40px; text-align: center; } #media-section .media-list { height: calc(100% - 60px); } #media-section #upload-zone, #media-section #upload-zone * { box-sizing: border-box; } #media-section #upload-zone { position: relative; } #media-section #upload-message { opacity: 0.15; font-size: 124px; color: #222; text-shadow: 0px 2px 3px #555; position: absolute; top: 60px; left: 50%; margin-left: -224px; } #media-section #upload-zone .dz-preview { position: relative; display: inline-block; width: 120px; margin: 0.5em; } #media-section #upload-zone .dz-preview .dz-progress { display: block; height: 15px; border: 1px solid #aaa; } #media-section #upload-zone .dz-preview .dz-progress .dz-upload { display: block; height: 100%; width: 0; background: #babd3c; } #media-section #upload-zone .dz-preview .dz-error-message { color: red; display: none; } #media-section #upload-zone .dz-preview.dz-error .dz-error-message, #media-section #upload-zone .dz-preview.dz-error .dz-error-mark { display: block; } #media-section #upload-zone .dz-preview.dz-success .dz-success-mark { display: block; } #media-section #upload-zone .dz-preview .dz-error-mark, #media-section #upload-zone .dz-preview .dz-success-mark { position: absolute; display: none; left: 30px; top: 30px; width: 54px; height: 58px; left: 50%; margin-left: -27px; } /*# sourceMappingURL=style.css.map */ /*# sourceMappingURL=style.css.map */
Java
<!DOCTYPE html> <html lang="en-US"> <!-- Mirrored from www.w3schools.com/tags/tryit.asp?filename=tryhtml_img_border_css by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:23:38 GMT --> <head> <title>Tryit Editor v2.3</title> <meta id="viewport" name='viewport'> <script> (function() { if ( navigator.userAgent.match(/iPad/i) ) { document.getElementById('viewport').setAttribute("content", "width=device-width, initial-scale=0.9"); } }()); </script> <link rel="stylesheet" href="../trycss.css"> <!--[if lt IE 8]> <style> .textareacontainer, .iframecontainer {width:48%;} .textarea, .iframe {height:800px;} #textareaCode, #iframeResult {height:700px;} .menu img {display:none;} </style> <![endif]--> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','../../www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-3855518-1', 'auto'); ga('require', 'displayfeatures'); ga('send', 'pageview'); </script> <script> var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; (function() { var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; var useSSL = 'https:' == document.location.protocol; gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(gads, node); })(); </script> <script> googletag.cmd.push(function() { googletag.defineSlot('/16833175/TryitLeaderboard', [[728, 90], [970, 90]], 'div-gpt-ad-1383036313516-0').addService(googletag.pubads()); googletag.pubads().setTargeting("content","trytags"); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); </script> <script type="text/javascript"> function submitTryit() { var t=document.getElementById("textareaCode").value; t=t.replace(/=/gi,"w3equalsign"); var pos=t.search(/script/i) while (pos>0) { t=t.substring(0,pos) + "w3" + t.substr(pos,3) + "w3" + t.substr(pos+3,3) + "tag" + t.substr(pos+6); pos=t.search(/script/i); } if ( navigator.userAgent.match(/Safari/i) ) { t=escape(t); document.getElementById("bt").value="1"; } document.getElementById("code").value=t; document.getElementById("tryitform").action="tryit_view52a0.html?x=" + Math.random(); validateForm(); document.getElementById("iframeResult").contentWindow.name = "view"; document.getElementById("tryitform").submit(); } function validateForm() { var code=document.getElementById("code").value; if (code.length>8000) { document.getElementById("code").value="<h1>Error</h1>"; } } </script> <style> </style> </head> <body> <div id="ads"> <div style="position:relative;width:100%;margin-top:0px;margin-bottom:0px;"> <div style="width:974px;height:94px;position:relative;margin:0px;margin-top:5px;margin-bottom:5px;margin-right:auto;margin-left:auto;padding:0px;overflow:hidden;"> <!-- TryitLeaderboard --> <div id='div-gpt-ad-1383036313516-0' style='width:970px; height:90px;'> <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1383036313516-0'); }); </script> </div> <div style="clear:both"></div> </div> </div> </div> <div class="container"> <div class="textareacontainer"> <div class="textarea"> <div class="headerText" style="width:auto;float:left;">Edit This Code:</div> <div class="headerBtnDiv" style="width:auto;float:right;margin-top:8px;margin-right:2.4%;"><button class="submit" type="button" onclick="submitTryit()">See Result &raquo;</button></div> <div class="textareawrapper"> <textarea autocomplete="off" class="code_input" id="textareaCode" wrap="logical" xrows="30" xcols="50"><!DOCTYPE html> <html> <body> <img src="smiley.gif" alt="Smiley face" width="42" height="42" style="border:5px solid black"> </body> <!-- Mirrored from www.w3schools.com/tags/tryit.asp?filename=tryhtml_img_border_css by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:23:38 GMT --> </html> </textarea> <form autocomplete="off" style="margin:0px;display:none;" action="http://www.w3schools.com/tags/tryit_view.asp" method="post" target="view" id="tryitform" name="tryitform" onsubmit="validateForm();"> <input type="hidden" name="code" id="code" /> <input type="hidden" id="bt" name="bt" /> </form> </div> </div> </div> <div class="iframecontainer"> <div class="iframe"> <div class="headerText resultHeader">Result:</div> <div class="iframewrapper"> <iframe id="iframeResult" class="result_output" frameborder="0" name="view" xsrc="tryhtml_img_border_css.html"></iframe> </div> <div class="footerText">Try it Yourself - &copy; <a href="../index.html">w3schools.com</a></div> </div> </div> </div> <script>submitTryit()</script> </body> </html>
Java
using UnityEngine; using System.Collections; public class ButtonNextImage : MonoBehaviour { public GameObject nextImage; public bool lastImage; public string nextScene = ""; void OnMouseDown() { if(lastImage) { Application.LoadLevel(nextScene); return; } gameObject.SetActive (false); nextImage.SetActive (true); } }
Java
/** * Created by LPAC006013 on 23/11/14. */ /* * wiring Super fish to menu */ var sfvar = jQuery('div.menu'); var phoneSize = 600; jQuery(document).ready(function($) { //if screen size is bigger than phone's screen (Tablet,Desktop) if($(document).width() >= phoneSize) { // enable superfish sfvar.superfish({ delay: 500, speed: 'slow' }); jQuery("#menu-main-menu").addClass('clear'); var containerheight = jQuery("#menu-main-menu").height(); jQuery("#menu-main-menu").children().css("height",containerheight); } $(window).resize(function() { if($(document).width() >= phoneSize && !sfvar.hasClass('sf-js-enabled')) { sfvar.superfish({ delay: 500, speed: 'slow' }); } // phoneSize, disable superfish else if($(document).width() < phoneSize) { sfvar.superfish('destroy'); } }); });
Java
<?php /** * Multisite upgrade administration panel. * * @package WordPress * @subpackage Multisite * @since 3.0.0 */ /** Load WordPress Administration Bootstrap */ require_once(dirname(__FILE__) . '/admin.php'); if (!is_multisite()) wp_die(__('Multisite support is not enabled.')); require_once(ABSPATH . WPINC . '/http.php'); $title = __('Upgrade Network'); $parent_file = 'upgrade.php'; get_current_screen()->add_help_tab(array( 'id' => 'overview', 'title' => __('Overview'), 'content' => '<p>' . __('Only use this screen once you have updated to a new version of WordPress through Updates/Available Updates (via the Network Administration navigation menu or the Toolbar). Clicking the Upgrade Network button will step through each site in the network, five at a time, and make sure any database updates are applied.') . '</p>' . '<p>' . __('If a version update to core has not happened, clicking this button won&#8217;t affect anything.') . '</p>' . '<p>' . __('If this process fails for any reason, users logging in to their sites will force the same update.') . '</p>' )); get_current_screen()->set_help_sidebar( '<p><strong>' . __('For more information:') . '</strong></p>' . '<p>' . __('<a href="http://codex.wordpress.org/Network_Admin_Updates_Screen" target="_blank">Documentation on Upgrade Network</a>') . '</p>' . '<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>' ); require_once(ABSPATH . 'wp-admin/admin-header.php'); if (!current_user_can('manage_network')) wp_die(__('You do not have permission to access this page.')); echo '<div class="wrap">'; echo '<h2>' . __('Upgrade Network') . '</h2>'; $action = isset($_GET['action']) ? $_GET['action'] : 'show'; switch ($action) { case "upgrade": $n = (isset($_GET['n'])) ? intval($_GET['n']) : 0; if ($n < 5) { global $wp_db_version; update_site_option('wpmu_upgrade_site', $wp_db_version); } $blogs = $wpdb->get_results("SELECT blog_id FROM {$wpdb->blogs} WHERE site_id = '{$wpdb->siteid}' AND spam = '0' AND deleted = '0' AND archived = '0' ORDER BY registered DESC LIMIT {$n}, 5", ARRAY_A); if (empty($blogs)) { echo '<p>' . __('All done!') . '</p>'; break; } echo "<ul>"; foreach ((array)$blogs as $details) { switch_to_blog($details['blog_id']); $siteurl = site_url(); $upgrade_url = admin_url('upgrade.php?step=upgrade_db'); restore_current_blog(); echo "<li>$siteurl</li>"; $response = wp_remote_get($upgrade_url, array('timeout' => 120, 'httpversion' => '1.1')); if (is_wp_error($response)) wp_die(sprintf(__('Warning! Problem updating %1$s. Your server may not be able to connect to sites running on it. Error message: <em>%2$s</em>'), $siteurl, $response->get_error_message())); /** * Fires after the Multisite DB upgrade for each site is complete. * * @since MU * * @param array|WP_Error $response The upgrade response array or WP_Error on failure. */ do_action('after_mu_upgrade', $response); /** * Fires after each site has been upgraded. * * @since MU * * @param int $blog_id The id of the blog. */ do_action('wpmu_upgrade_site', $details['blog_id']); } echo "</ul>"; ?><p><?php _e('If your browser doesn&#8217;t start loading the next page automatically, click this link:'); ?> <a class="button" href="upgrade.php?action=upgrade&amp;n=<?php echo($n + 5) ?>"><?php _e("Next Sites"); ?></a> </p> <script type="text/javascript"> <!-- function nextpage() { location.href = "upgrade.php?action=upgrade&n=<?php echo ($n + 5) ?>"; } setTimeout("nextpage()", 250); //--> </script><?php break; case 'show': default: if (get_site_option('wpmu_upgrade_site') != $GLOBALS['wp_db_version']) : ?> <h3><?php _e('Database Upgrade Required'); ?></h3> <p><?php _e('WordPress has been updated! Before we send you on your way, we need to individually upgrade the sites in your network.'); ?></p> <?php endif; ?> <p><?php _e('The database upgrade process may take a little while, so please be patient.'); ?></p> <p><a class="button" href="upgrade.php?action=upgrade"><?php _e('Upgrade Network'); ?></a></p> <?php /** * Fires before the footer on the network upgrade screen. * * @since MU */ do_action('wpmu_upgrade_page'); break; } ?> </div> <?php include(ABSPATH . 'wp-admin/admin-footer.php'); ?>
Java
<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xml:base="http://machines.plannedobsolescence.net/51-2008" xmlns:dc="http://purl.org/dc/elements/1.1/"> <channel> <title>intro to digital media studies - symbiosis</title> <link>http://machines.plannedobsolescence.net/51-2008/taxonomy/term/120/0</link> <description></description> <language>en</language> <item> <title>reading response 5</title> <link>http://machines.plannedobsolescence.net/51-2008/node/92</link> <description>&lt;p&gt;Both Nelson and Licklider saw it extremely fit for the relationship of man and computer to drastically become more interdependent on each other. Nelson speaks of the EFL and machines like that described by V.Bush(memex), where the computer will have all the information that one would ever need, all at a desk, and Licklider envisioned men to by this day and age have been even more dependent on computers and not only restricted to desks and office areas.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;http://machines.plannedobsolescence.net/51-2008/node/92&quot;&gt;read more&lt;/a&gt;&lt;/p&gt;</description> <comments>http://machines.plannedobsolescence.net/51-2008/node/92#comments</comments> <category domain="http://machines.plannedobsolescence.net/51-2008/taxonomy/term/122">computer</category> <category domain="http://machines.plannedobsolescence.net/51-2008/taxonomy/term/121">man</category> <category domain="http://machines.plannedobsolescence.net/51-2008/taxonomy/term/120">symbiosis</category> <pubDate>Sun, 17 Feb 2008 19:30:48 +0000</pubDate> <dc:creator>bungbang</dc:creator> <guid isPermaLink="false">92 at http://machines.plannedobsolescence.net/51-2008</guid> </item> </channel> </rss>
Java
<html> <head> <link rel="stylesheet" href="../extjs/resources/css/ext-all.css" type="text/css" /> <script type="text/javascript" src="../extjs/ext-all.js"></script> <script type="text/javascript" src="sample.js"></script> </head> <body> </body> </html>
Java
#!/usr/bin/ruby -w class T_002aac < Test def description return "mkvmerge / audio only / in(AAC)" end def run merge("data/simple/v.aac", 1) return hash_tmp end end
Java
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html // // file: rbbirb.cpp // // Copyright (C) 2002-2011, International Business Machines Corporation and others. // All Rights Reserved. // // This file contains the RBBIRuleBuilder class implementation. This is the main class for // building (compiling) break rules into the tables required by the runtime // RBBI engine. // #include "unicode/utypes.h" #if !UCONFIG_NO_BREAK_ITERATION #include "unicode/brkiter.h" #include "unicode/rbbi.h" #include "unicode/ubrk.h" #include "unicode/unistr.h" #include "unicode/uniset.h" #include "unicode/uchar.h" #include "unicode/uchriter.h" #include "unicode/parsepos.h" #include "unicode/parseerr.h" #include "cmemory.h" #include "cstring.h" #include "rbbirb.h" #include "rbbinode.h" #include "rbbiscan.h" #include "rbbisetb.h" #include "rbbitblb.h" #include "rbbidata.h" #include "uassert.h" U_NAMESPACE_BEGIN //---------------------------------------------------------------------------------------- // // Constructor. // //---------------------------------------------------------------------------------------- RBBIRuleBuilder::RBBIRuleBuilder(const UnicodeString &rules, UParseError *parseErr, UErrorCode &status) : fRules(rules), fStrippedRules(rules) { fStatus = &status; // status is checked below fParseError = parseErr; fDebugEnv = NULL; #ifdef RBBI_DEBUG fDebugEnv = getenv("U_RBBIDEBUG"); #endif fForwardTree = NULL; fReverseTree = NULL; fSafeFwdTree = NULL; fSafeRevTree = NULL; fDefaultTree = &fForwardTree; fForwardTable = NULL; fRuleStatusVals = NULL; fChainRules = FALSE; fLBCMNoChain = FALSE; fLookAheadHardBreak = FALSE; fUSetNodes = NULL; fRuleStatusVals = NULL; fScanner = NULL; fSetBuilder = NULL; if (parseErr) { uprv_memset(parseErr, 0, sizeof(UParseError)); } if (U_FAILURE(status)) { return; } fUSetNodes = new UVector(status); // bcos status gets overwritten here fRuleStatusVals = new UVector(status); fScanner = new RBBIRuleScanner(this); fSetBuilder = new RBBISetBuilder(this); if (U_FAILURE(status)) { return; } if(fSetBuilder == 0 || fScanner == 0 || fUSetNodes == 0 || fRuleStatusVals == 0) { status = U_MEMORY_ALLOCATION_ERROR; } } //---------------------------------------------------------------------------------------- // // Destructor // //---------------------------------------------------------------------------------------- RBBIRuleBuilder::~RBBIRuleBuilder() { int i; for (i=0; ; i++) { RBBINode *n = (RBBINode *)fUSetNodes->elementAt(i); if (n==NULL) { break; } delete n; } delete fUSetNodes; delete fSetBuilder; delete fForwardTable; delete fForwardTree; delete fReverseTree; delete fSafeFwdTree; delete fSafeRevTree; delete fScanner; delete fRuleStatusVals; } //---------------------------------------------------------------------------------------- // // flattenData() - Collect up the compiled RBBI rule data and put it into // the format for saving in ICU data files, // which is also the format needed by the RBBI runtime engine. // //---------------------------------------------------------------------------------------- static int32_t align8(int32_t i) {return (i+7) & 0xfffffff8;} RBBIDataHeader *RBBIRuleBuilder::flattenData() { int32_t i; if (U_FAILURE(*fStatus)) { return NULL; } // Remove whitespace from the rules to make it smaller. // The rule parser has already removed comments. fStrippedRules = fScanner->stripRules(fStrippedRules); // Calculate the size of each section in the data. // Sizes here are padded up to a multiple of 8 for better memory alignment. // Sections sizes actually stored in the header are for the actual data // without the padding. // int32_t headerSize = align8(sizeof(RBBIDataHeader)); int32_t forwardTableSize = align8(fForwardTable->getTableSize()); int32_t reverseTableSize = align8(fForwardTable->getSafeTableSize()); int32_t trieSize = align8(fSetBuilder->getTrieSize()); int32_t statusTableSize = align8(fRuleStatusVals->size() * sizeof(int32_t)); int32_t rulesSize = align8((fStrippedRules.length()+1) * sizeof(UChar)); int32_t totalSize = headerSize + forwardTableSize + reverseTableSize + statusTableSize + trieSize + rulesSize; RBBIDataHeader *data = (RBBIDataHeader *)uprv_malloc(totalSize); if (data == NULL) { *fStatus = U_MEMORY_ALLOCATION_ERROR; return NULL; } uprv_memset(data, 0, totalSize); data->fMagic = 0xb1a0; data->fFormatVersion[0] = RBBI_DATA_FORMAT_VERSION[0]; data->fFormatVersion[1] = RBBI_DATA_FORMAT_VERSION[1]; data->fFormatVersion[2] = RBBI_DATA_FORMAT_VERSION[2]; data->fFormatVersion[3] = RBBI_DATA_FORMAT_VERSION[3]; data->fLength = totalSize; data->fCatCount = fSetBuilder->getNumCharCategories(); data->fFTable = headerSize; data->fFTableLen = forwardTableSize; data->fRTable = data->fFTable + data->fFTableLen; data->fRTableLen = reverseTableSize; data->fTrie = data->fRTable + data->fRTableLen; data->fTrieLen = fSetBuilder->getTrieSize(); data->fStatusTable = data->fTrie + trieSize; data->fStatusTableLen= statusTableSize; data->fRuleSource = data->fStatusTable + statusTableSize; data->fRuleSourceLen = fStrippedRules.length() * sizeof(UChar); uprv_memset(data->fReserved, 0, sizeof(data->fReserved)); fForwardTable->exportTable((uint8_t *)data + data->fFTable); fForwardTable->exportSafeTable((uint8_t *)data + data->fRTable); fSetBuilder->serializeTrie ((uint8_t *)data + data->fTrie); int32_t *ruleStatusTable = (int32_t *)((uint8_t *)data + data->fStatusTable); for (i=0; i<fRuleStatusVals->size(); i++) { ruleStatusTable[i] = fRuleStatusVals->elementAti(i); } fStrippedRules.extract((UChar *)((uint8_t *)data+data->fRuleSource), rulesSize/2+1, *fStatus); return data; } //---------------------------------------------------------------------------------------- // // createRuleBasedBreakIterator construct from source rules that are passed in // in a UnicodeString // //---------------------------------------------------------------------------------------- BreakIterator * RBBIRuleBuilder::createRuleBasedBreakIterator( const UnicodeString &rules, UParseError *parseError, UErrorCode &status) { // // Read the input rules, generate a parse tree, symbol table, // and list of all Unicode Sets referenced by the rules. // RBBIRuleBuilder builder(rules, parseError, status); if (U_FAILURE(status)) { // status checked here bcos build below doesn't return NULL; } RBBIDataHeader *data = builder.build(status); if (U_FAILURE(status)) { return nullptr; } // // Create a break iterator from the compiled rules. // (Identical to creation from stored pre-compiled rules) // // status is checked after init in construction. RuleBasedBreakIterator *This = new RuleBasedBreakIterator(data, status); if (U_FAILURE(status)) { delete This; This = NULL; } else if(This == NULL) { // test for NULL status = U_MEMORY_ALLOCATION_ERROR; } return This; } RBBIDataHeader *RBBIRuleBuilder::build(UErrorCode &status) { if (U_FAILURE(status)) { return nullptr; } fScanner->parse(); if (U_FAILURE(status)) { return nullptr; } // // UnicodeSet processing. // Munge the Unicode Sets to create a set of character categories. // Generate the mapping tables (TRIE) from input code points to // the character categories. // fSetBuilder->buildRanges(); // // Generate the DFA state transition table. // fForwardTable = new RBBITableBuilder(this, &fForwardTree, status); if (fForwardTable == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return nullptr; } fForwardTable->buildForwardTable(); optimizeTables(); fForwardTable->buildSafeReverseTable(status); #ifdef RBBI_DEBUG if (fDebugEnv && uprv_strstr(fDebugEnv, "states")) { fForwardTable->printStates(); fForwardTable->printRuleStatusTable(); fForwardTable->printReverseTable(); } #endif fSetBuilder->buildTrie(); // // Package up the compiled data into a memory image // in the run-time format. // RBBIDataHeader *data = flattenData(); // returns NULL if error if (U_FAILURE(status)) { return nullptr; } return data; } void RBBIRuleBuilder::optimizeTables() { // Begin looking for duplicates with char class 3. // Classes 0, 1 and 2 are special; they are unused, {bof} and {eof} respectively, // and should not have other categories merged into them. IntPair duplPair = {3, 0}; while (fForwardTable->findDuplCharClassFrom(&duplPair)) { fSetBuilder->mergeCategories(duplPair); fForwardTable->removeColumn(duplPair.second); } fForwardTable->removeDuplicateStates(); } U_NAMESPACE_END #endif /* #if !UCONFIG_NO_BREAK_ITERATION */
Java
/* Discovery of auto-inc and auto-dec instructions. Copyright (C) 2006-2015 Free Software Foundation, Inc. Contributed by Kenneth Zadeck <zadeck@naturalbridge.com> This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "hash-set.h" #include "machmode.h" #include "vec.h" #include "double-int.h" #include "input.h" #include "alias.h" #include "symtab.h" #include "wide-int.h" #include "inchash.h" #include "tree.h" #include "rtl.h" #include "tm_p.h" #include "hard-reg-set.h" #include "predict.h" #include "vec.h" #include "hashtab.h" #include "hash-set.h" #include "machmode.h" #include "input.h" #include "function.h" #include "dominance.h" #include "cfg.h" #include "cfgrtl.h" #include "basic-block.h" #include "insn-config.h" #include "regs.h" #include "flags.h" #include "except.h" #include "diagnostic-core.h" #include "recog.h" #include "expr.h" #include "tree-pass.h" #include "df.h" #include "dbgcnt.h" #include "target.h" /* This pass was originally removed from flow.c. However there is almost nothing that remains of that code. There are (4) basic forms that are matched: (1) FORM_PRE_ADD a <- b + c ... *a becomes a <- b ... *(a += c) pre (2) FORM_PRE_INC a += c ... *a becomes *(a += c) pre (3) FORM_POST_ADD *a ... b <- a + c (For this case to be true, b must not be assigned or used between the *a and the assignment to b. B must also be a Pmode reg.) becomes b <- a ... *(b += c) post (4) FORM_POST_INC *a ... a <- a + c becomes *(a += c) post There are three types of values of c. 1) c is a constant equal to the width of the value being accessed by the pointer. This is useful for machines that have HAVE_PRE_INCREMENT, HAVE_POST_INCREMENT, HAVE_PRE_DECREMENT or HAVE_POST_DECREMENT defined. 2) c is a constant not equal to the width of the value being accessed by the pointer. This is useful for machines that have HAVE_PRE_MODIFY_DISP, HAVE_POST_MODIFY_DISP defined. 3) c is a register. This is useful for machines that have HAVE_PRE_MODIFY_REG, HAVE_POST_MODIFY_REG The is one special case: if a already had an offset equal to it +- its width and that offset is equal to -c when the increment was before the ref or +c if the increment was after the ref, then if we can do the combination but switch the pre/post bit. */ #ifdef AUTO_INC_DEC enum form { FORM_PRE_ADD, FORM_PRE_INC, FORM_POST_ADD, FORM_POST_INC, FORM_last }; /* The states of the second operands of mem refs and inc insns. If no second operand of the mem_ref was found, it is assumed to just be ZERO. SIZE is the size of the mode accessed in the memref. The ANY is used for constants that are not +-size or 0. REG is used if the forms are reg1 + reg2. */ enum inc_state { INC_ZERO, /* == 0 */ INC_NEG_SIZE, /* == +size */ INC_POS_SIZE, /* == -size */ INC_NEG_ANY, /* == some -constant */ INC_POS_ANY, /* == some +constant */ INC_REG, /* == some register */ INC_last }; /* The eight forms that pre/post inc/dec can take. */ enum gen_form { NOTHING, SIMPLE_PRE_INC, /* ++size */ SIMPLE_POST_INC, /* size++ */ SIMPLE_PRE_DEC, /* --size */ SIMPLE_POST_DEC, /* size-- */ DISP_PRE, /* ++con */ DISP_POST, /* con++ */ REG_PRE, /* ++reg */ REG_POST /* reg++ */ }; /* Tmp mem rtx for use in cost modeling. */ static rtx mem_tmp; static enum inc_state set_inc_state (HOST_WIDE_INT val, int size) { if (val == 0) return INC_ZERO; if (val < 0) return (val == -size) ? INC_NEG_SIZE : INC_NEG_ANY; else return (val == size) ? INC_POS_SIZE : INC_POS_ANY; } /* The DECISION_TABLE that describes what form, if any, the increment or decrement will take. It is a three dimensional table. The first index is the type of constant or register found as the second operand of the inc insn. The second index is the type of constant or register found as the second operand of the memory reference (if no second operand exists, 0 is used). The third index is the form and location (relative to the mem reference) of inc insn. */ static bool initialized = false; static enum gen_form decision_table[INC_last][INC_last][FORM_last]; static void init_decision_table (void) { enum gen_form value; if (HAVE_PRE_INCREMENT || HAVE_PRE_MODIFY_DISP) { /* Prefer the simple form if both are available. */ value = (HAVE_PRE_INCREMENT) ? SIMPLE_PRE_INC : DISP_PRE; decision_table[INC_POS_SIZE][INC_ZERO][FORM_PRE_ADD] = value; decision_table[INC_POS_SIZE][INC_ZERO][FORM_PRE_INC] = value; decision_table[INC_POS_SIZE][INC_POS_SIZE][FORM_POST_ADD] = value; decision_table[INC_POS_SIZE][INC_POS_SIZE][FORM_POST_INC] = value; } if (HAVE_POST_INCREMENT || HAVE_POST_MODIFY_DISP) { /* Prefer the simple form if both are available. */ value = (HAVE_POST_INCREMENT) ? SIMPLE_POST_INC : DISP_POST; decision_table[INC_POS_SIZE][INC_ZERO][FORM_POST_ADD] = value; decision_table[INC_POS_SIZE][INC_ZERO][FORM_POST_INC] = value; decision_table[INC_POS_SIZE][INC_NEG_SIZE][FORM_PRE_ADD] = value; decision_table[INC_POS_SIZE][INC_NEG_SIZE][FORM_PRE_INC] = value; } if (HAVE_PRE_DECREMENT || HAVE_PRE_MODIFY_DISP) { /* Prefer the simple form if both are available. */ value = (HAVE_PRE_DECREMENT) ? SIMPLE_PRE_DEC : DISP_PRE; decision_table[INC_NEG_SIZE][INC_ZERO][FORM_PRE_ADD] = value; decision_table[INC_NEG_SIZE][INC_ZERO][FORM_PRE_INC] = value; decision_table[INC_NEG_SIZE][INC_NEG_SIZE][FORM_POST_ADD] = value; decision_table[INC_NEG_SIZE][INC_NEG_SIZE][FORM_POST_INC] = value; } if (HAVE_POST_DECREMENT || HAVE_POST_MODIFY_DISP) { /* Prefer the simple form if both are available. */ value = (HAVE_POST_DECREMENT) ? SIMPLE_POST_DEC : DISP_POST; decision_table[INC_NEG_SIZE][INC_ZERO][FORM_POST_ADD] = value; decision_table[INC_NEG_SIZE][INC_ZERO][FORM_POST_INC] = value; decision_table[INC_NEG_SIZE][INC_POS_SIZE][FORM_PRE_ADD] = value; decision_table[INC_NEG_SIZE][INC_POS_SIZE][FORM_PRE_INC] = value; } if (HAVE_PRE_MODIFY_DISP) { decision_table[INC_POS_ANY][INC_ZERO][FORM_PRE_ADD] = DISP_PRE; decision_table[INC_POS_ANY][INC_ZERO][FORM_PRE_INC] = DISP_PRE; decision_table[INC_POS_ANY][INC_POS_ANY][FORM_POST_ADD] = DISP_PRE; decision_table[INC_POS_ANY][INC_POS_ANY][FORM_POST_INC] = DISP_PRE; decision_table[INC_NEG_ANY][INC_ZERO][FORM_PRE_ADD] = DISP_PRE; decision_table[INC_NEG_ANY][INC_ZERO][FORM_PRE_INC] = DISP_PRE; decision_table[INC_NEG_ANY][INC_NEG_ANY][FORM_POST_ADD] = DISP_PRE; decision_table[INC_NEG_ANY][INC_NEG_ANY][FORM_POST_INC] = DISP_PRE; } if (HAVE_POST_MODIFY_DISP) { decision_table[INC_POS_ANY][INC_ZERO][FORM_POST_ADD] = DISP_POST; decision_table[INC_POS_ANY][INC_ZERO][FORM_POST_INC] = DISP_POST; decision_table[INC_POS_ANY][INC_NEG_ANY][FORM_PRE_ADD] = DISP_POST; decision_table[INC_POS_ANY][INC_NEG_ANY][FORM_PRE_INC] = DISP_POST; decision_table[INC_NEG_ANY][INC_ZERO][FORM_POST_ADD] = DISP_POST; decision_table[INC_NEG_ANY][INC_ZERO][FORM_POST_INC] = DISP_POST; decision_table[INC_NEG_ANY][INC_POS_ANY][FORM_PRE_ADD] = DISP_POST; decision_table[INC_NEG_ANY][INC_POS_ANY][FORM_PRE_INC] = DISP_POST; } /* This is much simpler than the other cases because we do not look for the reg1-reg2 case. Note that we do not have a INC_POS_REG and INC_NEG_REG states. Most of the use of such states would be on a target that had an R1 - R2 update address form. There is the remote possibility that you could also catch a = a + b; *(a - b) as a postdecrement of (a + b). However, it is unclear if *(a - b) would ever be generated on a machine that did not have that kind of addressing mode. The IA-64 and RS6000 will not do this, and I cannot speak for any other. If any architecture does have an a-b update for, these cases should be added. */ if (HAVE_PRE_MODIFY_REG) { decision_table[INC_REG][INC_ZERO][FORM_PRE_ADD] = REG_PRE; decision_table[INC_REG][INC_ZERO][FORM_PRE_INC] = REG_PRE; decision_table[INC_REG][INC_REG][FORM_POST_ADD] = REG_PRE; decision_table[INC_REG][INC_REG][FORM_POST_INC] = REG_PRE; } if (HAVE_POST_MODIFY_REG) { decision_table[INC_REG][INC_ZERO][FORM_POST_ADD] = REG_POST; decision_table[INC_REG][INC_ZERO][FORM_POST_INC] = REG_POST; } initialized = true; } /* Parsed fields of an inc insn of the form "reg_res = reg0+reg1" or "reg_res = reg0+c". */ static struct inc_insn { rtx_insn *insn; /* The insn being parsed. */ rtx pat; /* The pattern of the insn. */ bool reg1_is_const; /* True if reg1 is const, false if reg1 is a reg. */ enum form form; rtx reg_res; rtx reg0; rtx reg1; enum inc_state reg1_state;/* The form of the const if reg1 is a const. */ HOST_WIDE_INT reg1_val;/* Value if reg1 is const. */ } inc_insn; /* Dump the parsed inc insn to FILE. */ static void dump_inc_insn (FILE *file) { const char *f = ((inc_insn.form == FORM_PRE_ADD) || (inc_insn.form == FORM_PRE_INC)) ? "pre" : "post"; dump_insn_slim (file, inc_insn.insn); switch (inc_insn.form) { case FORM_PRE_ADD: case FORM_POST_ADD: if (inc_insn.reg1_is_const) fprintf (file, "found %s add(%d) r[%d]=r[%d]+%d\n", f, INSN_UID (inc_insn.insn), REGNO (inc_insn.reg_res), REGNO (inc_insn.reg0), (int) inc_insn.reg1_val); else fprintf (file, "found %s add(%d) r[%d]=r[%d]+r[%d]\n", f, INSN_UID (inc_insn.insn), REGNO (inc_insn.reg_res), REGNO (inc_insn.reg0), REGNO (inc_insn.reg1)); break; case FORM_PRE_INC: case FORM_POST_INC: if (inc_insn.reg1_is_const) fprintf (file, "found %s inc(%d) r[%d]+=%d\n", f, INSN_UID (inc_insn.insn), REGNO (inc_insn.reg_res), (int) inc_insn.reg1_val); else fprintf (file, "found %s inc(%d) r[%d]+=r[%d]\n", f, INSN_UID (inc_insn.insn), REGNO (inc_insn.reg_res), REGNO (inc_insn.reg1)); break; default: break; } } /* Parsed fields of a mem ref of the form "*(reg0+reg1)" or "*(reg0+c)". */ static struct mem_insn { rtx_insn *insn; /* The insn being parsed. */ rtx pat; /* The pattern of the insn. */ rtx *mem_loc; /* The address of the field that holds the mem */ /* that is to be replaced. */ bool reg1_is_const; /* True if reg1 is const, false if reg1 is a reg. */ rtx reg0; rtx reg1; /* This is either a reg or a const depending on reg1_is_const. */ enum inc_state reg1_state;/* The form of the const if reg1 is a const. */ HOST_WIDE_INT reg1_val;/* Value if reg1 is const. */ } mem_insn; /* Dump the parsed mem insn to FILE. */ static void dump_mem_insn (FILE *file) { dump_insn_slim (file, mem_insn.insn); if (mem_insn.reg1_is_const) fprintf (file, "found mem(%d) *(r[%d]+%d)\n", INSN_UID (mem_insn.insn), REGNO (mem_insn.reg0), (int) mem_insn.reg1_val); else fprintf (file, "found mem(%d) *(r[%d]+r[%d])\n", INSN_UID (mem_insn.insn), REGNO (mem_insn.reg0), REGNO (mem_insn.reg1)); } /* The following three arrays contain pointers to instructions. They are indexed by REGNO. At any point in the basic block where we are looking these three arrays contain, respectively, the next insn that uses REGNO, the next inc or add insn that uses REGNO and the next insn that sets REGNO. The arrays are not cleared when we move from block to block so whenever an insn is retrieved from these arrays, it's block number must be compared with the current block. */ static rtx_insn **reg_next_use = NULL; static rtx_insn **reg_next_inc_use = NULL; static rtx_insn **reg_next_def = NULL; /* Move dead note that match PATTERN to TO_INSN from FROM_INSN. We do not really care about moving any other notes from the inc or add insn. Moving the REG_EQUAL and REG_EQUIV is clearly wrong and it does not appear that there are any other kinds of relevant notes. */ static void move_dead_notes (rtx_insn *to_insn, rtx_insn *from_insn, rtx pattern) { rtx note; rtx next_note; rtx prev_note = NULL; for (note = REG_NOTES (from_insn); note; note = next_note) { next_note = XEXP (note, 1); if ((REG_NOTE_KIND (note) == REG_DEAD) && pattern == XEXP (note, 0)) { XEXP (note, 1) = REG_NOTES (to_insn); REG_NOTES (to_insn) = note; if (prev_note) XEXP (prev_note, 1) = next_note; else REG_NOTES (from_insn) = next_note; } else prev_note = note; } } /* Create a mov insn DEST_REG <- SRC_REG and insert it before NEXT_INSN. */ static rtx_insn * insert_move_insn_before (rtx_insn *next_insn, rtx dest_reg, rtx src_reg) { rtx_insn *insns; start_sequence (); emit_move_insn (dest_reg, src_reg); insns = get_insns (); end_sequence (); emit_insn_before (insns, next_insn); return insns; } /* Change mem_insn.mem_loc so that uses NEW_ADDR which has an increment of INC_REG. To have reached this point, the change is a legitimate one from a dataflow point of view. The only questions are is this a valid change to the instruction and is this a profitable change to the instruction. */ static bool attempt_change (rtx new_addr, rtx inc_reg) { /* There are four cases: For the two cases that involve an add instruction, we are going to have to delete the add and insert a mov. We are going to assume that the mov is free. This is fairly early in the backend and there are a lot of opportunities for removing that move later. In particular, there is the case where the move may be dead, this is what dead code elimination passes are for. The two cases where we have an inc insn will be handled mov free. */ basic_block bb = BLOCK_FOR_INSN (mem_insn.insn); rtx_insn *mov_insn = NULL; int regno; rtx mem = *mem_insn.mem_loc; machine_mode mode = GET_MODE (mem); rtx new_mem; int old_cost = 0; int new_cost = 0; bool speed = optimize_bb_for_speed_p (bb); PUT_MODE (mem_tmp, mode); XEXP (mem_tmp, 0) = new_addr; old_cost = (set_src_cost (mem, speed) + set_rtx_cost (PATTERN (inc_insn.insn), speed)); new_cost = set_src_cost (mem_tmp, speed); /* The first item of business is to see if this is profitable. */ if (old_cost < new_cost) { if (dump_file) fprintf (dump_file, "cost failure old=%d new=%d\n", old_cost, new_cost); return false; } /* Jump through a lot of hoops to keep the attributes up to date. We do not want to call one of the change address variants that take an offset even though we know the offset in many cases. These assume you are changing where the address is pointing by the offset. */ new_mem = replace_equiv_address_nv (mem, new_addr); if (! validate_change (mem_insn.insn, mem_insn.mem_loc, new_mem, 0)) { if (dump_file) fprintf (dump_file, "validation failure\n"); return false; } /* From here to the end of the function we are committed to the change, i.e. nothing fails. Generate any necessary movs, move any regnotes, and fix up the reg_next_{use,inc_use,def}. */ switch (inc_insn.form) { case FORM_PRE_ADD: /* Replace the addition with a move. Do it at the location of the addition since the operand of the addition may change before the memory reference. */ mov_insn = insert_move_insn_before (inc_insn.insn, inc_insn.reg_res, inc_insn.reg0); move_dead_notes (mov_insn, inc_insn.insn, inc_insn.reg0); regno = REGNO (inc_insn.reg_res); reg_next_def[regno] = mov_insn; reg_next_use[regno] = NULL; regno = REGNO (inc_insn.reg0); reg_next_use[regno] = mov_insn; df_recompute_luids (bb); break; case FORM_POST_INC: regno = REGNO (inc_insn.reg_res); if (reg_next_use[regno] == reg_next_inc_use[regno]) reg_next_inc_use[regno] = NULL; /* Fallthru. */ case FORM_PRE_INC: regno = REGNO (inc_insn.reg_res); reg_next_def[regno] = mem_insn.insn; reg_next_use[regno] = NULL; break; case FORM_POST_ADD: mov_insn = insert_move_insn_before (mem_insn.insn, inc_insn.reg_res, inc_insn.reg0); move_dead_notes (mov_insn, inc_insn.insn, inc_insn.reg0); /* Do not move anything to the mov insn because the instruction pointer for the main iteration has not yet hit that. It is still pointing to the mem insn. */ regno = REGNO (inc_insn.reg_res); reg_next_def[regno] = mem_insn.insn; reg_next_use[regno] = NULL; regno = REGNO (inc_insn.reg0); reg_next_use[regno] = mem_insn.insn; if ((reg_next_use[regno] == reg_next_inc_use[regno]) || (reg_next_inc_use[regno] == inc_insn.insn)) reg_next_inc_use[regno] = NULL; df_recompute_luids (bb); break; case FORM_last: default: gcc_unreachable (); } if (!inc_insn.reg1_is_const) { regno = REGNO (inc_insn.reg1); reg_next_use[regno] = mem_insn.insn; if ((reg_next_use[regno] == reg_next_inc_use[regno]) || (reg_next_inc_use[regno] == inc_insn.insn)) reg_next_inc_use[regno] = NULL; } delete_insn (inc_insn.insn); if (dump_file && mov_insn) { fprintf (dump_file, "inserting mov "); dump_insn_slim (dump_file, mov_insn); } /* Record that this insn has an implicit side effect. */ add_reg_note (mem_insn.insn, REG_INC, inc_reg); if (dump_file) { fprintf (dump_file, "****success "); dump_insn_slim (dump_file, mem_insn.insn); } return true; } /* Try to combine the instruction in INC_INSN with the instruction in MEM_INSN. First the form is determined using the DECISION_TABLE and the results of parsing the INC_INSN and the MEM_INSN. Assuming the form is ok, a prototype new address is built which is passed to ATTEMPT_CHANGE for final processing. */ static bool try_merge (void) { enum gen_form gen_form; rtx mem = *mem_insn.mem_loc; rtx inc_reg = inc_insn.form == FORM_POST_ADD ? inc_insn.reg_res : mem_insn.reg0; /* The width of the mem being accessed. */ int size = GET_MODE_SIZE (GET_MODE (mem)); rtx_insn *last_insn = NULL; machine_mode reg_mode = GET_MODE (inc_reg); switch (inc_insn.form) { case FORM_PRE_ADD: case FORM_PRE_INC: last_insn = mem_insn.insn; break; case FORM_POST_INC: case FORM_POST_ADD: last_insn = inc_insn.insn; break; case FORM_last: default: gcc_unreachable (); } /* Cannot handle auto inc of the stack. */ if (inc_reg == stack_pointer_rtx) { if (dump_file) fprintf (dump_file, "cannot inc stack %d failure\n", REGNO (inc_reg)); return false; } /* Look to see if the inc register is dead after the memory reference. If it is, do not do the combination. */ if (find_regno_note (last_insn, REG_DEAD, REGNO (inc_reg))) { if (dump_file) fprintf (dump_file, "dead failure %d\n", REGNO (inc_reg)); return false; } mem_insn.reg1_state = (mem_insn.reg1_is_const) ? set_inc_state (mem_insn.reg1_val, size) : INC_REG; inc_insn.reg1_state = (inc_insn.reg1_is_const) ? set_inc_state (inc_insn.reg1_val, size) : INC_REG; /* Now get the form that we are generating. */ gen_form = decision_table [inc_insn.reg1_state][mem_insn.reg1_state][inc_insn.form]; if (dbg_cnt (auto_inc_dec) == false) return false; switch (gen_form) { default: case NOTHING: return false; case SIMPLE_PRE_INC: /* ++size */ if (dump_file) fprintf (dump_file, "trying SIMPLE_PRE_INC\n"); return attempt_change (gen_rtx_PRE_INC (reg_mode, inc_reg), inc_reg); break; case SIMPLE_POST_INC: /* size++ */ if (dump_file) fprintf (dump_file, "trying SIMPLE_POST_INC\n"); return attempt_change (gen_rtx_POST_INC (reg_mode, inc_reg), inc_reg); break; case SIMPLE_PRE_DEC: /* --size */ if (dump_file) fprintf (dump_file, "trying SIMPLE_PRE_DEC\n"); return attempt_change (gen_rtx_PRE_DEC (reg_mode, inc_reg), inc_reg); break; case SIMPLE_POST_DEC: /* size-- */ if (dump_file) fprintf (dump_file, "trying SIMPLE_POST_DEC\n"); return attempt_change (gen_rtx_POST_DEC (reg_mode, inc_reg), inc_reg); break; case DISP_PRE: /* ++con */ if (dump_file) fprintf (dump_file, "trying DISP_PRE\n"); return attempt_change (gen_rtx_PRE_MODIFY (reg_mode, inc_reg, gen_rtx_PLUS (reg_mode, inc_reg, inc_insn.reg1)), inc_reg); break; case DISP_POST: /* con++ */ if (dump_file) fprintf (dump_file, "trying POST_DISP\n"); return attempt_change (gen_rtx_POST_MODIFY (reg_mode, inc_reg, gen_rtx_PLUS (reg_mode, inc_reg, inc_insn.reg1)), inc_reg); break; case REG_PRE: /* ++reg */ if (dump_file) fprintf (dump_file, "trying PRE_REG\n"); return attempt_change (gen_rtx_PRE_MODIFY (reg_mode, inc_reg, gen_rtx_PLUS (reg_mode, inc_reg, inc_insn.reg1)), inc_reg); break; case REG_POST: /* reg++ */ if (dump_file) fprintf (dump_file, "trying POST_REG\n"); return attempt_change (gen_rtx_POST_MODIFY (reg_mode, inc_reg, gen_rtx_PLUS (reg_mode, inc_reg, inc_insn.reg1)), inc_reg); break; } } /* Return the next insn that uses (if reg_next_use is passed in NEXT_ARRAY) or defines (if reg_next_def is passed in NEXT_ARRAY) REGNO in BB. */ static rtx_insn * get_next_ref (int regno, basic_block bb, rtx_insn **next_array) { rtx_insn *insn = next_array[regno]; /* Lazy about cleaning out the next_arrays. */ if (insn && BLOCK_FOR_INSN (insn) != bb) { next_array[regno] = NULL; insn = NULL; } return insn; } /* Reverse the operands in a mem insn. */ static void reverse_mem (void) { rtx tmp = mem_insn.reg1; mem_insn.reg1 = mem_insn.reg0; mem_insn.reg0 = tmp; } /* Reverse the operands in a inc insn. */ static void reverse_inc (void) { rtx tmp = inc_insn.reg1; inc_insn.reg1 = inc_insn.reg0; inc_insn.reg0 = tmp; } /* Return true if INSN is of a form "a = b op c" where a and b are regs. op is + if c is a reg and +|- if c is a const. Fill in INC_INSN with what is found. This function is called in two contexts, if BEFORE_MEM is true, this is called for each insn in the basic block. If BEFORE_MEM is false, it is called for the instruction in the block that uses the index register for some memory reference that is currently being processed. */ static bool parse_add_or_inc (rtx_insn *insn, bool before_mem) { rtx pat = single_set (insn); if (!pat) return false; /* Result must be single reg. */ if (!REG_P (SET_DEST (pat))) return false; if ((GET_CODE (SET_SRC (pat)) != PLUS) && (GET_CODE (SET_SRC (pat)) != MINUS)) return false; if (!REG_P (XEXP (SET_SRC (pat), 0))) return false; inc_insn.insn = insn; inc_insn.pat = pat; inc_insn.reg_res = SET_DEST (pat); inc_insn.reg0 = XEXP (SET_SRC (pat), 0); if (rtx_equal_p (inc_insn.reg_res, inc_insn.reg0)) inc_insn.form = before_mem ? FORM_PRE_INC : FORM_POST_INC; else inc_insn.form = before_mem ? FORM_PRE_ADD : FORM_POST_ADD; if (CONST_INT_P (XEXP (SET_SRC (pat), 1))) { /* Process a = b + c where c is a const. */ inc_insn.reg1_is_const = true; if (GET_CODE (SET_SRC (pat)) == PLUS) { inc_insn.reg1 = XEXP (SET_SRC (pat), 1); inc_insn.reg1_val = INTVAL (inc_insn.reg1); } else { inc_insn.reg1_val = -INTVAL (XEXP (SET_SRC (pat), 1)); inc_insn.reg1 = GEN_INT (inc_insn.reg1_val); } return true; } else if ((HAVE_PRE_MODIFY_REG || HAVE_POST_MODIFY_REG) && (REG_P (XEXP (SET_SRC (pat), 1))) && GET_CODE (SET_SRC (pat)) == PLUS) { /* Process a = b + c where c is a reg. */ inc_insn.reg1 = XEXP (SET_SRC (pat), 1); inc_insn.reg1_is_const = false; if (inc_insn.form == FORM_PRE_INC || inc_insn.form == FORM_POST_INC) return true; else if (rtx_equal_p (inc_insn.reg_res, inc_insn.reg1)) { /* Reverse the two operands and turn *_ADD into *_INC since a = c + a. */ reverse_inc (); inc_insn.form = before_mem ? FORM_PRE_INC : FORM_POST_INC; return true; } else return true; } return false; } /* A recursive function that checks all of the mem uses in ADDRESS_OF_X to see if any single one of them is compatible with what has been found in inc_insn. -1 is returned for success. 0 is returned if nothing was found and 1 is returned for failure. */ static int find_address (rtx *address_of_x) { rtx x = *address_of_x; enum rtx_code code = GET_CODE (x); const char *const fmt = GET_RTX_FORMAT (code); int i; int value = 0; int tem; if (code == MEM && rtx_equal_p (XEXP (x, 0), inc_insn.reg_res)) { /* Match with *reg0. */ mem_insn.mem_loc = address_of_x; mem_insn.reg0 = inc_insn.reg_res; mem_insn.reg1_is_const = true; mem_insn.reg1_val = 0; mem_insn.reg1 = GEN_INT (0); return -1; } if (code == MEM && GET_CODE (XEXP (x, 0)) == PLUS && rtx_equal_p (XEXP (XEXP (x, 0), 0), inc_insn.reg_res)) { rtx b = XEXP (XEXP (x, 0), 1); mem_insn.mem_loc = address_of_x; mem_insn.reg0 = inc_insn.reg_res; mem_insn.reg1 = b; mem_insn.reg1_is_const = inc_insn.reg1_is_const; if (CONST_INT_P (b)) { /* Match with *(reg0 + reg1) where reg1 is a const. */ HOST_WIDE_INT val = INTVAL (b); if (inc_insn.reg1_is_const && (inc_insn.reg1_val == val || inc_insn.reg1_val == -val)) { mem_insn.reg1_val = val; return -1; } } else if (!inc_insn.reg1_is_const && rtx_equal_p (inc_insn.reg1, b)) /* Match with *(reg0 + reg1). */ return -1; } if (code == SIGN_EXTRACT || code == ZERO_EXTRACT) { /* If REG occurs inside a MEM used in a bit-field reference, that is unacceptable. */ if (find_address (&XEXP (x, 0))) return 1; } if (x == inc_insn.reg_res) return 1; /* Time for some deep diving. */ for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--) { if (fmt[i] == 'e') { tem = find_address (&XEXP (x, i)); /* If this is the first use, let it go so the rest of the insn can be checked. */ if (value == 0) value = tem; else if (tem != 0) /* More than one match was found. */ return 1; } else if (fmt[i] == 'E') { int j; for (j = XVECLEN (x, i) - 1; j >= 0; j--) { tem = find_address (&XVECEXP (x, i, j)); /* If this is the first use, let it go so the rest of the insn can be checked. */ if (value == 0) value = tem; else if (tem != 0) /* More than one match was found. */ return 1; } } } return value; } /* Once a suitable mem reference has been found and the MEM_INSN structure has been filled in, FIND_INC is called to see if there is a suitable add or inc insn that follows the mem reference and determine if it is suitable to merge. In the case where the MEM_INSN has two registers in the reference, this function may be called recursively. The first time looking for an add of the first register, and if that fails, looking for an add of the second register. The FIRST_TRY parameter is used to only allow the parameters to be reversed once. */ static bool find_inc (bool first_try) { rtx_insn *insn; basic_block bb = BLOCK_FOR_INSN (mem_insn.insn); rtx_insn *other_insn; df_ref def; /* Make sure this reg appears only once in this insn. */ if (count_occurrences (PATTERN (mem_insn.insn), mem_insn.reg0, 1) != 1) { if (dump_file) fprintf (dump_file, "mem count failure\n"); return false; } if (dump_file) dump_mem_insn (dump_file); /* Find the next use that is an inc. */ insn = get_next_ref (REGNO (mem_insn.reg0), BLOCK_FOR_INSN (mem_insn.insn), reg_next_inc_use); if (!insn) return false; /* Even though we know the next use is an add or inc because it came from the reg_next_inc_use, we must still reparse. */ if (!parse_add_or_inc (insn, false)) { /* Next use was not an add. Look for one extra case. It could be that we have: *(a + b) ...= a; ...= b + a if we reverse the operands in the mem ref we would find this. Only try it once though. */ if (first_try && !mem_insn.reg1_is_const) { reverse_mem (); return find_inc (false); } else return false; } /* Need to assure that none of the operands of the inc instruction are assigned to by the mem insn. */ FOR_EACH_INSN_DEF (def, mem_insn.insn) { unsigned int regno = DF_REF_REGNO (def); if ((regno == REGNO (inc_insn.reg0)) || (regno == REGNO (inc_insn.reg_res))) { if (dump_file) fprintf (dump_file, "inc conflicts with store failure.\n"); return false; } if (!inc_insn.reg1_is_const && (regno == REGNO (inc_insn.reg1))) { if (dump_file) fprintf (dump_file, "inc conflicts with store failure.\n"); return false; } } if (dump_file) dump_inc_insn (dump_file); if (inc_insn.form == FORM_POST_ADD) { /* Make sure that there is no insn that assigns to inc_insn.res between the mem_insn and the inc_insn. */ rtx_insn *other_insn = get_next_ref (REGNO (inc_insn.reg_res), BLOCK_FOR_INSN (mem_insn.insn), reg_next_def); if (other_insn != inc_insn.insn) { if (dump_file) fprintf (dump_file, "result of add is assigned to between mem and inc insns.\n"); return false; } other_insn = get_next_ref (REGNO (inc_insn.reg_res), BLOCK_FOR_INSN (mem_insn.insn), reg_next_use); if (other_insn && (other_insn != inc_insn.insn) && (DF_INSN_LUID (inc_insn.insn) > DF_INSN_LUID (other_insn))) { if (dump_file) fprintf (dump_file, "result of add is used between mem and inc insns.\n"); return false; } /* For the post_add to work, the result_reg of the inc must not be used in the mem insn since this will become the new index register. */ if (reg_overlap_mentioned_p (inc_insn.reg_res, PATTERN (mem_insn.insn))) { if (dump_file) fprintf (dump_file, "base reg replacement failure.\n"); return false; } } if (mem_insn.reg1_is_const) { if (mem_insn.reg1_val == 0) { if (!inc_insn.reg1_is_const) { /* The mem looks like *r0 and the rhs of the add has two registers. */ int luid = DF_INSN_LUID (inc_insn.insn); if (inc_insn.form == FORM_POST_ADD) { /* The trick is that we are not going to increment r0, we are going to increment the result of the add insn. For this trick to be correct, the result reg of the inc must be a valid addressing reg. */ addr_space_t as = MEM_ADDR_SPACE (*mem_insn.mem_loc); if (GET_MODE (inc_insn.reg_res) != targetm.addr_space.address_mode (as)) { if (dump_file) fprintf (dump_file, "base reg mode failure.\n"); return false; } /* We also need to make sure that the next use of inc result is after the inc. */ other_insn = get_next_ref (REGNO (inc_insn.reg1), bb, reg_next_use); if (other_insn && luid > DF_INSN_LUID (other_insn)) return false; if (!rtx_equal_p (mem_insn.reg0, inc_insn.reg0)) reverse_inc (); } other_insn = get_next_ref (REGNO (inc_insn.reg1), bb, reg_next_def); if (other_insn && luid > DF_INSN_LUID (other_insn)) return false; } } /* Both the inc/add and the mem have a constant. Need to check that the constants are ok. */ else if ((mem_insn.reg1_val != inc_insn.reg1_val) && (mem_insn.reg1_val != -inc_insn.reg1_val)) return false; } else { /* The mem insn is of the form *(a + b) where a and b are both regs. It may be that in order to match the add or inc we need to treat it as if it was *(b + a). It may also be that the add is of the form a + c where c does not match b and then we just abandon this. */ int luid = DF_INSN_LUID (inc_insn.insn); rtx_insn *other_insn; /* Make sure this reg appears only once in this insn. */ if (count_occurrences (PATTERN (mem_insn.insn), mem_insn.reg1, 1) != 1) return false; if (inc_insn.form == FORM_POST_ADD) { /* For this trick to be correct, the result reg of the inc must be a valid addressing reg. */ addr_space_t as = MEM_ADDR_SPACE (*mem_insn.mem_loc); if (GET_MODE (inc_insn.reg_res) != targetm.addr_space.address_mode (as)) { if (dump_file) fprintf (dump_file, "base reg mode failure.\n"); return false; } if (rtx_equal_p (mem_insn.reg0, inc_insn.reg0)) { if (!rtx_equal_p (mem_insn.reg1, inc_insn.reg1)) { /* See comment above on find_inc (false) call. */ if (first_try) { reverse_mem (); return find_inc (false); } else return false; } /* Need to check that there are no assignments to b before the add insn. */ other_insn = get_next_ref (REGNO (inc_insn.reg1), bb, reg_next_def); if (other_insn && luid > DF_INSN_LUID (other_insn)) return false; /* All ok for the next step. */ } else { /* We know that mem_insn.reg0 must equal inc_insn.reg1 or else we would not have found the inc insn. */ reverse_mem (); if (!rtx_equal_p (mem_insn.reg0, inc_insn.reg0)) { /* See comment above on find_inc (false) call. */ if (first_try) return find_inc (false); else return false; } /* To have gotten here know that. *(b + a) ... = (b + a) We also know that the lhs of the inc is not b or a. We need to make sure that there are no assignments to b between the mem ref and the inc. */ other_insn = get_next_ref (REGNO (inc_insn.reg0), bb, reg_next_def); if (other_insn && luid > DF_INSN_LUID (other_insn)) return false; } /* Need to check that the next use of the add result is later than add insn since this will be the reg incremented. */ other_insn = get_next_ref (REGNO (inc_insn.reg_res), bb, reg_next_use); if (other_insn && luid > DF_INSN_LUID (other_insn)) return false; } else /* FORM_POST_INC. There is less to check here because we know that operands must line up. */ { if (!rtx_equal_p (mem_insn.reg1, inc_insn.reg1)) /* See comment above on find_inc (false) call. */ { if (first_try) { reverse_mem (); return find_inc (false); } else return false; } /* To have gotten here know that. *(a + b) ... = (a + b) We also know that the lhs of the inc is not b. We need to make sure that there are no assignments to b between the mem ref and the inc. */ other_insn = get_next_ref (REGNO (inc_insn.reg1), bb, reg_next_def); if (other_insn && luid > DF_INSN_LUID (other_insn)) return false; } } if (inc_insn.form == FORM_POST_INC) { other_insn = get_next_ref (REGNO (inc_insn.reg0), bb, reg_next_use); /* When we found inc_insn, we were looking for the next add or inc, not the next insn that used the reg. Because we are going to increment the reg in this form, we need to make sure that there were no intervening uses of reg. */ if (inc_insn.insn != other_insn) return false; } return try_merge (); } /* A recursive function that walks ADDRESS_OF_X to find all of the mem uses in pat that could be used as an auto inc or dec. It then calls FIND_INC for each one. */ static bool find_mem (rtx *address_of_x) { rtx x = *address_of_x; enum rtx_code code = GET_CODE (x); const char *const fmt = GET_RTX_FORMAT (code); int i; if (code == MEM && REG_P (XEXP (x, 0))) { /* Match with *reg0. */ mem_insn.mem_loc = address_of_x; mem_insn.reg0 = XEXP (x, 0); mem_insn.reg1_is_const = true; mem_insn.reg1_val = 0; mem_insn.reg1 = GEN_INT (0); if (find_inc (true)) return true; } if (code == MEM && GET_CODE (XEXP (x, 0)) == PLUS && REG_P (XEXP (XEXP (x, 0), 0))) { rtx reg1 = XEXP (XEXP (x, 0), 1); mem_insn.mem_loc = address_of_x; mem_insn.reg0 = XEXP (XEXP (x, 0), 0); mem_insn.reg1 = reg1; if (CONST_INT_P (reg1)) { mem_insn.reg1_is_const = true; /* Match with *(reg0 + c) where c is a const. */ mem_insn.reg1_val = INTVAL (reg1); if (find_inc (true)) return true; } else if (REG_P (reg1)) { /* Match with *(reg0 + reg1). */ mem_insn.reg1_is_const = false; if (find_inc (true)) return true; } } if (code == SIGN_EXTRACT || code == ZERO_EXTRACT) { /* If REG occurs inside a MEM used in a bit-field reference, that is unacceptable. */ return false; } /* Time for some deep diving. */ for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--) { if (fmt[i] == 'e') { if (find_mem (&XEXP (x, i))) return true; } else if (fmt[i] == 'E') { int j; for (j = XVECLEN (x, i) - 1; j >= 0; j--) if (find_mem (&XVECEXP (x, i, j))) return true; } } return false; } /* Try to combine all incs and decs by constant values with memory references in BB. */ static void merge_in_block (int max_reg, basic_block bb) { rtx_insn *insn; rtx_insn *curr; int success_in_block = 0; if (dump_file) fprintf (dump_file, "\n\nstarting bb %d\n", bb->index); FOR_BB_INSNS_REVERSE_SAFE (bb, insn, curr) { bool insn_is_add_or_inc = true; if (!NONDEBUG_INSN_P (insn)) continue; /* This continue is deliberate. We do not want the uses of the jump put into reg_next_use because it is not considered safe to combine a preincrement with a jump. */ if (JUMP_P (insn)) continue; if (dump_file) dump_insn_slim (dump_file, insn); /* Does this instruction increment or decrement a register? */ if (parse_add_or_inc (insn, true)) { int regno = REGNO (inc_insn.reg_res); /* Cannot handle case where there are three separate regs before a mem ref. Too many moves would be needed to be profitable. */ if ((inc_insn.form == FORM_PRE_INC) || inc_insn.reg1_is_const) { mem_insn.insn = get_next_ref (regno, bb, reg_next_use); if (mem_insn.insn) { bool ok = true; if (!inc_insn.reg1_is_const) { /* We are only here if we are going to try a HAVE_*_MODIFY_REG type transformation. c is a reg and we must sure that the path from the inc_insn to the mem_insn.insn is both def and use clear of c because the inc insn is going to move into the mem_insn.insn. */ int luid = DF_INSN_LUID (mem_insn.insn); rtx_insn *other_insn = get_next_ref (REGNO (inc_insn.reg1), bb, reg_next_use); if (other_insn && luid > DF_INSN_LUID (other_insn)) ok = false; other_insn = get_next_ref (REGNO (inc_insn.reg1), bb, reg_next_def); if (other_insn && luid > DF_INSN_LUID (other_insn)) ok = false; } if (dump_file) dump_inc_insn (dump_file); if (ok && find_address (&PATTERN (mem_insn.insn)) == -1) { if (dump_file) dump_mem_insn (dump_file); if (try_merge ()) { success_in_block++; insn_is_add_or_inc = false; } } } } } else { insn_is_add_or_inc = false; mem_insn.insn = insn; if (find_mem (&PATTERN (insn))) success_in_block++; } /* If the inc insn was merged with a mem, the inc insn is gone and there is noting to update. */ if (df_insn_info *insn_info = DF_INSN_INFO_GET (insn)) { df_ref def, use; /* Need to update next use. */ FOR_EACH_INSN_INFO_DEF (def, insn_info) { reg_next_use[DF_REF_REGNO (def)] = NULL; reg_next_inc_use[DF_REF_REGNO (def)] = NULL; reg_next_def[DF_REF_REGNO (def)] = insn; } FOR_EACH_INSN_INFO_USE (use, insn_info) { reg_next_use[DF_REF_REGNO (use)] = insn; if (insn_is_add_or_inc) reg_next_inc_use[DF_REF_REGNO (use)] = insn; else reg_next_inc_use[DF_REF_REGNO (use)] = NULL; } } else if (dump_file) fprintf (dump_file, "skipping update of deleted insn %d\n", INSN_UID (insn)); } /* If we were successful, try again. There may have been several opportunities that were interleaved. This is rare but gcc.c-torture/compile/pr17273.c actually exhibits this. */ if (success_in_block) { /* In this case, we must clear these vectors since the trick of testing if the stale insn in the block will not work. */ memset (reg_next_use, 0, max_reg * sizeof (rtx)); memset (reg_next_inc_use, 0, max_reg * sizeof (rtx)); memset (reg_next_def, 0, max_reg * sizeof (rtx)); df_recompute_luids (bb); merge_in_block (max_reg, bb); } } #endif /* Discover auto-inc auto-dec instructions. */ namespace { const pass_data pass_data_inc_dec = { RTL_PASS, /* type */ "auto_inc_dec", /* name */ OPTGROUP_NONE, /* optinfo_flags */ TV_AUTO_INC_DEC, /* tv_id */ 0, /* properties_required */ 0, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ TODO_df_finish, /* todo_flags_finish */ }; class pass_inc_dec : public rtl_opt_pass { public: pass_inc_dec (gcc::context *ctxt) : rtl_opt_pass (pass_data_inc_dec, ctxt) {} /* opt_pass methods: */ virtual bool gate (function *) { #ifdef AUTO_INC_DEC return (optimize > 0 && flag_auto_inc_dec); #else return false; #endif } unsigned int execute (function *); }; // class pass_inc_dec unsigned int pass_inc_dec::execute (function *fun ATTRIBUTE_UNUSED) { #ifdef AUTO_INC_DEC basic_block bb; int max_reg = max_reg_num (); if (!initialized) init_decision_table (); mem_tmp = gen_rtx_MEM (Pmode, NULL_RTX); df_note_add_problem (); df_analyze (); reg_next_use = XCNEWVEC (rtx_insn *, max_reg); reg_next_inc_use = XCNEWVEC (rtx_insn *, max_reg); reg_next_def = XCNEWVEC (rtx_insn *, max_reg); FOR_EACH_BB_FN (bb, fun) merge_in_block (max_reg, bb); free (reg_next_use); free (reg_next_inc_use); free (reg_next_def); mem_tmp = NULL; #endif return 0; } } // anon namespace rtl_opt_pass * make_pass_inc_dec (gcc::context *ctxt) { return new pass_inc_dec (ctxt); }
Java
/* Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 Mark Aylett <mark.aylett@gmail.com> This file is part of Aug written by Mark Aylett. Aug is released under the GPL with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. Aug is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Aug is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef AUGUTIL_PWD_H #define AUGUTIL_PWD_H /** * @file augutil/pwd.h * * Password functions. */ #include "augutil/md5.h" #define AUG_MAXPASSWORD 128 typedef char aug_pwd_t[AUG_MAXPASSWORD + 1]; AUGUTIL_API char* aug_getpass(const char* prompt, char* buf, size_t len); AUGUTIL_API char* aug_digestpass(const char* username, const char* realm, const char* password, aug_md5base64_t base64); #endif /* AUGUTIL_PWD_H */
Java
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Monroe puts in 24, Knicks defeat the Pistons 121 to 115</title> <link rel="stylesheet" type="text/css" href="../css/style.css"> </head> <body> <h1>Monroe puts in 24, Knicks defeat the Pistons 121 to 115</h1> </br> <h2 style="color:gray">by NBANLP Recap Generator</h2> </br></br> <img src="../img/08/01.jpg" alt="No image loaded" align="right" style="height:50%; width:50%;margin-left:20px;margin-bottom:20px;"> <p>Greg Monroe recorded 24 points for the Pistons. Andrea Bargnani contributed well to the Knicks total, recording 23 points. The Pistons largest lead was by 18 with 3 minutes remaining in the 2nd.</p> <p>Greg put up 24 points for the Pistons in a good scoring contribution. Monroe contributed 2 assists and 13 rebounds.</p> <p>Andrea made contributions in scoring with 23 points for the Knicks. Bargnani got 4 assists and 12 rebounds for the Knicks.</p> <p>The Pistons were up by as much as 18 points in the 2nd with a 51-33 lead.</p> <p>Drummond fouled out with 6:03 remaining in double overtime.</p> <p>Galloway recorded his last foul with 6:00 left in double overtime.</p> <p>Smith recorded his last foul with 6:00 remaining in double overtime.</p> <p>This result puts Pistons at 23-35 for the season, while the Knicks are 11-45. The Pistons have lost their last 2 games.</p> <p>Andre Drummond, Reggie Jackson, and Kentavious Caldwell-Pope combined for 46 points. Each scoring 15, 14, and 17 points respectively. Drummond recorded 1 assists and 15 rebounds for the Pistons. Jackson got 5 assists and 5 rebounds for the Pistons. Caldwell-Pope got 3 assists and 6 rebounds for the Pistons. Greg led the Pistons putting up 24 points, 2 assists, and 13 rebounds. Andrea led the Knicks putting up a total 23 points, 4 assists, and 12 rebounds.</p> </body> </html>
Java
<div class="clear left"> <div class="full-page-span33 home-island"> <div class="img-island isle1"> <h3>Isle Title 1</h3> <p class="tl"> Mei duis denique nostrum et, in pro choro</p> </div> <div> <p>Lorem ipsum Mei duis denique nostrum et, in pro choro consul, eam deterruisset definitionem te. Ne nam prima essent delicata, quie Sacto is. In fabellas technician.</p> </div> </div> <div class="full-page-span33 home-island"> <div class="img-island isle2"> <h3>Isle Title 2</h3> <p class="bl">Ne Nam Prima Essent Delicata</p> </div> <div> <p>Ot usu ut oblique senserit, ne usu saepe affert definitiones, mel euripidis persequeris id. Pri ad iudico conceptam, nostro apeirian no has Roseville.</p> </div> </div> <div class="full-page-span33 home-island"> <div class="img-island isle3"> <h3>Isle Title 3</h3> <p class="tr">Ut Oratio Moleskine Quo Prezi</p> </div> <div> <p> Ipsum cotidieque definitiones eos no, at dicant perfecto sea. At mollis definitionem duo, ludus primis sanctus id eam, an mei rebum debitis.</p> </div> </div> </div> <div class="clear left"> <div class="full-page-span33 home-facts"> <h3 class="med-body-headline">Our Services Include:</h3> <ul> <li>Fulli Assueverit</li> <li>Centrant Ailey Redactio Athasn</li> <li>Electric Oblique Senserit</li> <li>Nec Ro Aperiam</li> <li>At Mollis Definitionem Duo</li> <li>Radirum A Denique Adversarium namei</li> <ul> </div> <div class="full-page-span33 home-facts hf2nd-col"> <ul> <li>Tel Hasadipsci &#38; Ludis</li> <li>Respado Cotidieque &#38; Primus</li> <li>PAVT Monestatis</li> <li>Listaray, Billum &#38; Inlused</li> <li>24 Hour Elequist Sanktus</li> <li>Fresca Estinastos</li> <ul> </div> <div class="full-page-span33 home-facts hf2nd-col last-col"> <a href="#" class="frst-grn-btn tighten-text"><span class="subtext">Nov Ask Selen</span><br /> Falli Eloquentiam</a> <a href="#" class="lt-grn-btn tighten-text">Eleifend Asservated<br /><span class="subtext">Utom Requiem</span></a> </div> </div>
Java
/* * Copyright (C) 2003-2011 The Music Player Daemon Project * http://www.musicpd.org * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include "pcm_volume.h" #include "pcm_utils.h" #include "audio_format.h" #include <glib.h> #include <stdint.h> #include <string.h> #undef G_LOG_DOMAIN #define G_LOG_DOMAIN "pcm_volume" static void pcm_volume_change_8(int8_t *buffer, const int8_t *end, int volume) { while (buffer < end) { int32_t sample = *buffer; sample = (sample * volume + pcm_volume_dither() + PCM_VOLUME_1 / 2) / PCM_VOLUME_1; *buffer++ = pcm_range(sample, 8); } } static void pcm_volume_change_16(int16_t *buffer, const int16_t *end, int volume) { while (buffer < end) { int32_t sample = *buffer; sample = (sample * volume + pcm_volume_dither() + PCM_VOLUME_1 / 2) / PCM_VOLUME_1; *buffer++ = pcm_range(sample, 16); } } #ifdef __i386__ /** * Optimized volume function for i386. Use the EDX:EAX 2*32 bit * multiplication result instead of emulating 64 bit multiplication. */ static inline int32_t pcm_volume_sample_24(int32_t sample, int32_t volume, G_GNUC_UNUSED int32_t dither) { int32_t result; asm(/* edx:eax = sample * volume */ "imul %2\n" /* "add %3, %1\n" dithering disabled for now, because we have no overflow check - is dithering really important here? */ /* eax = edx:eax / PCM_VOLUME_1 */ "sal $22, %%edx\n" "shr $10, %1\n" "or %%edx, %1\n" : "=a"(result) : "0"(sample), "r"(volume) /* , "r"(dither) */ : "edx" ); return result; } #endif static void pcm_volume_change_24(int32_t *buffer, const int32_t *end, int volume) { while (buffer < end) { #ifdef __i386__ /* assembly version for i386 */ int32_t sample = *buffer; sample = pcm_volume_sample_24(sample, volume, pcm_volume_dither()); #else /* portable version */ int64_t sample = *buffer; sample = (sample * volume + pcm_volume_dither() + PCM_VOLUME_1 / 2) / PCM_VOLUME_1; #endif *buffer++ = pcm_range(sample, 24); } } static void pcm_volume_change_32(int32_t *buffer, const int32_t *end, int volume) { while (buffer < end) { #ifdef __i386__ /* assembly version for i386 */ int32_t sample = *buffer; *buffer++ = pcm_volume_sample_24(sample, volume, 0); #else /* portable version */ int64_t sample = *buffer; sample = (sample * volume + pcm_volume_dither() + PCM_VOLUME_1 / 2) / PCM_VOLUME_1; *buffer++ = pcm_range_64(sample, 32); #endif } } static void pcm_volume_change_float(float *buffer, const float *end, float volume) { while (buffer < end) { float sample = *buffer; sample *= volume; *buffer++ = sample; } } bool pcm_volume(void *buffer, size_t length, enum sample_format format, int volume) { if (volume == PCM_VOLUME_1) return true; if (volume <= 0) { memset(buffer, 0, length); return true; } const void *end = pcm_end_pointer(buffer, length); switch (format) { case SAMPLE_FORMAT_UNDEFINED: case SAMPLE_FORMAT_S24: case SAMPLE_FORMAT_DSD: case SAMPLE_FORMAT_DSD_LSBFIRST: /* not implemented */ return false; case SAMPLE_FORMAT_S8: pcm_volume_change_8(buffer, end, volume); return true; case SAMPLE_FORMAT_S16: pcm_volume_change_16(buffer, end, volume); return true; case SAMPLE_FORMAT_S24_P32: pcm_volume_change_24(buffer, end, volume); return true; case SAMPLE_FORMAT_S32: pcm_volume_change_32(buffer, end, volume); return true; case SAMPLE_FORMAT_FLOAT: pcm_volume_change_float(buffer, end, pcm_volume_to_float(volume)); return true; } /* unreachable */ assert(false); return false; }
Java
<?php /* $Id$ osCmax e-Commerce http://www.oscmax.com Copyright 2000 - 2011 osCmax Released under the GNU General Public License */ define('HEADING_TITLE', 'Ch&egrave;ques cadeaux envoy&eacute;s'); define('TABLE_HEADING_SENDERS_NAME', 'Nom de l\'expéditeur'); define('TABLE_HEADING_VOUCHER_VALUE', 'Valeur du bon'); define('TABLE_HEADING_VOUCHER_CODE', 'Code du bon'); define('TABLE_HEADING_DATE_SENT', 'Date de l\'envoi'); define('TABLE_HEADING_ACTION', 'Action'); define('TEXT_INFO_SENDERS_ID', 'Identifiant de l\'exp&eacute;diteur :'); define('TEXT_INFO_AMOUNT_SENT', 'Montant envoy&eacute; :'); define('TEXT_INFO_DATE_SENT', 'Date de l\'envoi :'); define('TEXT_INFO_VOUCHER_CODE', 'Code du ch&egrave;que :'); define('TEXT_INFO_EMAIL_ADDRESS', 'Adresse email :'); define('TEXT_INFO_DATE_REDEEMED', 'Date de validation :'); define('TEXT_INFO_IP_ADDRESS', 'Adresse IP :'); define('TEXT_INFO_CUSTOMERS_ID', 'Identifiant du client :'); define('TEXT_INFO_NOT_REDEEMED', 'Non valid&eacute;'); ?>
Java
# icprot Web application for displaying phylogeny and results of onekp.com data analysis
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="/benchmark/js/jquery.min.js"></script> <script type="text/javascript" src="/benchmark/js/js.cookie.js"></script> <title>BenchmarkTest01209</title> </head> <body> <form action="/benchmark/sqli-02/BenchmarkTest01209" method="POST" id="FormBenchmarkTest01209"> <div><label>Please explain your answer:</label></div> <br/> <div><textarea rows="4" cols="50" id="BenchmarkTest01209Area" name="BenchmarkTest01209Area"></textarea></div> <div><label>Any additional note for the reviewer:</label></div> <div><input type="text" id="answer" name="answer"></input></div> <br/> <div><label>An AJAX request will be sent with a header named BenchmarkTest01209 and value:</label> <input type="text" id="BenchmarkTest01209" name="BenchmarkTest01209" value="bar" class="safe"></input></div> <div><input type="button" id="login-btn" value="Login" onclick="submitForm()" /></div> </form> <div id="ajax-form-msg1"><pre><code class="prettyprint" id="code"></code></pre></div> <script> $('.safe').keypress(function (e) { if (e.which == 13) { submitForm(); return false; } }); function submitForm() { var formData = $("#FormBenchmarkTest01209").serialize(); var URL = $("#FormBenchmarkTest01209").attr("action"); var text = $("#FormBenchmarkTest01209 input[id=BenchmarkTest01209]").val(); var xhr = new XMLHttpRequest(); xhr.open("POST", URL, true); xhr.setRequestHeader('BenchmarkTest01209', text ); xhr.onreadystatechange = function () { if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) { $("#code").html(xhr.responseText); } else { $("#code").html("Error " + xhr.status + " occurred."); } } xhr.send(formData); } function escapeRegExp(str) { return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); } function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } String.prototype.decodeEscapeSequence = function() { var txt = replaceAll(this,";",""); txt = replaceAll(txt,"&#","\\"); return txt.replace(/\\x([0-9A-Fa-f]{2})/g, function() { return String.fromCharCode(parseInt(arguments[1], 16)); }); }; </script> </body> </html>
Java
/* * Copyright (C) 2008 by NXP Semiconductors * All rights reserved. * * @Author: Kevin Wells * @Descr: LPC3250 SLC NAND controller interface support functions * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include "lpc3250.h" #include <nand.h> #include <asm/errno.h> #include <asm/io.h> #define NAND_ALE_OFFS 4 #define NAND_CLE_OFFS 8 #define NAND_LARGE_BLOCK_PAGE_SIZE 2048 #define NAND_SMALL_BLOCK_PAGE_SIZE 512 static struct nand_ecclayout lpc32xx_nand_oob_16 = { .eccbytes = 6, .eccpos = {10, 11, 12, 13, 14, 15}, .oobfree = { {.offset = 0, . length = 4}, {.offset = 6, . length = 4} } }; extern int nand_correct_data(struct mtd_info *mtd, u_char *dat, u_char *read_ecc, u_char *calc_ecc); /* * DMA Descriptors * For Large Block: 17 descriptors = ((16 Data and ECC Read) + 1 Spare Area) * For Small Block: 5 descriptors = ((4 Data and ECC Read) + 1 Spare Area) */ static dmac_ll_t dmalist[(CONFIG_SYS_NAND_ECCSIZE/256) * 2 + 1]; static uint32_t ecc_buffer[8]; /* MAX ECC size */ static int dmachan = -1; #define XFER_PENDING ((SLCNAND->slc_stat & SLCSTAT_DMA_FIFO) | SLCNAND->slc_tc) static void lpc32xx_nand_init(void) { /* Enable clocks to the SLC NAND controller */ CLKPWR->clkpwr_nand_clk_ctrl = (CLKPWR_NANDCLK_SEL_SLC | CLKPWR_NANDCLK_SLCCLK_EN); /* Reset SLC NAND controller & clear ECC */ SLCNAND->slc_ctrl = (SLCCTRL_SW_RESET | SLCCTRL_ECC_CLEAR); /* 8-bit bus, no DMA, CE normal */ SLCNAND->slc_cfg = 0; /* Interrupts disabled and cleared */ SLCNAND->slc_ien = 0; SLCNAND->slc_icr = (SLCSTAT_INT_TC | SLCSTAT_INT_RDY_EN); SLCNAND->slc_tac = LPC32XX_SLC_NAND_TIMING; } static void lpc32xx_nand_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int ctrl) { struct nand_chip *this = mtd->priv; ulong IO_ADDR_W; if (ctrl & NAND_CTRL_CHANGE) { IO_ADDR_W = (ulong) this->IO_ADDR_W; IO_ADDR_W &= ~(NAND_CLE_OFFS | NAND_ALE_OFFS); if ( ctrl & NAND_CLE ) { IO_ADDR_W |= NAND_CLE_OFFS; } else if ( ctrl & NAND_ALE ) { IO_ADDR_W |= NAND_ALE_OFFS; } if ( ctrl & NAND_NCE ) { SLCNAND->slc_cfg |= SLCCFG_CE_LOW; } else { SLCNAND->slc_cfg &= ~SLCCFG_CE_LOW; } this->IO_ADDR_W = (void *) IO_ADDR_W; } if (cmd != NAND_CMD_NONE) { writel(cmd, this->IO_ADDR_W); } } static int lpc32xx_nand_ready(struct mtd_info *mtd) { /* Check the SLC NAND controller status */ return (SLCNAND->slc_stat & SLCSTAT_NAND_READY); } static u_char lpc32xx_read_byte(struct mtd_info *mtd) { struct nand_chip *this = mtd->priv; unsigned long *pReg = (unsigned long *) this->IO_ADDR_R; volatile unsigned long tmp32; tmp32 = *pReg; return (u_char) tmp32; } /* * lpc32xx_verify_buf - [DEFAULT] Verify chip data against buffer * mtd: MTD device structure * buf: buffer containing the data to compare * len: number of bytes to compare * * Default verify function for 8bit buswith */ static int lpc32xx_verify_buf(struct mtd_info *mtd, const u_char *buf, int len) { int i; struct nand_chip *this = mtd->priv; unsigned long *pReg = (unsigned long *) this->IO_ADDR_R; volatile unsigned long tmp32; for (i=0; i<len; i++) { tmp32 = *pReg; if (buf[i] != (u_char) tmp32) return -EFAULT; } return 0; } /* Prepares DMA descriptors for NAND RD/WR operations */ /* If the size is < 256 Bytes then it is assumed to be * an OOB transfer */ static void lpc32xx_nand_dma_configure(struct nand_chip *chip, const void * buffer, int size, int read) { uint32_t i, dmasrc, ctrl, ecc_ctrl, oob_ctrl, dmadst; void __iomem * base = chip->IO_ADDR_R; uint32_t *ecc_gen = ecc_buffer; /* * CTRL descriptor entry for reading ECC * Copy Multiple times to sync DMA with Flash Controller */ ecc_ctrl = (0x5 | DMAC_CHAN_SRC_BURST_1 | DMAC_CHAN_DEST_BURST_1 | DMAC_CHAN_SRC_WIDTH_32 | DMAC_CHAN_DEST_WIDTH_32 | DMAC_CHAN_DEST_AHB1); /* CTRL descriptor entry for reading/writing Data */ ctrl = 64 | /* 256/4 */ DMAC_CHAN_SRC_BURST_4 | DMAC_CHAN_DEST_BURST_4 | DMAC_CHAN_SRC_WIDTH_32 | DMAC_CHAN_DEST_WIDTH_32 | DMAC_CHAN_DEST_AHB1; /* CTRL descriptor entry for reading/writing Spare Area */ oob_ctrl = ((CONFIG_SYS_NAND_OOBSIZE / 4) | DMAC_CHAN_SRC_BURST_4 | DMAC_CHAN_DEST_BURST_4 | DMAC_CHAN_SRC_WIDTH_32 | DMAC_CHAN_DEST_WIDTH_32 | DMAC_CHAN_DEST_AHB1); if (read) { dmasrc = (uint32_t) (base + offsetof(SLCNAND_REGS_T, slc_dma_data)); dmadst = (uint32_t) (buffer); ctrl |= DMAC_CHAN_DEST_AUTOINC; } else { dmadst = (uint32_t) (base + offsetof(SLCNAND_REGS_T, slc_dma_data)); dmasrc = (uint32_t) (buffer); ctrl |= DMAC_CHAN_SRC_AUTOINC; } /* * Write Operation Sequence for Small Block NAND * ---------------------------------------------------------- * 1. X'fer 256 bytes of data from Memory to Flash. * 2. Copy generated ECC data from Register to Spare Area * 3. X'fer next 256 bytes of data from Memory to Flash. * 4. Copy generated ECC data from Register to Spare Area. * 5. X'fer 16 byets of Spare area from Memory to Flash. * Read Operation Sequence for Small Block NAND * ---------------------------------------------------------- * 1. X'fer 256 bytes of data from Flash to Memory. * 2. Copy generated ECC data from Register to ECC calc Buffer. * 3. X'fer next 256 bytes of data from Flash to Memory. * 4. Copy generated ECC data from Register to ECC calc Buffer. * 5. X'fer 16 bytes of Spare area from Flash to Memory. * Write Operation Sequence for Large Block NAND * ---------------------------------------------------------- * 1. Steps(1-4) of Write Operations repeate for four times * which generates 16 DMA descriptors to X'fer 2048 bytes of * data & 32 bytes of ECC data. * 2. X'fer 64 bytes of Spare area from Memory to Flash. * Read Operation Sequence for Large Block NAND * ---------------------------------------------------------- * 1. Steps(1-4) of Read Operations repeate for four times * which generates 16 DMA descriptors to X'fer 2048 bytes of * data & 32 bytes of ECC data. * 2. X'fer 64 bytes of Spare area from Flash to Memory. */ for (i = 0; i < size/256; i++) { dmalist[i*2].dma_src = (read ?(dmasrc) :(dmasrc + (i*256))); dmalist[i*2].dma_dest = (read ?(dmadst + (i*256)) :dmadst); dmalist[i*2].next_lli = (uint32_t) & dmalist[(i*2)+1]; dmalist[i*2].next_ctrl = ctrl; dmalist[(i*2) + 1].dma_src = (uint32_t) (base + offsetof(SLCNAND_REGS_T, slc_ecc)); dmalist[(i*2) + 1].dma_dest = (uint32_t) & ecc_gen[i]; dmalist[(i*2) + 1].next_lli = (uint32_t) & dmalist[(i*2)+2]; dmalist[(i*2) + 1].next_ctrl = ecc_ctrl; } if (i) { /* Data only transfer */ dmalist[(i*2) - 1].next_lli = 0; dmalist[(i*2) - 1].next_ctrl |= DMAC_CHAN_INT_TC_EN; return ; } /* OOB only transfer */ if (read) { dmasrc = (uint32_t) (base + offsetof(SLCNAND_REGS_T, slc_dma_data)); dmadst = (uint32_t) (buffer); oob_ctrl |= DMAC_CHAN_DEST_AUTOINC; } else { dmadst = (uint32_t) (base + offsetof(SLCNAND_REGS_T, slc_dma_data)); dmasrc = (uint32_t) (buffer); oob_ctrl |= DMAC_CHAN_SRC_AUTOINC; } /* Read/ Write Spare Area Data To/From Flash */ dmalist[i*2].dma_src = dmasrc; dmalist[i*2].dma_dest = dmadst; dmalist[i*2].next_lli = 0; dmalist[i*2].next_ctrl = (oob_ctrl | DMAC_CHAN_INT_TC_EN); } static void lpc32xx_nand_xfer(struct mtd_info *mtd, const u_char *buf, int len, int read) { struct nand_chip *chip = mtd->priv; uint32_t config; /* DMA Channel Configuration */ config = (read ? DMAC_CHAN_FLOW_D_P2M : DMAC_CHAN_FLOW_D_M2P) | (read ? DMAC_DEST_PERIP(0) : DMAC_DEST_PERIP(DMA_PERID_NAND1)) | (read ? DMAC_SRC_PERIP(DMA_PERID_NAND1) : DMAC_SRC_PERIP(0)) | DMAC_CHAN_ENABLE; /* Prepare DMA descriptors */ lpc32xx_nand_dma_configure(chip, buf, len, read); /* Setup SLC controller and start transfer */ if (read) SLCNAND->slc_cfg |= SLCCFG_DMA_DIR; else /* NAND_ECC_WRITE */ SLCNAND->slc_cfg &= ~SLCCFG_DMA_DIR; SLCNAND->slc_cfg |= SLCCFG_DMA_BURST; /* Write length for new transfers */ if (!XFER_PENDING) SLCNAND->slc_tc = len + (len != mtd->oobsize ? mtd->oobsize : 0); SLCNAND->slc_ctrl |= SLCCTRL_DMA_START; /* Start DMA transfers */ lpc32xx_dma_start_xfer(dmachan, dmalist, config); /* Wait for NAND to be ready */ while(!lpc32xx_nand_ready(mtd)); /* Wait till DMA transfer is DONE */ if (lpc32xx_dma_wait_status(dmachan)) { printk(KERN_ERR "NAND DMA transfer error!\r\n"); } /* Stop DMA & HW ECC */ SLCNAND->slc_ctrl &= ~SLCCTRL_DMA_START; SLCNAND->slc_cfg &= ~(SLCCFG_DMA_DIR | SLCCFG_DMA_BURST | SLCCFG_ECC_EN | SLCCFG_DMA_ECC); } static uint32_t slc_ecc_copy_to_buffer(uint8_t * spare, const uint32_t * ecc, int count) { int i; for (i = 0; i < (count * 3); i += 3) { uint32_t ce = ecc[i/3]; ce = ~(ce << 2) & 0xFFFFFF; spare[i+2] = (uint8_t)(ce & 0xFF); ce >>= 8; spare[i+1] = (uint8_t)(ce & 0xFF); ce >>= 8; spare[i] = (uint8_t)(ce & 0xFF); } return 0; } static int lpc32xx_ecc_calculate(struct mtd_info *mtd, const uint8_t *dat, uint8_t *ecc_code) { return slc_ecc_copy_to_buffer(ecc_code, ecc_buffer, CONFIG_SYS_NAND_ECCSIZE == NAND_LARGE_BLOCK_PAGE_SIZE ? 8 : 2); } /* * Enables and prepares SLC NAND controller * for doing data transfers with H/W ECC enabled. */ static void lpc32xx_hwecc_enable(struct mtd_info *mtd, int mode) { /* Clear ECC */ SLCNAND->slc_ctrl = SLCCTRL_ECC_CLEAR; /* Setup SLC controller for H/W ECC operations */ SLCNAND->slc_cfg |= (SLCCFG_ECC_EN | SLCCFG_DMA_ECC); } /* * lpc32xx_write_buf - [DEFAULT] write buffer to chip * mtd: MTD device structure * buf: data buffer * len: number of bytes to write * * Default write function for 8bit buswith */ static void lpc32xx_write_buf(struct mtd_info *mtd, const u_char *buf, int len) { lpc32xx_nand_xfer(mtd, buf, len, 0); } /* * lpc32xx_read_buf - [DEFAULT] read chip data into buffer * mtd: MTD device structure * buf: buffer to store date * len: number of bytes to read * * Default read function for 8bit buswith */ static void lpc32xx_read_buf(struct mtd_info *mtd, u_char *buf, int len) { lpc32xx_nand_xfer(mtd, buf, len, 1); } int board_nand_init(struct nand_chip *nand) { /* Initial NAND interface */ lpc32xx_nand_init(); /* Acquire a channel for our use */ dmachan = lpc32xx_dma_get_channel(); if (unlikely(dmachan < 0)){ printk(KERN_INFO "Unable to get a free DMA " "channel for NAND transfers\r\n"); return -1; } /* ECC mode and size */ nand->ecc.mode = NAND_ECC_HW; nand->ecc.bytes = CONFIG_SYS_NAND_ECCBYTES; nand->ecc.size = CONFIG_SYS_NAND_ECCSIZE; if(CONFIG_SYS_NAND_ECCSIZE != NAND_LARGE_BLOCK_PAGE_SIZE) nand->ecc.layout = &lpc32xx_nand_oob_16; nand->ecc.calculate = lpc32xx_ecc_calculate; nand->ecc.correct = nand_correct_data; nand->ecc.hwctl = lpc32xx_hwecc_enable; nand->cmd_ctrl = lpc32xx_nand_hwcontrol; nand->dev_ready = lpc32xx_nand_ready; nand->chip_delay = 2000; nand->read_buf = lpc32xx_read_buf; nand->write_buf = lpc32xx_write_buf; nand->read_byte = lpc32xx_read_byte; nand->verify_buf = lpc32xx_verify_buf; return 0; }
Java
# ganada
Java
/* * Copyright (C) 2005-2013 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Common.h" #include "Database/DatabaseEnv.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Opcodes.h" #include "Log.h" #include "UpdateMask.h" #include "World.h" #include "ObjectMgr.h" #include "SpellMgr.h" #include "Player.h" #include "Unit.h" #include "Spell.h" #include "DynamicObject.h" #include "Group.h" #include "UpdateData.h" #include "ObjectAccessor.h" #include "Policies/Singleton.h" #include "Totem.h" #include "Creature.h" #include "Formulas.h" #include "BattleGround/BattleGround.h" #include "OutdoorPvP/OutdoorPvP.h" #include "CreatureAI.h" #include "ScriptMgr.h" #include "Util.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "CellImpl.h" #include "MapManager.h" #define NULL_AURA_SLOT 0xFF pAuraHandler AuraHandler[TOTAL_AURAS] = { &Aura::HandleNULL, // 0 SPELL_AURA_NONE &Aura::HandleBindSight, // 1 SPELL_AURA_BIND_SIGHT &Aura::HandleModPossess, // 2 SPELL_AURA_MOD_POSSESS &Aura::HandlePeriodicDamage, // 3 SPELL_AURA_PERIODIC_DAMAGE &Aura::HandleAuraDummy, // 4 SPELL_AURA_DUMMY &Aura::HandleModConfuse, // 5 SPELL_AURA_MOD_CONFUSE &Aura::HandleModCharm, // 6 SPELL_AURA_MOD_CHARM &Aura::HandleModFear, // 7 SPELL_AURA_MOD_FEAR &Aura::HandlePeriodicHeal, // 8 SPELL_AURA_PERIODIC_HEAL &Aura::HandleModAttackSpeed, // 9 SPELL_AURA_MOD_ATTACKSPEED &Aura::HandleModThreat, // 10 SPELL_AURA_MOD_THREAT &Aura::HandleModTaunt, // 11 SPELL_AURA_MOD_TAUNT &Aura::HandleAuraModStun, // 12 SPELL_AURA_MOD_STUN &Aura::HandleModDamageDone, // 13 SPELL_AURA_MOD_DAMAGE_DONE &Aura::HandleNoImmediateEffect, // 14 SPELL_AURA_MOD_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonusTaken and Unit::SpellBaseDamageBonusTaken &Aura::HandleNoImmediateEffect, // 15 SPELL_AURA_DAMAGE_SHIELD implemented in Unit::DealMeleeDamage &Aura::HandleModStealth, // 16 SPELL_AURA_MOD_STEALTH &Aura::HandleNoImmediateEffect, // 17 SPELL_AURA_MOD_STEALTH_DETECT implemented in Unit::isVisibleForOrDetect &Aura::HandleInvisibility, // 18 SPELL_AURA_MOD_INVISIBILITY &Aura::HandleInvisibilityDetect, // 19 SPELL_AURA_MOD_INVISIBILITY_DETECTION &Aura::HandleAuraModTotalHealthPercentRegen, // 20 SPELL_AURA_OBS_MOD_HEALTH &Aura::HandleAuraModTotalManaPercentRegen, // 21 SPELL_AURA_OBS_MOD_MANA &Aura::HandleAuraModResistance, // 22 SPELL_AURA_MOD_RESISTANCE &Aura::HandlePeriodicTriggerSpell, // 23 SPELL_AURA_PERIODIC_TRIGGER_SPELL &Aura::HandlePeriodicEnergize, // 24 SPELL_AURA_PERIODIC_ENERGIZE &Aura::HandleAuraModPacify, // 25 SPELL_AURA_MOD_PACIFY &Aura::HandleAuraModRoot, // 26 SPELL_AURA_MOD_ROOT &Aura::HandleAuraModSilence, // 27 SPELL_AURA_MOD_SILENCE &Aura::HandleNoImmediateEffect, // 28 SPELL_AURA_REFLECT_SPELLS implement in Unit::SpellHitResult &Aura::HandleAuraModStat, // 29 SPELL_AURA_MOD_STAT &Aura::HandleAuraModSkill, // 30 SPELL_AURA_MOD_SKILL &Aura::HandleAuraModIncreaseSpeed, // 31 SPELL_AURA_MOD_INCREASE_SPEED &Aura::HandleAuraModIncreaseMountedSpeed, // 32 SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED &Aura::HandleAuraModDecreaseSpeed, // 33 SPELL_AURA_MOD_DECREASE_SPEED &Aura::HandleAuraModIncreaseHealth, // 34 SPELL_AURA_MOD_INCREASE_HEALTH &Aura::HandleAuraModIncreaseEnergy, // 35 SPELL_AURA_MOD_INCREASE_ENERGY &Aura::HandleAuraModShapeshift, // 36 SPELL_AURA_MOD_SHAPESHIFT &Aura::HandleAuraModEffectImmunity, // 37 SPELL_AURA_EFFECT_IMMUNITY &Aura::HandleAuraModStateImmunity, // 38 SPELL_AURA_STATE_IMMUNITY &Aura::HandleAuraModSchoolImmunity, // 39 SPELL_AURA_SCHOOL_IMMUNITY &Aura::HandleAuraModDmgImmunity, // 40 SPELL_AURA_DAMAGE_IMMUNITY &Aura::HandleAuraModDispelImmunity, // 41 SPELL_AURA_DISPEL_IMMUNITY &Aura::HandleAuraProcTriggerSpell, // 42 SPELL_AURA_PROC_TRIGGER_SPELL implemented in Unit::ProcDamageAndSpellFor and Unit::HandleProcTriggerSpell &Aura::HandleNoImmediateEffect, // 43 SPELL_AURA_PROC_TRIGGER_DAMAGE implemented in Unit::ProcDamageAndSpellFor &Aura::HandleAuraTrackCreatures, // 44 SPELL_AURA_TRACK_CREATURES &Aura::HandleAuraTrackResources, // 45 SPELL_AURA_TRACK_RESOURCES &Aura::HandleUnused, // 46 SPELL_AURA_46 &Aura::HandleAuraModParryPercent, // 47 SPELL_AURA_MOD_PARRY_PERCENT &Aura::HandleUnused, // 48 SPELL_AURA_48 &Aura::HandleAuraModDodgePercent, // 49 SPELL_AURA_MOD_DODGE_PERCENT &Aura::HandleUnused, // 50 SPELL_AURA_MOD_BLOCK_SKILL obsolete? &Aura::HandleAuraModBlockPercent, // 51 SPELL_AURA_MOD_BLOCK_PERCENT &Aura::HandleAuraModCritPercent, // 52 SPELL_AURA_MOD_CRIT_PERCENT &Aura::HandlePeriodicLeech, // 53 SPELL_AURA_PERIODIC_LEECH &Aura::HandleModHitChance, // 54 SPELL_AURA_MOD_HIT_CHANCE &Aura::HandleModSpellHitChance, // 55 SPELL_AURA_MOD_SPELL_HIT_CHANCE &Aura::HandleAuraTransform, // 56 SPELL_AURA_TRANSFORM &Aura::HandleModSpellCritChance, // 57 SPELL_AURA_MOD_SPELL_CRIT_CHANCE &Aura::HandleAuraModIncreaseSwimSpeed, // 58 SPELL_AURA_MOD_INCREASE_SWIM_SPEED &Aura::HandleNoImmediateEffect, // 59 SPELL_AURA_MOD_DAMAGE_DONE_CREATURE implemented in Unit::MeleeDamageBonusDone and Unit::SpellDamageBonusDone &Aura::HandleAuraModPacifyAndSilence, // 60 SPELL_AURA_MOD_PACIFY_SILENCE &Aura::HandleAuraModScale, // 61 SPELL_AURA_MOD_SCALE &Aura::HandlePeriodicHealthFunnel, // 62 SPELL_AURA_PERIODIC_HEALTH_FUNNEL &Aura::HandleUnused, // 63 SPELL_AURA_PERIODIC_MANA_FUNNEL obsolete? &Aura::HandlePeriodicManaLeech, // 64 SPELL_AURA_PERIODIC_MANA_LEECH &Aura::HandleModCastingSpeed, // 65 SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK &Aura::HandleFeignDeath, // 66 SPELL_AURA_FEIGN_DEATH &Aura::HandleAuraModDisarm, // 67 SPELL_AURA_MOD_DISARM &Aura::HandleAuraModStalked, // 68 SPELL_AURA_MOD_STALKED &Aura::HandleSchoolAbsorb, // 69 SPELL_AURA_SCHOOL_ABSORB implemented in Unit::CalculateAbsorbAndResist &Aura::HandleUnused, // 70 SPELL_AURA_EXTRA_ATTACKS Useless, used by only one spell that has only visual effect &Aura::HandleModSpellCritChanceShool, // 71 SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL &Aura::HandleModPowerCostPCT, // 72 SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT &Aura::HandleModPowerCost, // 73 SPELL_AURA_MOD_POWER_COST_SCHOOL &Aura::HandleNoImmediateEffect, // 74 SPELL_AURA_REFLECT_SPELLS_SCHOOL implemented in Unit::SpellHitResult &Aura::HandleNoImmediateEffect, // 75 SPELL_AURA_MOD_LANGUAGE implemented in WorldSession::HandleMessagechatOpcode &Aura::HandleFarSight, // 76 SPELL_AURA_FAR_SIGHT &Aura::HandleModMechanicImmunity, // 77 SPELL_AURA_MECHANIC_IMMUNITY &Aura::HandleAuraMounted, // 78 SPELL_AURA_MOUNTED &Aura::HandleModDamagePercentDone, // 79 SPELL_AURA_MOD_DAMAGE_PERCENT_DONE &Aura::HandleModPercentStat, // 80 SPELL_AURA_MOD_PERCENT_STAT &Aura::HandleNoImmediateEffect, // 81 SPELL_AURA_SPLIT_DAMAGE_PCT implemented in Unit::CalculateAbsorbAndResist &Aura::HandleWaterBreathing, // 82 SPELL_AURA_WATER_BREATHING &Aura::HandleModBaseResistance, // 83 SPELL_AURA_MOD_BASE_RESISTANCE &Aura::HandleModRegen, // 84 SPELL_AURA_MOD_REGEN &Aura::HandleModPowerRegen, // 85 SPELL_AURA_MOD_POWER_REGEN &Aura::HandleChannelDeathItem, // 86 SPELL_AURA_CHANNEL_DEATH_ITEM &Aura::HandleNoImmediateEffect, // 87 SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN implemented in Unit::MeleeDamageBonusTaken and Unit::SpellDamageBonusTaken &Aura::HandleNoImmediateEffect, // 88 SPELL_AURA_MOD_HEALTH_REGEN_PERCENT implemented in Player::RegenerateHealth &Aura::HandlePeriodicDamagePCT, // 89 SPELL_AURA_PERIODIC_DAMAGE_PERCENT &Aura::HandleUnused, // 90 SPELL_AURA_MOD_RESIST_CHANCE Useless &Aura::HandleNoImmediateEffect, // 91 SPELL_AURA_MOD_DETECT_RANGE implemented in Creature::GetAttackDistance &Aura::HandlePreventFleeing, // 92 SPELL_AURA_PREVENTS_FLEEING &Aura::HandleModUnattackable, // 93 SPELL_AURA_MOD_UNATTACKABLE &Aura::HandleNoImmediateEffect, // 94 SPELL_AURA_INTERRUPT_REGEN implemented in Player::RegenerateAll &Aura::HandleAuraGhost, // 95 SPELL_AURA_GHOST &Aura::HandleNoImmediateEffect, // 96 SPELL_AURA_SPELL_MAGNET implemented in Unit::SelectMagnetTarget &Aura::HandleManaShield, // 97 SPELL_AURA_MANA_SHIELD implemented in Unit::CalculateAbsorbAndResist &Aura::HandleAuraModSkill, // 98 SPELL_AURA_MOD_SKILL_TALENT &Aura::HandleAuraModAttackPower, // 99 SPELL_AURA_MOD_ATTACK_POWER &Aura::HandleUnused, //100 SPELL_AURA_AURAS_VISIBLE obsolete? all player can see all auras now &Aura::HandleModResistancePercent, //101 SPELL_AURA_MOD_RESISTANCE_PCT &Aura::HandleNoImmediateEffect, //102 SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS implemented in Unit::MeleeDamageBonusDone &Aura::HandleAuraModTotalThreat, //103 SPELL_AURA_MOD_TOTAL_THREAT &Aura::HandleAuraWaterWalk, //104 SPELL_AURA_WATER_WALK &Aura::HandleAuraFeatherFall, //105 SPELL_AURA_FEATHER_FALL &Aura::HandleAuraHover, //106 SPELL_AURA_HOVER &Aura::HandleAddModifier, //107 SPELL_AURA_ADD_FLAT_MODIFIER &Aura::HandleAddModifier, //108 SPELL_AURA_ADD_PCT_MODIFIER &Aura::HandleNoImmediateEffect, //109 SPELL_AURA_ADD_TARGET_TRIGGER &Aura::HandleModPowerRegenPCT, //110 SPELL_AURA_MOD_POWER_REGEN_PERCENT &Aura::HandleNoImmediateEffect, //111 SPELL_AURA_ADD_CASTER_HIT_TRIGGER implemented in Unit::SelectMagnetTarget &Aura::HandleNoImmediateEffect, //112 SPELL_AURA_OVERRIDE_CLASS_SCRIPTS implemented in diff functions. &Aura::HandleNoImmediateEffect, //113 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonusTaken &Aura::HandleNoImmediateEffect, //114 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT implemented in Unit::MeleeDamageBonusTaken &Aura::HandleNoImmediateEffect, //115 SPELL_AURA_MOD_HEALING implemented in Unit::SpellBaseHealingBonusTaken &Aura::HandleNoImmediateEffect, //116 SPELL_AURA_MOD_REGEN_DURING_COMBAT imppemented in Player::RegenerateAll and Player::RegenerateHealth &Aura::HandleNoImmediateEffect, //117 SPELL_AURA_MOD_MECHANIC_RESISTANCE implemented in Unit::MagicSpellHitResult &Aura::HandleNoImmediateEffect, //118 SPELL_AURA_MOD_HEALING_PCT implemented in Unit::SpellHealingBonusTaken &Aura::HandleUnused, //119 SPELL_AURA_SHARE_PET_TRACKING useless &Aura::HandleAuraUntrackable, //120 SPELL_AURA_UNTRACKABLE &Aura::HandleAuraEmpathy, //121 SPELL_AURA_EMPATHY &Aura::HandleModOffhandDamagePercent, //122 SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT &Aura::HandleModTargetResistance, //123 SPELL_AURA_MOD_TARGET_RESISTANCE &Aura::HandleAuraModRangedAttackPower, //124 SPELL_AURA_MOD_RANGED_ATTACK_POWER &Aura::HandleNoImmediateEffect, //125 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonusTaken &Aura::HandleNoImmediateEffect, //126 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT implemented in Unit::MeleeDamageBonusTaken &Aura::HandleNoImmediateEffect, //127 SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonusDone &Aura::HandleModPossessPet, //128 SPELL_AURA_MOD_POSSESS_PET &Aura::HandleAuraModIncreaseSpeed, //129 SPELL_AURA_MOD_SPEED_ALWAYS &Aura::HandleAuraModIncreaseMountedSpeed, //130 SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS &Aura::HandleNoImmediateEffect, //131 SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS implemented in Unit::MeleeDamageBonusDone &Aura::HandleAuraModIncreaseEnergyPercent, //132 SPELL_AURA_MOD_INCREASE_ENERGY_PERCENT &Aura::HandleAuraModIncreaseHealthPercent, //133 SPELL_AURA_MOD_INCREASE_HEALTH_PERCENT &Aura::HandleAuraModRegenInterrupt, //134 SPELL_AURA_MOD_MANA_REGEN_INTERRUPT &Aura::HandleModHealingDone, //135 SPELL_AURA_MOD_HEALING_DONE &Aura::HandleNoImmediateEffect, //136 SPELL_AURA_MOD_HEALING_DONE_PERCENT implemented in Unit::SpellHealingBonusDone &Aura::HandleModTotalPercentStat, //137 SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE &Aura::HandleModMeleeSpeedPct, //138 SPELL_AURA_MOD_MELEE_HASTE &Aura::HandleForceReaction, //139 SPELL_AURA_FORCE_REACTION &Aura::HandleAuraModRangedHaste, //140 SPELL_AURA_MOD_RANGED_HASTE &Aura::HandleRangedAmmoHaste, //141 SPELL_AURA_MOD_RANGED_AMMO_HASTE &Aura::HandleAuraModBaseResistancePCT, //142 SPELL_AURA_MOD_BASE_RESISTANCE_PCT &Aura::HandleAuraModResistanceExclusive, //143 SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE &Aura::HandleAuraSafeFall, //144 SPELL_AURA_SAFE_FALL implemented in WorldSession::HandleMovementOpcodes &Aura::HandleUnused, //145 SPELL_AURA_CHARISMA obsolete? &Aura::HandleUnused, //146 SPELL_AURA_PERSUADED obsolete? &Aura::HandleModMechanicImmunityMask, //147 SPELL_AURA_MECHANIC_IMMUNITY_MASK implemented in Unit::IsImmuneToSpell and Unit::IsImmuneToSpellEffect (check part) &Aura::HandleAuraRetainComboPoints, //148 SPELL_AURA_RETAIN_COMBO_POINTS &Aura::HandleNoImmediateEffect, //149 SPELL_AURA_RESIST_PUSHBACK implemented in Spell::Delayed and Spell::DelayedChannel &Aura::HandleShieldBlockValue, //150 SPELL_AURA_MOD_SHIELD_BLOCKVALUE_PCT &Aura::HandleAuraTrackStealthed, //151 SPELL_AURA_TRACK_STEALTHED &Aura::HandleNoImmediateEffect, //152 SPELL_AURA_MOD_DETECTED_RANGE implemented in Creature::GetAttackDistance &Aura::HandleNoImmediateEffect, //153 SPELL_AURA_SPLIT_DAMAGE_FLAT implemented in Unit::CalculateAbsorbAndResist &Aura::HandleNoImmediateEffect, //154 SPELL_AURA_MOD_STEALTH_LEVEL implemented in Unit::isVisibleForOrDetect &Aura::HandleNoImmediateEffect, //155 SPELL_AURA_MOD_WATER_BREATHING implemented in Player::getMaxTimer &Aura::HandleNoImmediateEffect, //156 SPELL_AURA_MOD_REPUTATION_GAIN implemented in Player::CalculateReputationGain &Aura::HandleUnused, //157 SPELL_AURA_PET_DAMAGE_MULTI (single test like spell 20782, also single for 214 aura) &Aura::HandleShieldBlockValue, //158 SPELL_AURA_MOD_SHIELD_BLOCKVALUE &Aura::HandleNoImmediateEffect, //159 SPELL_AURA_NO_PVP_CREDIT implemented in Player::RewardHonor &Aura::HandleNoImmediateEffect, //160 SPELL_AURA_MOD_AOE_AVOIDANCE implemented in Unit::MagicSpellHitResult &Aura::HandleNoImmediateEffect, //161 SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT implemented in Player::RegenerateAll and Player::RegenerateHealth &Aura::HandleAuraPowerBurn, //162 SPELL_AURA_POWER_BURN_MANA &Aura::HandleNoImmediateEffect, //163 SPELL_AURA_MOD_CRIT_DAMAGE_BONUS implemented in Unit::CalculateMeleeDamage and Unit::SpellCriticalDamageBonus &Aura::HandleUnused, //164 useless, only one test spell &Aura::HandleNoImmediateEffect, //165 SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonusDone &Aura::HandleAuraModAttackPowerPercent, //166 SPELL_AURA_MOD_ATTACK_POWER_PCT &Aura::HandleAuraModRangedAttackPowerPercent, //167 SPELL_AURA_MOD_RANGED_ATTACK_POWER_PCT &Aura::HandleNoImmediateEffect, //168 SPELL_AURA_MOD_DAMAGE_DONE_VERSUS implemented in Unit::SpellDamageBonusDone, Unit::MeleeDamageBonusDone &Aura::HandleNoImmediateEffect, //169 SPELL_AURA_MOD_CRIT_PERCENT_VERSUS implemented in Unit::DealDamageBySchool, Unit::DoAttackDamage, Unit::SpellCriticalBonus &Aura::HandleDetectAmore, //170 SPELL_AURA_DETECT_AMORE only for Detect Amore spell &Aura::HandleAuraModIncreaseSpeed, //171 SPELL_AURA_MOD_SPEED_NOT_STACK &Aura::HandleAuraModIncreaseMountedSpeed, //172 SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK &Aura::HandleUnused, //173 SPELL_AURA_ALLOW_CHAMPION_SPELLS only for Proclaim Champion spell &Aura::HandleModSpellDamagePercentFromStat, //174 SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT implemented in Unit::SpellBaseDamageBonusDone &Aura::HandleModSpellHealingPercentFromStat, //175 SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT implemented in Unit::SpellBaseHealingBonusDone &Aura::HandleSpiritOfRedemption, //176 SPELL_AURA_SPIRIT_OF_REDEMPTION only for Spirit of Redemption spell, die at aura end &Aura::HandleNULL, //177 SPELL_AURA_AOE_CHARM &Aura::HandleNoImmediateEffect, //178 SPELL_AURA_MOD_DEBUFF_RESISTANCE implemented in Unit::MagicSpellHitResult &Aura::HandleNoImmediateEffect, //179 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE implemented in Unit::SpellCriticalBonus &Aura::HandleNoImmediateEffect, //180 SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS implemented in Unit::SpellDamageBonusDone &Aura::HandleUnused, //181 SPELL_AURA_MOD_FLAT_SPELL_CRIT_DAMAGE_VERSUS unused &Aura::HandleAuraModResistenceOfStatPercent, //182 SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT &Aura::HandleNoImmediateEffect, //183 SPELL_AURA_MOD_CRITICAL_THREAT only used in 28746, implemented in ThreatCalcHelper::CalcThreat &Aura::HandleNoImmediateEffect, //184 SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst &Aura::HandleNoImmediateEffect, //185 SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst &Aura::HandleNoImmediateEffect, //186 SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE implemented in Unit::MagicSpellHitResult &Aura::HandleNoImmediateEffect, //187 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE implemented in Unit::GetUnitCriticalChance &Aura::HandleNoImmediateEffect, //188 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE implemented in Unit::GetUnitCriticalChance &Aura::HandleModRating, //189 SPELL_AURA_MOD_RATING &Aura::HandleNoImmediateEffect, //190 SPELL_AURA_MOD_FACTION_REPUTATION_GAIN implemented in Player::CalculateReputationGain &Aura::HandleAuraModUseNormalSpeed, //191 SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED &Aura::HandleModMeleeRangedSpeedPct, //192 SPELL_AURA_MOD_MELEE_RANGED_HASTE &Aura::HandleModCombatSpeedPct, //193 SPELL_AURA_HASTE_ALL (in fact combat (any type attack) speed pct) &Aura::HandleUnused, //194 SPELL_AURA_MOD_DEPRICATED_1 not used now (old SPELL_AURA_MOD_SPELL_DAMAGE_OF_INTELLECT) &Aura::HandleUnused, //195 SPELL_AURA_MOD_DEPRICATED_2 not used now (old SPELL_AURA_MOD_SPELL_HEALING_OF_INTELLECT) &Aura::HandleNULL, //196 SPELL_AURA_MOD_COOLDOWN &Aura::HandleNoImmediateEffect, //197 SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE implemented in Unit::SpellCriticalBonus Unit::GetUnitCriticalChance &Aura::HandleUnused, //198 SPELL_AURA_MOD_ALL_WEAPON_SKILLS &Aura::HandleNoImmediateEffect, //199 SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT implemented in Unit::MagicSpellHitResult &Aura::HandleNoImmediateEffect, //200 SPELL_AURA_MOD_XP_PCT implemented in Player::GiveXP &Aura::HandleAuraAllowFlight, //201 SPELL_AURA_FLY this aura enable flight mode... &Aura::HandleNoImmediateEffect, //202 SPELL_AURA_IGNORE_COMBAT_RESULT implemented in Unit::MeleeSpellHitResult &Aura::HandleNoImmediateEffect, //203 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE implemented in Unit::CalculateMeleeDamage and Unit::SpellCriticalDamageBonus &Aura::HandleNoImmediateEffect, //204 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE implemented in Unit::CalculateMeleeDamage and Unit::SpellCriticalDamageBonus &Aura::HandleNoImmediateEffect, //205 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_DAMAGE implemented in Unit::SpellCriticalDamageBonus &Aura::HandleAuraModIncreaseFlightSpeed, //206 SPELL_AURA_MOD_FLIGHT_SPEED &Aura::HandleAuraModIncreaseFlightSpeed, //207 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED &Aura::HandleAuraModIncreaseFlightSpeed, //208 SPELL_AURA_MOD_FLIGHT_SPEED_STACKING &Aura::HandleAuraModIncreaseFlightSpeed, //209 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_STACKING &Aura::HandleAuraModIncreaseFlightSpeed, //210 SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACKING &Aura::HandleAuraModIncreaseFlightSpeed, //211 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_NOT_STACKING &Aura::HandleAuraModRangedAttackPowerOfStatPercent, //212 SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_STAT_PERCENT &Aura::HandleNoImmediateEffect, //213 SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT implemented in Player::RewardRage &Aura::HandleNULL, //214 Tamed Pet Passive &Aura::HandleArenaPreparation, //215 SPELL_AURA_ARENA_PREPARATION &Aura::HandleModCastingSpeed, //216 SPELL_AURA_HASTE_SPELLS &Aura::HandleUnused, //217 unused &Aura::HandleAuraModRangedHaste, //218 SPELL_AURA_HASTE_RANGED &Aura::HandleModManaRegen, //219 SPELL_AURA_MOD_MANA_REGEN_FROM_STAT &Aura::HandleUnused, //220 SPELL_AURA_MOD_RATING_FROM_STAT &Aura::HandleNULL, //221 ignored &Aura::HandleUnused, //222 unused &Aura::HandleNULL, //223 Cold Stare &Aura::HandleUnused, //224 unused &Aura::HandleNoImmediateEffect, //225 SPELL_AURA_PRAYER_OF_MENDING &Aura::HandleAuraPeriodicDummy, //226 SPELL_AURA_PERIODIC_DUMMY &Aura::HandlePeriodicTriggerSpellWithValue, //227 SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE &Aura::HandleNoImmediateEffect, //228 SPELL_AURA_DETECT_STEALTH &Aura::HandleNoImmediateEffect, //229 SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE implemented in Unit::SpellDamageBonusTaken &Aura::HandleAuraModIncreaseMaxHealth, //230 Commanding Shout &Aura::HandleNoImmediateEffect, //231 SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE &Aura::HandleNoImmediateEffect, //232 SPELL_AURA_MECHANIC_DURATION_MOD implement in Unit::CalculateAuraDuration &Aura::HandleNULL, //233 set model id to the one of the creature with id m_modifier.m_miscvalue &Aura::HandleNoImmediateEffect, //234 SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK implement in Unit::CalculateAuraDuration &Aura::HandleAuraModDispelResist, //235 SPELL_AURA_MOD_DISPEL_RESIST implement in Unit::MagicSpellHitResult &Aura::HandleUnused, //236 unused &Aura::HandleModSpellDamagePercentFromAttackPower, //237 SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER implemented in Unit::SpellBaseDamageBonusDone &Aura::HandleModSpellHealingPercentFromAttackPower, //238 SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER implemented in Unit::SpellBaseHealingBonusDone &Aura::HandleAuraModScale, //239 SPELL_AURA_MOD_SCALE_2 only in Noggenfogger Elixir (16595) before 2.3.0 aura 61 &Aura::HandleAuraModExpertise, //240 SPELL_AURA_MOD_EXPERTISE &Aura::HandleForceMoveForward, //241 Forces the caster to move forward &Aura::HandleUnused, //242 unused &Aura::HandleUnused, //243 used by two test spells &Aura::HandleComprehendLanguage, //244 SPELL_AURA_COMPREHEND_LANGUAGE &Aura::HandleUnused, //245 unused &Aura::HandleUnused, //246 unused &Aura::HandleAuraMirrorImage, //247 SPELL_AURA_MIRROR_IMAGE target to become a clone of the caster &Aura::HandleNoImmediateEffect, //248 SPELL_AURA_MOD_COMBAT_RESULT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst &Aura::HandleNULL, //249 &Aura::HandleAuraModIncreaseHealth, //250 SPELL_AURA_MOD_INCREASE_HEALTH_2 &Aura::HandleNULL, //251 SPELL_AURA_MOD_ENEMY_DODGE &Aura::HandleUnused, //252 unused &Aura::HandleUnused, //253 unused &Aura::HandleUnused, //254 unused &Aura::HandleUnused, //255 unused &Aura::HandleUnused, //256 unused &Aura::HandleUnused, //257 unused &Aura::HandleUnused, //258 unused &Aura::HandleUnused, //259 unused &Aura::HandleUnused, //260 unused &Aura::HandleNULL //261 SPELL_AURA_261 some phased state (44856 spell) }; static AuraType const frozenAuraTypes[] = { SPELL_AURA_MOD_ROOT, SPELL_AURA_MOD_STUN, SPELL_AURA_NONE }; Aura::Aura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) : m_spellmod(NULL), m_periodicTimer(0), m_periodicTick(0), m_removeMode(AURA_REMOVE_BY_DEFAULT), m_effIndex(eff), m_positive(false), m_isPeriodic(false), m_isAreaAura(false), m_isPersistent(false), m_in_use(0), m_spellAuraHolder(holder) { MANGOS_ASSERT(target); MANGOS_ASSERT(spellproto && spellproto == sSpellStore.LookupEntry(spellproto->Id) && "`info` must be pointer to sSpellStore element"); m_currentBasePoints = currentBasePoints ? *currentBasePoints : spellproto->CalculateSimpleValue(eff); m_positive = IsPositiveEffect(spellproto, m_effIndex); m_applyTime = time(NULL); int32 damage; if (!caster) damage = m_currentBasePoints; else { damage = caster->CalculateSpellDamage(target, spellproto, m_effIndex, &m_currentBasePoints); if (!damage && castItem && castItem->GetItemSuffixFactor()) { ItemRandomSuffixEntry const* item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(castItem->GetItemRandomPropertyId())); if (item_rand_suffix) { for (int k = 0; k < 3; ++k) { SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(item_rand_suffix->enchant_id[k]); if (pEnchant) { for (int t = 0; t < 3; ++t) { if (pEnchant->spellid[t] != spellproto->Id) continue; damage = uint32((item_rand_suffix->prefix[k] * castItem->GetItemSuffixFactor()) / 10000); break; } } if (damage) break; } } } } DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Aura: construct Spellid : %u, Aura : %u Target : %d Damage : %d", spellproto->Id, spellproto->EffectApplyAuraName[eff], spellproto->EffectImplicitTargetA[eff], damage); SetModifier(AuraType(spellproto->EffectApplyAuraName[eff]), damage, spellproto->EffectAmplitude[eff], spellproto->EffectMiscValue[eff]); Player* modOwner = caster ? caster->GetSpellModOwner() : NULL; // Apply periodic time mod if (modOwner && m_modifier.periodictime) modOwner->ApplySpellMod(spellproto->Id, SPELLMOD_ACTIVATION_TIME, m_modifier.periodictime); // Start periodic on next tick or at aura apply if (!spellproto->HasAttribute(SPELL_ATTR_EX5_START_PERIODIC_AT_APPLY)) m_periodicTimer = m_modifier.periodictime; } Aura::~Aura() { } AreaAura::AreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem) { m_isAreaAura = true; // caster==NULL in constructor args if target==caster in fact Unit* caster_ptr = caster ? caster : target; m_radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellproto->EffectRadiusIndex[m_effIndex])); if (Player* modOwner = caster_ptr->GetSpellModOwner()) modOwner->ApplySpellMod(spellproto->Id, SPELLMOD_RADIUS, m_radius); switch (spellproto->Effect[eff]) { case SPELL_EFFECT_APPLY_AREA_AURA_PARTY: m_areaAuraType = AREA_AURA_PARTY; break; case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND: m_areaAuraType = AREA_AURA_FRIEND; break; case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY: m_areaAuraType = AREA_AURA_ENEMY; if (target == caster_ptr) m_modifier.m_auraname = SPELL_AURA_NONE; // Do not do any effect on self break; case SPELL_EFFECT_APPLY_AREA_AURA_PET: m_areaAuraType = AREA_AURA_PET; break; case SPELL_EFFECT_APPLY_AREA_AURA_OWNER: m_areaAuraType = AREA_AURA_OWNER; if (target == caster_ptr) m_modifier.m_auraname = SPELL_AURA_NONE; break; default: sLog.outError("Wrong spell effect in AreaAura constructor"); MANGOS_ASSERT(false); break; } // totems are immune to any kind of area auras if (target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->IsTotem()) m_modifier.m_auraname = SPELL_AURA_NONE; } AreaAura::~AreaAura() { } PersistentAreaAura::PersistentAreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem) { m_isPersistent = true; } PersistentAreaAura::~PersistentAreaAura() { } SingleEnemyTargetAura::SingleEnemyTargetAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem) { if (caster) m_castersTargetGuid = caster->GetTypeId() == TYPEID_PLAYER ? ((Player*)caster)->GetSelectionGuid() : caster->GetTargetGuid(); } SingleEnemyTargetAura::~SingleEnemyTargetAura() { } Unit* SingleEnemyTargetAura::GetTriggerTarget() const { return ObjectAccessor::GetUnit(*(m_spellAuraHolder->GetTarget()), m_castersTargetGuid); } Aura* CreateAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) { if (IsAreaAuraEffect(spellproto->Effect[eff])) return new AreaAura(spellproto, eff, currentBasePoints, holder, target, caster, castItem); uint32 triggeredSpellId = spellproto->EffectTriggerSpell[eff]; if (SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(triggeredSpellId)) for (int i = 0; i < MAX_EFFECT_INDEX; ++i) if (triggeredSpellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_ENEMY) return new SingleEnemyTargetAura(spellproto, eff, currentBasePoints, holder, target, caster, castItem); return new Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem); } SpellAuraHolder* CreateSpellAuraHolder(SpellEntry const* spellproto, Unit* target, WorldObject* caster, Item* castItem) { return new SpellAuraHolder(spellproto, target, caster, castItem); } void Aura::SetModifier(AuraType t, int32 a, uint32 pt, int32 miscValue) { m_modifier.m_auraname = t; m_modifier.m_amount = a; m_modifier.m_miscvalue = miscValue; m_modifier.periodictime = pt; } void Aura::Update(uint32 diff) { if (m_isPeriodic) { m_periodicTimer -= diff; if (m_periodicTimer <= 0) // tick also at m_periodicTimer==0 to prevent lost last tick in case max m_duration == (max m_periodicTimer)*N { // update before applying (aura can be removed in TriggerSpell or PeriodicTick calls) m_periodicTimer += m_modifier.periodictime; ++m_periodicTick; // for some infinity auras in some cases can overflow and reset PeriodicTick(); } } } void AreaAura::Update(uint32 diff) { // update for the caster of the aura if (GetCasterGuid() == GetTarget()->GetObjectGuid()) { Unit* caster = GetTarget(); if (!caster->hasUnitState(UNIT_STAT_ISOLATED)) { Unit* owner = caster->GetCharmerOrOwner(); if (!owner) owner = caster; Spell::UnitList targets; switch (m_areaAuraType) { case AREA_AURA_PARTY: { Group* pGroup = NULL; if (owner->GetTypeId() == TYPEID_PLAYER) pGroup = ((Player*)owner)->GetGroup(); if (pGroup) { uint8 subgroup = ((Player*)owner)->GetSubGroup(); for (GroupReference* itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* Target = itr->getSource(); if (Target && Target->isAlive() && Target->GetSubGroup() == subgroup && caster->IsFriendlyTo(Target)) { if (caster->IsWithinDistInMap(Target, m_radius)) targets.push_back(Target); Pet* pet = Target->GetPet(); if (pet && pet->isAlive() && caster->IsWithinDistInMap(pet, m_radius)) targets.push_back(pet); } } } else { // add owner if (owner != caster && caster->IsWithinDistInMap(owner, m_radius)) targets.push_back(owner); // add caster's pet Unit* pet = caster->GetPet(); if (pet && caster->IsWithinDistInMap(pet, m_radius)) targets.push_back(pet); } break; } case AREA_AURA_FRIEND: { MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(caster, m_radius); MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(targets, u_check); Cell::VisitAllObjects(caster, searcher, m_radius); break; } case AREA_AURA_ENEMY: { MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(caster, m_radius); // No GetCharmer in searcher MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(targets, u_check); Cell::VisitAllObjects(caster, searcher, m_radius); break; } case AREA_AURA_OWNER: case AREA_AURA_PET: { if (owner != caster && caster->IsWithinDistInMap(owner, m_radius)) targets.push_back(owner); break; } } for (Spell::UnitList::iterator tIter = targets.begin(); tIter != targets.end(); ++tIter) { // flag for seelction is need apply aura to current iteration target bool apply = true; // we need ignore present caster self applied are auras sometime // in cases if this only auras applied for spell effect Unit::SpellAuraHolderBounds spair = (*tIter)->GetSpellAuraHolderBounds(GetId()); for (Unit::SpellAuraHolderMap::const_iterator i = spair.first; i != spair.second; ++i) { if (i->second->IsDeleted()) continue; Aura* aur = i->second->GetAuraByEffectIndex(m_effIndex); if (!aur) continue; switch (m_areaAuraType) { case AREA_AURA_ENEMY: // non caster self-casted auras (non stacked) if (aur->GetModifier()->m_auraname != SPELL_AURA_NONE) apply = false; break; default: // in generic case not allow stacking area auras apply = false; break; } if (!apply) break; } if (!apply) continue; // Skip some targets (TODO: Might require better checks, also unclear how the actual caster must/can be handled) if (GetSpellProto()->HasAttribute(SPELL_ATTR_EX3_TARGET_ONLY_PLAYER) && (*tIter)->GetTypeId() != TYPEID_PLAYER) continue; if (SpellEntry const* actualSpellInfo = sSpellMgr.SelectAuraRankForLevel(GetSpellProto(), (*tIter)->getLevel())) { int32 actualBasePoints = m_currentBasePoints; // recalculate basepoints for lower rank (all AreaAura spell not use custom basepoints?) if (actualSpellInfo != GetSpellProto()) actualBasePoints = actualSpellInfo->CalculateSimpleValue(m_effIndex); SpellAuraHolder* holder = (*tIter)->GetSpellAuraHolder(actualSpellInfo->Id, GetCasterGuid()); bool addedToExisting = true; if (!holder) { holder = CreateSpellAuraHolder(actualSpellInfo, (*tIter), caster); addedToExisting = false; } holder->SetAuraDuration(GetAuraDuration()); AreaAura* aur = new AreaAura(actualSpellInfo, m_effIndex, &actualBasePoints, holder, (*tIter), caster, NULL); holder->AddAura(aur, m_effIndex); if (addedToExisting) { (*tIter)->AddAuraToModList(aur); holder->SetInUse(true); aur->ApplyModifier(true, true); holder->SetInUse(false); } else (*tIter)->AddSpellAuraHolder(holder); } } } Aura::Update(diff); } else // aura at non-caster { Unit* caster = GetCaster(); Unit* target = GetTarget(); Aura::Update(diff); // remove aura if out-of-range from caster (after teleport for example) // or caster is isolated or caster no longer has the aura // or caster is (no longer) friendly bool needFriendly = (m_areaAuraType == AREA_AURA_ENEMY ? false : true); if (!caster || caster->hasUnitState(UNIT_STAT_ISOLATED) || !caster->IsWithinDistInMap(target, m_radius) || !caster->HasAura(GetId(), GetEffIndex()) || caster->IsFriendlyTo(target) != needFriendly ) { target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid()); } else if (m_areaAuraType == AREA_AURA_PARTY) // check if in same sub group { // not check group if target == owner or target == pet if (caster->GetCharmerOrOwnerGuid() != target->GetObjectGuid() && caster->GetObjectGuid() != target->GetCharmerOrOwnerGuid()) { Player* check = caster->GetCharmerOrOwnerPlayerOrPlayerItself(); Group* pGroup = check ? check->GetGroup() : NULL; if (pGroup) { Player* checkTarget = target->GetCharmerOrOwnerPlayerOrPlayerItself(); if (!checkTarget || !pGroup->SameSubGroup(check, checkTarget)) target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid()); } else target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid()); } } else if (m_areaAuraType == AREA_AURA_PET || m_areaAuraType == AREA_AURA_OWNER) { if (target->GetObjectGuid() != caster->GetCharmerOrOwnerGuid()) target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid()); } } } void PersistentAreaAura::Update(uint32 diff) { bool remove = false; // remove the aura if its caster or the dynamic object causing it was removed // or if the target moves too far from the dynamic object if (Unit* caster = GetCaster()) { DynamicObject* dynObj = caster->GetDynObject(GetId(), GetEffIndex()); if (dynObj) { if (!GetTarget()->IsWithinDistInMap(dynObj, dynObj->GetRadius())) { remove = true; dynObj->RemoveAffected(GetTarget()); // let later reapply if target return to range } } else remove = true; } else remove = true; Aura::Update(diff); if (remove) GetTarget()->RemoveAura(GetId(), GetEffIndex()); } void Aura::ApplyModifier(bool apply, bool Real) { AuraType aura = m_modifier.m_auraname; GetHolder()->SetInUse(true); SetInUse(true); if (aura < TOTAL_AURAS) (*this.*AuraHandler [aura])(apply, Real); SetInUse(false); GetHolder()->SetInUse(false); } bool Aura::isAffectedOnSpell(SpellEntry const* spell) const { if (m_spellmod) return m_spellmod->isAffectedOnSpell(spell); // Check family name if (spell->SpellFamilyName != GetSpellProto()->SpellFamilyName) return false; ClassFamilyMask mask = sSpellMgr.GetSpellAffectMask(GetId(), GetEffIndex()); return spell->IsFitToFamilyMask(mask); } bool Aura::CanProcFrom(SpellEntry const* spell, uint32 EventProcEx, uint32 procEx, bool active, bool useClassMask) const { // Check EffectClassMask (in pre-3.x stored in spell_affect in fact) ClassFamilyMask mask = sSpellMgr.GetSpellAffectMask(GetId(), GetEffIndex()); // if no class mask defined, or spell_proc_event has SpellFamilyName=0 - allow proc if (!useClassMask || !mask) { if (!(EventProcEx & PROC_EX_EX_TRIGGER_ALWAYS)) { // Check for extra req (if none) and hit/crit if (EventProcEx == PROC_EX_NONE) { // No extra req, so can trigger only for active (damage/healing present) and hit/crit if ((procEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) && active) return true; else return false; } else // Passive spells hits here only if resist/reflect/immune/evade { // Passive spells can`t trigger if need hit (exclude cases when procExtra include non-active flags) if ((EventProcEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT) & procEx) && !active) return false; } } return true; } else { // SpellFamilyName check is performed in SpellMgr::IsSpellProcEventCanTriggeredBy and it is done once for whole holder // note: SpellFamilyName is not checked if no spell_proc_event is defined return mask.IsFitToFamilyMask(spell->SpellFamilyFlags); } } void Aura::ReapplyAffectedPassiveAuras(Unit* target, bool owner_mode) { // we need store cast item guids for self casted spells // expected that not exist permanent auras from stackable auras from different items std::map<uint32, ObjectGuid> affectedSelf; std::set<uint32> affectedAuraCaster; for (Unit::SpellAuraHolderMap::const_iterator itr = target->GetSpellAuraHolderMap().begin(); itr != target->GetSpellAuraHolderMap().end(); ++itr) { // permanent passive or permanent area aura // passive spells can be affected only by own or owner spell mods) if ((itr->second->IsPermanent() && ((owner_mode && itr->second->IsPassive()) || itr->second->IsAreaAura())) && // non deleted and not same aura (any with same spell id) !itr->second->IsDeleted() && itr->second->GetId() != GetId() && // and affected by aura isAffectedOnSpell(itr->second->GetSpellProto())) { // only applied by self or aura caster if (itr->second->GetCasterGuid() == target->GetObjectGuid()) affectedSelf[itr->second->GetId()] = itr->second->GetCastItemGuid(); else if (itr->second->GetCasterGuid() == GetCasterGuid()) affectedAuraCaster.insert(itr->second->GetId()); } } if (!affectedSelf.empty()) { Player* pTarget = target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : NULL; for (std::map<uint32, ObjectGuid>::const_iterator map_itr = affectedSelf.begin(); map_itr != affectedSelf.end(); ++map_itr) { Item* item = pTarget && map_itr->second ? pTarget->GetItemByGuid(map_itr->second) : NULL; target->RemoveAurasDueToSpell(map_itr->first); target->CastSpell(target, map_itr->first, true, item); } } if (!affectedAuraCaster.empty()) { Unit* caster = GetCaster(); for (std::set<uint32>::const_iterator set_itr = affectedAuraCaster.begin(); set_itr != affectedAuraCaster.end(); ++set_itr) { target->RemoveAurasDueToSpell(*set_itr); if (caster) caster->CastSpell(GetTarget(), *set_itr, true); } } } struct ReapplyAffectedPassiveAurasHelper { explicit ReapplyAffectedPassiveAurasHelper(Aura* _aura) : aura(_aura) {} void operator()(Unit* unit) const { aura->ReapplyAffectedPassiveAuras(unit, true); } Aura* aura; }; void Aura::ReapplyAffectedPassiveAuras() { // not reapply spell mods with charges (use original value because processed and at remove) if (GetSpellProto()->procCharges) return; // not reapply some spell mods ops (mostly speedup case) switch (m_modifier.m_miscvalue) { case SPELLMOD_DURATION: case SPELLMOD_CHARGES: case SPELLMOD_NOT_LOSE_CASTING_TIME: case SPELLMOD_CASTING_TIME: case SPELLMOD_COOLDOWN: case SPELLMOD_COST: case SPELLMOD_ACTIVATION_TIME: case SPELLMOD_CASTING_TIME_OLD: return; } // reapply talents to own passive persistent auras ReapplyAffectedPassiveAuras(GetTarget(), true); // re-apply talents/passives/area auras applied to pet/totems (it affected by player spellmods) GetTarget()->CallForAllControlledUnits(ReapplyAffectedPassiveAurasHelper(this), CONTROLLED_PET | CONTROLLED_TOTEMS); // re-apply talents/passives/area auras applied to group members (it affected by player spellmods) if (Group* group = ((Player*)GetTarget())->GetGroup()) for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) if (Player* member = itr->getSource()) if (member != GetTarget() && member->IsInMap(GetTarget())) ReapplyAffectedPassiveAuras(member, false); } /*********************************************************/ /*** BASIC AURA FUNCTION ***/ /*********************************************************/ void Aura::HandleAddModifier(bool apply, bool Real) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER || !Real) return; if (m_modifier.m_miscvalue >= MAX_SPELLMOD) return; if (apply) { SpellEntry const* spellProto = GetSpellProto(); // Add custom charges for some mod aura switch (spellProto->Id) { case 17941: // Shadow Trance case 22008: // Netherwind Focus case 34936: // Backlash GetHolder()->SetAuraCharges(1); break; } m_spellmod = new SpellModifier( SpellModOp(m_modifier.m_miscvalue), SpellModType(m_modifier.m_auraname), // SpellModType value == spell aura types m_modifier.m_amount, this, // prevent expire spell mods with (charges > 0 && m_stackAmount > 1) // all this spell expected expire not at use but at spell proc event check spellProto->StackAmount > 1 ? 0 : GetHolder()->GetAuraCharges()); } ((Player*)GetTarget())->AddSpellMod(m_spellmod, apply); ReapplyAffectedPassiveAuras(); } void Aura::TriggerSpell() { ObjectGuid casterGUID = GetCasterGuid(); Unit* triggerTarget = GetTriggerTarget(); if (!casterGUID || !triggerTarget) return; // generic casting code with custom spells and target/caster customs uint32 trigger_spell_id = GetSpellProto()->EffectTriggerSpell[m_effIndex]; SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id); SpellEntry const* auraSpellInfo = GetSpellProto(); uint32 auraId = auraSpellInfo->Id; Unit* target = GetTarget(); Unit* triggerCaster = triggerTarget; WorldObject* triggerTargetObject = NULL; // specific code for cases with no trigger spell provided in field if (triggeredSpellInfo == NULL) { switch (auraSpellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (auraId) { // Firestone Passive (1-5 ranks) case 758: case 17945: case 17947: case 17949: case 27252: { if (triggerTarget->GetTypeId() != TYPEID_PLAYER) return; Item* item = ((Player*)triggerTarget)->GetWeaponForAttack(BASE_ATTACK); if (!item) return; uint32 enchant_id = 0; switch (GetId()) { case 758: enchant_id = 1803; break; // Rank 1 case 17945: enchant_id = 1823; break; // Rank 2 case 17947: enchant_id = 1824; break; // Rank 3 case 17949: enchant_id = 1825; break; // Rank 4 case 27252: enchant_id = 2645; break; // Rank 5 default: return; } // remove old enchanting before applying new ((Player*)triggerTarget)->ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, false); item->SetEnchantment(TEMP_ENCHANTMENT_SLOT, enchant_id, m_modifier.periodictime + 1000, 0); // add new enchanting ((Player*)triggerTarget)->ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, true); return; } case 812: // Periodic Mana Burn { trigger_spell_id = 25779; // Mana Burn if (GetTarget()->GetTypeId() != TYPEID_UNIT) return; triggerTarget = ((Creature*)GetTarget())->SelectAttackingTarget(ATTACKING_TARGET_TOPAGGRO, 0, trigger_spell_id, SELECT_FLAG_POWER_MANA); if (!triggerTarget) return; break; } // // Polymorphic Ray // case 6965: break; // // Fire Nova (1-7 ranks) // case 8350: // case 8508: // case 8509: // case 11312: // case 11313: // case 25540: // case 25544: // break; case 9712: // Thaumaturgy Channel trigger_spell_id = 21029; break; // // Egan's Blaster // case 17368: break; // // Haunted // case 18347: break; // // Ranshalla Waiting // case 18953: break; // // Inferno // case 19695: break; // // Frostwolf Muzzle DND // case 21794: break; // // Alterac Ram Collar DND // case 21866: break; // // Celebras Waiting // case 21916: break; case 23170: // Brood Affliction: Bronze { target->CastSpell(target, 23171, true, NULL, this); return; } case 23184: // Mark of Frost case 25041: // Mark of Nature case 37125: // Mark of Death { std::list<Player*> targets; // spells existed in 1.x.x; 23183 - mark of frost; 25042 - mark of nature; both had radius of 100.0 yards in 1.x.x DBC // spells are used by Azuregos and the Emerald dragons in order to put a stun debuff on the players which resurrect during the encounter // in order to implement the missing spells we need to make a grid search for hostile players and check their auras; if they are marked apply debuff // spell 37127 used for the Mark of Death, is used server side, so it needs to be implemented here uint32 markSpellId = 0; uint32 debuffSpellId = 0; switch (auraId) { case 23184: markSpellId = 23182; debuffSpellId = 23186; break; case 25041: markSpellId = 25040; debuffSpellId = 25043; break; case 37125: markSpellId = 37128; debuffSpellId = 37131; break; } MaNGOS::AnyPlayerInObjectRangeWithAuraCheck u_check(GetTarget(), 100.0f, markSpellId); MaNGOS::PlayerListSearcher<MaNGOS::AnyPlayerInObjectRangeWithAuraCheck > checker(targets, u_check); Cell::VisitWorldObjects(GetTarget(), checker, 100.0f); for (std::list<Player*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) (*itr)->CastSpell((*itr), debuffSpellId, true, NULL, NULL, casterGUID); return; } case 23493: // Restoration { uint32 heal = triggerTarget->GetMaxHealth() / 10; triggerTarget->DealHeal(triggerTarget, heal, auraSpellInfo); if (int32 mana = triggerTarget->GetMaxPower(POWER_MANA)) { mana /= 10; triggerTarget->EnergizeBySpell(triggerTarget, 23493, mana, POWER_MANA); } return; } // // Stoneclaw Totem Passive TEST // case 23792: break; // // Axe Flurry // case 24018: break; case 24210: // Mark of Arlokk { // Replacement for (classic) spell 24211 (doesn't exist anymore) std::list<Creature*> lList; // Search for all Zulian Prowler in range MaNGOS::AllCreaturesOfEntryInRangeCheck check(triggerTarget, 15101, 15.0f); MaNGOS::CreatureListSearcher<MaNGOS::AllCreaturesOfEntryInRangeCheck> searcher(lList, check); Cell::VisitGridObjects(triggerTarget, searcher, 15.0f); for (std::list<Creature*>::const_iterator itr = lList.begin(); itr != lList.end(); ++itr) if ((*itr)->isAlive()) (*itr)->AddThreat(triggerTarget, float(5000)); return; } // // Restoration // case 24379: break; // // Happy Pet // case 24716: break; case 24780: // Dream Fog { // Note: In 1.12 triggered spell 24781 still exists, need to script dummy effect for this spell then // Select an unfriendly enemy in 100y range and attack it if (target->GetTypeId() != TYPEID_UNIT) return; ThreatList const& tList = target->getThreatManager().getThreatList(); for (ThreatList::const_iterator itr = tList.begin(); itr != tList.end(); ++itr) { Unit* pUnit = target->GetMap()->GetUnit((*itr)->getUnitGuid()); if (pUnit && target->getThreatManager().getThreat(pUnit)) target->getThreatManager().modifyThreatPercent(pUnit, -100); } if (Unit* pEnemy = target->SelectRandomUnfriendlyTarget(target->getVictim(), 100.0f)) ((Creature*)target)->AI()->AttackStart(pEnemy); return; } // // Cannon Prep // case 24832: break; case 24834: // Shadow Bolt Whirl { uint32 spellForTick[8] = { 24820, 24821, 24822, 24823, 24835, 24836, 24837, 24838 }; uint32 tick = (GetAuraTicks() + 7/*-1*/) % 8; // casted in left/right (but triggered spell have wide forward cone) float forward = target->GetOrientation(); if (tick <= 3) target->SetOrientation(forward + 0.75f * M_PI_F - tick * M_PI_F / 8); // Left else target->SetOrientation(forward - 0.75f * M_PI_F + (8 - tick) * M_PI_F / 8); // Right triggerTarget->CastSpell(triggerTarget, spellForTick[tick], true, NULL, this, casterGUID); target->SetOrientation(forward); return; } // // Stink Trap // case 24918: break; // // Agro Drones // case 25152: break; case 25371: // Consume { int32 bpDamage = triggerTarget->GetMaxHealth() * 10 / 100; triggerTarget->CastCustomSpell(triggerTarget, 25373, &bpDamage, NULL, NULL, true, NULL, this, casterGUID); return; } // // Pain Spike // case 25572: break; case 26009: // Rotate 360 case 26136: // Rotate -360 { float newAngle = target->GetOrientation(); if (auraId == 26009) newAngle += M_PI_F / 40; else newAngle -= M_PI_F / 40; newAngle = MapManager::NormalizeOrientation(newAngle); target->SetFacingTo(newAngle); target->CastSpell(target, 26029, true); return; } // // Consume // case 26196: break; // // Berserk // case 26615: break; // // Defile // case 27177: break; // // Teleport: IF/UC // case 27601: break; // // Five Fat Finger Exploding Heart Technique // case 27673: break; // // Nitrous Boost // case 27746: break; // // Steam Tank Passive // case 27747: break; case 27808: // Frost Blast { int32 bpDamage = triggerTarget->GetMaxHealth() * 26 / 100; triggerTarget->CastCustomSpell(triggerTarget, 29879, &bpDamage, NULL, NULL, true, NULL, this, casterGUID); return; } // Detonate Mana case 27819: { // 50% Mana Burn int32 bpDamage = (int32)triggerTarget->GetPower(POWER_MANA) * 0.5f; triggerTarget->ModifyPower(POWER_MANA, -bpDamage); triggerTarget->CastCustomSpell(triggerTarget, 27820, &bpDamage, NULL, NULL, true, NULL, this, triggerTarget->GetObjectGuid()); return; } // // Controller Timer // case 28095: break; // Stalagg Chain and Feugen Chain case 28096: case 28111: { // X-Chain is casted by Tesla to X, so: caster == Tesla, target = X Unit* pCaster = GetCaster(); if (pCaster && pCaster->GetTypeId() == TYPEID_UNIT && !pCaster->IsWithinDistInMap(target, 60.0f)) { pCaster->InterruptNonMeleeSpells(true); ((Creature*)pCaster)->SetInCombatWithZone(); // Stalagg Tesla Passive or Feugen Tesla Passive pCaster->CastSpell(pCaster, auraId == 28096 ? 28097 : 28109, true, NULL, NULL, target->GetObjectGuid()); } return; } // Stalagg Tesla Passive and Feugen Tesla Passive case 28097: case 28109: { // X-Tesla-Passive is casted by Tesla on Tesla with original caster X, so: caster = X, target = Tesla Unit* pCaster = GetCaster(); if (pCaster && pCaster->GetTypeId() == TYPEID_UNIT) { if (pCaster->getVictim() && !pCaster->IsWithinDistInMap(target, 60.0f)) { if (Unit* pTarget = ((Creature*)pCaster)->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) target->CastSpell(pTarget, 28099, false);// Shock } else { // "Evade" target->RemoveAurasDueToSpell(auraId); target->DeleteThreatList(); target->CombatStop(true); // Recast chain (Stalagg Chain or Feugen Chain target->CastSpell(pCaster, auraId == 28097 ? 28096 : 28111, false); } } return; } // // Mark of Didier // case 28114: break; // // Communique Timer, camp // case 28346: break; // // Icebolt // case 28522: break; // // Silithyst // case 29519: break; case 29528: // Inoculate Nestlewood Owlkin // prevent error reports in case ignored player target if (triggerTarget->GetTypeId() != TYPEID_UNIT) return; break; // // Overload // case 29768: break; // // Return Fire // case 29788: break; // // Return Fire // case 29793: break; // // Return Fire // case 29794: break; // // Guardian of Icecrown Passive // case 29897: break; case 29917: // Feed Captured Animal trigger_spell_id = 29916; break; // // Flame Wreath // case 29946: break; // // Flame Wreath // case 29947: break; // // Mind Exhaustion Passive // case 30025: break; // // Nether Beam - Serenity // case 30401: break; case 30427: // Extract Gas { Unit* caster = GetCaster(); if (!caster) return; // move loot to player inventory and despawn target if (caster->GetTypeId() == TYPEID_PLAYER && triggerTarget->GetTypeId() == TYPEID_UNIT && ((Creature*)triggerTarget)->GetCreatureInfo()->type == CREATURE_TYPE_GAS_CLOUD) { Player* player = (Player*)caster; Creature* creature = (Creature*)triggerTarget; // missing lootid has been reported on startup - just return if (!creature->GetCreatureInfo()->SkinLootId) return; player->AutoStoreLoot(creature, creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, true); creature->ForcedDespawn(); } return; } case 30576: // Quake trigger_spell_id = 30571; break; // // Burning Maul // case 30598: break; // // Regeneration // case 30799: // case 30800: // case 30801: // break; // // Despawn Self - Smoke cloud // case 31269: break; // // Time Rift Periodic // case 31320: break; // // Corrupt Medivh // case 31326: break; case 31347: // Doom { target->CastSpell(target, 31350, true); target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); return; } case 31373: // Spellcloth { // Summon Elemental after create item triggerTarget->SummonCreature(17870, 0.0f, 0.0f, 0.0f, triggerTarget->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0); return; } // // Bloodmyst Tesla // case 31611: break; case 31944: // Doomfire { int32 damage = m_modifier.m_amount * ((GetAuraDuration() + m_modifier.periodictime) / GetAuraMaxDuration()); triggerTarget->CastCustomSpell(triggerTarget, 31969, &damage, NULL, NULL, true, NULL, this, casterGUID); return; } // // Teleport Test // case 32236: break; // // Earthquake // case 32686: break; // // Possess // case 33401: break; // // Draw Shadows // case 33563: break; // // Murmur's Touch // case 33711: break; case 34229: // Flame Quills { // cast 24 spells 34269-34289, 34314-34316 for (uint32 spell_id = 34269; spell_id != 34290; ++spell_id) triggerTarget->CastSpell(triggerTarget, spell_id, true, NULL, this, casterGUID); for (uint32 spell_id = 34314; spell_id != 34317; ++spell_id) triggerTarget->CastSpell(triggerTarget, spell_id, true, NULL, this, casterGUID); return; } // // Gravity Lapse // case 34480: break; // // Tornado // case 34683: break; // // Frostbite Rotate // case 34748: break; // // Arcane Flurry // case 34821: break; // // Interrupt Shutdown // case 35016: break; // // Interrupt Shutdown // case 35176: break; // // Inferno // case 35268: break; // // Salaadin's Tesla // case 35515: break; // // Ethereal Channel (Red) // case 35518: break; // // Nether Vapor // case 35879: break; // // Dark Portal Storm // case 36018: break; // // Burning Maul // case 36056: break; // // Living Grove Defender Lifespan // case 36061: break; // // Professor Dabiri Talks // case 36064: break; // // Kael Gaining Power // case 36091: break; // // They Must Burn Bomb Aura // case 36344: break; // // They Must Burn Bomb Aura (self) // case 36350: break; // // Stolen Ravenous Ravager Egg // case 36401: break; // // Activated Cannon // case 36410: break; // // Stolen Ravenous Ravager Egg // case 36418: break; // // Enchanted Weapons // case 36510: break; // // Cursed Scarab Periodic // case 36556: break; // // Cursed Scarab Despawn Periodic // case 36561: break; case 36573: // Vision Guide { if (GetAuraTicks() == 10 && target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->AreaExploredOrEventHappens(10525); target->RemoveAurasDueToSpell(36573); } return; } // // Cannon Charging (platform) // case 36785: break; // // Cannon Charging (self) // case 36860: break; case 37027: // Remote Toy trigger_spell_id = 37029; break; // // Mark of Death // case 37125: break; // // Arcane Flurry // case 37268: break; case 37429: // Spout (left) case 37430: // Spout (right) { float newAngle = target->GetOrientation(); if (auraId == 37429) newAngle += 2 * M_PI_F / 100; else newAngle -= 2 * M_PI_F / 100; newAngle = MapManager::NormalizeOrientation(newAngle); target->SetFacingTo(newAngle); target->CastSpell(target, 37433, true); return; } // // Karazhan - Chess NPC AI, Snapshot timer // case 37440: break; // // Karazhan - Chess NPC AI, action timer // case 37504: break; // // Karazhan - Chess: Is Square OCCUPIED aura (DND) // case 39400: break; // // Banish // case 37546: break; // // Shriveling Gaze // case 37589: break; // // Fake Aggro Radius (2 yd) // case 37815: break; // // Corrupt Medivh // case 37853: break; case 38495: // Eye of Grillok { target->CastSpell(target, 38530, true); return; } case 38554: // Absorb Eye of Grillok (Zezzak's Shard) { if (target->GetTypeId() != TYPEID_UNIT) return; if (Unit* caster = GetCaster()) caster->CastSpell(caster, 38495, true, NULL, this); else return; Creature* creatureTarget = (Creature*)target; creatureTarget->ForcedDespawn(); return; } // // Magic Sucker Device timer // case 38672: break; // // Tomb Guarding Charging // case 38751: break; // // Murmur's Touch // case 38794: break; case 39105: // Activate Nether-wraith Beacon (31742 Nether-wraith Beacon item) { float fX, fY, fZ; triggerTarget->GetClosePoint(fX, fY, fZ, triggerTarget->GetObjectBoundingRadius(), 20.0f); triggerTarget->SummonCreature(22408, fX, fY, fZ, triggerTarget->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0); return; } // // Drain World Tree Visual // case 39140: break; // // Quest - Dustin's Undead Dragon Visual aura // case 39259: break; // // Hellfire - The Exorcism, Jules releases darkness, aura // case 39306: break; // // Inferno // case 39346: break; // // Enchanted Weapons // case 39489: break; // // Shadow Bolt Whirl // case 39630: break; // // Shadow Bolt Whirl // case 39634: break; // // Shadow Inferno // case 39645: break; case 39857: // Tear of Azzinoth Summon Channel - it's not really supposed to do anything,and this only prevents the console spam trigger_spell_id = 39856; break; // // Soulgrinder Ritual Visual (Smashed) // case 39974: break; // // Simon Game Pre-game timer // case 40041: break; // // Knockdown Fel Cannon: The Aggro Check Aura // case 40113: break; // // Spirit Lance // case 40157: break; case 40398: // Demon Transform 2 switch (GetAuraTicks()) { case 1: if (target->HasAura(40506)) target->RemoveAurasDueToSpell(40506); else trigger_spell_id = 40506; break; case 2: trigger_spell_id = 40510; break; } break; case 40511: // Demon Transform 1 trigger_spell_id = 40398; break; // // Ancient Flames // case 40657: break; // // Ethereal Ring Cannon: Cannon Aura // case 40734: break; // // Cage Trap // case 40760: break; // // Random Periodic // case 40867: break; // // Prismatic Shield // case 40879: break; // // Aura of Desire // case 41350: break; // // Dementia // case 41404: break; // // Chaos Form // case 41629: break; // // Alert Drums // case 42177: break; // // Spout // case 42581: break; // // Spout // case 42582: break; // // Return to the Spirit Realm // case 44035: break; // // Curse of Boundless Agony // case 45050: break; // // Earthquake // case 46240: break; case 46736: // Personalized Weather trigger_spell_id = 46737; break; // // Stay Submerged // case 46981: break; // // Dragonblight Ram // case 47015: break; // // Party G.R.E.N.A.D.E. // case 51510: break; default: break; } break; } case SPELLFAMILY_MAGE: { switch (auraId) { case 66: // Invisibility // Here need periodic trigger reducing threat spell (or do it manually) return; default: break; } break; } // case SPELLFAMILY_WARRIOR: // { // switch(auraId) // { // // Wild Magic // case 23410: break; // // Corrupted Totems // case 23425: break; // default: // break; // } // break; // } // case SPELLFAMILY_PRIEST: // { // switch(auraId) // { // // Blue Beam // case 32930: break; // // Fury of the Dreghood Elders // case 35460: break; // default: // break; // } // break; // } case SPELLFAMILY_DRUID: { switch (auraId) { case 768: // Cat Form // trigger_spell_id not set and unknown effect triggered in this case, ignoring for while return; case 22842: // Frenzied Regeneration case 22895: case 22896: case 26999: { int32 LifePerRage = GetModifier()->m_amount; int32 lRage = target->GetPower(POWER_RAGE); if (lRage > 100) // rage stored as rage*10 lRage = 100; target->ModifyPower(POWER_RAGE, -lRage); int32 FRTriggerBasePoints = int32(lRage * LifePerRage / 10); target->CastCustomSpell(target, 22845, &FRTriggerBasePoints, NULL, NULL, true, NULL, this); return; } default: break; } break; } // case SPELLFAMILY_HUNTER: // { // switch(auraId) // { // // Frost Trap Aura // case 13810: // return; // // Rizzle's Frost Trap // case 39900: // return; // // Tame spells // case 19597: // Tame Ice Claw Bear // case 19676: // Tame Snow Leopard // case 19677: // Tame Large Crag Boar // case 19678: // Tame Adult Plainstrider // case 19679: // Tame Prairie Stalker // case 19680: // Tame Swoop // case 19681: // Tame Dire Mottled Boar // case 19682: // Tame Surf Crawler // case 19683: // Tame Armored Scorpid // case 19684: // Tame Webwood Lurker // case 19685: // Tame Nightsaber Stalker // case 19686: // Tame Strigid Screecher // case 30100: // Tame Crazed Dragonhawk // case 30103: // Tame Elder Springpaw // case 30104: // Tame Mistbat // case 30647: // Tame Barbed Crawler // case 30648: // Tame Greater Timberstrider // case 30652: // Tame Nightstalker // return; // default: // break; // } // break; // } case SPELLFAMILY_SHAMAN: { switch (auraId) { case 28820: // Lightning Shield (The Earthshatterer set trigger after cast Lighting Shield) { // Need remove self if Lightning Shield not active Unit::SpellAuraHolderMap const& auras = triggerTarget->GetSpellAuraHolderMap(); for (Unit::SpellAuraHolderMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { SpellEntry const* spell = itr->second->GetSpellProto(); if (spell->SpellFamilyName == SPELLFAMILY_SHAMAN && (spell->SpellFamilyFlags & UI64LIT(0x0000000000000400))) return; } triggerTarget->RemoveAurasDueToSpell(28820); return; } case 38443: // Totemic Mastery (Skyshatter Regalia (Shaman Tier 6) - bonus) { if (triggerTarget->IsAllTotemSlotsUsed()) triggerTarget->CastSpell(triggerTarget, 38437, true, NULL, this); else triggerTarget->RemoveAurasDueToSpell(38437); return; } default: break; } break; } default: break; } // Reget trigger spell proto triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id); } else // initial triggeredSpellInfo != NULL { // for channeled spell cast applied from aura owner to channel target (persistent aura affects already applied to true target) // come periodic casts applied to targets, so need seelct proper caster (ex. 15790) if (IsChanneledSpell(GetSpellProto()) && GetSpellProto()->Effect[GetEffIndex()] != SPELL_EFFECT_PERSISTENT_AREA_AURA) { // interesting 2 cases: periodic aura at caster of channeled spell if (target->GetObjectGuid() == casterGUID) { triggerCaster = target; if (WorldObject* channelTarget = target->GetMap()->GetWorldObject(target->GetChannelObjectGuid())) { if (channelTarget->isType(TYPEMASK_UNIT)) triggerTarget = (Unit*)channelTarget; else triggerTargetObject = channelTarget; } } // or periodic aura at caster channel target else if (Unit* caster = GetCaster()) { if (target->GetObjectGuid() == caster->GetChannelObjectGuid()) { triggerCaster = caster; triggerTarget = target; } } } // Spell exist but require custom code switch (auraId) { case 9347: // Mortal Strike { if (target->GetTypeId() != TYPEID_UNIT) return; // expected selection current fight target triggerTarget = ((Creature*)target)->SelectAttackingTarget(ATTACKING_TARGET_TOPAGGRO, 0, triggeredSpellInfo); if (!triggerTarget) return; break; } case 1010: // Curse of Idiocy { // TODO: spell casted by result in correct way mostly // BUT: // 1) target show casting at each triggered cast: target don't must show casting animation for any triggered spell // but must show affect apply like item casting // 2) maybe aura must be replace by new with accumulative stat mods instead stacking // prevent cast by triggered auras if (casterGUID == triggerTarget->GetObjectGuid()) return; // stop triggering after each affected stats lost > 90 int32 intelectLoss = 0; int32 spiritLoss = 0; Unit::AuraList const& mModStat = triggerTarget->GetAurasByType(SPELL_AURA_MOD_STAT); for (Unit::AuraList::const_iterator i = mModStat.begin(); i != mModStat.end(); ++i) { if ((*i)->GetId() == 1010) { switch ((*i)->GetModifier()->m_miscvalue) { case STAT_INTELLECT: intelectLoss += (*i)->GetModifier()->m_amount; break; case STAT_SPIRIT: spiritLoss += (*i)->GetModifier()->m_amount; break; default: break; } } } if (intelectLoss <= -90 && spiritLoss <= -90) return; break; } case 16191: // Mana Tide { triggerTarget->CastCustomSpell(triggerTarget, trigger_spell_id, &m_modifier.m_amount, NULL, NULL, true, NULL, this); return; } case 33525: // Ground Slam triggerTarget->CastSpell(triggerTarget, trigger_spell_id, true, NULL, this, casterGUID); return; case 38736: // Rod of Purification - for quest 10839 (Veil Skith: Darkstone of Terokk) { if (Unit* caster = GetCaster()) caster->CastSpell(triggerTarget, trigger_spell_id, true, NULL, this); return; } case 44883: // Encapsulate { // Self cast spell, hence overwrite caster (only channeled spell where the triggered spell deals dmg to SELF) triggerCaster = triggerTarget; break; } } } // All ok cast by default case if (triggeredSpellInfo) { if (triggerTargetObject) triggerCaster->CastSpell(triggerTargetObject->GetPositionX(), triggerTargetObject->GetPositionY(), triggerTargetObject->GetPositionZ(), triggeredSpellInfo, true, NULL, this, casterGUID); else triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, NULL, this, casterGUID); } else { if (Unit* caster = GetCaster()) { if (triggerTarget->GetTypeId() != TYPEID_UNIT || !sScriptMgr.OnEffectDummy(caster, GetId(), GetEffIndex(), (Creature*)triggerTarget)) sLog.outError("Aura::TriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?", GetId(), GetEffIndex()); } } } void Aura::TriggerSpellWithValue() { ObjectGuid casterGuid = GetCasterGuid(); Unit* target = GetTriggerTarget(); if (!casterGuid || !target) return; // generic casting code with custom spells and target/caster customs uint32 trigger_spell_id = GetSpellProto()->EffectTriggerSpell[m_effIndex]; int32 basepoints0 = GetModifier()->m_amount; target->CastCustomSpell(target, trigger_spell_id, &basepoints0, NULL, NULL, true, NULL, this, casterGuid); } /*********************************************************/ /*** AURA EFFECTS ***/ /*********************************************************/ void Aura::HandleAuraDummy(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; Unit* target = GetTarget(); // AT APPLY if (apply) { switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (GetId()) { case 1515: // Tame beast // FIX_ME: this is 2.0.12 threat effect replaced in 2.1.x by dummy aura, must be checked for correctness if (target->CanHaveThreatList()) if (Unit* caster = GetCaster()) target->AddThreat(caster, 10.0f, false, GetSpellSchoolMask(GetSpellProto()), GetSpellProto()); return; case 7057: // Haunting Spirits // expected to tick with 30 sec period (tick part see in Aura::PeriodicTick) m_isPeriodic = true; m_modifier.periodictime = 30 * IN_MILLISECONDS; m_periodicTimer = m_modifier.periodictime; return; case 10255: // Stoned { if (Unit* caster = GetCaster()) { if (caster->GetTypeId() != TYPEID_UNIT) return; caster->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); caster->addUnitState(UNIT_STAT_ROOT); } return; } case 13139: // net-o-matic // root to self part of (root_target->charge->root_self sequence if (Unit* caster = GetCaster()) caster->CastSpell(caster, 13138, true, NULL, this); return; case 28832: // Mark of Korth'azz case 28833: // Mark of Blaumeux case 28834: // Mark of Rivendare case 28835: // Mark of Zeliek { int32 damage = 0; switch (GetStackAmount()) { case 1: return; case 2: damage = 500; break; case 3: damage = 1500; break; case 4: damage = 4000; break; case 5: damage = 12500; break; default: damage = 14000 + 1000 * GetStackAmount(); break; } if (Unit* caster = GetCaster()) caster->CastCustomSpell(target, 28836, &damage, NULL, NULL, true, NULL, this); return; } case 31606: // Stormcrow Amulet { CreatureInfo const* cInfo = ObjectMgr::GetCreatureTemplate(17970); // we must assume db or script set display id to native at ending flight (if not, target is stuck with this model) if (cInfo) target->SetDisplayId(Creature::ChooseDisplayId(cInfo)); return; } case 32045: // Soul Charge case 32051: case 32052: { // max duration is 2 minutes, but expected to be random duration // real time randomness is unclear, using max 30 seconds here // see further down for expire of this aura GetHolder()->SetAuraDuration(urand(1, 30)*IN_MILLISECONDS); return; } case 33326: // Stolen Soul Dispel { target->RemoveAurasDueToSpell(32346); return; } case 36587: // Vision Guide { target->CastSpell(target, 36573, true, NULL, this); return; } // Gender spells case 38224: // Illidari Agent Illusion case 37096: // Blood Elf Illusion case 46354: // Blood Elf Illusion { uint8 gender = target->getGender(); uint32 spellId; switch (GetId()) { case 38224: spellId = (gender == GENDER_MALE ? 38225 : 38227); break; case 37096: spellId = (gender == GENDER_MALE ? 37092 : 37094); break; case 46354: spellId = (gender == GENDER_MALE ? 46355 : 46356); break; default: return; } target->CastSpell(target, spellId, true, NULL, this); return; } case 39850: // Rocket Blast if (roll_chance_i(20)) // backfire stun target->CastSpell(target, 51581, true, NULL, this); return; case 43873: // Headless Horseman Laugh target->PlayDistanceSound(11965); return; case 46699: // Requires No Ammo if (target->GetTypeId() == TYPEID_PLAYER) // not use ammo and not allow use ((Player*)target)->RemoveAmmo(); return; case 48025: // Headless Horseman's Mount Spell::SelectMountByAreaAndSkill(target, GetSpellProto(), 51621, 48024, 51617, 48023, 0); return; } break; } case SPELLFAMILY_WARRIOR: { switch (GetId()) { case 41099: // Battle Stance { if (target->GetTypeId() != TYPEID_UNIT) return; // Stance Cooldown target->CastSpell(target, 41102, true, NULL, this); // Battle Aura target->CastSpell(target, 41106, true, NULL, this); // equipment ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32614); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 0); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0); return; } case 41100: // Berserker Stance { if (target->GetTypeId() != TYPEID_UNIT) return; // Stance Cooldown target->CastSpell(target, 41102, true, NULL, this); // Berserker Aura target->CastSpell(target, 41107, true, NULL, this); // equipment ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32614); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 0); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0); return; } case 41101: // Defensive Stance { if (target->GetTypeId() != TYPEID_UNIT) return; // Stance Cooldown target->CastSpell(target, 41102, true, NULL, this); // Defensive Aura target->CastSpell(target, 41105, true, NULL, this); // equipment ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32604); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 31467); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0); return; } } break; } case SPELLFAMILY_SHAMAN: { // Earth Shield if ((GetSpellProto()->SpellFamilyFlags & UI64LIT(0x40000000000))) { // prevent double apply bonuses if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading()) { if (Unit* caster = GetCaster()) { m_modifier.m_amount = caster->SpellHealingBonusDone(target, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE); m_modifier.m_amount = target->SpellHealingBonusTaken(caster, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE); } } return; } break; } } } // AT REMOVE else { if (IsQuestTameSpell(GetId()) && target->isAlive()) { Unit* caster = GetCaster(); if (!caster || !caster->isAlive()) return; uint32 finalSpellId = 0; switch (GetId()) { case 19548: finalSpellId = 19597; break; case 19674: finalSpellId = 19677; break; case 19687: finalSpellId = 19676; break; case 19688: finalSpellId = 19678; break; case 19689: finalSpellId = 19679; break; case 19692: finalSpellId = 19680; break; case 19693: finalSpellId = 19684; break; case 19694: finalSpellId = 19681; break; case 19696: finalSpellId = 19682; break; case 19697: finalSpellId = 19683; break; case 19699: finalSpellId = 19685; break; case 19700: finalSpellId = 19686; break; case 30646: finalSpellId = 30647; break; case 30653: finalSpellId = 30648; break; case 30654: finalSpellId = 30652; break; case 30099: finalSpellId = 30100; break; case 30102: finalSpellId = 30103; break; case 30105: finalSpellId = 30104; break; } if (finalSpellId) caster->CastSpell(target, finalSpellId, true, NULL, this); return; } switch (GetId()) { case 10255: // Stoned { if (Unit* caster = GetCaster()) { if (caster->GetTypeId() != TYPEID_UNIT) return; // see dummy effect of spell 10254 for removal of flags etc caster->CastSpell(caster, 10254, true); } return; } case 12479: // Hex of Jammal'an target->CastSpell(target, 12480, true, NULL, this); return; case 12774: // (DND) Belnistrasz Idol Shutdown Visual { if (m_removeMode == AURA_REMOVE_BY_DEATH) return; // Idom Rool Camera Shake <- wtf, don't drink while making spellnames? if (Unit* caster = GetCaster()) caster->CastSpell(caster, 12816, true); return; } case 28169: // Mutating Injection { // Mutagen Explosion target->CastSpell(target, 28206, true, NULL, this); // Poison Cloud target->CastSpell(target, 28240, true, NULL, this); return; } case 32045: // Soul Charge { if (m_removeMode == AURA_REMOVE_BY_EXPIRE) target->CastSpell(target, 32054, true, NULL, this); return; } case 32051: // Soul Charge { if (m_removeMode == AURA_REMOVE_BY_EXPIRE) target->CastSpell(target, 32057, true, NULL, this); return; } case 32052: // Soul Charge { if (m_removeMode == AURA_REMOVE_BY_EXPIRE) target->CastSpell(target, 32053, true, NULL, this); return; } case 32286: // Focus Target Visual { if (m_removeMode == AURA_REMOVE_BY_EXPIRE) target->CastSpell(target, 32301, true, NULL, this); return; } case 35079: // Misdirection, triggered buff { if (Unit* pCaster = GetCaster()) pCaster->RemoveAurasDueToSpell(34477); return; } case 36730: // Flame Strike { target->CastSpell(target, 36731, true, NULL, this); return; } case 41099: // Battle Stance { // Battle Aura target->RemoveAurasDueToSpell(41106); return; } case 41100: // Berserker Stance { // Berserker Aura target->RemoveAurasDueToSpell(41107); return; } case 41101: // Defensive Stance { // Defensive Aura target->RemoveAurasDueToSpell(41105); return; } case 42385: // Alcaz Survey Aura { target->CastSpell(target, 42316, true, NULL, this); return; } case 42454: // Captured Totem { if (m_removeMode == AURA_REMOVE_BY_DEFAULT) { if (target->getDeathState() != CORPSE) return; Unit* pCaster = GetCaster(); if (!pCaster) return; // Captured Totem Test Credit if (Player* pPlayer = pCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) pPlayer->CastSpell(pPlayer, 42455, true); } return; } case 42517: // Beam to Zelfrax { // expecting target to be a dummy creature Creature* pSummon = target->SummonCreature(23864, 0.0f, 0.0f, 0.0f, target->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0); Unit* pCaster = GetCaster(); if (pSummon && pCaster) pSummon->GetMotionMaster()->MovePoint(0, pCaster->GetPositionX(), pCaster->GetPositionY(), pCaster->GetPositionZ()); return; } case 44191: // Flame Strike { if (target->GetMap()->IsDungeon()) { uint32 spellId = target->GetMap()->IsRegularDifficulty() ? 44190 : 46163; target->CastSpell(target, spellId, true, NULL, this); } return; } case 45934: // Dark Fiend { // Kill target if dispelled if (m_removeMode == AURA_REMOVE_BY_DISPEL) target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); return; } case 46308: // Burning Winds { // casted only at creatures at spawn target->CastSpell(target, 47287, true, NULL, this); return; } } } // AT APPLY & REMOVE switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (GetId()) { case 6606: // Self Visual - Sleep Until Cancelled (DND) { if (apply) { target->SetStandState(UNIT_STAND_STATE_SLEEP); target->addUnitState(UNIT_STAT_ROOT); } else { target->clearUnitState(UNIT_STAT_ROOT); target->SetStandState(UNIT_STAND_STATE_STAND); } return; } case 24658: // Unstable Power { if (apply) { Unit* caster = GetCaster(); if (!caster) return; caster->CastSpell(target, 24659, true, NULL, NULL, GetCasterGuid()); } else target->RemoveAurasDueToSpell(24659); return; } case 24661: // Restless Strength { if (apply) { Unit* caster = GetCaster(); if (!caster) return; caster->CastSpell(target, 24662, true, NULL, NULL, GetCasterGuid()); } else target->RemoveAurasDueToSpell(24662); return; } case 29266: // Permanent Feign Death case 31261: // Permanent Feign Death (Root) case 37493: // Feign Death { // Unclear what the difference really is between them. // Some has effect1 that makes the difference, however not all. // Some appear to be used depending on creature location, in water, at solid ground, in air/suspended, etc // For now, just handle all the same way if (target->GetTypeId() == TYPEID_UNIT) target->SetFeignDeath(apply); return; } case 32216: // Victorious if (target->getClass() == CLASS_WARRIOR) target->ModifyAuraState(AURA_STATE_WARRIOR_VICTORY_RUSH, apply); return; case 35356: // Spawn Feign Death case 35357: // Spawn Feign Death { if (target->GetTypeId() == TYPEID_UNIT) { // Flags not set like it's done in SetFeignDeath() // UNIT_DYNFLAG_DEAD does not appear with these spells. // All of the spells appear to be present at spawn and not used to feign in combat or similar. if (apply) { target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH); target->addUnitState(UNIT_STAT_DIED); } else { target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH); target->clearUnitState(UNIT_STAT_DIED); } } return; } case 40133: // Summon Fire Elemental { Unit* caster = GetCaster(); if (!caster) return; Unit* owner = caster->GetOwner(); if (owner && owner->GetTypeId() == TYPEID_PLAYER) { if (apply) owner->CastSpell(owner, 8985, true); else ((Player*)owner)->RemovePet(PET_SAVE_REAGENTS); } return; } case 40132: // Summon Earth Elemental { Unit* caster = GetCaster(); if (!caster) return; Unit* owner = caster->GetOwner(); if (owner && owner->GetTypeId() == TYPEID_PLAYER) { if (apply) owner->CastSpell(owner, 19704, true); else ((Player*)owner)->RemovePet(PET_SAVE_REAGENTS); } return; } case 40214: // Dragonmaw Illusion { if (apply) { target->CastSpell(target, 40216, true); target->CastSpell(target, 42016, true); } else { target->RemoveAurasDueToSpell(40216); target->RemoveAurasDueToSpell(42016); } return; } case 42515: // Jarl Beam { // aura animate dead (fainted) state for the duration, but we need to animate the death itself (correct way below?) if (Unit* pCaster = GetCaster()) pCaster->ApplyModFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH, apply); // Beam to Zelfrax at remove if (!apply) target->CastSpell(target, 42517, true); return; } case 27978: case 40131: if (apply) target->m_AuraFlags |= UNIT_AURAFLAG_ALIVE_INVISIBLE; else target->m_AuraFlags |= ~UNIT_AURAFLAG_ALIVE_INVISIBLE; return; } break; } case SPELLFAMILY_MAGE: { // Hypothermia if (GetId() == 41425) { target->ModifyAuraState(AURA_STATE_HYPOTHERMIA, apply); return; } break; } case SPELLFAMILY_DRUID: { switch (GetId()) { case 34246: // Idol of the Emerald Queen { if (target->GetTypeId() != TYPEID_PLAYER) return; if (apply) // dummy not have proper effectclassmask m_spellmod = new SpellModifier(SPELLMOD_DOT, SPELLMOD_FLAT, m_modifier.m_amount / 7, GetId(), UI64LIT(0x001000000000)); ((Player*)target)->AddSpellMod(m_spellmod, apply); return; } } // Lifebloom if (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x1000000000)) { if (apply) { if (Unit* caster = GetCaster()) { // prevent double apply bonuses if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading()) { // Lifebloom ignore stack amount m_modifier.m_amount /= GetStackAmount(); m_modifier.m_amount = caster->SpellHealingBonusDone(target, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE); m_modifier.m_amount = target->SpellHealingBonusTaken(caster, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE); } } } else { // Final heal on duration end if (m_removeMode != AURA_REMOVE_BY_EXPIRE) return; // final heal if (target->IsInWorld() && GetStackAmount() > 0) { // Lifebloom dummy store single stack amount always int32 amount = m_modifier.m_amount; target->CastCustomSpell(target, 33778, &amount, NULL, NULL, true, NULL, this, GetCasterGuid()); } } return; } // Predatory Strikes if (target->GetTypeId() == TYPEID_PLAYER && GetSpellProto()->SpellIconID == 1563) { ((Player*)target)->UpdateAttackPowerAndDamage(); return; } break; } case SPELLFAMILY_ROGUE: break; case SPELLFAMILY_HUNTER: { switch (GetId()) { // Improved Aspect of the Viper case 38390: { if (target->GetTypeId() == TYPEID_PLAYER) { if (apply) // + effect value for Aspect of the Viper m_spellmod = new SpellModifier(SPELLMOD_EFFECT1, SPELLMOD_FLAT, m_modifier.m_amount, GetId(), UI64LIT(0x4000000000000)); ((Player*)target)->AddSpellMod(m_spellmod, apply); } return; } } break; } case SPELLFAMILY_SHAMAN: { switch (GetId()) { case 6495: // Sentry Totem { if (target->GetTypeId() != TYPEID_PLAYER) return; Totem* totem = target->GetTotem(TOTEM_SLOT_AIR); if (totem && apply) ((Player*)target)->GetCamera().SetView(totem); else ((Player*)target)->GetCamera().ResetView(); return; } } // Improved Weapon Totems if (GetSpellProto()->SpellIconID == 57 && target->GetTypeId() == TYPEID_PLAYER) { if (apply) { switch (m_effIndex) { case 0: // Windfury Totem m_spellmod = new SpellModifier(SPELLMOD_EFFECT1, SPELLMOD_PCT, m_modifier.m_amount, GetId(), UI64LIT(0x00200000000)); break; case 1: // Flametongue Totem m_spellmod = new SpellModifier(SPELLMOD_EFFECT1, SPELLMOD_PCT, m_modifier.m_amount, GetId(), UI64LIT(0x00400000000)); break; default: return; } } ((Player*)target)->AddSpellMod(m_spellmod, apply); return; } break; } } // pet auras if (PetAura const* petSpell = sSpellMgr.GetPetAura(GetId())) { if (apply) target->AddPetAura(petSpell); else target->RemovePetAura(petSpell); return; } if (GetEffIndex() == EFFECT_INDEX_0 && target->GetTypeId() == TYPEID_PLAYER) { SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAuraMapBounds(GetId()); if (saBounds.first != saBounds.second) { uint32 zone, area; target->GetZoneAndAreaId(zone, area); for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) { // some auras remove at aura remove if (!itr->second->IsFitToRequirements((Player*)target, zone, area)) target->RemoveAurasDueToSpell(itr->second->spellId); // some auras applied at aura apply else if (itr->second->autocast) { if (!target->HasAura(itr->second->spellId, EFFECT_INDEX_0)) target->CastSpell(target, itr->second->spellId, true); } } } } // script has to "handle with care", only use where data are not ok to use in the above code. if (target->GetTypeId() == TYPEID_UNIT) sScriptMgr.OnAuraDummy(this, apply); } void Aura::HandleAuraMounted(bool apply, bool Real) { // only at real add/remove aura if (!Real) return; Unit* target = GetTarget(); if (apply) { CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue); if (!ci) { sLog.outErrorDb("AuraMounted: `creature_template`='%u' not found in database (only need it modelid)", m_modifier.m_miscvalue); return; } uint32 display_id = Creature::ChooseDisplayId(ci); CreatureModelInfo const* minfo = sObjectMgr.GetCreatureModelRandomGender(display_id); if (minfo) display_id = minfo->modelid; target->Mount(display_id, GetId()); } else { target->Unmount(true); } } void Aura::HandleAuraWaterWalk(bool apply, bool Real) { // only at real add/remove aura if (!Real) return; GetTarget()->SetWaterWalk(apply); } void Aura::HandleAuraFeatherFall(bool apply, bool Real) { // only at real add/remove aura if (!Real) return; Unit* target = GetTarget(); WorldPacket data; if (apply) data.Initialize(SMSG_MOVE_FEATHER_FALL, 8 + 4); else data.Initialize(SMSG_MOVE_NORMAL_FALL, 8 + 4); data << target->GetPackGUID(); data << uint32(0); target->SendMessageToSet(&data, true); // start fall from current height if (!apply && target->GetTypeId() == TYPEID_PLAYER) ((Player*)target)->SetFallInformation(0, target->GetPositionZ()); } void Aura::HandleAuraHover(bool apply, bool Real) { // only at real add/remove aura if (!Real) return; WorldPacket data; if (apply) data.Initialize(SMSG_MOVE_SET_HOVER, 8 + 4); else data.Initialize(SMSG_MOVE_UNSET_HOVER, 8 + 4); data << GetTarget()->GetPackGUID(); data << uint32(0); GetTarget()->SendMessageToSet(&data, true); } void Aura::HandleWaterBreathing(bool /*apply*/, bool /*Real*/) { // update timers in client if (GetTarget()->GetTypeId() == TYPEID_PLAYER) ((Player*)GetTarget())->UpdateMirrorTimers(); } void Aura::HandleAuraModShapeshift(bool apply, bool Real) { if (!Real) return; ShapeshiftForm form = ShapeshiftForm(m_modifier.m_miscvalue); SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(form); if (!ssEntry) { sLog.outError("Unknown shapeshift form %u in spell %u", form, GetId()); return; } uint32 modelid = 0; Powers PowerType = POWER_MANA; Unit* target = GetTarget(); if (ssEntry->modelID_A) { // i will asume that creatures will always take the defined model from the dbc // since no field in creature_templates describes wether an alliance or // horde modelid should be used at shapeshifting if (target->GetTypeId() != TYPEID_PLAYER) modelid = ssEntry->modelID_A; else { // players are a bit different since the dbc has seldomly an horde modelid if (Player::TeamForRace(target->getRace()) == HORDE) { // get model for race ( in 2.2.4 no horde models in dbc field, only 0 in it modelid = sObjectMgr.GetModelForRace(ssEntry->modelID_A, target->getRaceMask()); } // nothing found in above, so use default if (!modelid) modelid = ssEntry->modelID_A; } } // remove polymorph before changing display id to keep new display id switch (form) { case FORM_CAT: case FORM_TREE: case FORM_TRAVEL: case FORM_AQUA: case FORM_BEAR: case FORM_DIREBEAR: case FORM_FLIGHT_EPIC: case FORM_FLIGHT: case FORM_MOONKIN: { // remove movement affects target->RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT, GetHolder()); Unit::AuraList const& slowingAuras = target->GetAurasByType(SPELL_AURA_MOD_DECREASE_SPEED); for (Unit::AuraList::const_iterator iter = slowingAuras.begin(); iter != slowingAuras.end();) { SpellEntry const* aurSpellInfo = (*iter)->GetSpellProto(); uint32 aurMechMask = GetAllSpellMechanicMask(aurSpellInfo); // If spell that caused this aura has Croud Control or Daze effect if ((aurMechMask & MECHANIC_NOT_REMOVED_BY_SHAPESHIFT) || // some Daze spells have these parameters instead of MECHANIC_DAZE (skip snare spells) (aurSpellInfo->SpellIconID == 15 && aurSpellInfo->Dispel == 0 && (aurMechMask & (1 << (MECHANIC_SNARE - 1))) == 0)) { ++iter; continue; } // All OK, remove aura now target->RemoveAurasDueToSpellByCancel(aurSpellInfo->Id); iter = slowingAuras.begin(); } // and polymorphic affects if (target->IsPolymorphed()) target->RemoveAurasDueToSpell(target->getTransForm()); break; } default: break; } if (apply) { // remove other shapeshift before applying a new one target->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT, GetHolder()); if (modelid > 0) target->SetDisplayId(modelid); // now only powertype must be set switch (form) { case FORM_CAT: PowerType = POWER_ENERGY; break; case FORM_BEAR: case FORM_DIREBEAR: case FORM_BATTLESTANCE: case FORM_BERSERKERSTANCE: case FORM_DEFENSIVESTANCE: PowerType = POWER_RAGE; break; default: break; } if (PowerType != POWER_MANA) { // reset power to default values only at power change if (target->getPowerType() != PowerType) target->setPowerType(PowerType); switch (form) { case FORM_CAT: case FORM_BEAR: case FORM_DIREBEAR: { // get furor proc chance int32 furorChance = 0; Unit::AuraList const& mDummy = target->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator i = mDummy.begin(); i != mDummy.end(); ++i) { if ((*i)->GetSpellProto()->SpellIconID == 238) { furorChance = (*i)->GetModifier()->m_amount; break; } } if (m_modifier.m_miscvalue == FORM_CAT) { target->SetPower(POWER_ENERGY, 0); if (irand(1, 100) <= furorChance) target->CastSpell(target, 17099, true, NULL, this); } else { target->SetPower(POWER_RAGE, 0); if (irand(1, 100) <= furorChance) target->CastSpell(target, 17057, true, NULL, this); } break; } case FORM_BATTLESTANCE: case FORM_DEFENSIVESTANCE: case FORM_BERSERKERSTANCE: { uint32 Rage_val = 0; // Stance mastery + Tactical mastery (both passive, and last have aura only in defense stance, but need apply at any stance switch) if (target->GetTypeId() == TYPEID_PLAYER) { PlayerSpellMap const& sp_list = ((Player*)target)->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) continue; SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first); if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellIconID == 139) Rage_val += target->CalculateSpellDamage(target, spellInfo, EFFECT_INDEX_0) * 10; } } if (target->GetPower(POWER_RAGE) > Rage_val) target->SetPower(POWER_RAGE, Rage_val); break; } default: break; } } target->SetShapeshiftForm(form); // a form can give the player a new castbar with some spells.. this is a clientside process.. // serverside just needs to register the new spells so that player isn't kicked as cheater if (target->GetTypeId() == TYPEID_PLAYER) for (uint32 i = 0; i < 8; ++i) if (ssEntry->spellId[i]) ((Player*)target)->addSpell(ssEntry->spellId[i], true, false, false, false); } else { if (modelid > 0) target->SetDisplayId(target->GetNativeDisplayId()); if (target->getClass() == CLASS_DRUID) target->setPowerType(POWER_MANA); target->SetShapeshiftForm(FORM_NONE); switch (form) { // Nordrassil Harness - bonus case FORM_BEAR: case FORM_DIREBEAR: case FORM_CAT: if (Aura* dummy = target->GetDummyAura(37315)) target->CastSpell(target, 37316, true, NULL, dummy); break; // Nordrassil Regalia - bonus case FORM_MOONKIN: if (Aura* dummy = target->GetDummyAura(37324)) target->CastSpell(target, 37325, true, NULL, dummy); break; default: break; } // look at the comment in apply-part if (target->GetTypeId() == TYPEID_PLAYER) for (uint32 i = 0; i < 8; ++i) if (ssEntry->spellId[i]) ((Player*)target)->removeSpell(ssEntry->spellId[i], false, false, false); } // adding/removing linked auras // add/remove the shapeshift aura's boosts HandleShapeshiftBoosts(apply); if (target->GetTypeId() == TYPEID_PLAYER) ((Player*)target)->InitDataForForm(); } void Aura::HandleAuraTransform(bool apply, bool Real) { Unit* target = GetTarget(); if (apply) { // special case (spell specific functionality) if (m_modifier.m_miscvalue == 0) { switch (GetId()) { case 16739: // Orb of Deception { uint32 orb_model = target->GetNativeDisplayId(); switch (orb_model) { // Troll Female case 1479: target->SetDisplayId(10134); break; // Troll Male case 1478: target->SetDisplayId(10135); break; // Tauren Male case 59: target->SetDisplayId(10136); break; // Human Male case 49: target->SetDisplayId(10137); break; // Human Female case 50: target->SetDisplayId(10138); break; // Orc Male case 51: target->SetDisplayId(10139); break; // Orc Female case 52: target->SetDisplayId(10140); break; // Dwarf Male case 53: target->SetDisplayId(10141); break; // Dwarf Female case 54: target->SetDisplayId(10142); break; // NightElf Male case 55: target->SetDisplayId(10143); break; // NightElf Female case 56: target->SetDisplayId(10144); break; // Undead Female case 58: target->SetDisplayId(10145); break; // Undead Male case 57: target->SetDisplayId(10146); break; // Tauren Female case 60: target->SetDisplayId(10147); break; // Gnome Male case 1563: target->SetDisplayId(10148); break; // Gnome Female case 1564: target->SetDisplayId(10149); break; // BloodElf Female case 15475: target->SetDisplayId(17830); break; // BloodElf Male case 15476: target->SetDisplayId(17829); break; // Dranei Female case 16126: target->SetDisplayId(17828); break; // Dranei Male case 16125: target->SetDisplayId(17827); break; default: break; } break; } case 42365: // Murloc costume target->SetDisplayId(21723); break; // case 44186: // Gossip NPC Appearance - All, Brewfest // break; // case 48305: // Gossip NPC Appearance - All, Spirit of Competition // break; case 50517: // Dread Corsair case 51926: // Corsair Costume { // expected for players uint32 race = target->getRace(); switch (race) { case RACE_HUMAN: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25037 : 25048); break; case RACE_ORC: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25039 : 25050); break; case RACE_DWARF: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25034 : 25045); break; case RACE_NIGHTELF: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25038 : 25049); break; case RACE_UNDEAD: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25042 : 25053); break; case RACE_TAUREN: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25040 : 25051); break; case RACE_GNOME: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25035 : 25046); break; case RACE_TROLL: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25041 : 25052); break; case RACE_GOBLIN: // not really player race (3.x), but model exist target->SetDisplayId(target->getGender() == GENDER_MALE ? 25036 : 25047); break; case RACE_BLOODELF: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25032 : 25043); break; case RACE_DRAENEI: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25033 : 25044); break; } break; } // case 50531: // Gossip NPC Appearance - All, Pirate Day // break; // case 51010: // Dire Brew // break; default: sLog.outError("Aura::HandleAuraTransform, spell %u does not have creature entry defined, need custom defined model.", GetId()); break; } } else // m_modifier.m_miscvalue != 0 { uint32 model_id; CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue); if (!ci) { model_id = 16358; // pig pink ^_^ sLog.outError("Auras: unknown creature id = %d (only need its modelid) Form Spell Aura Transform in Spell ID = %d", m_modifier.m_miscvalue, GetId()); } else model_id = Creature::ChooseDisplayId(ci); // Will use the default model here target->SetDisplayId(model_id); // creature case, need to update equipment if additional provided if (ci && target->GetTypeId() == TYPEID_UNIT) ((Creature*)target)->LoadEquipment(ci->equipmentId, false); // Dragonmaw Illusion (set mount model also) if (GetId() == 42016 && target->GetMountID() && !target->GetAurasByType(SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED).empty()) target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 16314); } // update active transform spell only not set or not overwriting negative by positive case if (!target->getTransForm() || !IsPositiveSpell(GetId()) || IsPositiveSpell(target->getTransForm())) target->setTransForm(GetId()); // polymorph case if (Real && target->GetTypeId() == TYPEID_PLAYER && target->IsPolymorphed()) { // for players, start regeneration after 1s (in polymorph fast regeneration case) // only if caster is Player (after patch 2.4.2) if (GetCasterGuid().IsPlayer()) ((Player*)target)->setRegenTimer(1 * IN_MILLISECONDS); // dismount polymorphed target (after patch 2.4.2) if (target->IsMounted()) target->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED, GetHolder()); } } else // !apply { // ApplyModifier(true) will reapply it if need target->setTransForm(0); target->SetDisplayId(target->GetNativeDisplayId()); // apply default equipment for creature case if (target->GetTypeId() == TYPEID_UNIT) ((Creature*)target)->LoadEquipment(((Creature*)target)->GetCreatureInfo()->equipmentId, true); // re-apply some from still active with preference negative cases Unit::AuraList const& otherTransforms = target->GetAurasByType(SPELL_AURA_TRANSFORM); if (!otherTransforms.empty()) { // look for other transform auras Aura* handledAura = *otherTransforms.begin(); for (Unit::AuraList::const_iterator i = otherTransforms.begin(); i != otherTransforms.end(); ++i) { // negative auras are preferred if (!IsPositiveSpell((*i)->GetSpellProto()->Id)) { handledAura = *i; break; } } handledAura->ApplyModifier(true); } // Dragonmaw Illusion (restore mount model) if (GetId() == 42016 && target->GetMountID() == 16314) { if (!target->GetAurasByType(SPELL_AURA_MOUNTED).empty()) { uint32 cr_id = target->GetAurasByType(SPELL_AURA_MOUNTED).front()->GetModifier()->m_miscvalue; if (CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(cr_id)) { uint32 display_id = Creature::ChooseDisplayId(ci); CreatureModelInfo const* minfo = sObjectMgr.GetCreatureModelRandomGender(display_id); if (minfo) display_id = minfo->modelid; target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, display_id); } } } } } void Aura::HandleForceReaction(bool apply, bool Real) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; if (!Real) return; Player* player = (Player*)GetTarget(); uint32 faction_id = m_modifier.m_miscvalue; ReputationRank faction_rank = ReputationRank(m_modifier.m_amount); player->GetReputationMgr().ApplyForceReaction(faction_id, faction_rank, apply); player->GetReputationMgr().SendForceReactions(); // stop fighting if at apply forced rank friendly or at remove real rank friendly if ((apply && faction_rank >= REP_FRIENDLY) || (!apply && player->GetReputationRank(faction_id) >= REP_FRIENDLY)) player->StopAttackFaction(faction_id); } void Aura::HandleAuraModSkill(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; uint32 prot = GetSpellProto()->EffectMiscValue[m_effIndex]; int32 points = GetModifier()->m_amount; ((Player*)GetTarget())->ModifySkillBonus(prot, (apply ? points : -points), m_modifier.m_auraname == SPELL_AURA_MOD_SKILL_TALENT); if (prot == SKILL_DEFENSE) ((Player*)GetTarget())->UpdateDefenseBonusesMod(); } void Aura::HandleChannelDeathItem(bool apply, bool Real) { if (Real && !apply) { if (m_removeMode != AURA_REMOVE_BY_DEATH) return; // Item amount if (m_modifier.m_amount <= 0) return; SpellEntry const* spellInfo = GetSpellProto(); if (spellInfo->EffectItemType[m_effIndex] == 0) return; Unit* victim = GetTarget(); Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) return; // Soul Shard (target req.) if (spellInfo->EffectItemType[m_effIndex] == 6265) { // Only from non-grey units if (!((Player*)caster)->isHonorOrXPTarget(victim) || (victim->GetTypeId() == TYPEID_UNIT && !((Player*)caster)->isAllowedToLoot((Creature*)victim))) return; } // Adding items uint32 noSpaceForCount = 0; uint32 count = m_modifier.m_amount; ItemPosCountVec dest; InventoryResult msg = ((Player*)caster)->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, spellInfo->EffectItemType[m_effIndex], count, &noSpaceForCount); if (msg != EQUIP_ERR_OK) { count -= noSpaceForCount; ((Player*)caster)->SendEquipError(msg, NULL, NULL, spellInfo->EffectItemType[m_effIndex]); if (count == 0) return; } Item* newitem = ((Player*)caster)->StoreNewItem(dest, spellInfo->EffectItemType[m_effIndex], true); ((Player*)caster)->SendNewItem(newitem, count, true, true); } } void Aura::HandleBindSight(bool apply, bool /*Real*/) { Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) return; Camera& camera = ((Player*)caster)->GetCamera(); if (apply) camera.SetView(GetTarget()); else camera.ResetView(); } void Aura::HandleFarSight(bool apply, bool /*Real*/) { Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) return; Camera& camera = ((Player*)caster)->GetCamera(); if (apply) camera.SetView(GetTarget()); else camera.ResetView(); } void Aura::HandleAuraTrackCreatures(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; if (apply) GetTarget()->RemoveNoStackAurasDueToAuraHolder(GetHolder()); if (apply) GetTarget()->SetFlag(PLAYER_TRACK_CREATURES, uint32(1) << (m_modifier.m_miscvalue - 1)); else GetTarget()->RemoveFlag(PLAYER_TRACK_CREATURES, uint32(1) << (m_modifier.m_miscvalue - 1)); } void Aura::HandleAuraTrackResources(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; if (apply) GetTarget()->RemoveNoStackAurasDueToAuraHolder(GetHolder()); if (apply) GetTarget()->SetFlag(PLAYER_TRACK_RESOURCES, uint32(1) << (m_modifier.m_miscvalue - 1)); else GetTarget()->RemoveFlag(PLAYER_TRACK_RESOURCES, uint32(1) << (m_modifier.m_miscvalue - 1)); } void Aura::HandleAuraTrackStealthed(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; if (apply) GetTarget()->RemoveNoStackAurasDueToAuraHolder(GetHolder()); GetTarget()->ApplyModByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_TRACK_STEALTHED, apply); } void Aura::HandleAuraModScale(bool apply, bool /*Real*/) { GetTarget()->ApplyPercentModFloatValue(OBJECT_FIELD_SCALE_X, float(m_modifier.m_amount), apply); GetTarget()->UpdateModelData(); } void Aura::HandleModPossess(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); // not possess yourself if (GetCasterGuid() == target->GetObjectGuid()) return; Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) return; Player* p_caster = (Player*)caster; Camera& camera = p_caster->GetCamera(); if (apply) { target->addUnitState(UNIT_STAT_CONTROLLED); target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); target->SetCharmerGuid(p_caster->GetObjectGuid()); target->setFaction(p_caster->getFaction()); // target should became visible at SetView call(if not visible before): // otherwise client\p_caster will ignore packets from the target(SetClientControl for example) camera.SetView(target); p_caster->SetCharm(target); p_caster->SetClientControl(target, 1); p_caster->SetMover(target); target->CombatStop(true); target->DeleteThreatList(); target->getHostileRefManager().deleteReferences(); if (CharmInfo* charmInfo = target->InitCharmInfo(target)) { charmInfo->InitPossessCreateSpells(); charmInfo->SetReactState(REACT_PASSIVE); charmInfo->SetCommandState(COMMAND_STAY); } p_caster->PossessSpellInitialize(); if (target->GetTypeId() == TYPEID_UNIT) { ((Creature*)target)->AIM_Initialize(); } else if (target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->SetClientControl(target, 0); } } else { p_caster->SetCharm(NULL); p_caster->SetClientControl(target, 0); p_caster->SetMover(NULL); // there is a possibility that target became invisible for client\p_caster at ResetView call: // it must be called after movement control unapplying, not before! the reason is same as at aura applying camera.ResetView(); p_caster->RemovePetActionBar(); // on delete only do caster related effects if (m_removeMode == AURA_REMOVE_BY_DELETE) return; target->clearUnitState(UNIT_STAT_CONTROLLED); target->CombatStop(true); target->DeleteThreatList(); target->getHostileRefManager().deleteReferences(); target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); target->SetCharmerGuid(ObjectGuid()); if (target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->setFactionForRace(target->getRace()); ((Player*)target)->SetClientControl(target, 1); } else if (target->GetTypeId() == TYPEID_UNIT) { CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo(); target->setFaction(cinfo->faction_A); } if (target->GetTypeId() == TYPEID_UNIT) { ((Creature*)target)->AIM_Initialize(); target->AttackedBy(caster); } } } void Aura::HandleModPossessPet(bool apply, bool Real) { if (!Real) return; Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) return; Unit* target = GetTarget(); if (target->GetTypeId() != TYPEID_UNIT || !((Creature*)target)->IsPet()) return; Pet* pet = (Pet*)target; Player* p_caster = (Player*)caster; Camera& camera = p_caster->GetCamera(); if (apply) { pet->addUnitState(UNIT_STAT_CONTROLLED); // target should became visible at SetView call(if not visible before): // otherwise client\p_caster will ignore packets from the target(SetClientControl for example) camera.SetView(pet); p_caster->SetCharm(pet); p_caster->SetClientControl(pet, 1); ((Player*)caster)->SetMover(pet); pet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); pet->StopMoving(); pet->GetMotionMaster()->Clear(false); pet->GetMotionMaster()->MoveIdle(); } else { p_caster->SetCharm(NULL); p_caster->SetClientControl(pet, 0); p_caster->SetMover(NULL); // there is a possibility that target became invisible for client\p_caster at ResetView call: // it must be called after movement control unapplying, not before! the reason is same as at aura applying camera.ResetView(); // on delete only do caster related effects if (m_removeMode == AURA_REMOVE_BY_DELETE) return; pet->clearUnitState(UNIT_STAT_CONTROLLED); pet->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); pet->AttackStop(); // out of range pet dismissed if (!pet->IsWithinDistInMap(p_caster, pet->GetMap()->GetVisibilityDistance())) { p_caster->RemovePet(PET_SAVE_REAGENTS); } else { pet->GetMotionMaster()->MoveFollow(caster, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); } } } void Aura::HandleModCharm(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); // not charm yourself if (GetCasterGuid() == target->GetObjectGuid()) return; Unit* caster = GetCaster(); if (!caster) return; if (apply) { // is it really need after spell check checks? target->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM, GetHolder()); target->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS, GetHolder()); target->SetCharmerGuid(GetCasterGuid()); target->setFaction(caster->getFaction()); target->CastStop(target == caster ? GetId() : 0); caster->SetCharm(target); target->CombatStop(true); target->DeleteThreatList(); target->getHostileRefManager().deleteReferences(); if (target->GetTypeId() == TYPEID_UNIT) { ((Creature*)target)->AIM_Initialize(); CharmInfo* charmInfo = target->InitCharmInfo(target); charmInfo->InitCharmCreateSpells(); charmInfo->SetReactState(REACT_DEFENSIVE); if (caster->GetTypeId() == TYPEID_PLAYER && caster->getClass() == CLASS_WARLOCK) { CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo(); if (cinfo && cinfo->type == CREATURE_TYPE_DEMON) { // creature with pet number expected have class set if (target->GetByteValue(UNIT_FIELD_BYTES_0, 1) == 0) { if (cinfo->unit_class == 0) sLog.outErrorDb("Creature (Entry: %u) have unit_class = 0 but used in charmed spell, that will be result client crash.", cinfo->Entry); else sLog.outError("Creature (Entry: %u) have unit_class = %u but at charming have class 0!!! that will be result client crash.", cinfo->Entry, cinfo->unit_class); target->SetByteValue(UNIT_FIELD_BYTES_0, 1, CLASS_MAGE); } // just to enable stat window charmInfo->SetPetNumber(sObjectMgr.GeneratePetNumber(), true); // if charmed two demons the same session, the 2nd gets the 1st one's name target->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); } } } if (caster->GetTypeId() == TYPEID_PLAYER) ((Player*)caster)->CharmSpellInitialize(); } else { target->SetCharmerGuid(ObjectGuid()); if (target->GetTypeId() == TYPEID_PLAYER) ((Player*)target)->setFactionForRace(target->getRace()); else { CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo(); // restore faction if (((Creature*)target)->IsPet()) { if (Unit* owner = target->GetOwner()) target->setFaction(owner->getFaction()); else if (cinfo) target->setFaction(cinfo->faction_A); } else if (cinfo) // normal creature target->setFaction(cinfo->faction_A); // restore UNIT_FIELD_BYTES_0 if (cinfo && caster->GetTypeId() == TYPEID_PLAYER && caster->getClass() == CLASS_WARLOCK && cinfo->type == CREATURE_TYPE_DEMON) { // DB must have proper class set in field at loading, not req. restore, including workaround case at apply // m_target->SetByteValue(UNIT_FIELD_BYTES_0, 1, cinfo->unit_class); if (target->GetCharmInfo()) target->GetCharmInfo()->SetPetNumber(0, true); else sLog.outError("Aura::HandleModCharm: target (GUID: %u TypeId: %u) has a charm aura but no charm info!", target->GetGUIDLow(), target->GetTypeId()); } } caster->SetCharm(NULL); if (caster->GetTypeId() == TYPEID_PLAYER) ((Player*)caster)->RemovePetActionBar(); target->CombatStop(true); target->DeleteThreatList(); target->getHostileRefManager().deleteReferences(); if (target->GetTypeId() == TYPEID_UNIT) { ((Creature*)target)->AIM_Initialize(); target->AttackedBy(caster); } } } void Aura::HandleModConfuse(bool apply, bool Real) { if (!Real) return; GetTarget()->SetConfused(apply, GetCasterGuid(), GetId()); } void Aura::HandleModFear(bool apply, bool Real) { if (!Real) return; GetTarget()->SetFeared(apply, GetCasterGuid(), GetId()); } void Aura::HandleFeignDeath(bool apply, bool Real) { if (!Real) return; GetTarget()->SetFeignDeath(apply, GetCasterGuid(), GetId()); } void Aura::HandleAuraModDisarm(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); if (!apply && target->HasAuraType(GetModifier()->m_auraname)) return; target->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED, apply); if (target->GetTypeId() != TYPEID_PLAYER) return; // main-hand attack speed already set to special value for feral form already and don't must change and reset at remove. if (target->IsInFeralForm()) return; if (apply) target->SetAttackTime(BASE_ATTACK, BASE_ATTACK_TIME); else ((Player*)target)->SetRegularAttackTime(); target->UpdateDamagePhysical(BASE_ATTACK); } void Aura::HandleAuraModStun(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); if (apply) { // Frost stun aura -> freeze/unfreeze target if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST) target->ModifyAuraState(AURA_STATE_FROZEN, apply); target->addUnitState(UNIT_STAT_STUNNED); target->SetTargetGuid(ObjectGuid()); target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); target->CastStop(target->GetObjectGuid() == GetCasterGuid() ? GetId() : 0); // Creature specific if (target->GetTypeId() != TYPEID_PLAYER) target->StopMoving(); else { ((Player*)target)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE); target->SetStandState(UNIT_STAND_STATE_STAND);// in 1.5 client } target->SetRoot(true); // Summon the Naj'entus Spine GameObject on target if spell is Impaling Spine if (GetId() == 39837) { GameObject* pObj = new GameObject; if (pObj->Create(target->GetMap()->GenerateLocalLowGuid(HIGHGUID_GAMEOBJECT), 185584, target->GetMap(), target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation())) { pObj->SetRespawnTime(GetAuraDuration() / IN_MILLISECONDS); pObj->SetSpellId(GetId()); target->AddGameObject(pObj); target->GetMap()->Add(pObj); } else delete pObj; } } else { // Frost stun aura -> freeze/unfreeze target if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST) { bool found_another = false; for (AuraType const* itr = &frozenAuraTypes[0]; *itr != SPELL_AURA_NONE; ++itr) { Unit::AuraList const& auras = target->GetAurasByType(*itr); for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i) { if (GetSpellSchoolMask((*i)->GetSpellProto()) & SPELL_SCHOOL_MASK_FROST) { found_another = true; break; } } if (found_another) break; } if (!found_another) target->ModifyAuraState(AURA_STATE_FROZEN, apply); } // Real remove called after current aura remove from lists, check if other similar auras active if (target->HasAuraType(SPELL_AURA_MOD_STUN)) return; target->clearUnitState(UNIT_STAT_STUNNED); target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); if (!target->hasUnitState(UNIT_STAT_ROOT)) // prevent allow move if have also root effect { if (target->getVictim() && target->isAlive()) target->SetTargetGuid(target->getVictim()->GetObjectGuid()); target->SetRoot(false); } // Wyvern Sting if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_HUNTER && GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000100000000000)) { Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) return; uint32 spell_id = 0; switch (GetId()) { case 19386: spell_id = 24131; break; case 24132: spell_id = 24134; break; case 24133: spell_id = 24135; break; case 27068: spell_id = 27069; break; default: sLog.outError("Spell selection called for unexpected original spell %u, new spell for this spell family?", GetId()); return; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id); if (!spellInfo) return; caster->CastSpell(target, spellInfo, true, NULL, this); return; } } } void Aura::HandleModStealth(bool apply, bool Real) { Unit* target = GetTarget(); if (apply) { // drop flag at stealth in bg target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION); // only at real aura add if (Real) { target->SetStandFlags(UNIT_STAND_FLAGS_CREEP); if (target->GetTypeId() == TYPEID_PLAYER) target->SetByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_STEALTH); // apply only if not in GM invisibility (and overwrite invisibility state) if (target->GetVisibility() != VISIBILITY_OFF) { target->SetVisibility(VISIBILITY_GROUP_NO_DETECT); target->SetVisibility(VISIBILITY_GROUP_STEALTH); } // for RACE_NIGHTELF stealth if (target->GetTypeId() == TYPEID_PLAYER && GetId() == 20580) target->CastSpell(target, 21009, true, NULL, this); // apply full stealth period bonuses only at first stealth aura in stack if (target->GetAurasByType(SPELL_AURA_MOD_STEALTH).size() <= 1) { Unit::AuraList const& mDummyAuras = target->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) { // Master of Subtlety if ((*i)->GetSpellProto()->SpellIconID == 2114) { target->RemoveAurasDueToSpell(31666); int32 bp = (*i)->GetModifier()->m_amount; target->CastCustomSpell(target, 31665, &bp, NULL, NULL, true); break; } } } } } else { // for RACE_NIGHTELF stealth if (Real && target->GetTypeId() == TYPEID_PLAYER && GetId() == 20580) target->RemoveAurasDueToSpell(21009); // only at real aura remove of _last_ SPELL_AURA_MOD_STEALTH if (Real && !target->HasAuraType(SPELL_AURA_MOD_STEALTH)) { // if no GM invisibility if (target->GetVisibility() != VISIBILITY_OFF) { target->RemoveStandFlags(UNIT_STAND_FLAGS_CREEP); if (target->GetTypeId() == TYPEID_PLAYER) target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_STEALTH); // restore invisibility if any if (target->HasAuraType(SPELL_AURA_MOD_INVISIBILITY)) { target->SetVisibility(VISIBILITY_GROUP_NO_DETECT); target->SetVisibility(VISIBILITY_GROUP_INVISIBILITY); } else target->SetVisibility(VISIBILITY_ON); } // apply delayed talent bonus remover at last stealth aura remove Unit::AuraList const& mDummyAuras = target->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) { // Master of Subtlety if ((*i)->GetSpellProto()->SpellIconID == 2114) { target->CastSpell(target, 31666, true); break; } } } } } void Aura::HandleInvisibility(bool apply, bool Real) { Unit* target = GetTarget(); if (apply) { target->m_invisibilityMask |= (1 << m_modifier.m_miscvalue); target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION); if (Real && target->GetTypeId() == TYPEID_PLAYER) { // apply glow vision target->SetByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW); } // apply only if not in GM invisibility and not stealth if (target->GetVisibility() == VISIBILITY_ON) { // Aura not added yet but visibility code expect temporary add aura target->SetVisibility(VISIBILITY_GROUP_NO_DETECT); target->SetVisibility(VISIBILITY_GROUP_INVISIBILITY); } } else { // recalculate value at modifier remove (current aura already removed) target->m_invisibilityMask = 0; Unit::AuraList const& auras = target->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY); for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) target->m_invisibilityMask |= (1 << (*itr)->GetModifier()->m_miscvalue); // only at real aura remove and if not have different invisibility auras. if (Real && target->m_invisibilityMask == 0) { // remove glow vision if (target->GetTypeId() == TYPEID_PLAYER) target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW); // apply only if not in GM invisibility & not stealthed while invisible if (target->GetVisibility() != VISIBILITY_OFF) { // if have stealth aura then already have stealth visibility if (!target->HasAuraType(SPELL_AURA_MOD_STEALTH)) target->SetVisibility(VISIBILITY_ON); } } } } void Aura::HandleInvisibilityDetect(bool apply, bool Real) { Unit* target = GetTarget(); if (apply) { target->m_detectInvisibilityMask |= (1 << m_modifier.m_miscvalue); } else { // recalculate value at modifier remove (current aura already removed) target->m_detectInvisibilityMask = 0; Unit::AuraList const& auras = target->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION); for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) target->m_detectInvisibilityMask |= (1 << (*itr)->GetModifier()->m_miscvalue); } if (Real && target->GetTypeId() == TYPEID_PLAYER) ((Player*)target)->GetCamera().UpdateVisibilityForOwner(); } void Aura::HandleDetectAmore(bool apply, bool /*real*/) { GetTarget()->ApplyModByteFlag(PLAYER_FIELD_BYTES2, 1, (PLAYER_FIELD_BYTE2_DETECT_AMORE_0 << m_modifier.m_amount), apply); } void Aura::HandleAuraModRoot(bool apply, bool Real) { // only at real add/remove aura if (!Real) return; Unit* target = GetTarget(); if (apply) { // Frost root aura -> freeze/unfreeze target if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST) target->ModifyAuraState(AURA_STATE_FROZEN, apply); target->addUnitState(UNIT_STAT_ROOT); target->SetTargetGuid(ObjectGuid()); // Save last orientation if (target->getVictim()) target->SetOrientation(target->GetAngle(target->getVictim())); if (target->GetTypeId() == TYPEID_PLAYER) { target->SetRoot(true); // Clear unit movement flags ((Player*)target)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE); } else target->StopMoving(); } else { // Frost root aura -> freeze/unfreeze target if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST) { bool found_another = false; for (AuraType const* itr = &frozenAuraTypes[0]; *itr != SPELL_AURA_NONE; ++itr) { Unit::AuraList const& auras = target->GetAurasByType(*itr); for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i) { if (GetSpellSchoolMask((*i)->GetSpellProto()) & SPELL_SCHOOL_MASK_FROST) { found_another = true; break; } } if (found_another) break; } if (!found_another) target->ModifyAuraState(AURA_STATE_FROZEN, apply); } // Real remove called after current aura remove from lists, check if other similar auras active if (target->HasAuraType(SPELL_AURA_MOD_ROOT)) return; target->clearUnitState(UNIT_STAT_ROOT); if (!target->hasUnitState(UNIT_STAT_STUNNED)) // prevent allow move if have also stun effect { if (target->getVictim() && target->isAlive()) target->SetTargetGuid(target->getVictim()->GetObjectGuid()); if (target->GetTypeId() == TYPEID_PLAYER) target->SetRoot(false); } } } void Aura::HandleAuraModSilence(bool apply, bool Real) { // only at real add/remove aura if (!Real) return; Unit* target = GetTarget(); if (apply) { target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED); // Stop cast only spells vs PreventionType == SPELL_PREVENTION_TYPE_SILENCE for (uint32 i = CURRENT_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) if (Spell* spell = target->GetCurrentSpell(CurrentSpellTypes(i))) if (spell->m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE) // Stop spells on prepare or casting state target->InterruptSpell(CurrentSpellTypes(i), false); switch (GetId()) { // Arcane Torrent (Energy) case 25046: { Unit* caster = GetCaster(); if (!caster) return; // Search Mana Tap auras on caster Aura* dummy = caster->GetDummyAura(28734); if (dummy) { int32 bp = dummy->GetStackAmount() * 10; caster->CastCustomSpell(caster, 25048, &bp, NULL, NULL, true); caster->RemoveAurasDueToSpell(28734); } } } } else { // Real remove called after current aura remove from lists, check if other similar auras active if (target->HasAuraType(SPELL_AURA_MOD_SILENCE)) return; target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED); } } void Aura::HandleModThreat(bool apply, bool Real) { // only at real add/remove aura if (!Real) return; Unit* target = GetTarget(); if (!target->isAlive()) return; int level_diff = 0; int multiplier = 0; switch (GetId()) { // Arcane Shroud case 26400: level_diff = target->getLevel() - 60; multiplier = 2; break; // The Eye of Diminution case 28862: level_diff = target->getLevel() - 60; multiplier = 1; break; } if (level_diff > 0) m_modifier.m_amount += multiplier * level_diff; if (target->GetTypeId() == TYPEID_PLAYER) for (int8 x = 0; x < MAX_SPELL_SCHOOL; ++x) if (m_modifier.m_miscvalue & int32(1 << x)) ApplyPercentModFloatVar(target->m_threatModifier[x], float(m_modifier.m_amount), apply); } void Aura::HandleAuraModTotalThreat(bool apply, bool Real) { // only at real add/remove aura if (!Real) return; Unit* target = GetTarget(); if (!target->isAlive() || target->GetTypeId() != TYPEID_PLAYER) return; Unit* caster = GetCaster(); if (!caster || !caster->isAlive()) return; float threatMod = apply ? float(m_modifier.m_amount) : float(-m_modifier.m_amount); target->getHostileRefManager().threatAssist(caster, threatMod, GetSpellProto()); } void Aura::HandleModTaunt(bool apply, bool Real) { // only at real add/remove aura if (!Real) return; Unit* target = GetTarget(); if (!target->isAlive() || !target->CanHaveThreatList()) return; Unit* caster = GetCaster(); if (!caster || !caster->isAlive()) return; if (apply) target->TauntApply(caster); else { // When taunt aura fades out, mob will switch to previous target if current has less than 1.1 * secondthreat target->TauntFadeOut(caster); } } /*********************************************************/ /*** MODIFY SPEED ***/ /*********************************************************/ void Aura::HandleAuraModIncreaseSpeed(bool /*apply*/, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; GetTarget()->UpdateSpeed(MOVE_RUN, true); } void Aura::HandleAuraModIncreaseMountedSpeed(bool /*apply*/, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; GetTarget()->UpdateSpeed(MOVE_RUN, true); } void Aura::HandleAuraModIncreaseFlightSpeed(bool apply, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; Unit* target = GetTarget(); // Enable Fly mode for flying mounts if (m_modifier.m_auraname == SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED) { WorldPacket data; if (apply) data.Initialize(SMSG_MOVE_SET_CAN_FLY, 12); else data.Initialize(SMSG_MOVE_UNSET_CAN_FLY, 12); data << target->GetPackGUID(); data << uint32(0); // unknown target->SendMessageToSet(&data, true); // Players on flying mounts must be immune to polymorph if (target->GetTypeId() == TYPEID_PLAYER) target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); // Dragonmaw Illusion (overwrite mount model, mounted aura already applied) if (apply && target->HasAura(42016, EFFECT_INDEX_0) && target->GetMountID()) target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 16314); } target->UpdateSpeed(MOVE_FLIGHT, true); } void Aura::HandleAuraModIncreaseSwimSpeed(bool /*apply*/, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; GetTarget()->UpdateSpeed(MOVE_SWIM, true); } void Aura::HandleAuraModDecreaseSpeed(bool apply, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; Unit* target = GetTarget(); if (apply) { // Gronn Lord's Grasp, becomes stoned if (GetId() == 33572) { if (GetStackAmount() >= 5 && !target->HasAura(33652)) target->CastSpell(target, 33652, true); } } target->UpdateSpeed(MOVE_RUN, true); target->UpdateSpeed(MOVE_SWIM, true); target->UpdateSpeed(MOVE_FLIGHT, true); } void Aura::HandleAuraModUseNormalSpeed(bool /*apply*/, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; Unit* target = GetTarget(); target->UpdateSpeed(MOVE_RUN, true); target->UpdateSpeed(MOVE_SWIM, true); target->UpdateSpeed(MOVE_FLIGHT, true); } /*********************************************************/ /*** IMMUNITY ***/ /*********************************************************/ void Aura::HandleModMechanicImmunity(bool apply, bool /*Real*/) { uint32 misc = m_modifier.m_miscvalue; Unit* target = GetTarget(); if (apply && GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) { uint32 mechanic = 1 << (misc - 1); // immune movement impairment and loss of control (spell data have special structure for mark this case) if (IsSpellRemoveAllMovementAndControlLossEffects(GetSpellProto())) mechanic = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK; target->RemoveAurasAtMechanicImmunity(mechanic, GetId()); } target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, misc, apply); // special cases switch (misc) { case MECHANIC_INVULNERABILITY: target->ModifyAuraState(AURA_STATE_FORBEARANCE, apply); break; case MECHANIC_SHIELD: target->ModifyAuraState(AURA_STATE_WEAKENED_SOUL, apply); break; } // Bestial Wrath if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_HUNTER && GetSpellProto()->SpellIconID == 1680) { // The Beast Within cast on owner if talent present if (Unit* owner = target->GetOwner()) { // Search talent The Beast Within Unit::AuraList const& dummyAuras = owner->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i) { if ((*i)->GetSpellProto()->SpellIconID == 2229) { if (apply) owner->CastSpell(owner, 34471, true, NULL, this); else owner->RemoveAurasDueToSpell(34471); break; } } } } } void Aura::HandleModMechanicImmunityMask(bool apply, bool /*Real*/) { uint32 mechanic = m_modifier.m_miscvalue; if (apply && GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) GetTarget()->RemoveAurasAtMechanicImmunity(mechanic, GetId()); // check implemented in Unit::IsImmuneToSpell and Unit::IsImmuneToSpellEffect } // this method is called whenever we add / remove aura which gives m_target some imunity to some spell effect void Aura::HandleAuraModEffectImmunity(bool apply, bool /*Real*/) { Unit* target = GetTarget(); // when removing flag aura, handle flag drop if (!apply && target->GetTypeId() == TYPEID_PLAYER && (GetSpellProto()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION)) { Player* player = (Player*)target; if (BattleGround* bg = player->GetBattleGround()) bg->EventPlayerDroppedFlag(player); else if (OutdoorPvP* outdoorPvP = sOutdoorPvPMgr.GetScript(player->GetCachedZoneId())) outdoorPvP->HandleDropFlag(player, GetSpellProto()->Id); } target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, m_modifier.m_miscvalue, apply); } void Aura::HandleAuraModStateImmunity(bool apply, bool Real) { if (apply && Real && GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) { Unit::AuraList const& auraList = GetTarget()->GetAurasByType(AuraType(m_modifier.m_miscvalue)); for (Unit::AuraList::const_iterator itr = auraList.begin(); itr != auraList.end();) { if (auraList.front() != this) // skip itself aura (it already added) { GetTarget()->RemoveAurasDueToSpell(auraList.front()->GetId()); itr = auraList.begin(); } else ++itr; } } GetTarget()->ApplySpellImmune(GetId(), IMMUNITY_STATE, m_modifier.m_miscvalue, apply); } void Aura::HandleAuraModSchoolImmunity(bool apply, bool Real) { Unit* target = GetTarget(); target->ApplySpellImmune(GetId(), IMMUNITY_SCHOOL, m_modifier.m_miscvalue, apply); // remove all flag auras (they are positive, but they must be removed when you are immune) if (GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY) && GetSpellProto()->HasAttribute(SPELL_ATTR_EX2_DAMAGE_REDUCED_SHIELD)) target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION); // TODO: optimalize this cycle - use RemoveAurasWithInterruptFlags call or something else if (Real && apply && GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY) && IsPositiveSpell(GetId())) // Only positive immunity removes auras { uint32 school_mask = m_modifier.m_miscvalue; Unit::SpellAuraHolderMap& Auras = target->GetSpellAuraHolderMap(); for (Unit::SpellAuraHolderMap::iterator iter = Auras.begin(), next; iter != Auras.end(); iter = next) { next = iter; ++next; SpellEntry const* spell = iter->second->GetSpellProto(); if ((GetSpellSchoolMask(spell) & school_mask) // Check for school mask && !spell->HasAttribute(SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) // Spells unaffected by invulnerability && !iter->second->IsPositive() // Don't remove positive spells && spell->Id != GetId()) // Don't remove self { target->RemoveAurasDueToSpell(spell->Id); if (Auras.empty()) break; else next = Auras.begin(); } } } if (Real && GetSpellProto()->Mechanic == MECHANIC_BANISH) { if (apply) target->addUnitState(UNIT_STAT_ISOLATED); else target->clearUnitState(UNIT_STAT_ISOLATED); } } void Aura::HandleAuraModDmgImmunity(bool apply, bool /*Real*/) { GetTarget()->ApplySpellImmune(GetId(), IMMUNITY_DAMAGE, m_modifier.m_miscvalue, apply); } void Aura::HandleAuraModDispelImmunity(bool apply, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; GetTarget()->ApplySpellDispelImmunity(GetSpellProto(), DispelType(m_modifier.m_miscvalue), apply); } void Aura::HandleAuraProcTriggerSpell(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); switch (GetId()) { // some spell have charges by functionality not have its in spell data case 28200: // Ascendance (Talisman of Ascendance trinket) if (apply) GetHolder()->SetAuraCharges(6); break; default: break; } } void Aura::HandleAuraModStalked(bool apply, bool /*Real*/) { // used by spells: Hunter's Mark, Mind Vision, Syndicate Tracker (MURP) DND if (apply) GetTarget()->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TRACK_UNIT); else GetTarget()->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TRACK_UNIT); } /*********************************************************/ /*** PERIODIC ***/ /*********************************************************/ void Aura::HandlePeriodicTriggerSpell(bool apply, bool /*Real*/) { m_isPeriodic = apply; Unit* target = GetTarget(); if (!apply) { switch (GetId()) { case 66: // Invisibility if (m_removeMode == AURA_REMOVE_BY_EXPIRE) target->CastSpell(target, 32612, true, NULL, this); return; case 29213: // Curse of the Plaguebringer if (m_removeMode != AURA_REMOVE_BY_DISPEL) // Cast Wrath of the Plaguebringer if not dispelled target->CastSpell(target, 29214, true, 0, this); return; case 42783: // Wrath of the Astrom... if (m_removeMode == AURA_REMOVE_BY_EXPIRE && GetEffIndex() + 1 < MAX_EFFECT_INDEX) target->CastSpell(target, GetSpellProto()->CalculateSimpleValue(SpellEffectIndex(GetEffIndex() + 1)), true); return; default: break; } } } void Aura::HandlePeriodicTriggerSpellWithValue(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::HandlePeriodicEnergize(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::HandleAuraPowerBurn(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::HandleAuraPeriodicDummy(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; Unit* target = GetTarget(); // For prevent double apply bonuses bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading()); SpellEntry const* spell = GetSpellProto(); switch (spell->SpellFamilyName) { case SPELLFAMILY_ROGUE: { // Master of Subtlety if (spell->Id == 31666 && !apply) { target->RemoveAurasDueToSpell(31665); break; } break; } case SPELLFAMILY_HUNTER: { // Aspect of the Viper if (spell->SpellFamilyFlags & UI64LIT(0x0004000000000000)) { // Update regen on remove if (!apply && target->GetTypeId() == TYPEID_PLAYER) ((Player*)target)->UpdateManaRegen(); break; } break; } } m_isPeriodic = apply; } void Aura::HandlePeriodicHeal(bool apply, bool /*Real*/) { m_isPeriodic = apply; Unit* target = GetTarget(); // For prevent double apply bonuses bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading()); // Custom damage calculation after if (apply) { if (loading) return; Unit* caster = GetCaster(); if (!caster) return; m_modifier.m_amount = caster->SpellHealingBonusDone(target, GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount()); } } void Aura::HandlePeriodicDamage(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; m_isPeriodic = apply; Unit* target = GetTarget(); SpellEntry const* spellProto = GetSpellProto(); // For prevent double apply bonuses bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading()); // Custom damage calculation after if (apply) { if (loading) return; Unit* caster = GetCaster(); if (!caster) return; switch (spellProto->SpellFamilyName) { case SPELLFAMILY_WARRIOR: { // Rend if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000020)) { // 0.00743*(($MWB+$mwb)/2+$AP/14*$MWS) bonus per tick float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK); int32 mws = caster->GetAttackTime(BASE_ATTACK); float mwb_min = caster->GetWeaponDamageRange(BASE_ATTACK, MINDAMAGE); float mwb_max = caster->GetWeaponDamageRange(BASE_ATTACK, MAXDAMAGE); m_modifier.m_amount += int32(((mwb_min + mwb_max) / 2 + ap * mws / 14000) * 0.00743f); } break; } case SPELLFAMILY_DRUID: { // Rip if (spellProto->SpellFamilyFlags & UI64LIT(0x000000000000800000)) { if (caster->GetTypeId() != TYPEID_PLAYER) break; // $AP * min(0.06*$cp, 0.24)/6 [Yes, there is no difference, whether 4 or 5 CPs are being used] uint8 cp = ((Player*)caster)->GetComboPoints(); // Idol of Feral Shadows. Cant be handled as SpellMod in SpellAura:Dummy due its dependency from CPs Unit::AuraList const& dummyAuras = caster->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr) { if ((*itr)->GetId() == 34241) { m_modifier.m_amount += cp * (*itr)->GetModifier()->m_amount; break; } } if (cp > 4) cp = 4; m_modifier.m_amount += int32(caster->GetTotalAttackPowerValue(BASE_ATTACK) * cp / 100); } break; } case SPELLFAMILY_ROGUE: { // Rupture if (spellProto->SpellFamilyFlags & UI64LIT(0x000000000000100000)) { if (caster->GetTypeId() != TYPEID_PLAYER) break; // Dmg/tick = $AP*min(0.01*$cp, 0.03) [Like Rip: only the first three CP increase the contribution from AP] uint8 cp = ((Player*)caster)->GetComboPoints(); if (cp > 3) cp = 3; m_modifier.m_amount += int32(caster->GetTotalAttackPowerValue(BASE_ATTACK) * cp / 100); } break; } default: break; } if (m_modifier.m_auraname == SPELL_AURA_PERIODIC_DAMAGE) { // SpellDamageBonusDone for magic spells if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellProto->DmgClass == SPELL_DAMAGE_CLASS_MAGIC) m_modifier.m_amount = caster->SpellDamageBonusDone(target, GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount()); // MeleeDamagebonusDone for weapon based spells else { WeaponAttackType attackType = GetWeaponAttackType(GetSpellProto()); m_modifier.m_amount = caster->MeleeDamageBonusDone(target, m_modifier.m_amount, attackType, GetSpellProto(), DOT, GetStackAmount()); } } } // remove time effects else { // Parasitic Shadowfiend - handle summoning of two Shadowfiends on DoT expire if (spellProto->Id == 41917) target->CastSpell(target, 41915, true); } } void Aura::HandlePeriodicDamagePCT(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::HandlePeriodicLeech(bool apply, bool /*Real*/) { m_isPeriodic = apply; // For prevent double apply bonuses bool loading = (GetTarget()->GetTypeId() == TYPEID_PLAYER && ((Player*)GetTarget())->GetSession()->PlayerLoading()); // Custom damage calculation after if (apply) { if (loading) return; Unit* caster = GetCaster(); if (!caster) return; m_modifier.m_amount = caster->SpellDamageBonusDone(GetTarget(), GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount()); } } void Aura::HandlePeriodicManaLeech(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::HandlePeriodicHealthFunnel(bool apply, bool /*Real*/) { m_isPeriodic = apply; // For prevent double apply bonuses bool loading = (GetTarget()->GetTypeId() == TYPEID_PLAYER && ((Player*)GetTarget())->GetSession()->PlayerLoading()); // Custom damage calculation after if (apply) { if (loading) return; Unit* caster = GetCaster(); if (!caster) return; m_modifier.m_amount = caster->SpellDamageBonusDone(GetTarget(), GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount()); } } /*********************************************************/ /*** MODIFY STATS ***/ /*********************************************************/ /********************************/ /*** RESISTANCE ***/ /********************************/ void Aura::HandleAuraModResistanceExclusive(bool apply, bool /*Real*/) { for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x) { if (m_modifier.m_miscvalue & int32(1 << x)) { GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), BASE_VALUE, float(m_modifier.m_amount), apply); if (GetTarget()->GetTypeId() == TYPEID_PLAYER) GetTarget()->ApplyResistanceBuffModsMod(SpellSchools(x), m_positive, float(m_modifier.m_amount), apply); } } } void Aura::HandleAuraModResistance(bool apply, bool /*Real*/) { for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x) { if (m_modifier.m_miscvalue & int32(1 << x)) { GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), TOTAL_VALUE, float(m_modifier.m_amount), apply); if (GetTarget()->GetTypeId() == TYPEID_PLAYER || ((Creature*)GetTarget())->IsPet()) GetTarget()->ApplyResistanceBuffModsMod(SpellSchools(x), m_positive, float(m_modifier.m_amount), apply); } } } void Aura::HandleAuraModBaseResistancePCT(bool apply, bool /*Real*/) { // only players have base stats if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { // pets only have base armor if (((Creature*)GetTarget())->IsPet() && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)) GetTarget()->HandleStatModifier(UNIT_MOD_ARMOR, BASE_PCT, float(m_modifier.m_amount), apply); } else { for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x) { if (m_modifier.m_miscvalue & int32(1 << x)) GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), BASE_PCT, float(m_modifier.m_amount), apply); } } } void Aura::HandleModResistancePercent(bool apply, bool /*Real*/) { Unit* target = GetTarget(); for (int8 i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i) { if (m_modifier.m_miscvalue & int32(1 << i)) { target->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + i), TOTAL_PCT, float(m_modifier.m_amount), apply); if (target->GetTypeId() == TYPEID_PLAYER || ((Creature*)target)->IsPet()) { target->ApplyResistanceBuffModsPercentMod(SpellSchools(i), true, float(m_modifier.m_amount), apply); target->ApplyResistanceBuffModsPercentMod(SpellSchools(i), false, float(m_modifier.m_amount), apply); } } } } void Aura::HandleModBaseResistance(bool apply, bool /*Real*/) { // only players have base stats if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { // only pets have base stats if (((Creature*)GetTarget())->IsPet() && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)) GetTarget()->HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(m_modifier.m_amount), apply); } else { for (int i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i) if (m_modifier.m_miscvalue & (1 << i)) GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + i), TOTAL_VALUE, float(m_modifier.m_amount), apply); } } /********************************/ /*** STAT ***/ /********************************/ void Aura::HandleAuraModStat(bool apply, bool /*Real*/) { if (m_modifier.m_miscvalue < -2 || m_modifier.m_miscvalue > 4) { sLog.outError("WARNING: Spell %u effect %u have unsupported misc value (%i) for SPELL_AURA_MOD_STAT ", GetId(), GetEffIndex(), m_modifier.m_miscvalue); return; } for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i) { // -1 or -2 is all stats ( misc < -2 checked in function beginning ) if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue == i) { // m_target->ApplyStatMod(Stats(i), m_modifier.m_amount,apply); GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_VALUE, float(m_modifier.m_amount), apply); if (GetTarget()->GetTypeId() == TYPEID_PLAYER || ((Creature*)GetTarget())->IsPet()) GetTarget()->ApplyStatBuffMod(Stats(i), float(m_modifier.m_amount), apply); } } } void Aura::HandleModPercentStat(bool apply, bool /*Real*/) { if (m_modifier.m_miscvalue < -1 || m_modifier.m_miscvalue > 4) { sLog.outError("WARNING: Misc Value for SPELL_AURA_MOD_PERCENT_STAT not valid"); return; } // only players have base stats if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i) { if (m_modifier.m_miscvalue == i || m_modifier.m_miscvalue == -1) GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), BASE_PCT, float(m_modifier.m_amount), apply); } } void Aura::HandleModSpellDamagePercentFromStat(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // Magic damage modifiers implemented in Unit::SpellDamageBonusDone // This information for client side use only // Recalculate bonus ((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus(); } void Aura::HandleModSpellHealingPercentFromStat(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // Recalculate bonus ((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus(); } void Aura::HandleAuraModDispelResist(bool apply, bool Real) { if (!Real || !apply) return; if (GetId() == 33206) GetTarget()->CastSpell(GetTarget(), 44416, true, NULL, this, GetCasterGuid()); } void Aura::HandleModSpellDamagePercentFromAttackPower(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // Magic damage modifiers implemented in Unit::SpellDamageBonusDone // This information for client side use only // Recalculate bonus ((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus(); } void Aura::HandleModSpellHealingPercentFromAttackPower(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // Recalculate bonus ((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus(); } void Aura::HandleModHealingDone(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // implemented in Unit::SpellHealingBonusDone // this information is for client side only ((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus(); } void Aura::HandleModTotalPercentStat(bool apply, bool /*Real*/) { if (m_modifier.m_miscvalue < -1 || m_modifier.m_miscvalue > 4) { sLog.outError("WARNING: Misc Value for SPELL_AURA_MOD_PERCENT_STAT not valid"); return; } Unit* target = GetTarget(); // save current and max HP before applying aura uint32 curHPValue = target->GetHealth(); uint32 maxHPValue = target->GetMaxHealth(); for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i) { if (m_modifier.m_miscvalue == i || m_modifier.m_miscvalue == -1) { target->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_PCT, float(m_modifier.m_amount), apply); if (target->GetTypeId() == TYPEID_PLAYER || ((Creature*)target)->IsPet()) target->ApplyStatPercentBuffMod(Stats(i), float(m_modifier.m_amount), apply); } } // recalculate current HP/MP after applying aura modifications (only for spells with 0x10 flag) if (m_modifier.m_miscvalue == STAT_STAMINA && maxHPValue > 0 && GetSpellProto()->HasAttribute(SPELL_ATTR_UNK4)) { // newHP = (curHP / maxHP) * newMaxHP = (newMaxHP * curHP) / maxHP -> which is better because no int -> double -> int conversion is needed uint32 newHPValue = (target->GetMaxHealth() * curHPValue) / maxHPValue; target->SetHealth(newHPValue); } } void Aura::HandleAuraModResistenceOfStatPercent(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; if (m_modifier.m_miscvalue != SPELL_SCHOOL_MASK_NORMAL) { // support required adding replace UpdateArmor by loop by UpdateResistence at intellect update // and include in UpdateResistence same code as in UpdateArmor for aura mod apply. sLog.outError("Aura SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT(182) need adding support for non-armor resistances!"); return; } // Recalculate Armor GetTarget()->UpdateArmor(); } /********************************/ /*** HEAL & ENERGIZE ***/ /********************************/ void Aura::HandleAuraModTotalHealthPercentRegen(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::HandleAuraModTotalManaPercentRegen(bool apply, bool /*Real*/) { if (m_modifier.periodictime == 0) m_modifier.periodictime = 1000; m_periodicTimer = m_modifier.periodictime; m_isPeriodic = apply; } void Aura::HandleModRegen(bool apply, bool /*Real*/) // eating { if (m_modifier.periodictime == 0) m_modifier.periodictime = 5000; m_periodicTimer = 5000; m_isPeriodic = apply; } void Aura::HandleModPowerRegen(bool apply, bool Real) // drinking { if (!Real) return; Powers pt = GetTarget()->getPowerType(); if (m_modifier.periodictime == 0) { // Anger Management (only spell use this aura for rage) if (pt == POWER_RAGE) m_modifier.periodictime = 3000; else m_modifier.periodictime = 2000; } m_periodicTimer = 5000; if (GetTarget()->GetTypeId() == TYPEID_PLAYER && m_modifier.m_miscvalue == POWER_MANA) ((Player*)GetTarget())->UpdateManaRegen(); m_isPeriodic = apply; } void Aura::HandleModPowerRegenPCT(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) return; if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // Update manaregen value if (m_modifier.m_miscvalue == POWER_MANA) ((Player*)GetTarget())->UpdateManaRegen(); } void Aura::HandleModManaRegen(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) return; if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // Note: an increase in regen does NOT cause threat. ((Player*)GetTarget())->UpdateManaRegen(); } void Aura::HandleComprehendLanguage(bool apply, bool /*Real*/) { if (apply) GetTarget()->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG); else GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG); } void Aura::HandleAuraModIncreaseHealth(bool apply, bool Real) { Unit* target = GetTarget(); // Special case with temporary increase max/current health switch (GetId()) { case 12976: // Warrior Last Stand triggered spell case 28726: // Nightmare Seed ( Nightmare Seed ) case 34511: // Valor (Bulwark of Kings, Bulwark of the Ancient Kings) case 44055: // Tremendous Fortitude (Battlemaster's Alacrity) { if (Real) { if (apply) { target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply); target->ModifyHealth(m_modifier.m_amount); } else { if (int32(target->GetHealth()) > m_modifier.m_amount) target->ModifyHealth(-m_modifier.m_amount); else target->SetHealth(1); target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply); } } return; } } // generic case target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply); } void Aura::HandleAuraModIncreaseMaxHealth(bool apply, bool /*Real*/) { Unit* target = GetTarget(); uint32 oldhealth = target->GetHealth(); double healthPercentage = (double)oldhealth / (double)target->GetMaxHealth(); target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply); // refresh percentage if (oldhealth > 0) { uint32 newhealth = uint32(ceil((double)target->GetMaxHealth() * healthPercentage)); if (newhealth == 0) newhealth = 1; target->SetHealth(newhealth); } } void Aura::HandleAuraModIncreaseEnergy(bool apply, bool /*Real*/) { Unit* target = GetTarget(); Powers powerType = target->getPowerType(); if (int32(powerType) != m_modifier.m_miscvalue) return; UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + powerType); target->HandleStatModifier(unitMod, TOTAL_VALUE, float(m_modifier.m_amount), apply); } void Aura::HandleAuraModIncreaseEnergyPercent(bool apply, bool /*Real*/) { Powers powerType = GetTarget()->getPowerType(); if (int32(powerType) != m_modifier.m_miscvalue) return; UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + powerType); GetTarget()->HandleStatModifier(unitMod, TOTAL_PCT, float(m_modifier.m_amount), apply); } void Aura::HandleAuraModIncreaseHealthPercent(bool apply, bool /*Real*/) { GetTarget()->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_PCT, float(m_modifier.m_amount), apply); } /********************************/ /*** FIGHT ***/ /********************************/ void Aura::HandleAuraModParryPercent(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; ((Player*)GetTarget())->UpdateParryPercentage(); } void Aura::HandleAuraModDodgePercent(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; ((Player*)GetTarget())->UpdateDodgePercentage(); // sLog.outError("BONUS DODGE CHANCE: + %f", float(m_modifier.m_amount)); } void Aura::HandleAuraModBlockPercent(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; ((Player*)GetTarget())->UpdateBlockPercentage(); // sLog.outError("BONUS BLOCK CHANCE: + %f", float(m_modifier.m_amount)); } void Aura::HandleAuraModRegenInterrupt(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) return; if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; ((Player*)GetTarget())->UpdateManaRegen(); } void Aura::HandleAuraModCritPercent(bool apply, bool Real) { Unit* target = GetTarget(); if (target->GetTypeId() != TYPEID_PLAYER) return; // apply item specific bonuses for already equipped weapon if (Real) { for (int i = 0; i < MAX_ATTACK; ++i) if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false)) ((Player*)target)->_ApplyWeaponDependentAuraCritMod(pItem, WeaponAttackType(i), this, apply); } // mods must be applied base at equipped weapon class and subclass comparison // with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask // m_modifier.m_miscvalue comparison with item generated damage types if (GetSpellProto()->EquippedItemClass == -1) { ((Player*)target)->HandleBaseModValue(CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply); ((Player*)target)->HandleBaseModValue(OFFHAND_CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply); ((Player*)target)->HandleBaseModValue(RANGED_CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply); } else { // done in Player::_ApplyWeaponDependentAuraMods } } void Aura::HandleModHitChance(bool apply, bool /*Real*/) { Unit* target = GetTarget(); if (target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->UpdateMeleeHitChances(); ((Player*)target)->UpdateRangedHitChances(); } else { target->m_modMeleeHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount); target->m_modRangedHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount); } } void Aura::HandleModSpellHitChance(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() == TYPEID_PLAYER) { ((Player*)GetTarget())->UpdateSpellHitChances(); } else { GetTarget()->m_modSpellHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount); } } void Aura::HandleModSpellCritChance(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; if (GetTarget()->GetTypeId() == TYPEID_PLAYER) { ((Player*)GetTarget())->UpdateAllSpellCritChances(); } else { GetTarget()->m_baseSpellCritChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount); } } void Aura::HandleModSpellCritChanceShool(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) return; if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; for (int school = SPELL_SCHOOL_NORMAL; school < MAX_SPELL_SCHOOL; ++school) if (m_modifier.m_miscvalue & (1 << school)) ((Player*)GetTarget())->UpdateSpellCritChance(school); } /********************************/ /*** ATTACK SPEED ***/ /********************************/ void Aura::HandleModCastingSpeed(bool apply, bool /*Real*/) { GetTarget()->ApplyCastTimePercentMod(float(m_modifier.m_amount), apply); } void Aura::HandleModMeleeRangedSpeedPct(bool apply, bool /*Real*/) { Unit* target = GetTarget(); target->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply); target->ApplyAttackTimePercentMod(OFF_ATTACK, float(m_modifier.m_amount), apply); target->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply); } void Aura::HandleModCombatSpeedPct(bool apply, bool /*Real*/) { Unit* target = GetTarget(); target->ApplyCastTimePercentMod(float(m_modifier.m_amount), apply); target->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply); target->ApplyAttackTimePercentMod(OFF_ATTACK, float(m_modifier.m_amount), apply); target->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply); } void Aura::HandleModAttackSpeed(bool apply, bool /*Real*/) { GetTarget()->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply); } void Aura::HandleModMeleeSpeedPct(bool apply, bool /*Real*/) { Unit* target = GetTarget(); target->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply); target->ApplyAttackTimePercentMod(OFF_ATTACK, float(m_modifier.m_amount), apply); } void Aura::HandleAuraModRangedHaste(bool apply, bool /*Real*/) { GetTarget()->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply); } void Aura::HandleRangedAmmoHaste(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; GetTarget()->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply); } /********************************/ /*** ATTACK POWER ***/ /********************************/ void Aura::HandleAuraModAttackPower(bool apply, bool /*Real*/) { GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(m_modifier.m_amount), apply); } void Aura::HandleAuraModRangedAttackPower(bool apply, bool /*Real*/) { if ((GetTarget()->getClassMask() & CLASSMASK_WAND_USERS) != 0) return; GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(m_modifier.m_amount), apply); } void Aura::HandleAuraModAttackPowerPercent(bool apply, bool /*Real*/) { // UNIT_FIELD_ATTACK_POWER_MULTIPLIER = multiplier - 1 GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_PCT, float(m_modifier.m_amount), apply); } void Aura::HandleAuraModRangedAttackPowerPercent(bool apply, bool /*Real*/) { if ((GetTarget()->getClassMask() & CLASSMASK_WAND_USERS) != 0) return; // UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER = multiplier - 1 GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_PCT, float(m_modifier.m_amount), apply); } void Aura::HandleAuraModRangedAttackPowerOfStatPercent(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) return; // Recalculate bonus if (GetTarget()->GetTypeId() == TYPEID_PLAYER && !(GetTarget()->getClassMask() & CLASSMASK_WAND_USERS)) ((Player*)GetTarget())->UpdateAttackPowerAndDamage(true); } /********************************/ /*** DAMAGE BONUS ***/ /********************************/ void Aura::HandleModDamageDone(bool apply, bool Real) { Unit* target = GetTarget(); // apply item specific bonuses for already equipped weapon if (Real && target->GetTypeId() == TYPEID_PLAYER) { for (int i = 0; i < MAX_ATTACK; ++i) if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false)) ((Player*)target)->_ApplyWeaponDependentAuraDamageMod(pItem, WeaponAttackType(i), this, apply); } // m_modifier.m_miscvalue is bitmask of spell schools // 1 ( 0-bit ) - normal school damage (SPELL_SCHOOL_MASK_NORMAL) // 126 - full bitmask all magic damages (SPELL_SCHOOL_MASK_MAGIC) including wands // 127 - full bitmask any damages // // mods must be applied base at equipped weapon class and subclass comparison // with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask // m_modifier.m_miscvalue comparison with item generated damage types if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL) != 0) { // apply generic physical damage bonuses including wand case if (GetSpellProto()->EquippedItemClass == -1 || target->GetTypeId() != TYPEID_PLAYER) { target->HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(m_modifier.m_amount), apply); target->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(m_modifier.m_amount), apply); target->HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(m_modifier.m_amount), apply); } else { // done in Player::_ApplyWeaponDependentAuraMods } if (target->GetTypeId() == TYPEID_PLAYER) { if (m_positive) target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS, m_modifier.m_amount, apply); else target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG, m_modifier.m_amount, apply); } } // Skip non magic case for speedup if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_MAGIC) == 0) return; if (GetSpellProto()->EquippedItemClass != -1 || GetSpellProto()->EquippedItemInventoryTypeMask != 0) { // wand magic case (skip generic to all item spell bonuses) // done in Player::_ApplyWeaponDependentAuraMods // Skip item specific requirements for not wand magic damage return; } // Magic damage modifiers implemented in Unit::SpellDamageBonusDone // This information for client side use only if (target->GetTypeId() == TYPEID_PLAYER) { if (m_positive) { for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i) { if ((m_modifier.m_miscvalue & (1 << i)) != 0) target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + i, m_modifier.m_amount, apply); } } else { for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i) { if ((m_modifier.m_miscvalue & (1 << i)) != 0) target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + i, m_modifier.m_amount, apply); } } Pet* pet = target->GetPet(); if (pet) pet->UpdateAttackPowerAndDamage(); } } void Aura::HandleModDamagePercentDone(bool apply, bool Real) { DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "AURA MOD DAMAGE type:%u negative:%u", m_modifier.m_miscvalue, m_positive ? 0 : 1); Unit* target = GetTarget(); // apply item specific bonuses for already equipped weapon if (Real && target->GetTypeId() == TYPEID_PLAYER) { for (int i = 0; i < MAX_ATTACK; ++i) if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false)) ((Player*)target)->_ApplyWeaponDependentAuraDamageMod(pItem, WeaponAttackType(i), this, apply); } // m_modifier.m_miscvalue is bitmask of spell schools // 1 ( 0-bit ) - normal school damage (SPELL_SCHOOL_MASK_NORMAL) // 126 - full bitmask all magic damages (SPELL_SCHOOL_MASK_MAGIC) including wand // 127 - full bitmask any damages // // mods must be applied base at equipped weapon class and subclass comparison // with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask // m_modifier.m_miscvalue comparison with item generated damage types if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL) != 0) { // apply generic physical damage bonuses including wand case if (GetSpellProto()->EquippedItemClass == -1 || target->GetTypeId() != TYPEID_PLAYER) { target->HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_PCT, float(m_modifier.m_amount), apply); target->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT, float(m_modifier.m_amount), apply); target->HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_PCT, float(m_modifier.m_amount), apply); } else { // done in Player::_ApplyWeaponDependentAuraMods } // For show in client if (target->GetTypeId() == TYPEID_PLAYER) target->ApplyModSignedFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT, m_modifier.m_amount / 100.0f, apply); } // Skip non magic case for speedup if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_MAGIC) == 0) return; if (GetSpellProto()->EquippedItemClass != -1 || GetSpellProto()->EquippedItemInventoryTypeMask != 0) { // wand magic case (skip generic to all item spell bonuses) // done in Player::_ApplyWeaponDependentAuraMods // Skip item specific requirements for not wand magic damage return; } // Magic damage percent modifiers implemented in Unit::SpellDamageBonusDone // Send info to client if (target->GetTypeId() == TYPEID_PLAYER) for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i) target->ApplyModSignedFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT + i, m_modifier.m_amount / 100.0f, apply); } void Aura::HandleModOffhandDamagePercent(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "AURA MOD OFFHAND DAMAGE"); GetTarget()->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT, float(m_modifier.m_amount), apply); } /********************************/ /*** POWER COST ***/ /********************************/ void Aura::HandleModPowerCostPCT(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; float amount = m_modifier.m_amount / 100.0f; for (int i = 0; i < MAX_SPELL_SCHOOL; ++i) if (m_modifier.m_miscvalue & (1 << i)) GetTarget()->ApplyModSignedFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER + i, amount, apply); } void Aura::HandleModPowerCost(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; for (int i = 0; i < MAX_SPELL_SCHOOL; ++i) if (m_modifier.m_miscvalue & (1 << i)) GetTarget()->ApplyModInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + i, m_modifier.m_amount, apply); } /*********************************************************/ /*** OTHERS ***/ /*********************************************************/ void Aura::HandleShapeshiftBoosts(bool apply) { uint32 spellId1 = 0; uint32 spellId2 = 0; uint32 HotWSpellId = 0; ShapeshiftForm form = ShapeshiftForm(GetModifier()->m_miscvalue); Unit* target = GetTarget(); switch (form) { case FORM_CAT: spellId1 = 3025; HotWSpellId = 24900; break; case FORM_TREE: spellId1 = 5420; break; case FORM_TRAVEL: spellId1 = 5419; break; case FORM_AQUA: spellId1 = 5421; break; case FORM_BEAR: spellId1 = 1178; spellId2 = 21178; HotWSpellId = 24899; break; case FORM_DIREBEAR: spellId1 = 9635; spellId2 = 21178; HotWSpellId = 24899; break; case FORM_BATTLESTANCE: spellId1 = 21156; break; case FORM_DEFENSIVESTANCE: spellId1 = 7376; break; case FORM_BERSERKERSTANCE: spellId1 = 7381; break; case FORM_MOONKIN: spellId1 = 24905; break; case FORM_FLIGHT: spellId1 = 33948; spellId2 = 34764; break; case FORM_FLIGHT_EPIC: spellId1 = 40122; spellId2 = 40121; break; case FORM_SPIRITOFREDEMPTION: spellId1 = 27792; spellId2 = 27795; // must be second, this important at aura remove to prevent to early iterator invalidation. break; case FORM_GHOSTWOLF: case FORM_AMBIENT: case FORM_GHOUL: case FORM_SHADOW: case FORM_STEALTH: case FORM_CREATURECAT: case FORM_CREATUREBEAR: break; } if (apply) { if (spellId1) target->CastSpell(target, spellId1, true, NULL, this); if (spellId2) target->CastSpell(target, spellId2, true, NULL, this); if (target->GetTypeId() == TYPEID_PLAYER) { const PlayerSpellMap& sp_list = ((Player*)target)->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) continue; if (itr->first == spellId1 || itr->first == spellId2) continue; SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first); if (!spellInfo || !IsNeedCastSpellAtFormApply(spellInfo, form)) continue; target->CastSpell(target, itr->first, true, NULL, this); } // Leader of the Pack if (((Player*)target)->HasSpell(17007)) { SpellEntry const* spellInfo = sSpellStore.LookupEntry(24932); if (spellInfo && spellInfo->Stances & (1 << (form - 1))) target->CastSpell(target, 24932, true, NULL, this); } // Heart of the Wild if (HotWSpellId) { Unit::AuraList const& mModTotalStatPct = target->GetAurasByType(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE); for (Unit::AuraList::const_iterator i = mModTotalStatPct.begin(); i != mModTotalStatPct.end(); ++i) { if ((*i)->GetSpellProto()->SpellIconID == 240 && (*i)->GetModifier()->m_miscvalue == 3) { int32 HotWMod = (*i)->GetModifier()->m_amount; if (GetModifier()->m_miscvalue == FORM_CAT) HotWMod /= 2; target->CastCustomSpell(target, HotWSpellId, &HotWMod, NULL, NULL, true, NULL, this); break; } } } } } else { if (spellId1) target->RemoveAurasDueToSpell(spellId1); if (spellId2) target->RemoveAurasDueToSpell(spellId2); Unit::SpellAuraHolderMap& tAuras = target->GetSpellAuraHolderMap(); for (Unit::SpellAuraHolderMap::iterator itr = tAuras.begin(); itr != tAuras.end();) { if (itr->second->IsRemovedOnShapeLost()) { target->RemoveAurasDueToSpell(itr->second->GetId()); itr = tAuras.begin(); } else ++itr; } } } void Aura::HandleAuraEmpathy(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_UNIT) return; CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(GetTarget()->GetEntry()); if (ci && ci->type == CREATURE_TYPE_BEAST) GetTarget()->ApplyModUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_SPECIALINFO, apply); } void Aura::HandleAuraUntrackable(bool apply, bool /*Real*/) { if (apply) GetTarget()->SetByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_UNTRACKABLE); else GetTarget()->RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_UNTRACKABLE); } void Aura::HandleAuraModPacify(bool apply, bool /*Real*/) { if (apply) GetTarget()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED); else GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED); } void Aura::HandleAuraModPacifyAndSilence(bool apply, bool Real) { HandleAuraModPacify(apply, Real); HandleAuraModSilence(apply, Real); } void Aura::HandleAuraGhost(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; if (apply) { GetTarget()->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST); } else { GetTarget()->RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST); } } void Aura::HandleAuraAllowFlight(bool apply, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; // allow fly WorldPacket data; if (apply) data.Initialize(SMSG_MOVE_SET_CAN_FLY, 12); else data.Initialize(SMSG_MOVE_UNSET_CAN_FLY, 12); data << GetTarget()->GetPackGUID(); data << uint32(0); // unk GetTarget()->SendMessageToSet(&data, true); } void Aura::HandleModRating(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating) if (m_modifier.m_miscvalue & (1 << rating)) ((Player*)GetTarget())->ApplyRatingMod(CombatRating(rating), m_modifier.m_amount, apply); } void Aura::HandleForceMoveForward(bool apply, bool Real) { if (!Real) return; if (apply) GetTarget()->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE); else GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE); } void Aura::HandleAuraModExpertise(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; ((Player*)GetTarget())->UpdateExpertise(BASE_ATTACK); ((Player*)GetTarget())->UpdateExpertise(OFF_ATTACK); } void Aura::HandleModTargetResistance(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; Unit* target = GetTarget(); // applied to damage as HandleNoImmediateEffect in Unit::CalculateAbsorbAndResist and Unit::CalcArmorReducedDamage // show armor penetration if (target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)) target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE, m_modifier.m_amount, apply); // show as spell penetration only full spell penetration bonuses (all resistances except armor and holy if (target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_SPELL) == SPELL_SCHOOL_MASK_SPELL) target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, m_modifier.m_amount, apply); } void Aura::HandleShieldBlockValue(bool apply, bool /*Real*/) { BaseModType modType = FLAT_MOD; if (m_modifier.m_auraname == SPELL_AURA_MOD_SHIELD_BLOCKVALUE_PCT) modType = PCT_MOD; if (GetTarget()->GetTypeId() == TYPEID_PLAYER) ((Player*)GetTarget())->HandleBaseModValue(SHIELD_BLOCK_VALUE, modType, float(m_modifier.m_amount), apply); } void Aura::HandleAuraRetainComboPoints(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; Player* target = (Player*)GetTarget(); // combo points was added in SPELL_EFFECT_ADD_COMBO_POINTS handler // remove only if aura expire by time (in case combo points amount change aura removed without combo points lost) if (!apply && m_removeMode == AURA_REMOVE_BY_EXPIRE && target->GetComboTargetGuid()) if (Unit* unit = ObjectAccessor::GetUnit(*GetTarget(), target->GetComboTargetGuid())) target->AddComboPoints(unit, -m_modifier.m_amount); } void Aura::HandleModUnattackable(bool Apply, bool Real) { if (Real && Apply) { GetTarget()->CombatStop(); GetTarget()->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION); } GetTarget()->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE, Apply); } void Aura::HandleSpiritOfRedemption(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; Unit* target = GetTarget(); // prepare spirit state if (apply) { if (target->GetTypeId() == TYPEID_PLAYER) { // disable breath/etc timers ((Player*)target)->StopMirrorTimers(); // set stand state (expected in this form) if (!target->IsStandState()) target->SetStandState(UNIT_STAND_STATE_STAND); } target->SetHealth(1); } // die at aura end else target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, GetSpellProto(), false); } void Aura::HandleSchoolAbsorb(bool apply, bool Real) { if (!Real) return; Unit* caster = GetCaster(); if (!caster) return; Unit* target = GetTarget(); SpellEntry const* spellProto = GetSpellProto(); if (apply) { // prevent double apply bonuses if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading()) { float DoneActualBenefit = 0.0f; switch (spellProto->SpellFamilyName) { case SPELLFAMILY_PRIEST: // Power Word: Shield if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000001)) { //+30% from +healing bonus DoneActualBenefit = caster->SpellBaseHealingBonusDone(GetSpellSchoolMask(spellProto)) * 0.3f; break; } break; case SPELLFAMILY_MAGE: // Frost Ward, Fire Ward if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000000100080108))) //+10% from +spell bonus DoneActualBenefit = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(spellProto)) * 0.1f; break; case SPELLFAMILY_WARLOCK: // Shadow Ward if (spellProto->SpellFamilyFlags == UI64LIT(0x00)) //+10% from +spell bonus DoneActualBenefit = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(spellProto)) * 0.1f; break; default: break; } DoneActualBenefit *= caster->CalculateLevelPenalty(GetSpellProto()); m_modifier.m_amount += (int32)DoneActualBenefit; } } } void Aura::PeriodicTick() { Unit* target = GetTarget(); SpellEntry const* spellProto = GetSpellProto(); switch (m_modifier.m_auraname) { case SPELL_AURA_PERIODIC_DAMAGE: case SPELL_AURA_PERIODIC_DAMAGE_PERCENT: { // don't damage target if not alive, possible death persistent effects if (!target->isAlive()) return; Unit* pCaster = GetCaster(); if (!pCaster) return; if (spellProto->Effect[GetEffIndex()] == SPELL_EFFECT_PERSISTENT_AREA_AURA && pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE) return; // Check for immune (not use charges) if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) return; // some auras remove at specific health level or more if (m_modifier.m_auraname == SPELL_AURA_PERIODIC_DAMAGE) { switch (GetId()) { case 43093: case 31956: case 38801: case 35321: case 38363: case 39215: case 48920: { if (target->GetHealth() == target->GetMaxHealth()) { target->RemoveAurasDueToSpell(GetId()); return; } break; } case 38772: { uint32 percent = GetEffIndex() < EFFECT_INDEX_2 && spellProto->Effect[GetEffIndex()] == SPELL_EFFECT_DUMMY ? pCaster->CalculateSpellDamage(target, spellProto, SpellEffectIndex(GetEffIndex() + 1)) : 100; if (target->GetHealth() * 100 >= target->GetMaxHealth() * percent) { target->RemoveAurasDueToSpell(GetId()); return; } break; } default: break; } } uint32 absorb = 0; uint32 resist = 0; CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL); // ignore non positive values (can be result apply spellmods to aura damage uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; uint32 pdamage; if (m_modifier.m_auraname == SPELL_AURA_PERIODIC_DAMAGE) pdamage = amount; else pdamage = uint32(target->GetMaxHealth() * amount / 100); // SpellDamageBonus for magic spells if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellProto->DmgClass == SPELL_DAMAGE_CLASS_MAGIC) pdamage = target->SpellDamageBonusTaken(pCaster, spellProto, pdamage, DOT, GetStackAmount()); // MeleeDamagebonus for weapon based spells else { WeaponAttackType attackType = GetWeaponAttackType(spellProto); pdamage = target->MeleeDamageBonusTaken(pCaster, pdamage, attackType, spellProto, DOT, GetStackAmount()); } // Calculate armor mitigation if it is a physical spell // But not for bleed mechanic spells if (GetSpellSchoolMask(spellProto) & SPELL_SCHOOL_MASK_NORMAL && GetEffectMechanic(spellProto, m_effIndex) != MECHANIC_BLEED) { uint32 pdamageReductedArmor = pCaster->CalcArmorReducedDamage(target, pdamage); cleanDamage.damage += pdamage - pdamageReductedArmor; pdamage = pdamageReductedArmor; } // Curse of Agony damage-per-tick calculation if (spellProto->SpellFamilyName == SPELLFAMILY_WARLOCK && (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000400)) && spellProto->SpellIconID == 544) { // 1..4 ticks, 1/2 from normal tick damage if (GetAuraTicks() <= 4) pdamage = pdamage / 2; // 9..12 ticks, 3/2 from normal tick damage else if (GetAuraTicks() >= 9) pdamage += (pdamage + 1) / 2; // +1 prevent 0.5 damage possible lost at 1..4 ticks // 5..8 ticks have normal tick damage } // As of 2.2 resilience reduces damage from DoT ticks as much as the chance to not be critically hit // Reduce dot damage from resilience for players if (target->GetTypeId() == TYPEID_PLAYER) pdamage -= ((Player*)target)->GetDotDamageReduction(pdamage); target->CalculateDamageAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), DOT, pdamage, &absorb, &resist, !GetSpellProto()->HasAttribute(SPELL_ATTR_EX2_CANT_REFLECTED)); DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s attacked %s for %u dmg inflicted by %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId()); pCaster->DealDamageMods(target, pdamage, &absorb); // Set trigger flag uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC; // | PROC_FLAG_SUCCESSFUL_HARMFUL_SPELL_HIT; uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;// | PROC_FLAG_TAKEN_HARMFUL_SPELL_HIT; pdamage = (pdamage <= absorb + resist) ? 0 : (pdamage - absorb - resist); SpellPeriodicAuraLogInfo pInfo(this, pdamage, absorb, resist, 0.0f); target->SendPeriodicAuraLog(&pInfo); if (pdamage) procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE; pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, PROC_EX_NORMAL_HIT, pdamage, BASE_ATTACK, spellProto); pCaster->DealDamage(target, pdamage, &cleanDamage, DOT, GetSpellSchoolMask(spellProto), spellProto, true); break; } case SPELL_AURA_PERIODIC_LEECH: case SPELL_AURA_PERIODIC_HEALTH_FUNNEL: { // don't damage target if not alive, possible death persistent effects if (!target->isAlive()) return; Unit* pCaster = GetCaster(); if (!pCaster) return; if (!pCaster->isAlive()) return; if (spellProto->Effect[GetEffIndex()] == SPELL_EFFECT_PERSISTENT_AREA_AURA && pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE) return; // Check for immune if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) return; uint32 absorb = 0; uint32 resist = 0; CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL); uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; // Calculate armor mitigation if it is a physical spell if (GetSpellSchoolMask(spellProto) & SPELL_SCHOOL_MASK_NORMAL) { uint32 pdamageReductedArmor = pCaster->CalcArmorReducedDamage(target, pdamage); cleanDamage.damage += pdamage - pdamageReductedArmor; pdamage = pdamageReductedArmor; } pdamage = target->SpellDamageBonusTaken(pCaster, spellProto, pdamage, DOT, GetStackAmount()); // As of 2.2 resilience reduces damage from DoT ticks as much as the chance to not be critically hit // Reduce dot damage from resilience for players if (target->GetTypeId() == TYPEID_PLAYER) pdamage -= ((Player*)target)->GetDotDamageReduction(pdamage); target->CalculateDamageAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), DOT, pdamage, &absorb, &resist, !spellProto->HasAttribute(SPELL_ATTR_EX2_CANT_REFLECTED)); if (target->GetHealth() < pdamage) pdamage = uint32(target->GetHealth()); DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s health leech of %s for %u dmg inflicted by %u abs is %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId(), absorb); pCaster->DealDamageMods(target, pdamage, &absorb); pCaster->SendSpellNonMeleeDamageLog(target, GetId(), pdamage, GetSpellSchoolMask(spellProto), absorb, resist, false, 0); float multiplier = spellProto->EffectMultipleValue[GetEffIndex()] > 0 ? spellProto->EffectMultipleValue[GetEffIndex()] : 1; // Set trigger flag uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC; // | PROC_FLAG_SUCCESSFUL_HARMFUL_SPELL_HIT; uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;// | PROC_FLAG_TAKEN_HARMFUL_SPELL_HIT; pdamage = (pdamage <= absorb + resist) ? 0 : (pdamage - absorb - resist); if (pdamage) procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE; pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, PROC_EX_NORMAL_HIT, pdamage, BASE_ATTACK, spellProto); int32 new_damage = pCaster->DealDamage(target, pdamage, &cleanDamage, DOT, GetSpellSchoolMask(spellProto), spellProto, false); if (!target->isAlive() && pCaster->IsNonMeleeSpellCasted(false)) for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) if (Spell* spell = pCaster->GetCurrentSpell(CurrentSpellTypes(i))) if (spell->m_spellInfo->Id == GetId()) spell->cancel(); if (Player* modOwner = pCaster->GetSpellModOwner()) modOwner->ApplySpellMod(GetId(), SPELLMOD_MULTIPLE_VALUE, multiplier); uint32 heal = pCaster->SpellHealingBonusTaken(pCaster, spellProto, int32(new_damage * multiplier), DOT, GetStackAmount()); int32 gain = pCaster->DealHeal(pCaster, heal, spellProto); pCaster->getHostileRefManager().threatAssist(pCaster, gain * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto); break; } case SPELL_AURA_PERIODIC_HEAL: case SPELL_AURA_OBS_MOD_HEALTH: { // don't heal target if not alive, mostly death persistent effects from items if (!target->isAlive()) return; Unit* pCaster = GetCaster(); if (!pCaster) return; // heal for caster damage (must be alive) if (target != pCaster && spellProto->SpellVisual == 163 && !pCaster->isAlive()) return; // ignore non positive values (can be result apply spellmods to aura damage uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; uint32 pdamage; if (m_modifier.m_auraname == SPELL_AURA_OBS_MOD_HEALTH) pdamage = uint32(target->GetMaxHealth() * amount / 100); else pdamage = amount; pdamage = target->SpellHealingBonusTaken(pCaster, spellProto, pdamage, DOT, GetStackAmount()); DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s heal of %s for %u health inflicted by %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId()); int32 gain = target->ModifyHealth(pdamage); SpellPeriodicAuraLogInfo pInfo(this, pdamage, 0, 0, 0.0f); target->SendPeriodicAuraLog(&pInfo); // Set trigger flag uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC; uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC; uint32 procEx = PROC_EX_NORMAL_HIT | PROC_EX_PERIODIC_POSITIVE; pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, procEx, gain, BASE_ATTACK, spellProto); // add HoTs to amount healed in bgs if (pCaster->GetTypeId() == TYPEID_PLAYER) if (BattleGround* bg = ((Player*)pCaster)->GetBattleGround()) bg->UpdatePlayerScore(((Player*)pCaster), SCORE_HEALING_DONE, gain); target->getHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto); // heal for caster damage if (target != pCaster && spellProto->SpellVisual == 163) { uint32 dmg = spellProto->manaPerSecond; if (pCaster->GetHealth() <= dmg && pCaster->GetTypeId() == TYPEID_PLAYER) { pCaster->RemoveAurasDueToSpell(GetId()); // finish current generic/channeling spells, don't affect autorepeat pCaster->FinishSpell(CURRENT_GENERIC_SPELL); pCaster->FinishSpell(CURRENT_CHANNELED_SPELL); } else { uint32 damage = gain; uint32 absorb = 0; pCaster->DealDamageMods(pCaster, damage, &absorb); pCaster->SendSpellNonMeleeDamageLog(pCaster, GetId(), damage, GetSpellSchoolMask(spellProto), absorb, 0, false, 0, false); CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL); pCaster->DealDamage(pCaster, damage, &cleanDamage, NODAMAGE, GetSpellSchoolMask(spellProto), spellProto, true); } } break; } case SPELL_AURA_PERIODIC_MANA_LEECH: { // don't damage target if not alive, possible death persistent effects if (!target->isAlive()) return; if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue >= MAX_POWERS) return; Powers power = Powers(m_modifier.m_miscvalue); // power type might have changed between aura applying and tick (druid's shapeshift) if (target->getPowerType() != power) return; Unit* pCaster = GetCaster(); if (!pCaster) return; if (!pCaster->isAlive()) return; if (GetSpellProto()->Effect[GetEffIndex()] == SPELL_EFFECT_PERSISTENT_AREA_AURA && pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE) return; // Check for immune (not use charges) if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) return; // ignore non positive values (can be result apply spellmods to aura damage uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s power leech of %s for %u dmg inflicted by %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId()); int32 drain_amount = target->GetPower(power) > pdamage ? pdamage : target->GetPower(power); // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) if (power == POWER_MANA && target->GetTypeId() == TYPEID_PLAYER) drain_amount -= ((Player*)target)->GetSpellCritDamageReduction(drain_amount); target->ModifyPower(power, -drain_amount); float gain_multiplier = 0.0f; if (pCaster->GetMaxPower(power) > 0) { gain_multiplier = spellProto->EffectMultipleValue[GetEffIndex()]; if (Player* modOwner = pCaster->GetSpellModOwner()) modOwner->ApplySpellMod(GetId(), SPELLMOD_MULTIPLE_VALUE, gain_multiplier); } SpellPeriodicAuraLogInfo pInfo(this, drain_amount, 0, 0, gain_multiplier); target->SendPeriodicAuraLog(&pInfo); if (int32 gain_amount = int32(drain_amount * gain_multiplier)) { int32 gain = pCaster->ModifyPower(power, gain_amount); if (GetId() == 5138) // Drain Mana if (Aura* petPart = GetHolder()->GetAuraByEffectIndex(EFFECT_INDEX_1)) if (int pet_gain = gain_amount * petPart->GetModifier()->m_amount / 100) pCaster->CastCustomSpell(pCaster, 32554, &pet_gain, NULL, NULL, true); target->AddThreat(pCaster, float(gain) * 0.5f, false, GetSpellSchoolMask(spellProto), spellProto); } // Some special cases switch (GetId()) { case 32960: // Mark of Kazzak { if (target->GetTypeId() == TYPEID_PLAYER && target->getPowerType() == POWER_MANA) { // Drain 5% of target's mana pdamage = target->GetMaxPower(POWER_MANA) * 5 / 100; drain_amount = target->GetPower(POWER_MANA) > pdamage ? pdamage : target->GetPower(POWER_MANA); target->ModifyPower(POWER_MANA, -drain_amount); SpellPeriodicAuraLogInfo pInfo(this, drain_amount, 0, 0, 0.0f); target->SendPeriodicAuraLog(&pInfo); } // no break here } case 21056: // Mark of Kazzak case 31447: // Mark of Kaz'rogal { uint32 triggerSpell = 0; switch (GetId()) { case 21056: triggerSpell = 21058; break; case 31447: triggerSpell = 31463; break; case 32960: triggerSpell = 32961; break; } if (target->GetTypeId() == TYPEID_PLAYER && target->GetPower(power) == 0) { target->CastSpell(target, triggerSpell, true, NULL, this); target->RemoveAurasDueToSpell(GetId()); } break; } } break; } case SPELL_AURA_PERIODIC_ENERGIZE: { // don't energize target if not alive, possible death persistent effects if (!target->isAlive()) return; // ignore non positive values (can be result apply spellmods to aura damage uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s energize %s for %u dmg inflicted by %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId()); if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue >= MAX_POWERS) break; Powers power = Powers(m_modifier.m_miscvalue); if (target->GetMaxPower(power) == 0) break; SpellPeriodicAuraLogInfo pInfo(this, pdamage, 0, 0, 0.0f); target->SendPeriodicAuraLog(&pInfo); int32 gain = target->ModifyPower(power, pdamage); if (Unit* pCaster = GetCaster()) target->getHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto); break; } case SPELL_AURA_OBS_MOD_MANA: { // don't energize target if not alive, possible death persistent effects if (!target->isAlive()) return; // ignore non positive values (can be result apply spellmods to aura damage uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; uint32 pdamage = uint32(target->GetMaxPower(POWER_MANA) * amount / 100); DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s energize %s for %u mana inflicted by %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId()); if (target->GetMaxPower(POWER_MANA) == 0) break; SpellPeriodicAuraLogInfo pInfo(this, pdamage, 0, 0, 0.0f); target->SendPeriodicAuraLog(&pInfo); int32 gain = target->ModifyPower(POWER_MANA, pdamage); if (Unit* pCaster = GetCaster()) target->getHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto); break; } case SPELL_AURA_POWER_BURN_MANA: { // don't mana burn target if not alive, possible death persistent effects if (!target->isAlive()) return; Unit* pCaster = GetCaster(); if (!pCaster) return; // Check for immune (not use charges) if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) return; int32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; Powers powerType = Powers(m_modifier.m_miscvalue); if (!target->isAlive() || target->getPowerType() != powerType) return; // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) if (powerType == POWER_MANA && target->GetTypeId() == TYPEID_PLAYER) pdamage -= ((Player*)target)->GetSpellCritDamageReduction(pdamage); uint32 gain = uint32(-target->ModifyPower(powerType, -pdamage)); gain = uint32(gain * spellProto->EffectMultipleValue[GetEffIndex()]); // maybe has to be sent different to client, but not by SMSG_PERIODICAURALOG SpellNonMeleeDamage damageInfo(pCaster, target, spellProto->Id, SpellSchoolMask(spellProto->SchoolMask)); pCaster->CalculateSpellDamage(&damageInfo, gain, spellProto); damageInfo.target->CalculateAbsorbResistBlock(pCaster, &damageInfo, spellProto); pCaster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb); pCaster->SendSpellNonMeleeDamageLog(&damageInfo); // Set trigger flag uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC; // | PROC_FLAG_SUCCESSFUL_HARMFUL_SPELL_HIT; uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;// | PROC_FLAG_TAKEN_HARMFUL_SPELL_HIT; uint32 procEx = createProcExtendMask(&damageInfo, SPELL_MISS_NONE); if (damageInfo.damage) procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE; pCaster->ProcDamageAndSpell(damageInfo.target, procAttacker, procVictim, procEx, damageInfo.damage, BASE_ATTACK, spellProto); pCaster->DealSpellDamage(&damageInfo, true); break; } case SPELL_AURA_MOD_REGEN: { // don't heal target if not alive, possible death persistent effects if (!target->isAlive()) return; int32 gain = target->ModifyHealth(m_modifier.m_amount); if (Unit* caster = GetCaster()) target->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto); break; } case SPELL_AURA_MOD_POWER_REGEN: { // don't energize target if not alive, possible death persistent effects if (!target->isAlive()) return; Powers pt = target->getPowerType(); if (int32(pt) != m_modifier.m_miscvalue) return; if (spellProto->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) { // eating anim target->HandleEmoteCommand(EMOTE_ONESHOT_EAT); } else if (GetId() == 20577) { // cannibalize anim target->HandleEmoteCommand(EMOTE_STATE_CANNIBALIZE); } // Anger Management // amount = 1+ 16 = 17 = 3,4*5 = 10,2*5/3 // so 17 is rounded amount for 5 sec tick grow ~ 1 range grow in 3 sec if (pt == POWER_RAGE) target->ModifyPower(pt, m_modifier.m_amount * 3 / 5); break; } // Here tick dummy auras case SPELL_AURA_DUMMY: // some spells have dummy aura case SPELL_AURA_PERIODIC_DUMMY: { PeriodicDummyTick(); break; } case SPELL_AURA_PERIODIC_TRIGGER_SPELL: { TriggerSpell(); break; } case SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE: { TriggerSpellWithValue(); break; } default: break; } } void Aura::PeriodicDummyTick() { SpellEntry const* spell = GetSpellProto(); Unit* target = GetTarget(); switch (spell->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (spell->Id) { // Forsaken Skills case 7054: { // Possibly need cast one of them (but // 7038 Forsaken Skill: Swords // 7039 Forsaken Skill: Axes // 7040 Forsaken Skill: Daggers // 7041 Forsaken Skill: Maces // 7042 Forsaken Skill: Staves // 7043 Forsaken Skill: Bows // 7044 Forsaken Skill: Guns // 7045 Forsaken Skill: 2H Axes // 7046 Forsaken Skill: 2H Maces // 7047 Forsaken Skill: 2H Swords // 7048 Forsaken Skill: Defense // 7049 Forsaken Skill: Fire // 7050 Forsaken Skill: Frost // 7051 Forsaken Skill: Holy // 7053 Forsaken Skill: Shadow return; } case 7057: // Haunting Spirits if (roll_chance_i(33)) target->CastSpell(target, m_modifier.m_amount, true, NULL, this); return; // // Panda // case 19230: break; // // Gossip NPC Periodic - Talk // case 33208: break; // // Gossip NPC Periodic - Despawn // case 33209: break; // // Steal Weapon // case 36207: break; // // Simon Game START timer, (DND) // case 39993: break; // // Harpooner's Mark // case 40084: break; // // Old Mount Spell // case 40154: break; // // Magnetic Pull // case 40581: break; // // Ethereal Ring: break; The Bolt Burst // case 40801: break; // // Crystal Prison // case 40846: break; // // Copy Weapon // case 41054: break; // // Ethereal Ring Visual, Lightning Aura // case 41477: break; // // Ethereal Ring Visual, Lightning Aura (Fork) // case 41525: break; // // Ethereal Ring Visual, Lightning Jumper Aura // case 41567: break; // // No Man's Land // case 41955: break; // // Headless Horseman - Fire // case 42074: break; // // Headless Horseman - Visual - Large Fire // case 42075: break; // // Headless Horseman - Start Fire, Periodic Aura // case 42140: break; // // Ram Speed Boost // case 42152: break; // // Headless Horseman - Fires Out Victory Aura // case 42235: break; // // Pumpkin Life Cycle // case 42280: break; // // Brewfest Request Chick Chuck Mug Aura // case 42537: break; // // Squashling // case 42596: break; // // Headless Horseman Climax, Head: Periodic // case 42603: break; case 42621: // Fire Bomb { // Cast the summon spells (42622 to 42627) with increasing chance uint32 rand = urand(0, 99); for (uint32 i = 1; i <= 6; ++i) { if (rand < i * (i + 1) / 2 * 5) { target->CastSpell(target, spell->Id + i, true); break; } } break; } // // Headless Horseman - Conflagrate, Periodic Aura // case 42637: break; // // Headless Horseman - Create Pumpkin Treats Aura // case 42774: break; // // Headless Horseman Climax - Summoning Rhyme Aura // case 42879: break; // // Tricky Treat // case 42919: break; // // Giddyup! // case 42924: break; // // Ram - Trot // case 42992: break; // // Ram - Canter // case 42993: break; // // Ram - Gallop // case 42994: break; // // Ram Level - Neutral // case 43310: break; // // Headless Horseman - Maniacal Laugh, Maniacal, Delayed 17 // case 43884: break; // // Headless Horseman - Maniacal Laugh, Maniacal, other, Delayed 17 // case 44000: break; // // Energy Feedback // case 44328: break; // // Romantic Picnic // case 45102: break; // // Romantic Picnic // case 45123: break; // // Looking for Love // case 45124: break; // // Kite - Lightning Strike Kite Aura // case 45197: break; // // Rocket Chicken // case 45202: break; // // Copy Offhand Weapon // case 45205: break; // // Upper Deck - Kite - Lightning Periodic Aura // case 45207: break; // // Kite -Sky Lightning Strike Kite Aura // case 45251: break; // // Ribbon Pole Dancer Check Aura // case 45390: break; // // Holiday - Midsummer, Ribbon Pole Periodic Visual // case 45406: break; // // Alliance Flag, Extra Damage Debuff // case 45898: break; // // Horde Flag, Extra Damage Debuff // case 45899: break; // // Ahune - Summoning Rhyme Aura // case 45926: break; // // Ahune - Slippery Floor // case 45945: break; // // Ahune's Shield // case 45954: break; // // Nether Vapor Lightning // case 45960: break; // // Darkness // case 45996: break; case 46041: // Summon Blood Elves Periodic target->CastSpell(target, 46037, true, NULL, this); target->CastSpell(target, roll_chance_i(50) ? 46038 : 46039, true, NULL, this); target->CastSpell(target, 46040, true, NULL, this); return; // // Transform Visual Missile Periodic // case 46205: break; // // Find Opening Beam End // case 46333: break; // // Ice Spear Control Aura // case 46371: break; // // Hailstone Chill // case 46458: break; // // Hailstone Chill, Internal // case 46465: break; // // Chill, Internal Shifter // case 46549: break; // // Summon Ice Spear Knockback Delayer // case 46878: break; // // Send Mug Control Aura // case 47369: break; // // Direbrew's Disarm (precast) // case 47407: break; // // Mole Machine Port Schedule // case 47489: break; // // Mole Machine Portal Schedule // case 49466: break; // // Drink Coffee // case 49472: break; // // Listening to Music // case 50493: break; // // Love Rocket Barrage // case 50530: break; // Exist more after, need add later default: break; } // Drink (item drink spells) if (GetEffIndex() > EFFECT_INDEX_0 && spell->EffectApplyAuraName[GetEffIndex()-1] == SPELL_AURA_MOD_POWER_REGEN) { if (target->GetTypeId() != TYPEID_PLAYER) return; // Search SPELL_AURA_MOD_POWER_REGEN aura for this spell and add bonus if (Aura* aura = GetHolder()->GetAuraByEffectIndex(SpellEffectIndex(GetEffIndex() - 1))) { aura->GetModifier()->m_amount = m_modifier.m_amount; ((Player*)target)->UpdateManaRegen(); // Disable continue m_isPeriodic = false; return; } return; } break; } case SPELLFAMILY_HUNTER: { // Aspect of the Viper switch (spell->Id) { case 34074: { if (target->GetTypeId() != TYPEID_PLAYER) return; // Should be manauser if (target->getPowerType() != POWER_MANA) return; Unit* caster = GetCaster(); if (!caster) return; // Regen amount is max (100% from spell) on 21% or less mana and min on 92.5% or greater mana (20% from spell) int mana = target->GetPower(POWER_MANA); int max_mana = target->GetMaxPower(POWER_MANA); int32 base_regen = caster->CalculateSpellDamage(target, GetSpellProto(), m_effIndex, &m_currentBasePoints); float regen_pct = 1.20f - 1.1f * mana / max_mana; if (regen_pct > 1.0f) regen_pct = 1.0f; else if (regen_pct < 0.2f) regen_pct = 0.2f; m_modifier.m_amount = int32(base_regen * regen_pct); ((Player*)target)->UpdateManaRegen(); return; } // // Knockdown Fel Cannon: break; The Aggro Burst // case 40119: break; } break; } default: break; } } void Aura::HandlePreventFleeing(bool apply, bool Real) { if (!Real) return; Unit::AuraList const& fearAuras = GetTarget()->GetAurasByType(SPELL_AURA_MOD_FEAR); if (!fearAuras.empty()) { if (apply) GetTarget()->SetFeared(false, fearAuras.front()->GetCasterGuid()); else GetTarget()->SetFeared(true); } } void Aura::HandleManaShield(bool apply, bool Real) { if (!Real) return; // prevent double apply bonuses if (apply && (GetTarget()->GetTypeId() != TYPEID_PLAYER || !((Player*)GetTarget())->GetSession()->PlayerLoading())) { if (Unit* caster = GetCaster()) { float DoneActualBenefit = 0.0f; switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_MAGE: if (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000008000)) { // Mana Shield // +50% from +spd bonus DoneActualBenefit = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(GetSpellProto())) * 0.5f; break; } break; default: break; } DoneActualBenefit *= caster->CalculateLevelPenalty(GetSpellProto()); m_modifier.m_amount += (int32)DoneActualBenefit; } } } void Aura::HandleArenaPreparation(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); target->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION, apply); if (apply) { // max regen powers at start preparation target->SetHealth(target->GetMaxHealth()); target->SetPower(POWER_MANA, target->GetMaxPower(POWER_MANA)); target->SetPower(POWER_ENERGY, target->GetMaxPower(POWER_ENERGY)); } else { // reset originally 0 powers at start/leave target->SetPower(POWER_RAGE, 0); } } void Aura::HandleAuraMirrorImage(bool apply, bool Real) { if (!Real) return; // Target of aura should always be creature (ref Spell::CheckCast) Creature* pCreature = (Creature*)GetTarget(); if (apply) { // Caster can be player or creature, the unit who pCreature will become an clone of. Unit* caster = GetCaster(); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 0, caster->getRace()); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 1, caster->getClass()); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 2, caster->getGender()); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 3, caster->getPowerType()); pCreature->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_CLONED); pCreature->SetDisplayId(caster->GetNativeDisplayId()); } else { const CreatureInfo* cinfo = pCreature->GetCreatureInfo(); const CreatureModelInfo* minfo = sObjectMgr.GetCreatureModelInfo(pCreature->GetNativeDisplayId()); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 0, 0); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 1, cinfo->unit_class); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 3, 0); pCreature->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_CLONED); pCreature->SetDisplayId(pCreature->GetNativeDisplayId()); } } void Aura::HandleAuraSafeFall(bool Apply, bool Real) { // implemented in WorldSession::HandleMovementOpcodes // only special case if (Apply && Real && GetId() == 32474 && GetTarget()->GetTypeId() == TYPEID_PLAYER) ((Player*)GetTarget())->ActivateTaxiPathTo(506, GetId()); } bool Aura::IsLastAuraOnHolder() { for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (i != GetEffIndex() && GetHolder()->m_auras[i]) return false; return true; } bool Aura::HasMechanic(uint32 mechanic) const { return GetSpellProto()->Mechanic == mechanic || GetSpellProto()->EffectMechanic[m_effIndex] == mechanic; } SpellAuraHolder::SpellAuraHolder(SpellEntry const* spellproto, Unit* target, WorldObject* caster, Item* castItem) : m_spellProto(spellproto), m_target(target), m_castItemGuid(castItem ? castItem->GetObjectGuid() : ObjectGuid()), m_auraSlot(MAX_AURAS), m_auraLevel(1), m_procCharges(0), m_stackAmount(1), m_timeCla(1000), m_removeMode(AURA_REMOVE_BY_DEFAULT), m_AuraDRGroup(DIMINISHING_NONE), m_permanent(false), m_isRemovedOnShapeLost(true), m_deleted(false), m_in_use(0) { MANGOS_ASSERT(target); MANGOS_ASSERT(spellproto && spellproto == sSpellStore.LookupEntry(spellproto->Id) && "`info` must be pointer to sSpellStore element"); if (!caster) m_casterGuid = target->GetObjectGuid(); else { // remove this assert when not unit casters will be supported MANGOS_ASSERT(caster->isType(TYPEMASK_UNIT)) m_casterGuid = caster->GetObjectGuid(); } m_applyTime = time(NULL); m_isPassive = IsPassiveSpell(spellproto); m_isDeathPersist = IsDeathPersistentSpell(spellproto); m_trackedAuraType= IsSingleTargetSpell(spellproto) ? TRACK_AURA_TYPE_SINGLE_TARGET : TRACK_AURA_TYPE_NOT_TRACKED; m_procCharges = spellproto->procCharges; m_isRemovedOnShapeLost = (GetCasterGuid() == m_target->GetObjectGuid() && m_spellProto->Stances && !m_spellProto->HasAttribute(SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT) && !m_spellProto->HasAttribute(SPELL_ATTR_NOT_SHAPESHIFT)); Unit* unitCaster = caster && caster->isType(TYPEMASK_UNIT) ? (Unit*)caster : NULL; m_duration = m_maxDuration = CalculateSpellDuration(spellproto, unitCaster); if (m_maxDuration == -1 || (m_isPassive && spellproto->DurationIndex == 0)) m_permanent = true; if (unitCaster) { if (Player* modOwner = unitCaster->GetSpellModOwner()) modOwner->ApplySpellMod(GetId(), SPELLMOD_CHARGES, m_procCharges); } // some custom stack values at aura holder create switch (m_spellProto->Id) { // some auras applied with max stack case 24575: // Brittle Armor case 24659: // Unstable Power case 24662: // Restless Strength case 26464: // Mercurial Shield m_stackAmount = m_spellProto->StackAmount; break; } for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) m_auras[i] = NULL; } void SpellAuraHolder::AddAura(Aura* aura, SpellEffectIndex index) { m_auras[index] = aura; } void SpellAuraHolder::RemoveAura(SpellEffectIndex index) { m_auras[index] = NULL; } void SpellAuraHolder::ApplyAuraModifiers(bool apply, bool real) { for (int32 i = 0; i < MAX_EFFECT_INDEX && !IsDeleted(); ++i) if (Aura* aur = GetAuraByEffectIndex(SpellEffectIndex(i))) aur->ApplyModifier(apply, real); } void SpellAuraHolder::_AddSpellAuraHolder() { if (!GetId()) return; if (!m_target) return; // Try find slot for aura uint8 slot = NULL_AURA_SLOT; Unit* caster = GetCaster(); // Lookup free slot // will be < MAX_AURAS slot (if find free) with !secondaura if (IsNeedVisibleSlot(caster)) { if (IsPositive()) // empty positive slot { for (uint8 i = 0; i < MAX_POSITIVE_AURAS; i++) { if (m_target->GetUInt32Value((uint16)(UNIT_FIELD_AURA + i)) == 0) { slot = i; break; } } } else // empty negative slot { for (uint8 i = MAX_POSITIVE_AURAS; i < MAX_AURAS; i++) { if (m_target->GetUInt32Value((uint16)(UNIT_FIELD_AURA + i)) == 0) { slot = i; break; } } } } // set infinity cooldown state for spells if (caster && caster->GetTypeId() == TYPEID_PLAYER) { if (m_spellProto->HasAttribute(SPELL_ATTR_DISABLED_WHILE_ACTIVE)) { Item* castItem = m_castItemGuid ? ((Player*)caster)->GetItemByGuid(m_castItemGuid) : NULL; ((Player*)caster)->AddSpellAndCategoryCooldowns(m_spellProto, castItem ? castItem->GetEntry() : 0, NULL, true); } } SetAuraSlot(slot); // Not update fields for not first spell's aura, all data already in fields if (slot < MAX_AURAS) // slot found { SetAura(slot, false); SetAuraFlag(slot, true); SetAuraLevel(slot, caster ? caster->getLevel() : sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)); UpdateAuraApplication(); // update for out of range group members m_target->UpdateAuraForGroup(slot); UpdateAuraDuration(); } //***************************************************** // Update target aura state flag (at 1 aura apply) // TODO: Make it easer //***************************************************** // Sitdown on apply aura req seated if (m_spellProto->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED && !m_target->IsSitState()) m_target->SetStandState(UNIT_STAND_STATE_SIT); // register aura diminishing on apply if (getDiminishGroup() != DIMINISHING_NONE) m_target->ApplyDiminishingAura(getDiminishGroup(), true); // Update Seals information if (IsSealSpell(GetSpellProto())) m_target->ModifyAuraState(AURA_STATE_JUDGEMENT, true); // Conflagrate aura state if (GetSpellProto()->IsFitToFamily(SPELLFAMILY_WARLOCK, UI64LIT(0x0000000000000004))) m_target->ModifyAuraState(AURA_STATE_CONFLAGRATE, true); // Faerie Fire (druid versions) if (m_spellProto->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000000000000400))) m_target->ModifyAuraState(AURA_STATE_FAERIE_FIRE, true); // Swiftmend state on Regrowth & Rejuvenation if (m_spellProto->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000000000000050))) m_target->ModifyAuraState(AURA_STATE_SWIFTMEND, true); // Deadly poison aura state if (m_spellProto->IsFitToFamily(SPELLFAMILY_ROGUE, UI64LIT(0x0000000000010000))) m_target->ModifyAuraState(AURA_STATE_DEADLY_POISON, true); } void SpellAuraHolder::_RemoveSpellAuraHolder() { // Remove all triggered by aura spells vs unlimited duration // except same aura replace case if (m_removeMode != AURA_REMOVE_BY_STACK) CleanupTriggeredSpells(); Unit* caster = GetCaster(); if (caster && IsPersistent()) if (DynamicObject* dynObj = caster->GetDynObject(GetId())) dynObj->RemoveAffected(m_target); // remove at-store spell cast items (for all remove modes?) if (m_target->GetTypeId() == TYPEID_PLAYER && m_removeMode != AURA_REMOVE_BY_DEFAULT && m_removeMode != AURA_REMOVE_BY_DELETE) if (ObjectGuid castItemGuid = GetCastItemGuid()) if (Item* castItem = ((Player*)m_target)->GetItemByGuid(castItemGuid)) ((Player*)m_target)->DestroyItemWithOnStoreSpell(castItem, GetId()); // passive auras do not get put in slots - said who? ;) // Note: but totem can be not accessible for aura target in time remove (to far for find in grid) // if(m_isPassive && !(caster && caster->GetTypeId() == TYPEID_UNIT && ((Creature*)caster)->IsTotem())) // return; uint8 slot = GetAuraSlot(); if (slot >= MAX_AURAS) // slot not set return; if (m_target->GetUInt32Value((uint16)(UNIT_FIELD_AURA + slot)) == 0) return; // unregister aura diminishing (and store last time) if (getDiminishGroup() != DIMINISHING_NONE) m_target->ApplyDiminishingAura(getDiminishGroup(), false); SetAura(slot, true); SetAuraFlag(slot, false); SetAuraLevel(slot, caster ? caster->getLevel() : sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)); m_procCharges = 0; m_stackAmount = 1; UpdateAuraApplication(); if (m_removeMode != AURA_REMOVE_BY_DELETE) { // update for out of range group members m_target->UpdateAuraForGroup(slot); //***************************************************** // Update target aura state flag (at last aura remove) //***************************************************** uint32 removeState = 0; ClassFamilyMask removeFamilyFlag = m_spellProto->SpellFamilyFlags; switch (m_spellProto->SpellFamilyName) { case SPELLFAMILY_PALADIN: if (IsSealSpell(m_spellProto)) removeState = AURA_STATE_JUDGEMENT; // Update Seals information break; case SPELLFAMILY_WARLOCK: if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000004))) removeState = AURA_STATE_CONFLAGRATE; // Conflagrate aura state break; case SPELLFAMILY_DRUID: if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000400))) removeState = AURA_STATE_FAERIE_FIRE; // Faerie Fire (druid versions) else if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000050))) { removeFamilyFlag = ClassFamilyMask(UI64LIT(0x00000000000050)); removeState = AURA_STATE_SWIFTMEND; // Swiftmend aura state } break; case SPELLFAMILY_ROGUE: if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000010000))) removeState = AURA_STATE_DEADLY_POISON; // Deadly poison aura state break; } // Remove state (but need check other auras for it) if (removeState) { bool found = false; Unit::SpellAuraHolderMap const& holders = m_target->GetSpellAuraHolderMap(); for (Unit::SpellAuraHolderMap::const_iterator i = holders.begin(); i != holders.end(); ++i) { SpellEntry const* auraSpellInfo = (*i).second->GetSpellProto(); if (auraSpellInfo->IsFitToFamily(SpellFamily(m_spellProto->SpellFamilyName), removeFamilyFlag)) { found = true; break; } } // this has been last aura if (!found) m_target->ModifyAuraState(AuraState(removeState), false); } // reset cooldown state for spells if (caster && caster->GetTypeId() == TYPEID_PLAYER) { if (GetSpellProto()->HasAttribute(SPELL_ATTR_DISABLED_WHILE_ACTIVE)) // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existing cases) ((Player*)caster)->SendCooldownEvent(GetSpellProto()); } } } void SpellAuraHolder::CleanupTriggeredSpells() { for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { if (!m_spellProto->EffectApplyAuraName[i]) continue; uint32 tSpellId = m_spellProto->EffectTriggerSpell[i]; if (!tSpellId) continue; SpellEntry const* tProto = sSpellStore.LookupEntry(tSpellId); if (!tProto) continue; if (GetSpellDuration(tProto) != -1) continue; // needed for spell 43680, maybe others // TODO: is there a spell flag, which can solve this in a more sophisticated way? if (m_spellProto->EffectApplyAuraName[i] == SPELL_AURA_PERIODIC_TRIGGER_SPELL && GetSpellDuration(m_spellProto) == int32(m_spellProto->EffectAmplitude[i])) continue; m_target->RemoveAurasDueToSpell(tSpellId); } } bool SpellAuraHolder::ModStackAmount(int32 num) { uint32 protoStackAmount = m_spellProto->StackAmount; // Can`t mod if (!protoStackAmount) return true; // Modify stack but limit it int32 stackAmount = m_stackAmount + num; if (stackAmount > (int32)protoStackAmount) stackAmount = protoStackAmount; else if (stackAmount <= 0) // Last aura from stack removed { m_stackAmount = 0; return true; // need remove aura } // Update stack amount SetStackAmount(stackAmount); return false; } void SpellAuraHolder::SetStackAmount(uint32 stackAmount) { Unit* target = GetTarget(); Unit* caster = GetCaster(); if (!target || !caster) return; bool refresh = stackAmount >= m_stackAmount; if (stackAmount != m_stackAmount) { m_stackAmount = stackAmount; UpdateAuraApplication(); for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { if (Aura* aur = m_auras[i]) { int32 bp = aur->GetBasePoints(); int32 amount = m_stackAmount * caster->CalculateSpellDamage(target, m_spellProto, SpellEffectIndex(i), &bp); // Reapply if amount change if (amount != aur->GetModifier()->m_amount) { aur->ApplyModifier(false, true); aur->GetModifier()->m_amount = amount; aur->ApplyModifier(true, true); } } } } if (refresh) // Stack increased refresh duration RefreshHolder(); } Unit* SpellAuraHolder::GetCaster() const { if (GetCasterGuid() == m_target->GetObjectGuid()) return m_target; return ObjectAccessor::GetUnit(*m_target, m_casterGuid);// player will search at any maps } bool SpellAuraHolder::IsWeaponBuffCoexistableWith(SpellAuraHolder const* ref) const { // only item casted spells if (!GetCastItemGuid()) return false; // Exclude Debuffs if (!IsPositive()) return false; // Exclude Non-generic Buffs and Executioner-Enchant if (GetSpellProto()->SpellFamilyName != SPELLFAMILY_GENERIC || GetId() == 42976) return false; // Exclude Stackable Buffs [ie: Blood Reserve] if (GetSpellProto()->StackAmount) return false; // only self applied player buffs if (m_target->GetTypeId() != TYPEID_PLAYER || m_target->GetObjectGuid() != GetCasterGuid()) return false; Item* castItem = ((Player*)m_target)->GetItemByGuid(GetCastItemGuid()); if (!castItem) return false; // Limit to Weapon-Slots if (!castItem->IsEquipped() || (castItem->GetSlot() != EQUIPMENT_SLOT_MAINHAND && castItem->GetSlot() != EQUIPMENT_SLOT_OFFHAND)) return false; // form different weapons return ref->GetCastItemGuid() && ref->GetCastItemGuid() != GetCastItemGuid(); } bool SpellAuraHolder::IsNeedVisibleSlot(Unit const* caster) const { bool totemAura = caster && caster->GetTypeId() == TYPEID_UNIT && ((Creature*)caster)->IsTotem(); for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { if (!m_auras[i]) continue; // special area auras cases switch (m_spellProto->Effect[i]) { case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY: return m_target != caster; case SPELL_EFFECT_APPLY_AREA_AURA_PET: case SPELL_EFFECT_APPLY_AREA_AURA_OWNER: case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND: case SPELL_EFFECT_APPLY_AREA_AURA_PARTY: // passive auras (except totem auras) do not get placed in caster slot return (m_target != caster || totemAura || !m_isPassive) && m_auras[i]->GetModifier()->m_auraname != SPELL_AURA_NONE; default: break; } } // passive auras (except totem auras) do not get placed in the slots return !m_isPassive || totemAura; } void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) { uint32 spellId1 = 0; uint32 spellId2 = 0; uint32 spellId3 = 0; uint32 spellId4 = 0; switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_MAGE: { switch (GetId()) { case 11189: // Frost Warding case 28332: { if (m_target->GetTypeId() == TYPEID_PLAYER && !apply) { // reflection chance (effect 1) of Frost Ward, applied in dummy effect if (SpellModifier* mod = ((Player*)m_target)->GetSpellMod(SPELLMOD_EFFECT2, GetId())) ((Player*)m_target)->AddSpellMod(mod, false); } return; } default: return; } break; } case SPELLFAMILY_WARRIOR: { if (!apply) { // Remove Blood Frenzy only if target no longer has any Deep Wound or Rend (applying is handled by procs) if (GetSpellProto()->Mechanic != MECHANIC_BLEED) return; // If target still has one of Warrior's bleeds, do nothing Unit::AuraList const& PeriodicDamage = m_target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE); for (Unit::AuraList::const_iterator i = PeriodicDamage.begin(); i != PeriodicDamage.end(); ++i) if ((*i)->GetCasterGuid() == GetCasterGuid() && (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARRIOR && (*i)->GetSpellProto()->Mechanic == MECHANIC_BLEED) return; spellId1 = 30069; // Blood Frenzy (Rank 1) spellId2 = 30070; // Blood Frenzy (Rank 2) } else return; break; } case SPELLFAMILY_HUNTER: { switch (GetId()) { // The Beast Within and Bestial Wrath - immunity case 19574: case 34471: { spellId1 = 24395; spellId2 = 24396; spellId3 = 24397; spellId4 = 26592; break; } // Misdirection, main spell case 34477: { if (!apply) m_target->getHostileRefManager().ResetThreatRedirection(); return; } default: return; } break; } default: return; } // prevent aura deletion, specially in multi-boost case SetInUse(true); if (apply) { if (spellId1) m_target->CastSpell(m_target, spellId1, true, NULL, NULL, GetCasterGuid()); if (spellId2 && !IsDeleted()) m_target->CastSpell(m_target, spellId2, true, NULL, NULL, GetCasterGuid()); if (spellId3 && !IsDeleted()) m_target->CastSpell(m_target, spellId3, true, NULL, NULL, GetCasterGuid()); if (spellId4 && !IsDeleted()) m_target->CastSpell(m_target, spellId4, true, NULL, NULL, GetCasterGuid()); } else { if (spellId1) m_target->RemoveAurasByCasterSpell(spellId1, GetCasterGuid()); if (spellId2) m_target->RemoveAurasByCasterSpell(spellId2, GetCasterGuid()); if (spellId3) m_target->RemoveAurasByCasterSpell(spellId3, GetCasterGuid()); if (spellId4) m_target->RemoveAurasByCasterSpell(spellId4, GetCasterGuid()); } SetInUse(false); } SpellAuraHolder::~SpellAuraHolder() { // note: auras in delete list won't be affected since they clear themselves from holder when adding to deletedAuraslist for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (Aura* aur = m_auras[i]) delete aur; } void SpellAuraHolder::Update(uint32 diff) { if (m_duration > 0) { m_duration -= diff; if (m_duration < 0) m_duration = 0; m_timeCla -= diff; if (m_timeCla <= 0) { if (Unit* caster = GetCaster()) { Powers powertype = Powers(GetSpellProto()->powerType); int32 manaPerSecond = GetSpellProto()->manaPerSecond + GetSpellProto()->manaPerSecondPerLevel * caster->getLevel(); m_timeCla = 1 * IN_MILLISECONDS; if (manaPerSecond) { if (powertype == POWER_HEALTH) caster->ModifyHealth(-manaPerSecond); else caster->ModifyPower(powertype, -manaPerSecond); } } } } for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (Aura* aura = m_auras[i]) aura->UpdateAura(diff); // Channeled aura required check distance from caster if (IsChanneledSpell(m_spellProto) && GetCasterGuid() != m_target->GetObjectGuid()) { Unit* caster = GetCaster(); if (!caster) { m_target->RemoveAurasByCasterSpell(GetId(), GetCasterGuid()); return; } // need check distance for channeled target only if (caster->GetChannelObjectGuid() == m_target->GetObjectGuid()) { // Get spell range float max_range = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellProto->rangeIndex)); if (Player* modOwner = caster->GetSpellModOwner()) modOwner->ApplySpellMod(GetId(), SPELLMOD_RANGE, max_range, NULL); if (!caster->IsWithinDistInMap(m_target, max_range)) { caster->InterruptSpell(CURRENT_CHANNELED_SPELL); return; } } } } void SpellAuraHolder::RefreshHolder() { SetAuraDuration(GetAuraMaxDuration()); UpdateAuraDuration(); } void SpellAuraHolder::SetAuraMaxDuration(int32 duration) { m_maxDuration = duration; // possible overwrite persistent state if (duration > 0) { if (!(IsPassive() && GetSpellProto()->DurationIndex == 0)) SetPermanent(false); } } bool SpellAuraHolder::HasMechanic(uint32 mechanic) const { if (mechanic == m_spellProto->Mechanic) return true; for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (m_auras[i] && m_spellProto->EffectMechanic[i] == mechanic) return true; return false; } bool SpellAuraHolder::HasMechanicMask(uint32 mechanicMask) const { if (mechanicMask & (1 << (m_spellProto->Mechanic - 1))) return true; for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (m_auras[i] && m_spellProto->EffectMechanic[i] && ((1 << (m_spellProto->EffectMechanic[i] - 1)) & mechanicMask)) return true; return false; } bool SpellAuraHolder::IsPersistent() const { for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (Aura* aur = m_auras[i]) if (aur->IsPersistent()) return true; return false; } bool SpellAuraHolder::IsAreaAura() const { for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (Aura* aur = m_auras[i]) if (aur->IsAreaAura()) return true; return false; } bool SpellAuraHolder::IsPositive() const { for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (Aura* aur = m_auras[i]) if (!aur->IsPositive()) return false; return true; } bool SpellAuraHolder::IsEmptyHolder() const { for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (m_auras[i]) return false; return true; } void SpellAuraHolder::UnregisterAndCleanupTrackedAuras() { TrackedAuraType trackedType = GetTrackedAuraType(); if (!trackedType) return; if (trackedType == TRACK_AURA_TYPE_SINGLE_TARGET) { if (Unit* caster = GetCaster()) caster->GetTrackedAuraTargets(trackedType).erase(GetSpellProto()); } m_trackedAuraType = TRACK_AURA_TYPE_NOT_TRACKED; } void SpellAuraHolder::SetAuraFlag(uint32 slot, bool add) { uint32 index = slot / 4; uint32 byte = (slot % 4) * 8; uint32 val = m_target->GetUInt32Value(UNIT_FIELD_AURAFLAGS + index); val &= ~((uint32)AFLAG_MASK << byte); if (add) { if (IsPositive()) val |= ((uint32)AFLAG_POSITIVE << byte); else val |= ((uint32)AFLAG_NEGATIVE << byte); } m_target->SetUInt32Value(UNIT_FIELD_AURAFLAGS + index, val); } void SpellAuraHolder::SetAuraLevel(uint32 slot, uint32 level) { uint32 index = slot / 4; uint32 byte = (slot % 4) * 8; uint32 val = m_target->GetUInt32Value(UNIT_FIELD_AURALEVELS + index); val &= ~(0xFF << byte); val |= (level << byte); m_target->SetUInt32Value(UNIT_FIELD_AURALEVELS + index, val); } void SpellAuraHolder::UpdateAuraApplication() { if (m_auraSlot >= MAX_AURAS) return; uint32 stackCount = m_procCharges > 0 ? m_procCharges * m_stackAmount : m_stackAmount; uint32 index = m_auraSlot / 4; uint32 byte = (m_auraSlot % 4) * 8; uint32 val = m_target->GetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS + index); val &= ~(0xFF << byte); // field expect count-1 for proper amount show, also prevent overflow at client side val |= ((uint8(stackCount <= 255 ? stackCount - 1 : 255 - 1)) << byte); m_target->SetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS + index, val); } void SpellAuraHolder::UpdateAuraDuration() { if (GetAuraSlot() >= MAX_AURAS || m_isPassive) return; if (m_target->GetTypeId() == TYPEID_PLAYER) { WorldPacket data(SMSG_UPDATE_AURA_DURATION, 5); data << uint8(GetAuraSlot()); data << uint32(GetAuraDuration()); ((Player*)m_target)->SendDirectMessage(&data); data.Initialize(SMSG_SET_EXTRA_AURA_INFO, (8 + 1 + 4 + 4 + 4)); data << m_target->GetPackGUID(); data << uint8(GetAuraSlot()); data << uint32(GetId()); data << uint32(GetAuraMaxDuration()); data << uint32(GetAuraDuration()); ((Player*)m_target)->SendDirectMessage(&data); } // not send in case player loading (will not work anyway until player not added to map), sent in visibility change code if (m_target->GetTypeId() == TYPEID_PLAYER && ((Player*)m_target)->GetSession()->PlayerLoading()) return; Unit* caster = GetCaster(); if (caster && caster->GetTypeId() == TYPEID_PLAYER && caster != m_target) SendAuraDurationForCaster((Player*)caster); } void SpellAuraHolder::SendAuraDurationForCaster(Player* caster) { WorldPacket data(SMSG_SET_EXTRA_AURA_INFO_NEED_UPDATE, (8 + 1 + 4 + 4 + 4)); data << m_target->GetPackGUID(); data << uint8(GetAuraSlot()); data << uint32(GetId()); data << uint32(GetAuraMaxDuration()); // full data << uint32(GetAuraDuration()); // remain caster->GetSession()->SendPacket(&data); }
Java
# CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 2.8 # The generator used is: SET(CMAKE_DEPENDS_GENERATOR "Unix Makefiles") # The top level Makefile was generated from the following files: SET(CMAKE_MAKEFILE_DEPENDS "CMakeCache.txt" "/home/guillaume/tf-cadence/gnuradio/zedboard/arm_cortex_a8_native.cmake" "../CMakeLists.txt" "../apps/CMakeLists.txt" "CMakeFiles/CMakeCCompiler.cmake" "CMakeFiles/CMakeCXXCompiler.cmake" "CMakeFiles/CMakeSystem.cmake" "../cmake/Modules/CMakeParseArgumentsCopy.cmake" "../cmake/Modules/FindCppUnit.cmake" "../cmake/Modules/FindGnuradioRuntime.cmake" "../cmake/Modules/GrMiscUtils.cmake" "../cmake/Modules/GrPlatform.cmake" "../cmake/Modules/GrPython.cmake" "../cmake/Modules/GrSwig.cmake" "../cmake/Modules/GrTest.cmake" "../cmake/cmake_uninstall.cmake.in" "../docs/CMakeLists.txt" "../grc/CMakeLists.txt" "../include/test1/CMakeLists.txt" "../lib/CMakeLists.txt" "../python/CMakeLists.txt" "../swig/CMakeLists.txt" "/usr/share/cmake-2.8/Modules/CMakeCCompiler.cmake.in" "/usr/share/cmake-2.8/Modules/CMakeCInformation.cmake" "/usr/share/cmake-2.8/Modules/CMakeCXXCompiler.cmake.in" "/usr/share/cmake-2.8/Modules/CMakeCXXInformation.cmake" "/usr/share/cmake-2.8/Modules/CMakeClDeps.cmake" "/usr/share/cmake-2.8/Modules/CMakeCommonLanguageInclude.cmake" "/usr/share/cmake-2.8/Modules/CMakeDetermineCCompiler.cmake" "/usr/share/cmake-2.8/Modules/CMakeDetermineCXXCompiler.cmake" "/usr/share/cmake-2.8/Modules/CMakeDetermineCompilerId.cmake" "/usr/share/cmake-2.8/Modules/CMakeDetermineSystem.cmake" "/usr/share/cmake-2.8/Modules/CMakeFindBinUtils.cmake" "/usr/share/cmake-2.8/Modules/CMakeFindFrameworks.cmake" "/usr/share/cmake-2.8/Modules/CMakeGenericSystem.cmake" "/usr/share/cmake-2.8/Modules/CMakeParseArguments.cmake" "/usr/share/cmake-2.8/Modules/CMakeSystem.cmake.in" "/usr/share/cmake-2.8/Modules/CMakeSystemSpecificInformation.cmake" "/usr/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake" "/usr/share/cmake-2.8/Modules/CMakeTestCXXCompiler.cmake" "/usr/share/cmake-2.8/Modules/CMakeTestCompilerCommon.cmake" "/usr/share/cmake-2.8/Modules/CMakeUnixFindMake.cmake" "/usr/share/cmake-2.8/Modules/Compiler/GNU-C.cmake" "/usr/share/cmake-2.8/Modules/Compiler/GNU-CXX.cmake" "/usr/share/cmake-2.8/Modules/Compiler/GNU.cmake" "/usr/share/cmake-2.8/Modules/FindBoost.cmake" "/usr/share/cmake-2.8/Modules/FindDoxygen.cmake" "/usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake" "/usr/share/cmake-2.8/Modules/FindPackageMessage.cmake" "/usr/share/cmake-2.8/Modules/FindPkgConfig.cmake" "/usr/share/cmake-2.8/Modules/FindPythonInterp.cmake" "/usr/share/cmake-2.8/Modules/FindPythonLibs.cmake" "/usr/share/cmake-2.8/Modules/FindSWIG.cmake" "/usr/share/cmake-2.8/Modules/Platform/Linux-GNU-C.cmake" "/usr/share/cmake-2.8/Modules/Platform/Linux-GNU-CXX.cmake" "/usr/share/cmake-2.8/Modules/Platform/Linux-GNU.cmake" "/usr/share/cmake-2.8/Modules/Platform/Linux.cmake" "/usr/share/cmake-2.8/Modules/Platform/UnixPaths.cmake" "/usr/share/cmake-2.8/Modules/SelectLibraryConfigurations.cmake" "/usr/share/cmake-2.8/Modules/UseSWIG.cmake" ) # The corresponding makefile is: SET(CMAKE_MAKEFILE_OUTPUTS "Makefile" "CMakeFiles/cmake.check_cache" ) # Byproducts of CMake generate step: SET(CMAKE_MAKEFILE_PRODUCTS "CMakeFiles/CMakeDirectoryInformation.cmake" "include/test1/CMakeFiles/CMakeDirectoryInformation.cmake" "lib/CMakeFiles/CMakeDirectoryInformation.cmake" "swig/CMakeFiles/CMakeDirectoryInformation.cmake" "python/CMakeFiles/CMakeDirectoryInformation.cmake" "grc/CMakeFiles/CMakeDirectoryInformation.cmake" "apps/CMakeFiles/CMakeDirectoryInformation.cmake" "docs/CMakeFiles/CMakeDirectoryInformation.cmake" ) # Dependency information for all targets: SET(CMAKE_DEPEND_INFO_FILES "CMakeFiles/uninstall.dir/DependInfo.cmake" "lib/CMakeFiles/gnuradio-test1.dir/DependInfo.cmake" "lib/CMakeFiles/test-test1.dir/DependInfo.cmake" "swig/CMakeFiles/_test1_swig.dir/DependInfo.cmake" "swig/CMakeFiles/_test1_swig_swig_tag.dir/DependInfo.cmake" "swig/CMakeFiles/pygen_swig_104a7.dir/DependInfo.cmake" "python/CMakeFiles/pygen_python_30562.dir/DependInfo.cmake" "apps/CMakeFiles/pygen_apps_9a6dd.dir/DependInfo.cmake" )
Java
<?php /* * * Copyright 2001-2012 Thomas Belliard, Laurent Delineau, Edouard Hue, Eric Lebrun * * This file is part of GEPI. * * GEPI is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GEPI 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 GEPI; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // On indique qu'il faut creer des variables non protégées (voir fonction cree_variables_non_protegees()) $variables_non_protegees = 'yes'; // Begin standart header $titre_page = "Saisie de commentaires-types"; // Initialisations files require_once("../lib/initialisations.inc.php"); // Resume session $resultat_session = $session_gepi->security_check(); if ($resultat_session == 'c') { header("Location: ../utilisateurs/mon_compte.php?change_mdp=yes"); die(); } else if ($resultat_session == '0') { header("Location: ../logout.php?auto=1"); die(); } // Check access // INSERT INTO droits VALUES ('/saisie/commentaires_types.php', 'V', 'V', 'V', 'V', 'F', 'F', 'V', 'Saisie de commentaires-types', ''); if (!checkAccess()) { header("Location: ../logout.php?auto=1"); die(); } //========================================== // End standart header require_once("../lib/header.inc.php"); if (!loadSettings()) { die("Erreur chargement settings"); } //========================================== $sql="CREATE TABLE IF NOT EXISTS `commentaires_types` ( `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `commentaire` TEXT NOT NULL , `num_periode` INT NOT NULL , `id_classe` INT NOT NULL ) ENGINE=MyISAM CHARACTER SET utf8 COLLATE utf8_general_ci;"; $resultat_creation_table=mysqli_query($GLOBALS["mysqli"], $sql); function get_classe_from_id($id){ //$sql="SELECT * FROM classes WHERE id='$id_classe[0]'"; $sql="SELECT * FROM classes WHERE id='$id'"; $resultat_classe=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_classe)!=1){ //echo "<p>ERREUR! La classe d'identifiant '$id_classe[0]' n'a pas pu être identifiée.</p>"; echo "<p>ERREUR! La classe d'identifiant '$id' n'a pas pu être identifiée.</p>"; } else{ $ligne_classe=mysqli_fetch_object($resultat_classe); $classe=$ligne_classe->classe; return $classe; } } ?> <p class="bold"><a href="../accueil.php">Retour</a> | <a href="commentaires_types.php">Saisir des commentaires</a> | <a href="commentaires_types.php?recopie=oui">Recopier des commentaires</a> </p> <?php /* if ((($_SESSION['statut']=='professeur') AND ((getSettingValue("GepiProfImprBul")!='yes') OR ((getSettingValue("GepiProfImprBul")=='yes') AND (getSettingValue("GepiProfImprBulSettings")!='yes')))) OR (($_SESSION['statut']=='scolarite') AND (getSettingValue("GepiScolImprBulSettings")!='yes')) OR (($_SESSION['statut']=='administrateur') AND (getSettingValue("GepiAdminImprBulSettings")!='yes'))) { die("Droits insuffisants pour effectuer cette opération"); } */ if ((($_SESSION['statut']=='professeur') AND (getSettingValue("CommentairesTypesPP")=='yes') AND (mysqli_num_rows(mysqli_query($GLOBALS["mysqli"], "SELECT 1=1 FROM j_eleves_professeurs WHERE professeur='".$_SESSION['login']."'"))>0)) OR (($_SESSION['statut']=='scolarite') AND (getSettingValue("CommentairesTypesScol")=='yes')) OR (($_SESSION['statut']=='cpe') AND (getSettingValue("CommentairesTypesCpe")=='yes')) ) { // Accès autorisé à la page } else{ die("Droits insuffisants pour effectuer cette opération"); } ?> <form name="formulaire" action="commentaires_types.php" method="post"> <?php echo add_token_field(); //echo "\$_GET['recopie']=".$_GET['recopie']."<br />"; $recopie=isset($_GET['recopie']) ? $_GET['recopie'] : (isset($_POST['recopie']) ? $_POST['recopie'] : ""); //echo "\$recopie=$recopie<br />"; if($recopie!="oui"){ // ============================================= // Définition/modification des commentaires-type // ============================================= if(!isset($_POST['id_classe'])){ // Choix de la classe //echo "<p>Pour quelle classe et quelles périodes souhaitez-vous définir/modifier les commentaires-type?</p>\n"; echo "<p>Pour quelle classe souhaitez-vous définir/modifier les commentaires-type?</p>\n"; echo "<blockquote>\n"; // A REVOIR: Il ne faut lister que les classes appropriées. //$sql="select distinct id,classe from classes order by classe"; // if ((($_SESSION['statut']=='professeur') AND (getSettingValue("CommentairesTypesPP")=='yes') AND (mysql_num_rows(mysql_query("SELECT 1=1 FROM j_eleves_professeurs WHERE professeur='".$_SESSION['login']."'"))>0)) // OR (($_SESSION['statut']=='scolarite') AND (getSettingValue("CommentairesTypesScol")=='yes'))) if($_SESSION['statut']=='professeur'){ $sql="SELECT DISTINCT c.id,c.classe FROM j_eleves_classes jec, classes c, j_eleves_professeurs jep WHERE jec.id_classe=c.id AND jec.login=jep.login AND jep.professeur='".$_SESSION['login']."' ORDER BY c.classe"; } elseif($_SESSION['statut']=='scolarite'){ $sql="SELECT DISTINCT c.id,c.classe FROM j_scol_classes jsc, classes c WHERE jsc.id_classe=c.id AND jsc.login='".$_SESSION['login']."' ORDER BY c.classe"; } elseif(($_SESSION['statut']=='cpe')&&(getSettingAOui('GepiRubConseilCpe'))) { $sql="SELECT DISTINCT c.id,c.classe FROM j_eleves_cpe jecpe, j_eleves_classes jec, classes c WHERE jec.id_classe=c.id AND jec.login=jecpe.e_login AND jecpe.cpe_login='".$_SESSION['login']."' ORDER BY c.classe"; } elseif(($_SESSION['statut']=='cpe')&&(getSettingAOui('GepiRubConseilCpeTous'))) { $sql="select distinct id,classe from classes order by classe"; } else { // CA NE DEVRAIT PAS ARRIVER... //$sql="select distinct id,classe from classes order by classe"; echo "<p>Statut incorrect.</p>\n"; die(); require("../lib/footer.inc.php"); } $resultat_classes=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_classes)==0){ echo "<p>Aucune classe n'est encore définie...</p>\n</form>\n</body>\n</html>\n"; exit(); } /* $cpt=0; while($ligne_classe=mysql_fetch_object($resultat_classes)){ if($cpt==0){ $checked="checked "; } else{ $checked=""; } //echo "<input type='radio' name='id_classe' value='$ligne_classe->id' $checked/> $ligne_classe->classe<br />\n"; echo "<input type='radio' name='id_classe' id='id_classe".$ligne_classe->id."' value='$ligne_classe->id' $checked/><label for='id_classe".$ligne_classe->id."' style='cursor: pointer;'> $ligne_classe->classe</label><br />\n"; $cpt++; } */ $nb_classes=mysqli_num_rows($resultat_classes); $nb_class_par_colonne=round($nb_classes/3); echo "<table width='100%'>\n"; echo "<tr valign='top' align='center'>\n"; $cpt=0; //echo "<td style='padding: 0 10px 0 10px'>\n"; echo "<td align='left'>\n"; while($ligne_classe=mysqli_fetch_object($resultat_classes)){ if(($cpt>0)&&(round($cpt/$nb_class_par_colonne)==$cpt/$nb_class_par_colonne)){ echo "</td>\n"; //echo "<td style='padding: 0 10px 0 10px'>\n"; echo "<td align='left'>\n"; } if($cpt==0){ $checked="checked "; } else{ $checked=""; } //echo "<input type='radio' name='id_classe' value='$ligne_classe->id' /> $ligne_classe->classe<br />\n"; echo "<input type='radio' name='id_classe' id='id_classe".$ligne_classe->id."' value='$ligne_classe->id' $checked/><label for='id_classe".$ligne_classe->id."' style='cursor: pointer;'> $ligne_classe->classe</label><br />\n"; $cpt++; } echo "</td>\n"; echo "</tr>\n"; echo "</table>\n"; echo "</blockquote>\n"; echo "<center><input type='submit' name='ok' value='Valider' /></center>\n"; } else{ if(!isset($_POST['num_periode'])){ // ================== // Choix des périodes // ================== // Récupération des variables: $id_classe=$_POST['id_classe']; //echo "\$id_classe=$id_classe<br />\n"; echo "<h2>Saisie/Modification des commentaires-types pour la classe de ".get_classe_from_id($id_classe)."</h2>\n"; // Rappel des commentaires-type saisis pour cette classe sur toutes les périodes définies: $sql="select * from periodes where id_classe='$id_classe' order by num_periode"; //echo "$sql<br />"; $resultat_num_periode=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_num_periode)==0){ echo "Aucune période n'est encore définie pour cette classe...<br />\n"; echo "</body>\n</html>\n"; exit(); } else{ echo "<p>Voici les commentaires-type actuellement saisis pour cette classe:</p>\n"; echo "<ul>\n"; while($ligne_periode=mysqli_fetch_object($resultat_num_periode)){ //for($i=0;$i<count($num_periode);$i++){ echo "<li>\n"; //$sql="select nom_periode from periodes where num_periode='$ligne_periode->num_periode'"; //$resultat_periode=mysql_query($sql); //$ligne_nom_periode=mysql_fetch_object($resultat_periode); //echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n"; echo "<p><b>$ligne_periode->nom_periode</b>:</p>\n"; // AFFICHER LES COMMENTAIRES-TYPE POUR CHAQUE PERIODE $sql="select * from commentaires_types where id_classe='$id_classe' and num_periode='$ligne_periode->num_periode' order by commentaire"; $resultat_commentaires=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_commentaires)>0){ echo "<ul>\n"; while($ligne_commentaires=mysqli_fetch_object($resultat_commentaires)){ echo "<li>".stripslashes(nl2br(trim($ligne_commentaires->commentaire)))."</li>\n"; } echo "</ul>\n"; } else{ echo "<p style='color:red;'>Aucun commentaire-type n'est saisi pour cette classe sur cette période.</p>\n"; } echo "</li>\n"; } echo "</ul>\n"; } // Choix des périodes: echo "<p>Pour quelles périodes souhaitez-vous définir/modifier les commentaires-type?</p>\n"; //echo "<p>\n"; echo "<input type='hidden' name='id_classe' value='$id_classe' />\n"; // Récupération du nom de la classe $sql="select * from classes where id='$id_classe'"; $resultat_classe=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_classe)==0){ echo "<p>L'identifiant de la classe semble erroné.</p>\n</form>\n</body>\n</html>\n"; exit(); } $ligne_classe=mysqli_fetch_object($resultat_classe); $classe_courante="$ligne_classe->classe"; echo "<p><b>$classe_courante</b>: "; $sql="select * from periodes where id_classe='$id_classe' order by num_periode"; //echo "$sql<br />"; $resultat_num_periode=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_num_periode)==0){ echo "Aucune période n'est encore définie pour cette classe...<br />\n"; } else{ /* $ligne_num_periode=mysql_fetch_object($resultat_num_periode); $sql="select * from periodes where num_periode='$ligne_num_periode->num_periode'"; $resultat_periode=mysql_query($sql); $ligne_periode=mysql_fetch_object($resultat_periode); //echo "<input type='checkbox' name='num_periode[]' value='$ligne_periode->num_periode'> $ligne_periode->nom_periode\n"; echo "<input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_periode->num_periode."' value='$ligne_periode->num_periode' /><label for='num_periode_".$ligne_periode->num_periode."' style='cursor: pointer;'> $ligne_periode->nom_periode</label>\n"; while($ligne_num_periode=mysql_fetch_object($resultat_num_periode)){ //$cpt++; $sql="select * from periodes where num_periode='$ligne_num_periode->num_periode'"; $resultat_periode=mysql_query($sql); $ligne_periode=mysql_fetch_object($resultat_periode); //echo " &nbsp;&nbsp;&nbsp;- <input type='checkbox' name='num_periode[]' value='$ligne_periode->num_periode'> $ligne_periode->nom_periode\n"; echo " &nbsp;&nbsp;&nbsp;- <input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_periode->num_periode."' value='$ligne_periode->num_periode' /><label for='num_periode_".$ligne_periode->num_periode."' style='cursor: pointer;'> $ligne_periode->nom_periode</label>\n"; } */ $cpt_per=0; while($ligne_num_periode=mysqli_fetch_object($resultat_num_periode)){ if($cpt_per>0) {echo " &nbsp;&nbsp;&nbsp;- ";} echo "<input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_num_periode->num_periode."' value='$ligne_num_periode->num_periode' /><label for='num_periode_".$ligne_num_periode->num_periode."' style='cursor: pointer;'> $ligne_num_periode->nom_periode</label>\n"; $cpt_per++; } echo "<br />\n"; } echo "</p>\n"; echo "<center><input type='submit' name='ok' value='Valider' /></center>\n"; } else { check_token(false); // ============================================================== // Saisie, modification, suppression, validation des commentaires // ============================================================== // Récupération des variables: $id_classe=$_POST['id_classe']; $num_periode=$_POST['num_periode']; $suppr=isset($_POST['suppr']) ? $_POST['suppr'] : ""; /* $nom_log = "app_eleve_".$k."_".$i; //echo "\$nom_log=$nom_log<br />"; if (isset($NON_PROTECT[$nom_log])){ $app = traitement_magic_quotes(corriger_caracteres($NON_PROTECT[$nom_log])); } else{ $app = ""; } */ $compteur_nb_commentaires=isset($_POST['compteur_nb_commentaires']) ? $_POST['compteur_nb_commentaires'] : NULL; //if(isset($_POST['commentaire_1'])){ if(isset($compteur_nb_commentaires)){ //if(isset($_POST['commentaire'])){ // Récupération des variables: //$commentaire=$_POST['commentaire']; //$commentaire=html_entity_decode($_POST['commentaire']); // Nettoyage des commentaires déjà saisis pour cette classe et ces périodes: $sql="delete from commentaires_types where id_classe='$id_classe' and (num_periode='$num_periode[0]'"; for($i=1;$i<count($num_periode);$i++){ $sql=$sql." or num_periode='$num_periode[$i]'"; } $sql=$sql.")"; //echo "sql=$sql<br />"; $resultat_nettoyage=mysqli_query($GLOBALS["mysqli"], $sql); // Validation des saisies/modifs... //for($i=1;$i<=count($commentaire);$i++){ for($i=1;$i<=$compteur_nb_commentaires;$i++){ //echo "\$suppr[$i]=$suppr[$i]<br />"; //if(($suppr[$i]=="")&&($commentaire[$i]!="")){ //if((!isset($suppr[$i]))&&($commentaire[$i]!="")){ if(!isset($suppr[$i])) { $nom_log = "commentaire_".$i; if (isset($NON_PROTECT[$nom_log])){ $commentaire_courant = traitement_magic_quotes(corriger_caracteres($NON_PROTECT[$nom_log])); if($commentaire_courant!=""){ for($j=0;$j<count($num_periode);$j++){ //$sql="insert into commentaires_types values('','$commentaire[$i]','$num_periode[$j]','$id_classe')"; //========================= // MODIF: boireaus 20071121 //$sql="insert into commentaires_types values('','".html_entity_decode($commentaire[$i])."','$num_periode[$j]','$id_classe')"; //$tmp_commentaire=my_ereg_replace("&#039;","'",html_entity_decode($commentaire[$i])); //$sql="insert into commentaires_types values('','".addslashes($tmp_commentaire)."','$num_periode[$j]','$id_classe')"; //$sql="insert into commentaires_types values('','".addslashes($commentaire_courant)."','$num_periode[$j]','$id_classe')"; $sql="insert into commentaires_types values('','".$commentaire_courant."','$num_periode[$j]','$id_classe')"; //========================= //echo "sql=$sql<br />"; $resultat_insertion_commentaire=mysqli_query($GLOBALS["mysqli"], $sql); } } } } } } echo "<input type='hidden' name='id_classe' value='$id_classe' />\n"; /* echo "$id_classe: "; for($i=0;$i<count($num_periode);$i++){ echo "$num_periode[$i] -"; } echo "<br />"; */ // Récupération du nom de la classe $sql="select * from classes where id='$id_classe'"; $resultat_classe=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_classe)==0){ echo "<p>L'identifiant de la classe semble erroné.</p>\n</form>\n</body>\n</html>\n"; exit(); } $ligne_classe=mysqli_fetch_object($resultat_classe); $classe_courante="$ligne_classe->classe"; //echo "<p><b>Classe de $classe_courante</b></p>\n"; echo "<h2>Classe de $classe_courante</h2>\n"; // Recherche des commentaires déjà saisis: //$sql="select * from commentaires_types where id_classe='$id_classe' and (num_periode='$num_periode[0]'"; //$sql="select distinct commentaire,id from commentaires_types where id_classe='$id_classe' and (num_periode='$num_periode[0]'"; $sql="select distinct commentaire,id from commentaires_types where id_classe='$id_classe' and (num_periode='$num_periode[0]'"; echo "<input type='hidden' name='num_periode[0]' value='$num_periode[0]' />\n"; for($i=1;$i<count($num_periode);$i++){ $sql=$sql." or num_periode='$num_periode[$i]'"; echo "<input type='hidden' name='num_periode[$i]' value='$num_periode[$i]' />\n"; } //$sql=$sql.")"; $sql=$sql.") order by commentaire"; //echo "$sql"; $resultat_commentaires=mysqli_query($GLOBALS["mysqli"], $sql); $cpt=1; if(mysqli_num_rows($resultat_commentaires)!=0){ echo "<p>Voici la liste des commentaires-type existants pour la classe et la/les période(s) choisie(s):</p>\n"; echo "<blockquote>\n"; echo "<table class='boireaus' border='1'>\n"; echo "<tr style='text-align:center;'>\n"; echo "<th>Commentaire</th>\n"; echo "<th>Supprimer</th>\n"; echo "</tr>\n"; $precedent_commentaire=""; //$cpt=1; $alt=1; while($ligne_commentaire=mysqli_fetch_object($resultat_commentaires)){ if("$ligne_commentaire->commentaire"!="$precedent_commentaire"){ $alt=$alt*(-1); echo "<tr class='lig$alt' style='text-align:center;'>\n"; echo "<td>"; //echo "<textarea name='commentaire[$cpt]' cols='60'>".stripslashes($ligne_commentaire->commentaire)."</textarea>"; echo "<textarea name='no_anti_inject_commentaire_".$cpt."' cols='60' onchange='changement()'>".stripslashes($ligne_commentaire->commentaire)."</textarea>"; echo "</td>\n"; echo "<td><input type='checkbox' name='suppr[$cpt]' value='$ligne_commentaire->id' /></td>\n"; echo "</tr>\n"; $cpt++; $precedent_commentaire="$ligne_commentaire->commentaire"; } } echo "</table>\n"; echo "</blockquote>\n"; } echo "<p>Saisie d'un nouveau commentaire:</p>"; echo "<blockquote>\n"; //echo "<textarea name='commentaire[$cpt]' cols='60'></textarea><br />\n"; echo "<textarea name='no_anti_inject_commentaire_".$cpt."' id='no_anti_inject_commentaire_".$cpt."' cols='60' onchange='changement()'></textarea><br />\n"; echo "<input type='hidden' name='compteur_nb_commentaires' value='$cpt' />\n"; echo "<center><input type='submit' name='ok' value='Valider' /></center>\n"; echo "</blockquote>\n"; echo "<script type='text/javascript'> document.getElementById('no_anti_inject_commentaire_".$cpt."').focus(); </script>\n"; } } } else{ //================================================================== // ============================================================== // ============================ // Recopie de commentaires-type // ============================ echo "<input type='hidden' name='recopie' value='oui' />\n"; if(!isset($_POST['id_classe'])){ // ========================= // Choix de la classe modèle // ========================= echo "<p>De quelle classe souhaitez-vous recopier les commentaires-type?</p>\n"; echo "<blockquote>\n"; $sql="select distinct id,classe from classes order by classe"; $resultat_classes=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_classes)==0){ echo "<p>Aucune classe n'est encore définie...</p>\n</form>\n</body>\n</html>\n"; exit(); } $nb_classes=mysqli_num_rows($resultat_classes); $nb_class_par_colonne=round($nb_classes/3); echo "<table width='100%'>\n"; echo "<tr valign='top' align='center'>\n"; $cpt=0; //echo "<td style='padding: 0 10px 0 10px'>\n"; echo "<td align='left'>\n"; while($ligne_classe=mysqli_fetch_object($resultat_classes)){ if(($cpt>0)&&(round($cpt/$nb_class_par_colonne)==$cpt/$nb_class_par_colonne)){ echo "</td>\n"; //echo "<td style='padding: 0 10px 0 10px'>\n"; echo "<td align='left'>\n"; } //echo "<input type='radio' name='id_classe' value='$ligne_classe->id' /> $ligne_classe->classe<br />\n"; echo "<input type='radio' name='id_classe' id='id_classe".$ligne_classe->id."' value='$ligne_classe->id' /><label for='id_classe".$ligne_classe->id."' style='cursor: pointer;'> $ligne_classe->classe</label><br />\n"; $cpt++; } echo "</td>\n"; echo "</tr>\n"; echo "</table>\n"; echo "</blockquote>\n"; echo "<center><input type='submit' name='ok' value='Valider' /></center>\n"; } else{ // ============================ // La classe-modèle est choisie // ============================ // Récupération des variables: $id_classe=$_POST['id_classe']; echo "<h2>Recopie de commentaires-types</h2>\n"; /* echo "<p>Voici les commentaires-type saisis pour cette classe:</p>\n"; echo "<ul>\n"; for($i=0;$i<count($num_periode);$i++){ echo "<li>\n"; $sql="select nom_periode from periodes where num_periode='$num_periode[$i]'"; $resultat_periode=mysql_query($sql); $ligne_nom_periode=mysql_fetch_object($resultat_periode); echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n"; echo "<input type='hidden' name='num_periode[$i]' value='$num_periode[$i]'>\n"; // AFFICHER LES COMMENTAIRES-TYPE POUR CHAQUE PERIODE $sql="select * from commentaires_types where id_classe='$id_classe' and num_periode='$num_periode[$i]' order by commentaire"; $resultat_commentaires=mysql_query($sql); echo "<ul>\n"; while($ligne_commentaires=mysql_fetch_object($resultat_commentaires)){ echo "<li>".stripslashes(nl2br(trim($ligne_commentaires->commentaire)))."</li>\n"; } echo "</ul>\n"; echo "</li>\n"; } echo "</ul>\n"; */ echo "<input type='hidden' name='id_classe' value='$id_classe' />\n"; // Récupération du nom de la classe $sql="select * from classes where id='$id_classe'"; $resultat_classe=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_classe)==0){ echo "<p>L'identifiant de la classe semble erroné.</p>\n</form>\n</body>\n</html>\n"; exit(); } $ligne_classe=mysqli_fetch_object($resultat_classe); $classe_source="$ligne_classe->classe"; echo "<p><b>Classe modèle:</b> $classe_source</p>\n"; if(!isset($_POST['num_periode'])){ // ============================= // Choix des périodes à recopier // ============================= // Rappel des commentaires-type saisis pour cette classe sur toutes les périodes définies: $sql="select * from periodes where id_classe='$id_classe' order by num_periode"; //echo "$sql<br />"; $resultat_num_periode=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_num_periode)==0){ echo "Aucune période n'est encore définie pour cette classe...<br />\n"; echo "</body>\n</html>\n"; exit(); } else{ $compteur_commentaires=0; echo "<p>Voici les commentaires-type saisis pour cette classe:</p>\n"; echo "<ul>\n"; while($ligne_periode=mysqli_fetch_object($resultat_num_periode)){ //for($i=0;$i<count($num_periode);$i++){ echo "<li>\n"; //$sql="select nom_periode from periodes where num_periode='$ligne_periode->num_periode'"; //$resultat_periode=mysql_query($sql); //$ligne_nom_periode=mysql_fetch_object($resultat_periode); //echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n"; echo "<p><b>$ligne_periode->nom_periode</b>:</p>\n"; // AFFICHER LES COMMENTAIRES-TYPE POUR CHAQUE PERIODE $sql="select * from commentaires_types where id_classe='$id_classe' and num_periode='$ligne_periode->num_periode' order by commentaire"; $resultat_commentaires=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_commentaires)>0){ echo "<ul>\n"; while($ligne_commentaires=mysqli_fetch_object($resultat_commentaires)){ echo "<li>".stripslashes(nl2br(trim($ligne_commentaires->commentaire)))."</li>\n"; $compteur_commentaires++; } echo "</ul>\n"; } else{ echo "<p style='color:red;'>Aucun commentaire-type n'est saisi pour cette classe sur cette période.</p>\n"; //echo "</body>\n</html>\n"; //exit(); } echo "</li>\n"; } echo "</ul>\n"; if($compteur_commentaires==0){ echo "</body>\n</html>\n"; exit(); } } // Choix des périodes: echo "<p>Pour quelles périodes souhaitez-vous recopier les commentaires-type?</p>\n"; //echo "<p>\n"; //echo "<input type='hidden' name='id_classe' value='$id_classe'>\n"; //echo "<p><b>$classe_source</b>: "; $sql="select * from periodes where id_classe='$id_classe' order by num_periode"; //echo "$sql<br />"; $resultat_num_periode=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_num_periode)==0){ echo "<p>Aucune période n'est encore définie pour cette classe...</p>\n"; } else{ /* $ligne_num_periode=mysql_fetch_object($resultat_num_periode); $sql="select * from periodes where num_periode='$ligne_num_periode->num_periode'"; $resultat_periode=mysql_query($sql); $ligne_periode=mysql_fetch_object($resultat_periode); //echo "<input type='checkbox' name='num_periode[]' value='$ligne_periode->num_periode'> $ligne_periode->nom_periode\n"; echo "<input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_periode->num_periode."' value='$ligne_periode->num_periode' /><label for='num_periode_".$ligne_periode->num_periode."' style='cursor: pointer;'> $ligne_periode->nom_periode</label>\n"; while($ligne_num_periode=mysql_fetch_object($resultat_num_periode)){ //$cpt++; $sql="select * from periodes where num_periode='$ligne_num_periode->num_periode'"; $resultat_periode=mysql_query($sql); $ligne_periode=mysql_fetch_object($resultat_periode); //echo " &nbsp;&nbsp;&nbsp;- <input type='checkbox' name='num_periode[]' value='$ligne_periode->num_periode'> $ligne_periode->nom_periode\n"; echo " &nbsp;&nbsp;&nbsp;- <input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_periode->num_periode."' value='$ligne_periode->num_periode' /><label for='num_periode_".$ligne_periode->num_periode."' style='cursor: pointer;'> $ligne_periode->nom_periode</label>\n"; } */ $cpt_per=0; while($ligne_num_periode=mysqli_fetch_object($resultat_num_periode)){ if($cpt_per>0) {echo " &nbsp;&nbsp;&nbsp;- ";} echo "<input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_num_periode->num_periode."' value='$ligne_num_periode->num_periode' /><label for='num_periode_".$ligne_num_periode->num_periode."' style='cursor: pointer;'> $ligne_num_periode->nom_periode</label>\n"; $cpt_per++; } echo "<br />\n"; echo "<center><input type='submit' name='ok' value='Valider' /></center>\n"; } //echo "</p>\n"; //echo "<input type='submit' name='ok' value='Valider'>\n"; } else{ // ========================================================= // La classe-modèle et les périodes à recopier sont choisies // ========================================================= // Récupération des variables: $num_periode=$_POST['num_periode']; /* echo "<p>Voici les commentaires-type saisis pour cette classe:</p>\n"; echo "<ul>\n"; for($i=0;$i<count($num_periode);$i++){ echo "<li>\n"; $sql="select nom_periode from periodes where num_periode='$num_periode[$i]'"; $resultat_periode=mysql_query($sql); $ligne_nom_periode=mysql_fetch_object($resultat_periode); echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n"; echo "<input type='hidden' name='num_periode[$i]' value='$num_periode[$i]'>\n"; // AFFICHER LES COMMENTAIRES-TYPE POUR CHAQUE PERIODE $sql="select * from commentaires_types where id_classe='$id_classe' and num_periode='$num_periode[$i]' order by commentaire"; $resultat_commentaires=mysql_query($sql); echo "<ul>\n"; while($ligne_commentaires=mysql_fetch_object($resultat_commentaires)){ echo "<li>".stripslashes(nl2br(trim($ligne_commentaires->commentaire)))."</li>\n"; } echo "</ul>\n"; echo "</li>\n"; } echo "</ul>\n"; */ if(!isset($_POST['id_dest_classe'])){ // ========================================================== // Choix des classes vers lesquelles la recopie doit se faire // ========================================================== echo "<p>Voici les commentaires-type saisis pour cette classe et les périodes choisies:</p>\n"; echo "<ul>\n"; for($i=0;$i<count($num_periode);$i++){ echo "<li>\n"; $sql="select nom_periode from periodes where num_periode='$num_periode[$i]'"; $resultat_periode=mysqli_query($GLOBALS["mysqli"], $sql); $ligne_nom_periode=mysqli_fetch_object($resultat_periode); echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n"; echo "<input type='hidden' name='num_periode[$i]' value='$num_periode[$i]' />\n"; // AFFICHER LES COMMENTAIRES-TYPE POUR CHAQUE PERIODE $sql="select * from commentaires_types where id_classe='$id_classe' and num_periode='$num_periode[$i]' order by commentaire"; $resultat_commentaires=mysqli_query($GLOBALS["mysqli"], $sql); echo "<ul>\n"; while($ligne_commentaires=mysqli_fetch_object($resultat_commentaires)){ echo "<li>".stripslashes(nl2br(trim($ligne_commentaires->commentaire)))."</li>\n"; } echo "</ul>\n"; echo "</li>\n"; } echo "</ul>\n"; echo "<p>Pour quelles classes souhaitez-vous supprimer les commentaires-type existant et les remplacer par ceux de $classe_source?</p>\n"; // AJOUTER UN JavaScript POUR 'Tout cocher' //$sql="select distinct id,classe from classes order by classe"; if($_SESSION['statut']=='professeur'){ $sql="SELECT DISTINCT c.id,c.classe FROM j_eleves_classes jec, classes c, j_eleves_professeurs jep WHERE jec.id_classe=c.id AND jec.login=jep.login AND jep.professeur='".$_SESSION['login']."' ORDER BY c.classe"; } elseif($_SESSION['statut']=='scolarite'){ $sql="SELECT DISTINCT c.id,c.classe FROM j_scol_classes jsc, classes c WHERE jsc.id_classe=c.id AND jsc.login='".$_SESSION['login']."' ORDER BY c.classe"; } else{ // CA NE DEVRAIT PAS ARRIVER... $sql="select distinct id,classe from classes order by classe"; } $resultat_classes=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_classes)==0){ echo "<p>Aucune classe n'est encore définie...</p>\n</form>\n</body>\n</html>\n"; exit(); } $cpt=0; while($ligne_classe=mysqli_fetch_object($resultat_classes)){ if("$ligne_classe->id"!="$id_classe"){ echo "<label for='id_dest_classe$cpt' style='cursor: pointer;'><input type='checkbox' name='id_dest_classe[]' id='id_dest_classe$cpt' value='$ligne_classe->id' /> $ligne_classe->classe</label><br />\n"; $cpt++; } } //echo "</blockquote>\n"; echo "<!--script language='JavaScript'--> <script language='JavaScript' type='text/javascript'> function tout_cocher(){ for(i=0;i<$cpt;i++){ document.getElementById('id_dest_classe'+i).checked=true; } } function tout_decocher(){ for(i=0;i<$cpt;i++){ document.getElementById('id_dest_classe'+i).checked=false; } } </script> "; echo "<input type='button' name='toutcocher' value='Tout cocher' onClick='tout_cocher();' /> - \n"; echo "<input type='button' name='toutdecocher' value='Tout décocher' onClick='tout_decocher();' />\n"; echo "<center><input type='submit' name='ok' value='Valider' /></center>\n"; } else { check_token(false); // ======================= // Recopie proprement dite // ======================= $id_dest_classe=$_POST['id_dest_classe']; //echo count($num_periode)."<br />"; //flush(); // Nettoyage des commentaires déjà saisis pour ces classes et ces périodes: for($i=0;$i<count($id_dest_classe);$i++){ $sql="delete from commentaires_types where id_classe='$id_dest_classe[$i]' and (num_periode='$num_periode[0]'"; //for($i=0;$i<count($num_periode);$i++){ for($j=1;$j<count($num_periode);$j++){ $sql=$sql." or num_periode='$num_periode[$j]'"; } $sql=$sql.")"; //echo "sql=$sql<br />"; $resultat_nettoyage=mysqli_query($GLOBALS["mysqli"], $sql); } /* $sql="select commentaire from commentaires_types where id_classe='$id_classe' and (num_periode='$num_periode[0]'"; for($i=1;$i<count($num_periode);$i++){ $sql=$sql." or num_periode='$num_periode[$i]'"; } $sql=$sql.") order by commentaire"; echo "sql=$sql<br />"; $resultat_commentaires_source=mysql_query($sql); if(mysql_num_rows($resultat_commentaires_source)==0){ echo "<p>C'est malin... il n'existe pas de commentaires-type pour la/les classe(s) et la/les période(s) choisie(s).<br />\nDe plus, les commentaires existants ont été supprimés...</p>\n"; } else{ while($ligne_commentaires_source=mysql_fetch_object($resultat_commentaires_source)){ } } */ for($i=0;$i<count($num_periode);$i++){ // Nom de la période courante: $sql="select nom_periode from periodes where num_periode='$num_periode[$i]'"; $resultat_periode=mysqli_query($GLOBALS["mysqli"], $sql); $ligne_nom_periode=mysqli_fetch_object($resultat_periode); echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n"; echo "<blockquote>\n"; // Récupération des commentaires à insérer: $sql="select commentaire from commentaires_types where id_classe='$id_classe' and num_periode='$num_periode[$i]' order by commentaire"; //echo "sql=$sql<br />"; $resultat_commentaires_source=mysqli_query($GLOBALS["mysqli"], $sql); if(mysqli_num_rows($resultat_commentaires_source)==0){ echo "<p>C'est malin... il n'existe pas de commentaires-type pour la classe modèle et la période choisie.<br />\nDe plus, les commentaires existants pour les classes destination ont été supprimés...</p>\n"; } else{ while($ligne_commentaires_source=mysqli_fetch_object($resultat_commentaires_source)){ echo "<table>\n"; for($j=0;$j<count($id_dest_classe);$j++){ // Récupération du nom de la classe: $sql="select classe from classes where id='$id_dest_classe[$j]'"; $resultat_classe_dest=mysqli_query($GLOBALS["mysqli"], $sql); $ligne_classe_dest=mysqli_fetch_object($resultat_classe_dest); //echo "<b>Insertion pour $ligne_classe_dest->classe:</b><br /> ".stripslashes(nl2br(trim($ligne_commentaires_source->commentaire)))."<br />\n"; echo "<tr valign=\"top\"><td><b>Insertion pour $ligne_classe_dest->classe:</b></td><td> ".stripslashes(nl2br(trim($ligne_commentaires_source->commentaire)))."</td></tr>\n"; //$sql="insert into commentaires_types values('','$ligne_commentaires_source->commentaire','$num_periode[$i]','$id_dest_classe[$j]')"; $commentaire_courant=traitement_magic_quotes(corriger_caracteres($ligne_commentaires_source->commentaire)); $sql="insert into commentaires_types values('','$commentaire_courant','$num_periode[$i]','$id_dest_classe[$j]')"; //echo "sql=$sql<br />"; $resultat_insertion_commentaire=mysqli_query($GLOBALS["mysqli"], $sql); } echo "</table>\n"; } echo "<p>Insertions terminées pour la période.</p>\n"; } echo "</blockquote>\n"; } /* // Validation des saisies/modifs... for($i=1;$i<=count($commentaire);$i++){ echo "\$suppr[$i]=$suppr[$i]<br />"; if(($suppr[$i]=="")&&($commentaire[$i]!="")){ for($j=0;$j<count($num_periode);$j++){ $sql="insert into commentaires_types values('','$commentaire[$i]','$num_periode[$j]','$id_classe')"; echo "sql=$sql<br />"; $resultat_insertion_commentaire=mysql_query($sql); } } } */ } } } } ?> </form> <p><br /></p> <?php require("../lib/footer.inc.php"); ?>
Java
# Makefile.in generated by automake 1.13.3 from Makefile.am. # Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. ##### ##### am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgincludedir = $(includedir)/libtool pkglibdir = $(libdir)/libtool pkglibexecdir = $(libexecdir)/libtool am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = i686-pc-linux-gnu host_triplet = i686-pc-linux-gnu DIST_COMMON = $(srcdir)/libltdl/Makefile.inc INSTALL NEWS README \ AUTHORS ChangeLog $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/configure $(am__configure_deps) \ $(srcdir)/config-h.in $(top_srcdir)/libltdl/lt__dirent.c \ $(top_srcdir)/libltdl/argz.c $(top_srcdir)/libltdl/lt__strl.c \ $(top_srcdir)/libltdl/config/depcomp $(doc_libtool_TEXINFOS) \ $(top_srcdir)/libltdl/config/mdate-sh \ $(srcdir)/doc/version.texi $(srcdir)/doc/stamp-vti \ $(top_srcdir)/libltdl/config/texinfo.tex $(dist_man1_MANS) \ $(am__include_HEADERS_DIST) $(am__ltdlinclude_HEADERS_DIST) \ $(top_srcdir)/libltdl/config/test-driver COPYING THANKS TODO \ libltdl/config/compile libltdl/config/config.guess \ libltdl/config/config.sub libltdl/config/depcomp \ libltdl/config/install-sh libltdl/config/mdate-sh \ libltdl/config/missing libltdl/config/texinfo.tex \ libltdl/config/ltmain.sh $(top_srcdir)/libltdl/config/compile \ $(top_srcdir)/libltdl/config/config.guess \ $(top_srcdir)/libltdl/config/config.sub \ $(top_srcdir)/libltdl/config/install-sh \ $(top_srcdir)/libltdl/config/ltmain.sh \ $(top_srcdir)/libltdl/config/missing am__append_1 = libltdl/ltdl.h am__append_2 = libltdl/libltdl.la #am__append_3 = libltdl/libltdlc.la am__append_4 = $(CXX_TESTS) # f77demo-static-exec.test might be interactive on MSYS. am__append_5 = $(F77_TESTS) am__append_6 = $(FC_TESTS) subdir = . SUBDIRS = ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/libltdl/m4/argz.m4 \ $(top_srcdir)/libltdl/m4/autobuild.m4 \ $(top_srcdir)/libltdl/m4/libtool.m4 \ $(top_srcdir)/libltdl/m4/ltdl.m4 \ $(top_srcdir)/libltdl/m4/ltoptions.m4 \ $(top_srcdir)/libltdl/m4/ltsugar.m4 \ $(top_srcdir)/libltdl/m4/ltversion.m4 \ $(top_srcdir)/libltdl/m4/lt~obsolete.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ configure.lineno config.status.lineno mkinstalldirs = $(install_sh) -d CONFIG_HEADER = config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \ "$(DESTDIR)$(infodir)" "$(DESTDIR)$(man1dir)" \ "$(DESTDIR)$(includedir)" "$(DESTDIR)$(ltdlincludedir)" LTLIBRARIES = $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES) libltdl_dld_link_la_DEPENDENCIES = am__dirstamp = $(am__leading_dot)dirstamp am_libltdl_dld_link_la_OBJECTS = libltdl/loaders/dld_link.lo libltdl_dld_link_la_OBJECTS = $(am_libltdl_dld_link_la_OBJECTS) AM_V_lt = $(am__v_lt_$(V)) am__v_lt_ = $(am__v_lt_$(AM_DEFAULT_VERBOSITY)) am__v_lt_0 = --silent am__v_lt_1 = libltdl_dld_link_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(libltdl_dld_link_la_LDFLAGS) \ $(LDFLAGS) -o $@ am__DEPENDENCIES_1 = libltdl_dlopen_la_DEPENDENCIES = $(am__DEPENDENCIES_1) am_libltdl_dlopen_la_OBJECTS = libltdl/loaders/dlopen.lo libltdl_dlopen_la_OBJECTS = $(am_libltdl_dlopen_la_OBJECTS) libltdl_dlopen_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(libltdl_dlopen_la_LDFLAGS) $(LDFLAGS) \ -o $@ libltdl_dyld_la_LIBADD = am_libltdl_dyld_la_OBJECTS = libltdl/loaders/dyld.lo libltdl_dyld_la_OBJECTS = $(am_libltdl_dyld_la_OBJECTS) libltdl_dyld_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(libltdl_dyld_la_LDFLAGS) $(LDFLAGS) \ -o $@ LIBOBJDIR = libltdl/ am_libltdl_libltdl_la_OBJECTS = \ libltdl/loaders/libltdl_libltdl_la-preopen.lo \ libltdl/libltdl_libltdl_la-lt__alloc.lo \ libltdl/libltdl_libltdl_la-lt_dlloader.lo \ libltdl/libltdl_libltdl_la-lt_error.lo \ libltdl/libltdl_libltdl_la-ltdl.lo \ libltdl/libltdl_libltdl_la-slist.lo libltdl_libltdl_la_OBJECTS = $(am_libltdl_libltdl_la_OBJECTS) libltdl_libltdl_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(libltdl_libltdl_la_LDFLAGS) \ $(LDFLAGS) -o $@ am_libltdl_libltdl_la_rpath = -rpath $(libdir) am__objects_1 = libltdl/loaders/libltdl_libltdlc_la-preopen.lo \ libltdl/libltdl_libltdlc_la-lt__alloc.lo \ libltdl/libltdl_libltdlc_la-lt_dlloader.lo \ libltdl/libltdl_libltdlc_la-lt_error.lo \ libltdl/libltdl_libltdlc_la-ltdl.lo \ libltdl/libltdl_libltdlc_la-slist.lo am_libltdl_libltdlc_la_OBJECTS = $(am__objects_1) libltdl_libltdlc_la_OBJECTS = $(am_libltdl_libltdlc_la_OBJECTS) libltdl_libltdlc_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(libltdl_libltdlc_la_LDFLAGS) \ $(LDFLAGS) -o $@ #am_libltdl_libltdlc_la_rpath = libltdl_load_add_on_la_LIBADD = am_libltdl_load_add_on_la_OBJECTS = libltdl/loaders/load_add_on.lo libltdl_load_add_on_la_OBJECTS = $(am_libltdl_load_add_on_la_OBJECTS) libltdl_load_add_on_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(libltdl_load_add_on_la_LDFLAGS) \ $(LDFLAGS) -o $@ libltdl_loadlibrary_la_LIBADD = am_libltdl_loadlibrary_la_OBJECTS = libltdl/loaders/loadlibrary.lo libltdl_loadlibrary_la_OBJECTS = $(am_libltdl_loadlibrary_la_OBJECTS) libltdl_loadlibrary_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(libltdl_loadlibrary_la_LDFLAGS) \ $(LDFLAGS) -o $@ libltdl_shl_load_la_DEPENDENCIES = $(am__DEPENDENCIES_1) am_libltdl_shl_load_la_OBJECTS = libltdl/loaders/shl_load.lo libltdl_shl_load_la_OBJECTS = $(am_libltdl_shl_load_la_OBJECTS) libltdl_shl_load_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(libltdl_shl_load_la_LDFLAGS) \ $(LDFLAGS) -o $@ SCRIPTS = $(bin_SCRIPTS) AM_V_P = $(am__v_P_$(V)) am__v_P_ = $(am__v_P_$(AM_DEFAULT_VERBOSITY)) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_$(V)) am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_$(V)) am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I. depcomp = $(SHELL) $(top_srcdir)/libltdl/config/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_$(V)) am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_$(V)) am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libltdl_dld_link_la_SOURCES) $(libltdl_dlopen_la_SOURCES) \ $(libltdl_dyld_la_SOURCES) $(libltdl_libltdl_la_SOURCES) \ $(libltdl_libltdlc_la_SOURCES) \ $(libltdl_load_add_on_la_SOURCES) \ $(libltdl_loadlibrary_la_SOURCES) \ $(libltdl_shl_load_la_SOURCES) DIST_SOURCES = $(libltdl_dld_link_la_SOURCES) \ $(libltdl_dlopen_la_SOURCES) $(libltdl_dyld_la_SOURCES) \ $(libltdl_libltdl_la_SOURCES) $(libltdl_libltdlc_la_SOURCES) \ $(libltdl_load_add_on_la_SOURCES) \ $(libltdl_loadlibrary_la_SOURCES) \ $(libltdl_shl_load_la_SOURCES) AM_V_DVIPS = $(am__v_DVIPS_$(V)) am__v_DVIPS_ = $(am__v_DVIPS_$(AM_DEFAULT_VERBOSITY)) am__v_DVIPS_0 = @echo " DVIPS " $@; am__v_DVIPS_1 = AM_V_MAKEINFO = $(am__v_MAKEINFO_$(V)) am__v_MAKEINFO_ = $(am__v_MAKEINFO_$(AM_DEFAULT_VERBOSITY)) am__v_MAKEINFO_0 = @echo " MAKEINFO" $@; am__v_MAKEINFO_1 = AM_V_INFOHTML = $(am__v_INFOHTML_$(V)) am__v_INFOHTML_ = $(am__v_INFOHTML_$(AM_DEFAULT_VERBOSITY)) am__v_INFOHTML_0 = @echo " INFOHTML" $@; am__v_INFOHTML_1 = AM_V_TEXI2DVI = $(am__v_TEXI2DVI_$(V)) am__v_TEXI2DVI_ = $(am__v_TEXI2DVI_$(AM_DEFAULT_VERBOSITY)) am__v_TEXI2DVI_0 = @echo " TEXI2DVI" $@; am__v_TEXI2DVI_1 = AM_V_TEXI2PDF = $(am__v_TEXI2PDF_$(V)) am__v_TEXI2PDF_ = $(am__v_TEXI2PDF_$(AM_DEFAULT_VERBOSITY)) am__v_TEXI2PDF_0 = @echo " TEXI2PDF" $@; am__v_TEXI2PDF_1 = AM_V_texinfo = $(am__v_texinfo_$(V)) am__v_texinfo_ = $(am__v_texinfo_$(AM_DEFAULT_VERBOSITY)) am__v_texinfo_0 = -q am__v_texinfo_1 = AM_V_texidevnull = $(am__v_texidevnull_$(V)) am__v_texidevnull_ = $(am__v_texidevnull_$(AM_DEFAULT_VERBOSITY)) am__v_texidevnull_0 = > /dev/null am__v_texidevnull_1 = INFO_DEPS = $(srcdir)/doc/libtool.info TEXINFO_TEX = $(top_srcdir)/libltdl/config/texinfo.tex am__TEXINFO_TEX_DIR = $(top_srcdir)/libltdl/config DVIS = doc/libtool.dvi PDFS = doc/libtool.pdf PSS = doc/libtool.ps HTMLS = doc/libtool.html TEXINFOS = doc/libtool.texi TEXI2DVI = texi2dvi TEXI2PDF = $(TEXI2DVI) --pdf --batch MAKEINFOHTML = $(MAKEINFO) --html AM_MAKEINFOHTMLFLAGS = $(AM_MAKEINFOFLAGS) DVIPS = dvips RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac man1dir = $(mandir)/man1 NROFF = nroff MANS = $(dist_man1_MANS) am__include_HEADERS_DIST = libltdl/ltdl.h am__ltdlinclude_HEADERS_DIST = libltdl/libltdl/lt_system.h \ libltdl/libltdl/lt_error.h libltdl/libltdl/lt_dlloader.h HEADERS = $(include_HEADERS) $(ltdlinclude_HEADERS) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ cscope check recheck distdir dist dist-all distcheck am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \ $(LISP)config-h.in # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags CSCOPE = cscope am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = .test am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/libltdl/config/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi am__post_remove_distdir = $(am__remove_distdir) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" DIST_ARCHIVES = $(distdir).tar.gz $(distdir).tar.xz GZIP_ENV = --best DIST_TARGETS = dist-xz dist-gzip distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print pkgdatadir = ${datadir}/libtool ACLOCAL = ${SHELL} /usr/src/libtool/libtool/libltdl/config/missing aclocal-1.13 AMTAR = $${TAR-tar} AM_DEFAULT_VERBOSITY = 1 AR = ar ARGZ_H = AS = as AUTOCONF = ${SHELL} /usr/src/libtool/libtool/libltdl/config/missing autoconf AUTOHEADER = ${SHELL} /usr/src/libtool/libtool/libltdl/config/missing autoheader AUTOM4TE = autom4te AUTOMAKE = ${SHELL} /usr/src/libtool/libtool/libltdl/config/missing automake-1.13 AUTOTEST = $(AUTOM4TE) --language=autotest AWK = gawk CC = gcc CCDEPMODE = depmode=gcc3 CFLAGS = -g -O2 CONFIG_STATUS_DEPENDENCIES = $(top_srcdir)/ChangeLog CONF_SUBDIRS = tests/cdemo tests/demo tests/depdemo tests/f77demo tests/fcdemo tests/mdemo tests/mdemo2 tests/pdemo tests/tagdemo CPP = gcc -E CPPFLAGS = CXX = g++ CXXCPP = g++ -E CXXDEPMODE = depmode=gcc3 CXXFLAGS = -g -O2 CYGPATH_W = echo DEFS = -DHAVE_CONFIG_H DEPDIR = .deps DIST_MAKEFILE_LIST = tests/cdemo/Makefile tests/demo/Makefile tests/depdemo/Makefile tests/f77demo/Makefile tests/fcdemo/Makefile tests/mdemo/Makefile tests/mdemo2/Makefile tests/pdemo/Makefile tests/tagdemo/Makefile DLLTOOL = false DSYMUTIL = DUMPBIN = ECHO_C = ECHO_N = -n ECHO_T = EGREP = /usr/bin/grep -E EXEEXT = F77 = gfortran FC = gfortran FCFLAGS = -g -O2 FFLAGS = -g -O2 FGREP = /usr/bin/grep -F GCJ = gcj GCJFLAGS = -g -O2 GOC = gccgo GREP = /usr/bin/grep HELP2MAN = ${SHELL} /usr/src/libtool/libtool/libltdl/config/missing help2man INSTALL = /usr/bin/ginstall -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s LASTRELEASE = 2.4.1 LD = /usr/i686-linux-gnu/bin/ld LDFLAGS = LIBADD_DL = -ldl LIBADD_DLD_LINK = LIBADD_DLOPEN = -ldl LIBADD_SHL_LOAD = LIBOBJS = ${LIBOBJDIR}lt__strl$U.o LIBS = -ldl LIBTOOL = $(SHELL) $(top_builddir)/libtool LIPO = LN_S = ln -s LTDLOPEN = libltdl LTLIBOBJS = ${LIBOBJDIR}lt__strl$U.lo LT_CONFIG_H = config.h LT_DLLOADERS = libltdl/dlopen.la LT_DLPREOPEN = -dlpreopen libltdl/dlopen.la M4SH = $(AUTOM4TE) --language=m4sh MAKEINFO = ${SHELL} /usr/src/libtool/libtool/libltdl/config/missing makeinfo MANIFEST_TOOL = : MKDIR_P = /usr/bin/mkdir -p NM = /usr/bin/nm -B NMEDIT = OBJDUMP = objdump OBJEXT = o ORDER = | OTOOL = OTOOL64 = PACKAGE = libtool PACKAGE_BUGREPORT = bug-libtool@gnu.org PACKAGE_NAME = GNU Libtool PACKAGE_STRING = GNU Libtool 2.4.2 PACKAGE_TARNAME = libtool PACKAGE_URL = http://www.gnu.org/software/libtool/ PACKAGE_VERSION = 2.4.2 PATH_SEPARATOR = : RANLIB = ranlib RC = SED = /usr/bin/sed SET_MAKE = SHELL = /bin/sh STRIP = strip TIMESTAMP = VERSION = 2.4.2 abs_builddir = /usr/src/libtool/libtool abs_srcdir = /usr/src/libtool/libtool abs_top_builddir = /usr/src/libtool/libtool abs_top_srcdir = /usr/src/libtool/libtool ac_ct_AR = ar ac_ct_CC = gcc ac_ct_CXX = g++ ac_ct_DUMPBIN = ac_ct_F77 = gfortran ac_ct_FC = gfortran aclocaldir = ${datadir}/aclocal am__include = include am__leading_dot = . am__quote = am__tar = $${TAR-tar} chof - "$$tardir" am__untar = $${TAR-tar} xf - bindir = ${exec_prefix}/bin build = i686-pc-linux-gnu build_alias = build_cpu = i686 build_os = linux-gnu build_vendor = pc builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host = i686-pc-linux-gnu host_alias = host_cpu = i686 host_os = linux-gnu host_vendor = pc htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = ${SHELL} /usr/src/libtool/libtool/libltdl/config/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = $(MKDIR_P) oldincludedir = /usr/include package_revision = 1.3337 pdfdir = ${docdir} prefix = /usr/local program_transform_name = s,x,x, psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sys_symbol_underscore = no sysconfdir = ${prefix}/etc target_alias = to_host_file_cmd = func_convert_file_noop to_tool_file_cmd = func_convert_file_noop top_build_prefix = top_builddir = . top_srcdir = . ACLOCAL_AMFLAGS = -I libltdl/m4 # -I$(srcdir) is needed for user that built libltdl with a sub-Automake # (not as a sub-package!) using 'nostdinc': AM_CPPFLAGS = -DLT_CONFIG_H='<$(LT_CONFIG_H)>' -DLTDL -I. -I$(srcdir) \ -Ilibltdl -I$(srcdir)/libltdl -I$(srcdir)/libltdl/libltdl AM_LDFLAGS = -no-undefined DIST_SUBDIRS = . $(CONF_SUBDIRS) # Use `$(srcdir)' for the benefit of non-GNU makes: this is # how libtoolize.in appears in our dependencies. EXTRA_DIST = bootstrap $(srcdir)/libtoolize.in $(auxdir)/ltmain.m4sh \ $(auxdir)/mkstamp $(sh_files) ChangeLog.1996 ChangeLog.1997 \ ChangeLog.1998 ChangeLog.1999 ChangeLog.2000 ChangeLog.2001 \ ChangeLog.2002 ChangeLog.2003 ChangeLog.2004 ChangeLog.2005 \ ChangeLog.2006 ChangeLog.2007 ChangeLog.2008 ChangeLog.2009 \ ChangeLog.2010 $(m4dir)/ltversion.in \ $(srcdir)/$(m4dir)/ltversion.m4 $(srcdir)/$(auxdir)/ltmain.sh \ libtoolize.m4sh libltdl/lt__dirent.c libltdl/lt__strl.c \ libltdl/COPYING.LIB libltdl/configure.ac libltdl/Makefile.am \ libltdl/aclocal.m4 libltdl/Makefile.in libltdl/configure \ libltdl/config-h.in libltdl/README libltdl/argz_.h \ libltdl/argz.c $(srcdir)/libltdl/stamp-mk \ $(m4dir)/lt~obsolete.m4 $(srcdir)/doc/notes.txt \ $(edit_readme_alpha) $(srcdir)/$(TESTSUITE) $(TESTSUITE_AT) \ $(srcdir)/tests/package.m4 $(srcdir)/tests/defs.in \ tests/defs.m4sh $(COMMON_TESTS) $(CXX_TESTS) $(F77_TESTS) \ $(FC_TESTS) $(INTERACTIVE_TESTS) BUILT_SOURCES = libtool libtoolize libltdl/$(ARGZ_H) CLEANFILES = libtool libtoolize libtoolize.tmp $(auxdir)/ltmain.tmp \ $(m4dir)/ltversion.tmp libltdl/libltdl.la libltdl/libltdlc.la \ libltdl/libdlloader.la $(LIBOBJS) $(LTLIBOBJS) MOSTLYCLEANFILES = libltdl/argz.h libltdl/argz.h-t DISTCLEANFILES = libtool.dvi tests/atconfig tests/defs MAINTAINERCLEANFILES = $(dist_man1_MANS) include_HEADERS = $(am__append_1) noinst_LTLIBRARIES = $(LT_DLLOADERS) $(am__append_3) lib_LTLIBRARIES = $(am__append_2) EXTRA_LTLIBRARIES = libltdl/dlopen.la libltdl/dld_link.la \ libltdl/dyld.la libltdl/load_add_on.la libltdl/loadlibrary.la \ libltdl/shl_load.la auxdir = libltdl/config m4dir = libltdl/m4 # Using `cd' in backquotes may print the directory name, use this instead: lt__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd MKSTAMP = $(SHELL) $(srcdir)/$(auxdir)/mkstamp timestamp = set dummy `$(MKSTAMP) $(srcdir)`; shift; \ case $(VERSION) in \ *[acegikmoqsuwy]) TIMESTAMP=" $$1 $$2" ;; \ *) TIMESTAMP="" ;; \ esac rebuild = rebuild=:; $(timestamp); correctver=$$1 # ---------- # # Bootstrap. # # ---------- # sh_files = $(auxdir)/general.m4sh $(auxdir)/getopt.m4sh bootstrap_edit = sed \ -e 's,@MACRO_VERSION\@,$(VERSION),g' \ -e "s,@MACRO_REVISION\@,$$correctver,g" \ -e "s,@MACRO_SERIAL\@,$$serial,g" \ -e 's,@PACKAGE\@,$(PACKAGE),g' \ -e 's,@PACKAGE_BUGREPORT\@,$(PACKAGE_BUGREPORT),g' \ -e 's,@PACKAGE_URL\@,$(PACKAGE_URL),g' \ -e 's,@PACKAGE_NAME\@,$(PACKAGE_NAME),g' \ -e "s,@package_revision\@,$$correctver,g" \ -e 's,@PACKAGE_STRING\@,$(PACKAGE_NAME) $(VERSION),g' \ -e 's,@PACKAGE_TARNAME\@,$(PACKAGE),g' \ -e 's,@PACKAGE_VERSION\@,$(VERSION),g' \ -e "s,@TIMESTAMP\@,$$TIMESTAMP,g" \ -e 's,@VERSION\@,$(VERSION),g' LTDL_BOOTSTRAP_DEPS = $(srcdir)/libltdl/aclocal.m4 \ $(srcdir)/libltdl/stamp-mk \ $(srcdir)/libltdl/configure \ $(srcdir)/libltdl/config-h.in configure_edit = sed \ -e 's,@aclocal_DATA\@,$(aclocalfiles),g' \ -e 's,@aclocaldir\@,$(aclocaldir),g' \ -e 's,@datadir\@,$(datadir),g' \ -e 's,@EGREP\@,$(EGREP),g' \ -e 's,@FGREP\@,$(FGREP),g' \ -e 's,@GREP\@,$(GREP),g' \ -e 's,@host_triplet\@,$(host_triplet),g' \ -e 's,@LN_S\@,$(LN_S),g' \ -e "s,@pkgconfig_files\@,$(auxfiles),g" \ -e 's,@pkgdatadir\@,$(pkgdatadir),g' \ -e "s,@pkgltdl_files\@,$(ltdldatafiles),g" \ -e 's,@prefix\@,$(prefix),g' \ -e 's,@SED\@,$(SED),g' # The libtool distributor and the standalone libtool script. bin_SCRIPTS = libtoolize libtool LTDL_VERSION_INFO = -version-info 10:0:3 ltdlincludedir = $(includedir)/libltdl ltdlinclude_HEADERS = libltdl/libltdl/lt_system.h \ libltdl/libltdl/lt_error.h \ libltdl/libltdl/lt_dlloader.h libltdl_libltdl_la_SOURCES = libltdl/libltdl/lt__alloc.h \ libltdl/libltdl/lt__dirent.h \ libltdl/libltdl/lt__glibc.h \ libltdl/libltdl/lt__private.h \ libltdl/libltdl/lt__strl.h \ libltdl/libltdl/lt_dlloader.h \ libltdl/libltdl/lt_error.h \ libltdl/libltdl/lt_system.h \ libltdl/libltdl/slist.h \ libltdl/loaders/preopen.c \ libltdl/lt__alloc.c \ libltdl/lt_dlloader.c \ libltdl/lt_error.c \ libltdl/ltdl.c \ libltdl/ltdl.h \ libltdl/slist.c libltdl_libltdl_la_CPPFLAGS = -DLTDLOPEN=$(LTDLOPEN) $(AM_CPPFLAGS) libltdl_libltdl_la_LDFLAGS = $(AM_LDFLAGS) $(LTDL_VERSION_INFO) $(LT_DLPREOPEN) libltdl_libltdl_la_LIBADD = $(LTLIBOBJS) libltdl_libltdl_la_DEPENDENCIES = $(LT_DLLOADERS) $(LTLIBOBJS) libltdl_libltdlc_la_SOURCES = $(libltdl_libltdl_la_SOURCES) libltdl_libltdlc_la_CPPFLAGS = -DLTDLOPEN=$(LTDLOPEN)c $(AM_CPPFLAGS) libltdl_libltdlc_la_LDFLAGS = $(AM_LDFLAGS) $(LT_DLPREOPEN) libltdl_libltdlc_la_LIBADD = $(libltdl_libltdl_la_LIBADD) libltdl_libltdlc_la_DEPENDENCIES = $(libltdl_libltdl_la_DEPENDENCIES) libltdl_dlopen_la_SOURCES = libltdl/loaders/dlopen.c libltdl_dlopen_la_LDFLAGS = -module -avoid-version libltdl_dlopen_la_LIBADD = $(LIBADD_DLOPEN) libltdl_dld_link_la_SOURCES = libltdl/loaders/dld_link.c libltdl_dld_link_la_LDFLAGS = -module -avoid-version libltdl_dld_link_la_LIBADD = -ldld libltdl_dyld_la_SOURCES = libltdl/loaders/dyld.c libltdl_dyld_la_LDFLAGS = -module -avoid-version libltdl_load_add_on_la_SOURCES = libltdl/loaders/load_add_on.c libltdl_load_add_on_la_LDFLAGS = -module -avoid-version libltdl_loadlibrary_la_SOURCES = libltdl/loaders/loadlibrary.c libltdl_loadlibrary_la_LDFLAGS = -module -avoid-version libltdl_shl_load_la_SOURCES = libltdl/loaders/shl_load.c libltdl_shl_load_la_LDFLAGS = -module -avoid-version libltdl_shl_load_la_LIBADD = $(LIBADD_SHL_LOAD) sub_aclocal_m4_deps = \ $(srcdir)/libltdl/configure.ac \ $(m4dir)/libtool.m4 \ $(m4dir)/ltoptions.m4 \ $(m4dir)/ltdl.m4 \ $(srcdir)/$(m4dir)/ltversion.m4 \ $(m4dir)/ltsugar.m4 \ $(m4dir)/argz.m4 \ $(m4dir)/lt~obsolete.m4 sub_configure_deps = $(sub_aclocal_m4_deps) $(srcdir)/libltdl/aclocal.m4 info_TEXINFOS = doc/libtool.texi doc_libtool_TEXINFOS = doc/PLATFORMS doc/fdl.texi doc/notes.texi dist_man1_MANS = $(srcdir)/doc/libtool.1 $(srcdir)/doc/libtoolize.1 update_mans = \ PATH=".$(PATH_SEPARATOR)$$PATH"; export PATH; \ $(HELP2MAN) --output=$@ # These are required by libtoolize and must be executable when installed. # The timestamps on these files must be preserved carefully so we install, # uninstall and set executable with custom rules here. auxexefiles = config/compile config/config.guess config/config.sub \ config/depcomp config/install-sh config/missing auxfiles = $(auxexefiles) config/ltmain.sh # Everything that gets picked up by aclocal is automatically distributed, # this is the list of macro files we install on the user's system. aclocalfiles = m4/argz.m4 m4/libtool.m4 m4/ltdl.m4 m4/ltoptions.m4 \ m4/ltsugar.m4 m4/ltversion.m4 m4/lt~obsolete.m4 ltdldatafiles = libltdl/COPYING.LIB \ libltdl/README \ libltdl/Makefile.inc \ libltdl/Makefile.am \ libltdl/configure.ac \ libltdl/aclocal.m4 \ libltdl/Makefile.in \ libltdl/config-h.in \ libltdl/configure \ libltdl/argz_.h \ libltdl/argz.c \ libltdl/loaders/dld_link.c \ libltdl/loaders/dlopen.c \ libltdl/loaders/dyld.c \ libltdl/loaders/load_add_on.c \ libltdl/loaders/loadlibrary.c \ libltdl/loaders/shl_load.c \ libltdl/lt__dirent.c \ libltdl/lt__strl.c \ $(libltdl_libltdl_la_SOURCES) edit_readme_alpha = $(auxdir)/edit-readme-alpha # The testsuite files are evaluated in the order given here. TESTSUITE = tests/testsuite TESTSUITE_AT = tests/testsuite.at \ tests/getopt-m4sh.at \ tests/libtoolize.at \ tests/help.at \ tests/duplicate_members.at \ tests/duplicate_conv.at \ tests/duplicate_deps.at \ tests/flags.at \ tests/inherited_flags.at \ tests/convenience.at \ tests/link-order.at \ tests/link-order2.at \ tests/fail.at \ tests/shlibpath.at \ tests/runpath-in-lalib.at \ tests/static.at \ tests/export.at \ tests/search-path.at \ tests/indirect_deps.at \ tests/archive-in-archive.at \ tests/exeext.at \ tests/execute-mode.at \ tests/bindir.at \ tests/cwrapper.at \ tests/deplib-in-subdir.at \ tests/infer-tag.at \ tests/localization.at \ tests/nocase.at \ tests/install.at \ tests/versioning.at \ tests/destdir.at \ tests/old-m4-iface.at \ tests/am-subdir.at \ tests/lt_dlexit.at \ tests/lt_dladvise.at \ tests/lt_dlopen.at \ tests/lt_dlopen_a.at \ tests/lt_dlopenext.at \ tests/ltdl-libdir.at \ tests/ltdl-api.at \ tests/dlloader-api.at \ tests/loadlibrary.at \ tests/lalib-syntax.at \ tests/resident.at \ tests/slist.at \ tests/need_lib_prefix.at \ tests/standalone.at \ tests/subproject.at \ tests/nonrecursive.at \ tests/recursive.at \ tests/template.at \ tests/ctor.at \ tests/exceptions.at \ tests/early-libtool.at \ tests/with-pic.at \ tests/no-executables.at \ tests/deplibs-ident.at \ tests/configure-iface.at \ tests/stresstest.at \ tests/cmdline_wrap.at \ tests/pic_flag.at \ tests/darwin.at \ tests/dumpbin-symbols.at \ tests/deplibs-mingw.at \ tests/sysroot.at # Be sure to reexport important environment variables: TESTS_ENVIRONMENT = MAKE="$(MAKE)" CC="$(CC)" CFLAGS="$(CFLAGS)" \ CPP="$(CPP)" CPPFLAGS="$(CPPFLAGS)" LD="$(LD)" LDFLAGS="$(LDFLAGS)" \ LIBS="$(LIBS)" LN_S="$(LN_S)" NM="$(NM)" RANLIB="$(RANLIB)" \ AR="$(AR)" \ M4SH="$(M4SH)" SED="$(SED)" STRIP="$(STRIP)" lt_INSTALL="$(INSTALL)" \ MANIFEST_TOOL="$(MANIFEST_TOOL)" \ OBJEXT="$(OBJEXT)" EXEEXT="$(EXEEXT)" \ SHELL="$(SHELL)" CONFIG_SHELL="$(SHELL)" \ CXX="$(CXX)" CXXFLAGS="$(CXXFLAGS)" CXXCPP="$(CXXCPP)" \ F77="$(F77)" FFLAGS="$(FFLAGS)" \ FC="$(FC)" FCFLAGS="$(FCFLAGS)" \ GCJ="$(GCJ)" GCJFLAGS="$(GCJFLAGS)" \ lt_cv_to_host_file_cmd="$(to_host_file_cmd)" \ lt_cv_to_tool_file_cmd="$(to_tool_file_cmd)" BUILDCHECK_ENVIRONMENT = _lt_pkgdatadir="$(abs_top_srcdir)" \ LIBTOOLIZE="$(abs_top_builddir)/libtoolize" \ LIBTOOL="$(abs_top_builddir)/libtool" \ tst_aclocaldir="$(abs_top_srcdir)/libltdl/m4" INSTALLCHECK_ENVIRONMENT = \ LIBTOOLIZE="$(bindir)/`echo libtoolize | sed '$(program_transform_name)'`" \ LIBTOOL="$(bindir)/`echo libtool | sed '$(program_transform_name)'`" \ LTDLINCL="-I$(includedir)" \ LIBLTDL="$(libdir)/libltdl.la" \ tst_aclocaldir="$(aclocaldir)" CD_TESTDIR = abs_srcdir=`$(lt__cd) $(srcdir) && pwd`; cd tests testsuite_deps = tests/atconfig $(srcdir)/$(TESTSUITE) testsuite_deps_uninstalled = $(testsuite_deps) libltdl/libltdlc.la \ $(bin_SCRIPTS) $(LTDL_BOOTSTRAP_DEPS) # !WARNING! Don't add any new tests here, we are migrating to an # Autotest driven framework, please add new test cases # using the new framework above. When the migration is # complete this section should be removed. CXX_TESTS = \ tests/tagdemo-static.test \ tests/tagdemo-static-make.test \ tests/tagdemo-static-exec.test \ tests/tagdemo-conf.test \ tests/tagdemo-make.test \ tests/tagdemo-exec.test \ tests/tagdemo-shared.test \ tests/tagdemo-shared-make.test \ tests/tagdemo-shared-exec.test \ tests/tagdemo-undef.test \ tests/tagdemo-undef-make.test \ tests/tagdemo-undef-exec.test F77_TESTS = \ tests/f77demo-static.test \ tests/f77demo-static-make.test \ tests/f77demo-static-exec.test \ tests/f77demo-conf.test \ tests/f77demo-make.test \ tests/f77demo-exec.test \ tests/f77demo-shared.test \ tests/f77demo-shared-make.test \ tests/f77demo-shared-exec.test FC_TESTS = \ tests/fcdemo-static.test \ tests/fcdemo-static-make.test \ tests/fcdemo-static-exec.test \ tests/fcdemo-conf.test \ tests/fcdemo-make.test \ tests/fcdemo-exec.test \ tests/fcdemo-shared.test \ tests/fcdemo-shared-make.test \ tests/fcdemo-shared-exec.test COMMON_TESTS = \ tests/link.test \ tests/link-2.test \ tests/nomode.test \ tests/objectlist.test \ tests/quote.test \ tests/sh.test \ tests/suffix.test \ tests/tagtrace.test \ tests/cdemo-static.test \ tests/cdemo-static-make.test \ tests/cdemo-static-exec.test \ tests/demo-static.test \ tests/demo-static-make.test \ tests/demo-static-exec.test \ tests/demo-static-inst.test \ tests/demo-static-unst.test \ tests/depdemo-static.test \ tests/depdemo-static-make.test \ tests/depdemo-static-exec.test \ tests/depdemo-static-inst.test \ tests/depdemo-static-unst.test \ tests/mdemo-static.test \ tests/mdemo-static-make.test \ tests/mdemo-static-exec.test \ tests/mdemo-static-inst.test \ tests/mdemo-static-unst.test \ tests/cdemo-conf.test \ tests/cdemo-make.test \ tests/cdemo-exec.test \ tests/demo-conf.test \ tests/demo-make.test \ tests/demo-exec.test \ tests/demo-inst.test \ tests/demo-unst.test \ tests/demo-deplibs.test \ tests/depdemo-conf.test \ tests/depdemo-make.test \ tests/depdemo-exec.test \ tests/depdemo-inst.test \ tests/depdemo-unst.test \ tests/mdemo-conf.test \ tests/mdemo-make.test \ tests/mdemo-exec.test \ tests/mdemo-inst.test \ tests/mdemo-unst.test \ tests/mdemo-dryrun.test \ tests/mdemo2-conf.test \ tests/mdemo2-make.test \ tests/mdemo2-exec.test \ tests/pdemo-conf.test \ tests/pdemo-make.test \ tests/pdemo-exec.test \ tests/pdemo-inst.test \ tests/demo-nofast.test \ tests/demo-nofast-make.test \ tests/demo-nofast-exec.test \ tests/demo-nofast-inst.test \ tests/demo-nofast-unst.test \ tests/depdemo-nofast.test \ tests/depdemo-nofast-make.test \ tests/depdemo-nofast-exec.test \ tests/depdemo-nofast-inst.test \ tests/depdemo-nofast-unst.test \ tests/demo-pic.test \ tests/demo-pic-make.test \ tests/demo-pic-exec.test \ tests/demo-nopic.test \ tests/demo-nopic-make.test \ tests/demo-nopic-exec.test \ tests/cdemo-shared.test \ tests/cdemo-shared-make.test \ tests/cdemo-shared-exec.test \ tests/mdemo-shared.test \ tests/mdemo-shared-make.test \ tests/mdemo-shared-exec.test \ tests/mdemo-shared-inst.test \ tests/mdemo-shared-unst.test \ tests/cdemo-undef.test \ tests/cdemo-undef-make.test \ tests/cdemo-undef-exec.test # Actually, only demo-relink and depdemo-relink require interaction, # but they depend on the other tests being run beforehand. INTERACTIVE_TESTS = tests/demo-shared.test tests/demo-shared-make.test \ tests/demo-shared-exec.test tests/demo-shared-inst.test \ tests/demo-hardcode.test tests/demo-relink.test \ tests/demo-noinst-link.test tests/demo-shared-unst.test \ tests/depdemo-shared.test tests/depdemo-shared-make.test \ tests/depdemo-shared-exec.test tests/depdemo-shared-inst.test \ tests/depdemo-relink.test tests/depdemo-shared-unst.test \ $(am__append_5) NONINTERACTIVE_TESTS = $(COMMON_TESTS) $(am__append_4) $(am__append_6) TESTS = $(NONINTERACTIVE_TESTS) $(INTERACTIVE_TESTS) # For distclean, we may have to fake Makefiles in the test directories # so that descending in DIST_SUBDIRS works. # Hide the additional dependency from automake so it still outputs the rule. distclean_recursive = distclean-recursive all: $(BUILT_SOURCES) config.h $(MAKE) $(AM_MAKEFLAGS) all-recursive .SUFFIXES: .SUFFIXES: .c .dvi .lo .log .o .obj .ps .test .test$(EXEEXT) .trs am--refresh: Makefile @: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(srcdir)/libltdl/Makefile.inc $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ echo ' cd $(srcdir) && $(AUTOMAKE) --gnu'; \ $(am__cd) $(srcdir) && $(AUTOMAKE) --gnu \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ echo ' $(SHELL) ./config.status'; \ $(SHELL) ./config.status;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ esac; $(srcdir)/libltdl/Makefile.inc: $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) $(SHELL) ./config.status --recheck $(top_srcdir)/configure: $(am__configure_deps) $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): $(am__aclocal_m4_deps) $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) $(am__aclocal_m4_deps): config.h: stamp-h1 @if test ! -f $@; then rm -f stamp-h1; else :; fi @if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) stamp-h1; else :; fi stamp-h1: $(srcdir)/config-h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status config.h $(srcdir)/config-h.in: $(am__configure_deps) ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) rm -f stamp-h1 touch $@ distclean-hdr: -rm -f config.h stamp-h1 install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libltdl/loaders/$(am__dirstamp): @$(MKDIR_P) libltdl/loaders @: > libltdl/loaders/$(am__dirstamp) libltdl/loaders/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) libltdl/loaders/$(DEPDIR) @: > libltdl/loaders/$(DEPDIR)/$(am__dirstamp) libltdl/loaders/dld_link.lo: libltdl/loaders/$(am__dirstamp) \ libltdl/loaders/$(DEPDIR)/$(am__dirstamp) libltdl/$(am__dirstamp): @$(MKDIR_P) libltdl @: > libltdl/$(am__dirstamp) libltdl/dld_link.la: $(libltdl_dld_link_la_OBJECTS) $(libltdl_dld_link_la_DEPENDENCIES) $(EXTRA_libltdl_dld_link_la_DEPENDENCIES) libltdl/$(am__dirstamp) $(AM_V_CCLD)$(libltdl_dld_link_la_LINK) $(libltdl_dld_link_la_OBJECTS) $(libltdl_dld_link_la_LIBADD) $(LIBS) libltdl/loaders/dlopen.lo: libltdl/loaders/$(am__dirstamp) \ libltdl/loaders/$(DEPDIR)/$(am__dirstamp) libltdl/dlopen.la: $(libltdl_dlopen_la_OBJECTS) $(libltdl_dlopen_la_DEPENDENCIES) $(EXTRA_libltdl_dlopen_la_DEPENDENCIES) libltdl/$(am__dirstamp) $(AM_V_CCLD)$(libltdl_dlopen_la_LINK) $(libltdl_dlopen_la_OBJECTS) $(libltdl_dlopen_la_LIBADD) $(LIBS) libltdl/loaders/dyld.lo: libltdl/loaders/$(am__dirstamp) \ libltdl/loaders/$(DEPDIR)/$(am__dirstamp) libltdl/dyld.la: $(libltdl_dyld_la_OBJECTS) $(libltdl_dyld_la_DEPENDENCIES) $(EXTRA_libltdl_dyld_la_DEPENDENCIES) libltdl/$(am__dirstamp) $(AM_V_CCLD)$(libltdl_dyld_la_LINK) $(libltdl_dyld_la_OBJECTS) $(libltdl_dyld_la_LIBADD) $(LIBS) libltdl/loaders/libltdl_libltdl_la-preopen.lo: \ libltdl/loaders/$(am__dirstamp) \ libltdl/loaders/$(DEPDIR)/$(am__dirstamp) libltdl/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) libltdl/$(DEPDIR) @: > libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl_libltdl_la-lt__alloc.lo: libltdl/$(am__dirstamp) \ libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl_libltdl_la-lt_dlloader.lo: libltdl/$(am__dirstamp) \ libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl_libltdl_la-lt_error.lo: libltdl/$(am__dirstamp) \ libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl_libltdl_la-ltdl.lo: libltdl/$(am__dirstamp) \ libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl_libltdl_la-slist.lo: libltdl/$(am__dirstamp) \ libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl.la: $(libltdl_libltdl_la_OBJECTS) $(libltdl_libltdl_la_DEPENDENCIES) $(EXTRA_libltdl_libltdl_la_DEPENDENCIES) libltdl/$(am__dirstamp) $(AM_V_CCLD)$(libltdl_libltdl_la_LINK) $(am_libltdl_libltdl_la_rpath) $(libltdl_libltdl_la_OBJECTS) $(libltdl_libltdl_la_LIBADD) $(LIBS) libltdl/loaders/libltdl_libltdlc_la-preopen.lo: \ libltdl/loaders/$(am__dirstamp) \ libltdl/loaders/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl_libltdlc_la-lt__alloc.lo: libltdl/$(am__dirstamp) \ libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl_libltdlc_la-lt_dlloader.lo: libltdl/$(am__dirstamp) \ libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl_libltdlc_la-lt_error.lo: libltdl/$(am__dirstamp) \ libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl_libltdlc_la-ltdl.lo: libltdl/$(am__dirstamp) \ libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdl_libltdlc_la-slist.lo: libltdl/$(am__dirstamp) \ libltdl/$(DEPDIR)/$(am__dirstamp) libltdl/libltdlc.la: $(libltdl_libltdlc_la_OBJECTS) $(libltdl_libltdlc_la_DEPENDENCIES) $(EXTRA_libltdl_libltdlc_la_DEPENDENCIES) libltdl/$(am__dirstamp) $(AM_V_CCLD)$(libltdl_libltdlc_la_LINK) $(am_libltdl_libltdlc_la_rpath) $(libltdl_libltdlc_la_OBJECTS) $(libltdl_libltdlc_la_LIBADD) $(LIBS) libltdl/loaders/load_add_on.lo: libltdl/loaders/$(am__dirstamp) \ libltdl/loaders/$(DEPDIR)/$(am__dirstamp) libltdl/load_add_on.la: $(libltdl_load_add_on_la_OBJECTS) $(libltdl_load_add_on_la_DEPENDENCIES) $(EXTRA_libltdl_load_add_on_la_DEPENDENCIES) libltdl/$(am__dirstamp) $(AM_V_CCLD)$(libltdl_load_add_on_la_LINK) $(libltdl_load_add_on_la_OBJECTS) $(libltdl_load_add_on_la_LIBADD) $(LIBS) libltdl/loaders/loadlibrary.lo: libltdl/loaders/$(am__dirstamp) \ libltdl/loaders/$(DEPDIR)/$(am__dirstamp) libltdl/loadlibrary.la: $(libltdl_loadlibrary_la_OBJECTS) $(libltdl_loadlibrary_la_DEPENDENCIES) $(EXTRA_libltdl_loadlibrary_la_DEPENDENCIES) libltdl/$(am__dirstamp) $(AM_V_CCLD)$(libltdl_loadlibrary_la_LINK) $(libltdl_loadlibrary_la_OBJECTS) $(libltdl_loadlibrary_la_LIBADD) $(LIBS) libltdl/loaders/shl_load.lo: libltdl/loaders/$(am__dirstamp) \ libltdl/loaders/$(DEPDIR)/$(am__dirstamp) libltdl/shl_load.la: $(libltdl_shl_load_la_OBJECTS) $(libltdl_shl_load_la_DEPENDENCIES) $(EXTRA_libltdl_shl_load_la_DEPENDENCIES) libltdl/$(am__dirstamp) $(AM_V_CCLD)$(libltdl_shl_load_la_LINK) $(libltdl_shl_load_la_OBJECTS) $(libltdl_shl_load_la_LIBADD) $(LIBS) install-binSCRIPTS: $(bin_SCRIPTS) @$(NORMAL_INSTALL) @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n' \ -e 'h;s|.*|.|' \ -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) { files[d] = files[d] " " $$1; \ if (++n[d] == $(am__install_max)) { \ print "f", d, files[d]; n[d] = 0; files[d] = "" } } \ else { print "f", d "/" $$4, $$1 } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binSCRIPTS: @$(NORMAL_UNINSTALL) @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || exit 0; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 's,.*/,,;$(transform)'`; \ dir='$(DESTDIR)$(bindir)'; $(am__uninstall_files_from_dir) mostlyclean-compile: -rm -f *.$(OBJEXT) -rm -f libltdl/*.$(OBJEXT) -rm -f libltdl/*.lo -rm -f libltdl/loaders/*.$(OBJEXT) -rm -f libltdl/loaders/*.lo distclean-compile: -rm -f *.tab.c include libltdl/$(DEPDIR)/argz.Plo include libltdl/$(DEPDIR)/libltdl_libltdl_la-lt__alloc.Plo include libltdl/$(DEPDIR)/libltdl_libltdl_la-lt_dlloader.Plo include libltdl/$(DEPDIR)/libltdl_libltdl_la-lt_error.Plo include libltdl/$(DEPDIR)/libltdl_libltdl_la-ltdl.Plo include libltdl/$(DEPDIR)/libltdl_libltdl_la-slist.Plo include libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt__alloc.Plo include libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt_dlloader.Plo include libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt_error.Plo include libltdl/$(DEPDIR)/libltdl_libltdlc_la-ltdl.Plo include libltdl/$(DEPDIR)/libltdl_libltdlc_la-slist.Plo include libltdl/$(DEPDIR)/lt__dirent.Plo include libltdl/$(DEPDIR)/lt__strl.Plo include libltdl/loaders/$(DEPDIR)/dld_link.Plo include libltdl/loaders/$(DEPDIR)/dlopen.Plo include libltdl/loaders/$(DEPDIR)/dyld.Plo include libltdl/loaders/$(DEPDIR)/libltdl_libltdl_la-preopen.Plo include libltdl/loaders/$(DEPDIR)/libltdl_libltdlc_la-preopen.Plo include libltdl/loaders/$(DEPDIR)/load_add_on.Plo include libltdl/loaders/$(DEPDIR)/loadlibrary.Plo include libltdl/loaders/$(DEPDIR)/shl_load.Plo .c.o: $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ $(am__mv) $$depbase.Tpo $$depbase.Po # $(AM_V_CC)source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(COMPILE) -c -o $@ $< .c.obj: $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ $(am__mv) $$depbase.Tpo $$depbase.Po # $(AM_V_CC)source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ $(am__mv) $$depbase.Tpo $$depbase.Plo # $(AM_V_CC)source='$<' object='$@' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LTCOMPILE) -c -o $@ $< libltdl/loaders/libltdl_libltdl_la-preopen.lo: libltdl/loaders/preopen.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/loaders/libltdl_libltdl_la-preopen.lo -MD -MP -MF libltdl/loaders/$(DEPDIR)/libltdl_libltdl_la-preopen.Tpo -c -o libltdl/loaders/libltdl_libltdl_la-preopen.lo `test -f 'libltdl/loaders/preopen.c' || echo '$(srcdir)/'`libltdl/loaders/preopen.c $(AM_V_at)$(am__mv) libltdl/loaders/$(DEPDIR)/libltdl_libltdl_la-preopen.Tpo libltdl/loaders/$(DEPDIR)/libltdl_libltdl_la-preopen.Plo # $(AM_V_CC)source='libltdl/loaders/preopen.c' object='libltdl/loaders/libltdl_libltdl_la-preopen.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/loaders/libltdl_libltdl_la-preopen.lo `test -f 'libltdl/loaders/preopen.c' || echo '$(srcdir)/'`libltdl/loaders/preopen.c libltdl/libltdl_libltdl_la-lt__alloc.lo: libltdl/lt__alloc.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/libltdl_libltdl_la-lt__alloc.lo -MD -MP -MF libltdl/$(DEPDIR)/libltdl_libltdl_la-lt__alloc.Tpo -c -o libltdl/libltdl_libltdl_la-lt__alloc.lo `test -f 'libltdl/lt__alloc.c' || echo '$(srcdir)/'`libltdl/lt__alloc.c $(AM_V_at)$(am__mv) libltdl/$(DEPDIR)/libltdl_libltdl_la-lt__alloc.Tpo libltdl/$(DEPDIR)/libltdl_libltdl_la-lt__alloc.Plo # $(AM_V_CC)source='libltdl/lt__alloc.c' object='libltdl/libltdl_libltdl_la-lt__alloc.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/libltdl_libltdl_la-lt__alloc.lo `test -f 'libltdl/lt__alloc.c' || echo '$(srcdir)/'`libltdl/lt__alloc.c libltdl/libltdl_libltdl_la-lt_dlloader.lo: libltdl/lt_dlloader.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/libltdl_libltdl_la-lt_dlloader.lo -MD -MP -MF libltdl/$(DEPDIR)/libltdl_libltdl_la-lt_dlloader.Tpo -c -o libltdl/libltdl_libltdl_la-lt_dlloader.lo `test -f 'libltdl/lt_dlloader.c' || echo '$(srcdir)/'`libltdl/lt_dlloader.c $(AM_V_at)$(am__mv) libltdl/$(DEPDIR)/libltdl_libltdl_la-lt_dlloader.Tpo libltdl/$(DEPDIR)/libltdl_libltdl_la-lt_dlloader.Plo # $(AM_V_CC)source='libltdl/lt_dlloader.c' object='libltdl/libltdl_libltdl_la-lt_dlloader.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/libltdl_libltdl_la-lt_dlloader.lo `test -f 'libltdl/lt_dlloader.c' || echo '$(srcdir)/'`libltdl/lt_dlloader.c libltdl/libltdl_libltdl_la-lt_error.lo: libltdl/lt_error.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/libltdl_libltdl_la-lt_error.lo -MD -MP -MF libltdl/$(DEPDIR)/libltdl_libltdl_la-lt_error.Tpo -c -o libltdl/libltdl_libltdl_la-lt_error.lo `test -f 'libltdl/lt_error.c' || echo '$(srcdir)/'`libltdl/lt_error.c $(AM_V_at)$(am__mv) libltdl/$(DEPDIR)/libltdl_libltdl_la-lt_error.Tpo libltdl/$(DEPDIR)/libltdl_libltdl_la-lt_error.Plo # $(AM_V_CC)source='libltdl/lt_error.c' object='libltdl/libltdl_libltdl_la-lt_error.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/libltdl_libltdl_la-lt_error.lo `test -f 'libltdl/lt_error.c' || echo '$(srcdir)/'`libltdl/lt_error.c libltdl/libltdl_libltdl_la-ltdl.lo: libltdl/ltdl.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/libltdl_libltdl_la-ltdl.lo -MD -MP -MF libltdl/$(DEPDIR)/libltdl_libltdl_la-ltdl.Tpo -c -o libltdl/libltdl_libltdl_la-ltdl.lo `test -f 'libltdl/ltdl.c' || echo '$(srcdir)/'`libltdl/ltdl.c $(AM_V_at)$(am__mv) libltdl/$(DEPDIR)/libltdl_libltdl_la-ltdl.Tpo libltdl/$(DEPDIR)/libltdl_libltdl_la-ltdl.Plo # $(AM_V_CC)source='libltdl/ltdl.c' object='libltdl/libltdl_libltdl_la-ltdl.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/libltdl_libltdl_la-ltdl.lo `test -f 'libltdl/ltdl.c' || echo '$(srcdir)/'`libltdl/ltdl.c libltdl/libltdl_libltdl_la-slist.lo: libltdl/slist.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/libltdl_libltdl_la-slist.lo -MD -MP -MF libltdl/$(DEPDIR)/libltdl_libltdl_la-slist.Tpo -c -o libltdl/libltdl_libltdl_la-slist.lo `test -f 'libltdl/slist.c' || echo '$(srcdir)/'`libltdl/slist.c $(AM_V_at)$(am__mv) libltdl/$(DEPDIR)/libltdl_libltdl_la-slist.Tpo libltdl/$(DEPDIR)/libltdl_libltdl_la-slist.Plo # $(AM_V_CC)source='libltdl/slist.c' object='libltdl/libltdl_libltdl_la-slist.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdl_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/libltdl_libltdl_la-slist.lo `test -f 'libltdl/slist.c' || echo '$(srcdir)/'`libltdl/slist.c libltdl/loaders/libltdl_libltdlc_la-preopen.lo: libltdl/loaders/preopen.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/loaders/libltdl_libltdlc_la-preopen.lo -MD -MP -MF libltdl/loaders/$(DEPDIR)/libltdl_libltdlc_la-preopen.Tpo -c -o libltdl/loaders/libltdl_libltdlc_la-preopen.lo `test -f 'libltdl/loaders/preopen.c' || echo '$(srcdir)/'`libltdl/loaders/preopen.c $(AM_V_at)$(am__mv) libltdl/loaders/$(DEPDIR)/libltdl_libltdlc_la-preopen.Tpo libltdl/loaders/$(DEPDIR)/libltdl_libltdlc_la-preopen.Plo # $(AM_V_CC)source='libltdl/loaders/preopen.c' object='libltdl/loaders/libltdl_libltdlc_la-preopen.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/loaders/libltdl_libltdlc_la-preopen.lo `test -f 'libltdl/loaders/preopen.c' || echo '$(srcdir)/'`libltdl/loaders/preopen.c libltdl/libltdl_libltdlc_la-lt__alloc.lo: libltdl/lt__alloc.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/libltdl_libltdlc_la-lt__alloc.lo -MD -MP -MF libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt__alloc.Tpo -c -o libltdl/libltdl_libltdlc_la-lt__alloc.lo `test -f 'libltdl/lt__alloc.c' || echo '$(srcdir)/'`libltdl/lt__alloc.c $(AM_V_at)$(am__mv) libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt__alloc.Tpo libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt__alloc.Plo # $(AM_V_CC)source='libltdl/lt__alloc.c' object='libltdl/libltdl_libltdlc_la-lt__alloc.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/libltdl_libltdlc_la-lt__alloc.lo `test -f 'libltdl/lt__alloc.c' || echo '$(srcdir)/'`libltdl/lt__alloc.c libltdl/libltdl_libltdlc_la-lt_dlloader.lo: libltdl/lt_dlloader.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/libltdl_libltdlc_la-lt_dlloader.lo -MD -MP -MF libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt_dlloader.Tpo -c -o libltdl/libltdl_libltdlc_la-lt_dlloader.lo `test -f 'libltdl/lt_dlloader.c' || echo '$(srcdir)/'`libltdl/lt_dlloader.c $(AM_V_at)$(am__mv) libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt_dlloader.Tpo libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt_dlloader.Plo # $(AM_V_CC)source='libltdl/lt_dlloader.c' object='libltdl/libltdl_libltdlc_la-lt_dlloader.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/libltdl_libltdlc_la-lt_dlloader.lo `test -f 'libltdl/lt_dlloader.c' || echo '$(srcdir)/'`libltdl/lt_dlloader.c libltdl/libltdl_libltdlc_la-lt_error.lo: libltdl/lt_error.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/libltdl_libltdlc_la-lt_error.lo -MD -MP -MF libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt_error.Tpo -c -o libltdl/libltdl_libltdlc_la-lt_error.lo `test -f 'libltdl/lt_error.c' || echo '$(srcdir)/'`libltdl/lt_error.c $(AM_V_at)$(am__mv) libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt_error.Tpo libltdl/$(DEPDIR)/libltdl_libltdlc_la-lt_error.Plo # $(AM_V_CC)source='libltdl/lt_error.c' object='libltdl/libltdl_libltdlc_la-lt_error.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/libltdl_libltdlc_la-lt_error.lo `test -f 'libltdl/lt_error.c' || echo '$(srcdir)/'`libltdl/lt_error.c libltdl/libltdl_libltdlc_la-ltdl.lo: libltdl/ltdl.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/libltdl_libltdlc_la-ltdl.lo -MD -MP -MF libltdl/$(DEPDIR)/libltdl_libltdlc_la-ltdl.Tpo -c -o libltdl/libltdl_libltdlc_la-ltdl.lo `test -f 'libltdl/ltdl.c' || echo '$(srcdir)/'`libltdl/ltdl.c $(AM_V_at)$(am__mv) libltdl/$(DEPDIR)/libltdl_libltdlc_la-ltdl.Tpo libltdl/$(DEPDIR)/libltdl_libltdlc_la-ltdl.Plo # $(AM_V_CC)source='libltdl/ltdl.c' object='libltdl/libltdl_libltdlc_la-ltdl.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/libltdl_libltdlc_la-ltdl.lo `test -f 'libltdl/ltdl.c' || echo '$(srcdir)/'`libltdl/ltdl.c libltdl/libltdl_libltdlc_la-slist.lo: libltdl/slist.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libltdl/libltdl_libltdlc_la-slist.lo -MD -MP -MF libltdl/$(DEPDIR)/libltdl_libltdlc_la-slist.Tpo -c -o libltdl/libltdl_libltdlc_la-slist.lo `test -f 'libltdl/slist.c' || echo '$(srcdir)/'`libltdl/slist.c $(AM_V_at)$(am__mv) libltdl/$(DEPDIR)/libltdl_libltdlc_la-slist.Tpo libltdl/$(DEPDIR)/libltdl_libltdlc_la-slist.Plo # $(AM_V_CC)source='libltdl/slist.c' object='libltdl/libltdl_libltdlc_la-slist.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libltdl_libltdlc_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libltdl/libltdl_libltdlc_la-slist.lo `test -f 'libltdl/slist.c' || echo '$(srcdir)/'`libltdl/slist.c mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs -rm -rf libltdl/.libs libltdl/_libs -rm -rf libltdl/loaders/.libs libltdl/loaders/_libs distclean-libtool: -rm -f libtool config.lt doc/$(am__dirstamp): @$(MKDIR_P) doc @: > doc/$(am__dirstamp) $(srcdir)/doc/libtool.info: doc/libtool.texi $(srcdir)/doc/version.texi $(doc_libtool_TEXINFOS) $(AM_V_MAKEINFO)restore=: && backupdir="$(am__leading_dot)am$$$$" && \ am__cwd=`pwd` && $(am__cd) $(srcdir) && \ rm -rf $$backupdir && mkdir $$backupdir && \ if ($(MAKEINFO) --version) >/dev/null 2>&1; then \ for f in $@ $@-[0-9] $@-[0-9][0-9] $(@:.info=).i[0-9] $(@:.info=).i[0-9][0-9]; do \ if test -f $$f; then mv $$f $$backupdir; restore=mv; else :; fi; \ done; \ else :; fi && \ cd "$$am__cwd"; \ if $(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I doc -I $(srcdir)/doc \ -o $@ $(srcdir)/doc/libtool.texi; \ then \ rc=0; \ $(am__cd) $(srcdir); \ else \ rc=$$?; \ $(am__cd) $(srcdir) && \ $$restore $$backupdir/* `echo "./$@" | sed 's|[^/]*$$||'`; \ fi; \ rm -rf $$backupdir; exit $$rc doc/libtool.dvi: doc/libtool.texi $(srcdir)/doc/version.texi $(doc_libtool_TEXINFOS) doc/$(am__dirstamp) $(AM_V_TEXI2DVI)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \ MAKEINFO='$(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I doc -I $(srcdir)/doc' \ $(TEXI2DVI) $(AM_V_texinfo) --build-dir=$(@:.dvi=.t2d) -o $@ $(AM_V_texidevnull) \ `test -f 'doc/libtool.texi' || echo '$(srcdir)/'`doc/libtool.texi doc/libtool.pdf: doc/libtool.texi $(srcdir)/doc/version.texi $(doc_libtool_TEXINFOS) doc/$(am__dirstamp) $(AM_V_TEXI2PDF)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \ MAKEINFO='$(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I doc -I $(srcdir)/doc' \ $(TEXI2PDF) $(AM_V_texinfo) --build-dir=$(@:.pdf=.t2p) -o $@ $(AM_V_texidevnull) \ `test -f 'doc/libtool.texi' || echo '$(srcdir)/'`doc/libtool.texi doc/libtool.html: doc/libtool.texi $(srcdir)/doc/version.texi $(doc_libtool_TEXINFOS) doc/$(am__dirstamp) $(AM_V_MAKEINFO)rm -rf $(@:.html=.htp) $(AM_V_at)if $(MAKEINFOHTML) $(AM_MAKEINFOHTMLFLAGS) $(MAKEINFOFLAGS) -I doc -I $(srcdir)/doc \ -o $(@:.html=.htp) `test -f 'doc/libtool.texi' || echo '$(srcdir)/'`doc/libtool.texi; \ then \ rm -rf $@; \ if test ! -d $(@:.html=.htp) && test -d $(@:.html=); then \ mv $(@:.html=) $@; else mv $(@:.html=.htp) $@; fi; \ else \ if test ! -d $(@:.html=.htp) && test -d $(@:.html=); then \ rm -rf $(@:.html=); else rm -Rf $(@:.html=.htp) $@; fi; \ exit 1; \ fi $(srcdir)/doc/version.texi: $(srcdir)/doc/stamp-vti $(srcdir)/doc/stamp-vti: doc/libtool.texi $(top_srcdir)/configure test -f doc/$(am__dirstamp) || $(MAKE) $(AM_MAKEFLAGS) doc/$(am__dirstamp) @(dir=.; test -f ./doc/libtool.texi || dir=$(srcdir); \ set `$(SHELL) $(top_srcdir)/libltdl/config/mdate-sh $$dir/doc/libtool.texi`; \ echo "@set UPDATED $$1 $$2 $$3"; \ echo "@set UPDATED-MONTH $$2 $$3"; \ echo "@set EDITION $(VERSION)"; \ echo "@set VERSION $(VERSION)") > vti.tmp @cmp -s vti.tmp $(srcdir)/doc/version.texi \ || (echo "Updating $(srcdir)/doc/version.texi"; \ cp vti.tmp $(srcdir)/doc/version.texi) -@rm -f vti.tmp @cp $(srcdir)/doc/version.texi $@ mostlyclean-vti: -rm -f vti.tmp maintainer-clean-vti: -rm -f $(srcdir)/doc/stamp-vti $(srcdir)/doc/version.texi .dvi.ps: $(AM_V_DVIPS)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \ $(DVIPS) $(AM_V_texinfo) -o $@ $< uninstall-dvi-am: @$(NORMAL_UNINSTALL) @list='$(DVIS)'; test -n "$(dvidir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " rm -f '$(DESTDIR)$(dvidir)/$$f'"; \ rm -f "$(DESTDIR)$(dvidir)/$$f"; \ done uninstall-html-am: @$(NORMAL_UNINSTALL) @list='$(HTMLS)'; test -n "$(htmldir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " rm -rf '$(DESTDIR)$(htmldir)/$$f'"; \ rm -rf "$(DESTDIR)$(htmldir)/$$f"; \ done uninstall-info-am: @$(PRE_UNINSTALL) @if test -d '$(DESTDIR)$(infodir)' && $(am__can_run_installinfo); then \ list='$(INFO_DEPS)'; \ for file in $$list; do \ relfile=`echo "$$file" | sed 's|^.*/||'`; \ echo " install-info --info-dir='$(DESTDIR)$(infodir)' --remove '$(DESTDIR)$(infodir)/$$relfile'"; \ if install-info --info-dir="$(DESTDIR)$(infodir)" --remove "$(DESTDIR)$(infodir)/$$relfile"; \ then :; else test ! -f "$(DESTDIR)$(infodir)/$$relfile" || exit 1; fi; \ done; \ else :; fi @$(NORMAL_UNINSTALL) @list='$(INFO_DEPS)'; \ for file in $$list; do \ relfile=`echo "$$file" | sed 's|^.*/||'`; \ relfile_i=`echo "$$relfile" | sed 's|\.info$$||;s|$$|.i|'`; \ (if test -d "$(DESTDIR)$(infodir)" && cd "$(DESTDIR)$(infodir)"; then \ echo " cd '$(DESTDIR)$(infodir)' && rm -f $$relfile $$relfile-[0-9] $$relfile-[0-9][0-9] $$relfile_i[0-9] $$relfile_i[0-9][0-9]"; \ rm -f $$relfile $$relfile-[0-9] $$relfile-[0-9][0-9] $$relfile_i[0-9] $$relfile_i[0-9][0-9]; \ else :; fi); \ done uninstall-pdf-am: @$(NORMAL_UNINSTALL) @list='$(PDFS)'; test -n "$(pdfdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " rm -f '$(DESTDIR)$(pdfdir)/$$f'"; \ rm -f "$(DESTDIR)$(pdfdir)/$$f"; \ done uninstall-ps-am: @$(NORMAL_UNINSTALL) @list='$(PSS)'; test -n "$(psdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " rm -f '$(DESTDIR)$(psdir)/$$f'"; \ rm -f "$(DESTDIR)$(psdir)/$$f"; \ done dist-info: $(INFO_DEPS) @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ list='$(INFO_DEPS)'; \ for base in $$list; do \ case $$base in \ $(srcdir)/*) base=`echo "$$base" | sed "s|^$$srcdirstrip/||"`;; \ esac; \ if test -f $$base; then d=.; else d=$(srcdir); fi; \ base_i=`echo "$$base" | sed 's|\.info$$||;s|$$|.i|'`; \ for file in $$d/$$base $$d/$$base-[0-9] $$d/$$base-[0-9][0-9] $$d/$$base_i[0-9] $$d/$$base_i[0-9][0-9]; do \ if test -f $$file; then \ relfile=`expr "$$file" : "$$d/\(.*\)"`; \ test -f "$(distdir)/$$relfile" || \ cp -p $$file "$(distdir)/$$relfile"; \ else :; fi; \ done; \ done mostlyclean-aminfo: -rm -rf doc/libtool.t2d doc/libtool.t2p clean-aminfo: -test -z "doc/libtool.dvi doc/libtool.pdf doc/libtool.ps doc/libtool.html" \ || rm -rf doc/libtool.dvi doc/libtool.pdf doc/libtool.ps doc/libtool.html maintainer-clean-aminfo: @list='$(INFO_DEPS)'; for i in $$list; do \ i_i=`echo "$$i" | sed 's|\.info$$||;s|$$|.i|'`; \ echo " rm -f $$i $$i-[0-9] $$i-[0-9][0-9] $$i_i[0-9] $$i_i[0-9][0-9]"; \ rm -f $$i $$i-[0-9] $$i-[0-9][0-9] $$i_i[0-9] $$i_i[0-9][0-9]; \ done install-man1: $(dist_man1_MANS) @$(NORMAL_INSTALL) @list1='$(dist_man1_MANS)'; \ list2=''; \ test -n "$(man1dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man1dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man1dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.1[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \ done; } uninstall-man1: @$(NORMAL_UNINSTALL) @list='$(dist_man1_MANS)'; test -n "$(man1dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man1dir)'; $(am__uninstall_files_from_dir) install-includeHEADERS: $(include_HEADERS) @$(NORMAL_INSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) install-ltdlincludeHEADERS: $(ltdlinclude_HEADERS) @$(NORMAL_INSTALL) @list='$(ltdlinclude_HEADERS)'; test -n "$(ltdlincludedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(ltdlincludedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(ltdlincludedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(ltdlincludedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(ltdlincludedir)" || exit $$?; \ done uninstall-ltdlincludeHEADERS: @$(NORMAL_UNINSTALL) @list='$(ltdlinclude_HEADERS)'; test -n "$(ltdlincludedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(ltdlincludedir)'; $(am__uninstall_files_from_dir) # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscope: cscope.files test ! -s cscope.files \ || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS) clean-cscope: -rm -f cscope.files cscope.files: clean-cscope cscopelist cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags -rm -f cscope.out cscope.in.out cscope.po.out cscope.files # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ else \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) #.test$(EXEEXT).log: # @p='$<'; \ # $(am__set_b); \ # $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ # --log-file $$b.log --trs-file $$b.trs \ # $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ # "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) $(am__remove_distdir) test -d "$(distdir)" || mkdir "$(distdir)" @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-info dist-hook -test -n "$(am__skip_mode_fix)" \ || find "$(distdir)" -type d ! -perm -755 \ -exec chmod u+rwx,go+rx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ || chmod -R a+r "$(distdir)" dist-gzip: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__post_remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__post_remove_distdir) dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__post_remove_distdir) dist-xz: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__post_remove_distdir) dist-tarZ: distdir tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__post_remove_distdir) dist-shar: distdir shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz $(am__post_remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__post_remove_distdir) dist dist-all: $(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:' $(am__post_remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another # tarfile. distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac chmod -R a-w $(distdir) chmod u+w $(distdir) mkdir $(distdir)/_build $(distdir)/_inst chmod a-w $(distdir) test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && am__cwd=`pwd` \ && $(am__cd) $(distdir)/_build \ && ../configure --srcdir=.. --prefix="$$dc_install_base" \ $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) dvi \ && $(MAKE) $(AM_MAKEFLAGS) check \ && $(MAKE) $(AM_MAKEFLAGS) install \ && $(MAKE) $(AM_MAKEFLAGS) installcheck \ && $(MAKE) $(AM_MAKEFLAGS) uninstall \ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ distuninstallcheck \ && chmod -R a-w "$$dc_install_base" \ && ({ \ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ } || { rm -rf "$$dc_destdir"; exit 1; }) \ && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ && cd "$$am__cwd" \ || exit 1 $(am__post_remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: @test -n '$(distuninstallcheck_dir)' || { \ echo 'ERROR: trying to run $@ with an empty' \ '$$(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ $(am__cd) '$(distuninstallcheck_dir)' || { \ echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ fi ; \ $(distuninstallcheck_listfiles) ; \ exit 1; } >&2 distcleancheck: distclean @if test '$(srcdir)' = . ; then \ echo "ERROR: distcleancheck can only run from a VPATH build" ; \ exit 1 ; \ fi @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left in build directory after distclean:" ; \ $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am $(MAKE) $(AM_MAKEFLAGS) check-TESTS check-local check: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) check-recursive all-am: Makefile $(INFO_DEPS) $(LTLIBRARIES) $(SCRIPTS) $(MANS) \ $(HEADERS) config.h all-local installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" "$(DESTDIR)$(infodir)" "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(includedir)" "$(DESTDIR)$(ltdlincludedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(LIBOBJS)" || rm -f $(LIBOBJS) -test -z "$(LTLIBOBJS)" || rm -f $(LTLIBOBJS) -test -z "$(MOSTLYCLEANFILES)" || rm -f $(MOSTLYCLEANFILES) -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -rm -f doc/$(am__dirstamp) -rm -f libltdl/$(DEPDIR)/$(am__dirstamp) -rm -f libltdl/$(am__dirstamp) -rm -f libltdl/loaders/$(DEPDIR)/$(am__dirstamp) -rm -f libltdl/loaders/$(am__dirstamp) -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES) -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-aminfo clean-generic clean-libLTLIBRARIES \ clean-libtool clean-local clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf libltdl/$(DEPDIR) libltdl/loaders/$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-hdr distclean-libtool distclean-tags dvi: dvi-recursive dvi-am: $(DVIS) html: html-recursive html-am: $(HTMLS) info: info-recursive info-am: $(INFO_DEPS) install-data-am: install-data-local install-includeHEADERS \ install-info-am install-ltdlincludeHEADERS install-man install-dvi: install-dvi-recursive install-dvi-am: $(DVIS) @$(NORMAL_INSTALL) @list='$(DVIS)'; test -n "$(dvidir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(dvidir)'"; \ $(MKDIR_P) "$(DESTDIR)$(dvidir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(dvidir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(dvidir)" || exit $$?; \ done install-exec-am: install-binSCRIPTS install-libLTLIBRARIES install-html: install-html-recursive install-html-am: $(HTMLS) @$(NORMAL_INSTALL) @list='$(HTMLS)'; list2=; test -n "$(htmldir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(htmldir)'"; \ $(MKDIR_P) "$(DESTDIR)$(htmldir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p" || test -d "$$p"; then d=; else d="$(srcdir)/"; fi; \ $(am__strip_dir) \ d2=$$d$$p; \ if test -d "$$d2"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(htmldir)/$$f'"; \ $(MKDIR_P) "$(DESTDIR)$(htmldir)/$$f" || exit 1; \ echo " $(INSTALL_DATA) '$$d2'/* '$(DESTDIR)$(htmldir)/$$f'"; \ $(INSTALL_DATA) "$$d2"/* "$(DESTDIR)$(htmldir)/$$f" || exit $$?; \ else \ list2="$$list2 $$d2"; \ fi; \ done; \ test -z "$$list2" || { echo "$$list2" | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(htmldir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(htmldir)" || exit $$?; \ done; } install-info: install-info-recursive install-info-am: $(INFO_DEPS) @$(NORMAL_INSTALL) @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ list='$(INFO_DEPS)'; test -n "$(infodir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(infodir)'"; \ $(MKDIR_P) "$(DESTDIR)$(infodir)" || exit 1; \ fi; \ for file in $$list; do \ case $$file in \ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ esac; \ if test -f $$file; then d=.; else d=$(srcdir); fi; \ file_i=`echo "$$file" | sed 's|\.info$$||;s|$$|.i|'`; \ for ifile in $$d/$$file $$d/$$file-[0-9] $$d/$$file-[0-9][0-9] \ $$d/$$file_i[0-9] $$d/$$file_i[0-9][0-9] ; do \ if test -f $$ifile; then \ echo "$$ifile"; \ else : ; fi; \ done; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(infodir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(infodir)" || exit $$?; done @$(POST_INSTALL) @if $(am__can_run_installinfo); then \ list='$(INFO_DEPS)'; test -n "$(infodir)" || list=; \ for file in $$list; do \ relfile=`echo "$$file" | sed 's|^.*/||'`; \ echo " install-info --info-dir='$(DESTDIR)$(infodir)' '$(DESTDIR)$(infodir)/$$relfile'";\ install-info --info-dir="$(DESTDIR)$(infodir)" "$(DESTDIR)$(infodir)/$$relfile" || :;\ done; \ else : ; fi install-man: install-man1 install-pdf: install-pdf-recursive install-pdf-am: $(PDFS) @$(NORMAL_INSTALL) @list='$(PDFS)'; test -n "$(pdfdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(pdfdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(pdfdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pdfdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(pdfdir)" || exit $$?; done install-ps: install-ps-recursive install-ps-am: $(PSS) @$(NORMAL_INSTALL) @list='$(PSS)'; test -n "$(psdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(psdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(psdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(psdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(psdir)" || exit $$?; done installcheck-am: installcheck-local maintainer-clean: maintainer-clean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache -rm -rf libltdl/$(DEPDIR) libltdl/loaders/$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-aminfo \ maintainer-clean-generic maintainer-clean-vti mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-aminfo mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool mostlyclean-vti pdf: pdf-recursive pdf-am: $(PDFS) ps: ps-recursive ps-am: $(PSS) uninstall-am: uninstall-binSCRIPTS uninstall-dvi-am uninstall-html-am \ uninstall-includeHEADERS uninstall-info-am \ uninstall-libLTLIBRARIES uninstall-ltdlincludeHEADERS \ uninstall-man uninstall-pdf-am uninstall-ps-am @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook uninstall-man: uninstall-man1 .MAKE: $(am__recursive_targets) all check check-am install install-am \ install-strip uninstall-am .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am all-local \ am--refresh check check-TESTS check-am check-local clean \ clean-aminfo clean-cscope clean-generic clean-libLTLIBRARIES \ clean-libtool clean-local clean-noinstLTLIBRARIES cscope \ cscopelist-am ctags ctags-am dist dist-all dist-bzip2 \ dist-gzip dist-hook dist-info dist-lzip dist-shar dist-tarZ \ dist-xz dist-zip distcheck distclean distclean-compile \ distclean-generic distclean-hdr distclean-libtool \ distclean-tags distcleancheck distdir distuninstallcheck dvi \ dvi-am html html-am info info-am install install-am \ install-binSCRIPTS install-data install-data-am \ install-data-local install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am \ install-includeHEADERS install-info install-info-am \ install-libLTLIBRARIES install-ltdlincludeHEADERS install-man \ install-man1 install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installcheck-local installdirs installdirs-am maintainer-clean \ maintainer-clean-aminfo maintainer-clean-generic \ maintainer-clean-vti mostlyclean mostlyclean-aminfo \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ mostlyclean-vti pdf pdf-am ps ps-am recheck tags tags-am \ uninstall uninstall-am uninstall-binSCRIPTS uninstall-dvi-am \ uninstall-hook uninstall-html-am uninstall-includeHEADERS \ uninstall-info-am uninstall-libLTLIBRARIES \ uninstall-ltdlincludeHEADERS uninstall-man uninstall-man1 \ uninstall-pdf-am uninstall-ps-am $(srcdir)/$(m4dir)/ltversion.m4: $(m4dir)/ltversion.in configure.ac ChangeLog @target='$(srcdir)/$(m4dir)/ltversion.m4'; $(rebuild); \ if test -f "$$target"; then \ set dummy `sed -n '/^# serial /p' "$$target"`; shift; \ actualver=1.$$3; \ test "$$actualver" = "$$correctver" && rebuild=false; \ fi; \ for prereq in $?; do \ case $$prereq in *ChangeLog | *configure.ac);; *) rebuild=:;; esac; \ done; \ if $$rebuild; then \ cd $(srcdir); \ rm -f $(m4dir)/ltversion.tmp; \ serial=`echo "$$correctver" | sed 's,^1[.],,g'`; \ echo $(bootstrap_edit) \ $(srcdir)/$(m4dir)/ltversion.in \> $(srcdir)/$(m4dir)/ltversion.m4; \ $(bootstrap_edit) \ $(m4dir)/ltversion.in > $(m4dir)/ltversion.tmp; \ chmod a-w $(m4dir)/ltversion.tmp; \ mv -f $(m4dir)/ltversion.tmp $(m4dir)/ltversion.m4; \ fi $(srcdir)/$(auxdir)/ltmain.sh: $(sh_files) $(auxdir)/ltmain.m4sh configure.ac ChangeLog @target='$(srcdir)/$(auxdir)/ltmain.sh'; $(rebuild); \ if test -f "$$target"; then \ eval `sed -n '/^package_revision=/p' "$$target"`; \ actualver=$$package_revision; \ test "$$actualver" = "$$correctver" && rebuild=false; \ fi; \ for prereq in $?; do \ case $$prereq in *ChangeLog);; *) rebuild=:;; esac; \ done; \ if $$rebuild; then \ cd $(srcdir); \ rm -f $(auxdir)/ltmain.in $(auxdir)/ltmain.tmp \ $(auxdir)/ltmain.sh; \ echo $(M4SH) -B $(auxdir) $(auxdir)/ltmain.m4sh \ \> $(auxdir)/ltmain.in; \ $(M4SH) -B $(auxdir) $(auxdir)/ltmain.m4sh \ > $(auxdir)/ltmain.in; \ echo $(bootstrap_edit) \ $(srcdir)/$(auxdir)/ltmain.in "> $$target"; \ $(bootstrap_edit) -e '/^: \$${.*="@.*@"}$$/d' \ $(auxdir)/ltmain.in > $(auxdir)/ltmain.tmp; \ rm -f $(auxdir)/ltmain.in; \ chmod a-w $(auxdir)/ltmain.tmp; \ mv -f $(auxdir)/ltmain.tmp $(auxdir)/ltmain.sh; \ fi $(srcdir)/libtoolize.in: $(sh_files) libtoolize.m4sh Makefile.am cd $(srcdir); \ rm -f libtoolize.in libtoolize.tmp; \ $(M4SH) -B $(auxdir) libtoolize.m4sh > libtoolize.tmp; \ $(bootstrap_edit) libtoolize.tmp > libtoolize.in; \ rm -f libtoolize.tmp $(srcdir)/libltdl/Makefile.am: $(srcdir)/libltdl/Makefile.inc cd $(srcdir); \ in=libltdl/Makefile.inc; out=libltdl/Makefile.am; \ rm -f $$out; \ ( $(SED) -n '1,/^.. DO NOT REMOVE THIS LINE -- /p' $$in; \ { echo 'ACLOCAL_AMFLAGS = -I m4'; \ echo 'AUTOMAKE_OPTIONS = foreign'; \ echo 'AM_CPPFLAGS ='; \ echo 'AM_LDFLAGS ='; \ echo 'BUILT_SOURCES ='; \ echo 'include_HEADERS ='; \ echo 'noinst_LTLIBRARIES ='; \ echo 'lib_LTLIBRARIES ='; \ echo 'EXTRA_LTLIBRARIES ='; \ echo 'EXTRA_DIST ='; \ echo 'CLEANFILES ='; \ echo 'MOSTLYCLEANFILES ='; \ }; \ $(SED) -n '/^.. DO NOT REMOVE THIS LINE -- /,$$p' $$in | \ $(SED) -e 's,libltdl_,,; s,libltdl/,,; s,: libltdl/,: ,' \ -e 's,\$$(libltdl_,$$(,' \ ) | \ $(SED) -e '/^.. DO NOT REMOVE THIS LINE -- /d' \ -e '1s,^\(.. Makefile.\)inc.*,\1am -- Process this file with automake to produce Makefile.in,' > $$out; chmod a-w $(srcdir)/libltdl/Makefile.am all-local: $(LTDL_BOOTSTRAP_DEPS) libtoolize: $(srcdir)/libtoolize.in $(top_builddir)/config.status rm -f libtoolize.tmp libtoolize $(configure_edit) \ $(srcdir)/libtoolize.in > libtoolize.tmp chmod a+x libtoolize.tmp chmod a-w libtoolize.tmp mv -f libtoolize.tmp libtoolize # We used to do this with a 'stamp-vcl' file, but non-gmake builds # would rerun configure on every invocation, so now we manually # check the version numbers from the build rule when necessary. libtool: $(top_builddir)/config.status $(srcdir)/$(auxdir)/ltmain.sh ChangeLog @target=libtool; $(rebuild); \ if test -f "$$target"; then \ set dummy `./$$target --version | sed 1q`; actualver="$$5"; \ test "$$actualver" = "$$correctver" && rebuild=false; \ fi; \ for prereq in $?; do \ case $$prereq in *ChangeLog);; *) rebuild=:;; esac; \ done; \ if $$rebuild; then \ echo $(SHELL) ./config.status $$target; \ cd $(top_builddir) && $(SHELL) ./config.status $$target; \ fi .PHONY: configure-subdirs configure-subdirs distdir: $(DIST_MAKEFILE_LIST) tests/cdemo/Makefile tests/demo/Makefile tests/depdemo/Makefile tests/f77demo/Makefile tests/fcdemo/Makefile tests/mdemo/Makefile tests/mdemo2/Makefile tests/pdemo/Makefile tests/tagdemo/Makefile : dir=`echo $@ | sed 's,^[^/]*$$,.,;s,/[^/]*$$,,'`; \ test -d $$dir || mkdir $$dir || exit 1; \ abs_srcdir=`$(lt__cd) $(srcdir) && pwd`; \ (cd $$dir && $$abs_srcdir/$$dir/configure --with-dist) || exit 1 # We need the following in order to create an <argz.h> when the system # doesn't have one that works with the given compiler. all-local $(lib_OBJECTS): libltdl/$(ARGZ_H) libltdl/argz.h: libltdl/argz_.h $(mkinstalldirs) . libltdl/ cp $(srcdir)/libltdl/argz_.h $@-t mv $@-t $@ $(srcdir)/libltdl/Makefile.in: $(srcdir)/libltdl/Makefile.am \ $(srcdir)/libltdl/aclocal.m4 cd $(srcdir)/libltdl && $(AUTOMAKE) Makefile $(srcdir)/libltdl/stamp-mk: $(srcdir)/libltdl/Makefile.in cd $(srcdir)/libltdl && \ sed -e 's,config/mdate-sh,,' -e 's,config/texinfo.tex,,' \ -e 's,config/mkinstalldirs,,' \ < Makefile.in > Makefile.inT && \ mv -f Makefile.inT Makefile.in echo stamp > $@ $(srcdir)/libltdl/aclocal.m4: $(sub_aclocal_m4_deps) cd $(srcdir)/libltdl && $(ACLOCAL) -I m4 $(srcdir)/libltdl/configure: $(sub_configure_deps) cd $(srcdir)/libltdl && $(AUTOCONF) $(srcdir)/libltdl/config-h.in: $(sub_configure_deps) cd $(srcdir)/libltdl && $(AUTOHEADER) touch $@ all-local: $(srcdir)/doc/notes.txt $(srcdir)/doc/notes.txt: $(srcdir)/doc/notes.texi cd $(srcdir)/doc && \ $(MAKEINFO) --no-headers $(MAKEINFOFLAGS) -o notes.txt notes.texi $(srcdir)/doc/libtool.1: $(srcdir)/$(auxdir)/ltmain.sh $(update_mans) --help-option=--help-all libtool $(srcdir)/doc/libtoolize.1: $(srcdir)/libtoolize.in $(update_mans) libtoolize install-data-local: libltdl/Makefile.in @$(NORMAL_INSTALL) -rm -rf $(DESTDIR)$(pkgdatadir)/* $(mkinstalldirs) $(DESTDIR)$(aclocaldir) @list='$(aclocalfiles)'; for p in $$list; do \ f=`echo "$$p" | sed 's|^.*/||'`; \ echo " $(INSTALL_DATA) '$(srcdir)/$(m4dir)/$$f' '$(DESTDIR)$(aclocaldir)/$$f'"; \ $(INSTALL_DATA) "$(srcdir)/$(m4dir)/$$f" "$(DESTDIR)$(aclocaldir)/$$f"; \ done $(mkinstalldirs) $(DESTDIR)$(pkgdatadir) $(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/config @list='$(auxexefiles)' && for p in $$list; do \ echo " $(INSTALL_SCRIPT) '$(srcdir)/libltdl/$$p' '$(DESTDIR)$(pkgdatadir)/$$p'"; \ $(INSTALL_SCRIPT) "$(srcdir)/libltdl/$$p" "$(DESTDIR)$(pkgdatadir)/$$p"; \ done $(INSTALL_DATA) "$(srcdir)/libltdl/config/ltmain.sh" "$(DESTDIR)$(pkgdatadir)/config/ltmain.sh" $(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/libltdl $(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/libltdl/libltdl $(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/libltdl/loaders @list='$(ltdldatafiles)' && for p in $$list; do \ echo " $(INSTALL_DATA) '$(srcdir)/$$p' '$(DESTDIR)$(pkgdatadir)/$$p'"; \ $(INSTALL_DATA) "$(srcdir)/$$p" "$(DESTDIR)$(pkgdatadir)/$$p"; \ done -chmod a+x $(DESTDIR)$(pkgdatadir)/libltdl/configure uninstall-hook: @$(NORMAL_UNINSTALL) @list='$(ltdldatafiles) $(auxfiles)'; for f in $$list; do \ echo " rm -f '$(DESTDIR)$(pkgdatadir)/$$f'"; \ rm -f "$(DESTDIR)$(pkgdatadir)/$$f"; \ done @for p in $(aclocalfiles); do \ f=`echo "$$p" | sed 's|^.*/||'`; \ echo " rm -f '$(DESTDIR)$(aclocaldir)/$$f'"; \ rm -f "$(DESTDIR)$(aclocaldir)/$$f"; \ done dist-hook: case $(VERSION) in \ *[a-z]) $(SHELL) $(srcdir)/$(edit_readme_alpha) $(distdir)/README ;; \ esac for macro in LT_INIT AC_PROG_LIBTOOL AM_PROG_LIBTOOL; do \ if grep $$macro $(srcdir)/aclocal.m4 $(srcdir)/libltdl/aclocal.m4; then \ echo "Bogus $$macro macro contents in an aclocal.m4 file." >&2; \ exit 1; \ else :; fi; \ done # Use `$(srcdir)' for the benefit of non-GNU makes: this is # how `testsuite' appears in our dependencies. $(srcdir)/$(TESTSUITE): $(srcdir)/tests/package.m4 $(TESTSUITE_AT) Makefile.am cd $(srcdir)/tests && \ $(AUTOTEST) `echo $(TESTSUITE_AT) | sed 's,tests/,,g'` -o testsuite.tmp && \ mv -f testsuite.tmp testsuite $(srcdir)/tests/package.m4: $(srcdir)/configure.ac Makefile.am { \ echo '# Signature of the current package.'; \ echo 'm4_define([AT_PACKAGE_NAME], [GNU Libtool])'; \ echo 'm4_define([AT_PACKAGE_TARNAME], [libtool])'; \ echo 'm4_define([AT_PACKAGE_VERSION], [2.4.2])'; \ echo 'm4_define([AT_PACKAGE_STRING], [GNU Libtool 2.4.2])'; \ echo 'm4_define([AT_PACKAGE_BUGREPORT], [bug-libtool@gnu.org])'; \ echo 'm4_define([AT_PACKAGE_URL], [http://www.gnu.org/software/libtool/])'; \ } | $(bootstrap_edit) > $(srcdir)/tests/package.m4 tests/atconfig: $(top_builddir)/config.status $(SHELL) ./config.status tests/atconfig # Hook the test suite into the check rule check-local: $(testsuite_deps_uninstalled) $(CD_TESTDIR); \ CONFIG_SHELL="$(SHELL)" $(SHELL) $$abs_srcdir/$(TESTSUITE) \ $(TESTS_ENVIRONMENT) $(BUILDCHECK_ENVIRONMENT) $(TESTSUITEFLAGS) # Run the test suite on the *installed* tree. installcheck-local: $(testsuite_deps) $(CD_TESTDIR); \ CONFIG_SHELL="$(SHELL)" $(SHELL) $$abs_srcdir/$(TESTSUITE) \ $(TESTS_ENVIRONMENT) $(INSTALLCHECK_ENVIRONMENT) $(TESTSUITEFLAGS) \ AUTOTEST_PATH="$(exec_prefix)/bin" check-noninteractive-old: $(MAKE) $(AM_MAKEFLAGS) check-TESTS TESTS='$(NONINTERACTIVE_TESTS)' check-interactive-old: $(MAKE) $(AM_MAKEFLAGS) check-TESTS TESTS='$(INTERACTIVE_TESTS)' # Run only noninteractive parts of the new testsuite. check-noninteractive-new: $(testsuite_deps_uninstalled) $(CD_TESTDIR); \ CONFIG_SHELL="$(SHELL)" $(SHELL) $$abs_srcdir/$(TESTSUITE) \ $(TESTS_ENVIRONMENT) $(BUILDCHECK_ENVIRONMENT) \ -k !interactive INNER_TESTSUITEFLAGS=",!interactive" \ $(TESTSUITEFLAGS) # Run only interactive parts of the new testsuite. check-interactive-new: $(testsuite_deps_uninstalled) $(CD_TESTDIR); \ CONFIG_SHELL="$(SHELL)" $(SHELL) $$abs_srcdir/$(TESTSUITE) \ $(TESTS_ENVIRONMENT) $(BUILDCHECK_ENVIRONMENT) \ -k interactive -k recursive INNER_TESTSUITEFLAGS=",interactive" \ $(TESTSUITEFLAGS) check-interactive: check-interactive-old check-interactive-new check-noninteractive: check-noninteractive-old check-noninteractive-new # We need to remove any file droppings left behind by testsuite clean-local: clean-local-legacy -$(CD_TESTDIR); \ test -f $$abs_srcdir/$(TESTSUITE) && \ $(SHELL) $$abs_srcdir/$(TESTSUITE) --clean tests/tagdemo-undef-exec.log: tests/tagdemo-undef-make.log tests/tagdemo-undef-make.log: tests/tagdemo-undef.log tests/tagdemo-undef.log: tests/tagdemo-shared-exec.log tests/tagdemo-shared-exec.log: tests/tagdemo-shared-make.log tests/tagdemo-shared-make.log: tests/tagdemo-shared.log tests/tagdemo-shared.log: tests/tagdemo-exec.log tests/tagdemo-exec.log: tests/tagdemo-make.log tests/tagdemo-make.log: tests/tagdemo-conf.log tests/tagdemo-conf.log: tests/tagdemo-static-exec.log tests/tagdemo-static-exec.log: tests/tagdemo-static-make.log tests/tagdemo-static-make.log: tests/tagdemo-static.log tests/f77demo-shared-exec.log: tests/f77demo-shared-make.log tests/f77demo-shared-make.log: tests/f77demo-shared.log tests/f77demo-shared.log: tests/f77demo-exec.log tests/f77demo-exec.log: tests/f77demo-make.log tests/f77demo-make.log: tests/f77demo-conf.log tests/f77demo-conf.log: tests/f77demo-static-exec.log tests/f77demo-static-exec.log: tests/f77demo-static-make.log tests/f77demo-static-make.log: tests/f77demo-static.log tests/fcdemo-shared-exec.log: tests/fcdemo-shared-make.log tests/fcdemo-shared-make.log: tests/fcdemo-shared.log tests/fcdemo-shared.log: tests/fcdemo-exec.log tests/fcdemo-exec.log: tests/fcdemo-make.log tests/fcdemo-make.log: tests/fcdemo-conf.log tests/fcdemo-conf.log: tests/fcdemo-static-exec.log tests/fcdemo-static-exec.log: tests/fcdemo-static-make.log tests/fcdemo-static-make.log: tests/fcdemo-static.log tests/cdemo-undef-exec.log: tests/cdemo-undef-make.log tests/cdemo-undef-make.log: tests/cdemo-undef.log tests/cdemo-undef.log: | tests/cdemo-shared-exec.log tests/cdemo-shared-exec.log: tests/cdemo-shared-make.log tests/cdemo-shared-make.log: tests/cdemo-shared.log tests/cdemo-shared.log: | tests/cdemo-exec.log tests/cdemo-exec.log: tests/cdemo-make.log tests/cdemo-make.log: tests/cdemo-conf.log tests/cdemo-conf.log: | tests/cdemo-static-exec.log tests/cdemo-static-exec.log: tests/cdemo-static-make.log tests/cdemo-static-make.log: tests/cdemo-static.log tests/demo-shared-unst.log: tests/demo-noinst-link.log tests/demo-noinst-link.log: tests/demo-relink.log tests/demo-relink.log: tests/demo-hardcode.log tests/demo-hardcode.log: tests/demo-shared-inst.log tests/demo-shared-inst.log: tests/demo-shared-exec.log tests/demo-shared-exec.log: tests/demo-shared-make.log tests/demo-shared-make.log: tests/demo-shared.log tests/demo-shared.log: | tests/demo-nopic-exec.log tests/demo-nopic-exec.log: tests/demo-nopic-make.log tests/demo-nopic-make.log: tests/demo-nopic.log tests/demo-nopic.log: | tests/demo-pic-exec.log tests/demo-pic-exec.log: tests/demo-pic-make.log tests/demo-pic-make.log: tests/demo-pic.log tests/demo-pic.log: | tests/demo-nofast-unst.log tests/demo-nofast-unst.log: tests/demo-nofast-inst.log tests/demo-nofast-inst.log: tests/demo-nofast-exec.log tests/demo-nofast-exec.log: tests/demo-nofast-make.log tests/demo-nofast-make.log: tests/demo-nofast.log tests/demo-nofast.log: | tests/demo-deplibs.log tests/demo-deplibs.log: tests/demo-unst.log tests/demo-unst.log: tests/demo-inst.log tests/demo-inst.log: tests/demo-exec.log tests/demo-exec.log: tests/demo-make.log tests/demo-make.log: tests/demo-conf.log tests/demo-conf.log: | tests/demo-static-unst.log tests/demo-static-unst.log: tests/demo-static-inst.log tests/demo-static-inst.log: tests/demo-static-exec.log tests/demo-static-exec.log: tests/demo-static-make.log tests/demo-static-make.log: tests/demo-static.log tests/depdemo-shared-unst.log: tests/depdemo-relink.log tests/depdemo-relink.log: tests/depdemo-shared-inst.log tests/depdemo-shared-inst.log: tests/depdemo-shared-exec.log tests/depdemo-shared-exec.log: tests/depdemo-shared-make.log tests/depdemo-shared-make.log: tests/depdemo-shared.log tests/depdemo-shared.log: | tests/depdemo-nofast-unst.log tests/depdemo-nofast-unst.log: tests/depdemo-nofast-inst.log tests/depdemo-nofast-inst.log: tests/depdemo-nofast-exec.log tests/depdemo-nofast-exec.log: tests/depdemo-nofast-make.log tests/depdemo-nofast-make.log: tests/depdemo-nofast.log tests/depdemo-nofast.log: | tests/depdemo-unst.log tests/depdemo-unst.log: tests/depdemo-inst.log tests/depdemo-inst.log: tests/depdemo-exec.log tests/depdemo-exec.log: tests/depdemo-make.log tests/depdemo-make.log: tests/depdemo-conf.log tests/depdemo-conf.log: | tests/depdemo-static-unst.log tests/depdemo-static-unst.log: tests/depdemo-static-inst.log tests/depdemo-static-inst.log: tests/depdemo-static-exec.log tests/depdemo-static-exec.log: tests/depdemo-static-make.log tests/depdemo-static-make.log: tests/depdemo-static.log tests/mdemo-shared-unst.log: tests/mdemo-shared-inst.log tests/mdemo-shared-inst.log: tests/mdemo-shared-exec.log tests/mdemo-shared-exec.log: tests/mdemo-shared-make.log tests/mdemo-shared-make.log: tests/mdemo-shared.log tests/mdemo-shared.log: | tests/mdemo-dryrun.log \ tests/mdemo2-exec.log tests/mdemo-dryrun.log: tests/mdemo-unst.log tests/mdemo-unst.log: tests/mdemo-inst.log tests/mdemo-inst.log: tests/mdemo-exec.log tests/mdemo-exec.log: tests/mdemo-make.log tests/mdemo-make.log: tests/mdemo-conf.log tests/mdemo-conf.log: | tests/mdemo-static-unst.log tests/mdemo-static-unst.log: tests/mdemo-static-inst.log tests/mdemo-static-inst.log: tests/mdemo-static-exec.log tests/mdemo-static-exec.log: tests/mdemo-static-make.log tests/mdemo-static-make.log: tests/mdemo-static.log tests/mdemo2-exec.log: tests/mdemo2-make.log tests/mdemo2-make.log: tests/mdemo2-conf.log \ tests/mdemo-dryrun.log tests/pdemo-inst.log: tests/pdemo-exec.log tests/pdemo-exec.log: tests/pdemo-make.log tests/pdemo-make.log: tests/pdemo-conf.log # The defs script shouldn't be recreated whenever the Makefile is # regenerated since the source tree can be read-only. check-recursive: tests/defs tests/defs: $(srcdir)/tests/defs.in rm -f tests/defs.tmp tests/defs; \ $(configure_edit) $(srcdir)/tests/defs.in > tests/defs.tmp; \ mv -f tests/defs.tmp tests/defs # Use `$(srcdir)/tests' for the benefit of non-GNU makes: this is # how defs.in appears in our dependencies. $(srcdir)/tests/defs.in: $(auxdir)/general.m4sh tests/defs.m4sh Makefile.am cd $(srcdir); \ rm -f tests/defs.in; \ $(M4SH) -B $(auxdir) tests/defs.m4sh > tests/defs.in # We need to remove any files that the above tests created. clean-local-legacy: -for dir in $(CONF_SUBDIRS); do \ if test -f $$dir/Makefile; then \ (cd $$dir && $(MAKE) $(AM_MAKEFLAGS) distclean); \ else :; fi; \ done rm -rf _inst _inst-* $(distclean_recursive): fake-distclean-legacy .PHONY: fake-distclean-legacy fake-distclean-legacy: -for dir in $(CONF_SUBDIRS); do \ if test ! -f $$dir/Makefile; then \ $(mkinstalldirs) $$dir; \ echo 'distclean: ; rm -f Makefile' > $$dir/Makefile; \ else :; fi; \ done $(TESTS): tests/defs # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
Java
#include <iomanip> #include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n, p_i; cin >> n; double total = 0.0; for (size_t i = 0; i < n; i++) { cin >> p_i; total += p_i; } cout << setprecision(12) << fixed << (total / n) << endl; }
Java
<?php /** * @package SP Page Builder * @author JoomShaper http://www.joomshaper.com * @copyright Copyright (c) 2010 - 2016 JoomShaper * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later */ //no direct accees defined ('_JEXEC') or die ('restricted access'); class SppagebuilderAddonTab extends SppagebuilderAddons { public function render() { $class = (isset($this->addon->settings->class) && $this->addon->settings->class) ? $this->addon->settings->class : ''; $style = (isset($this->addon->settings->style) && $this->addon->settings->style) ? $this->addon->settings->style : ''; $title = (isset($this->addon->settings->title) && $this->addon->settings->title) ? $this->addon->settings->title : ''; $heading_selector = (isset($this->addon->settings->heading_selector) && $this->addon->settings->heading_selector) ? $this->addon->settings->heading_selector : 'h3'; //Output $output = '<div class="sppb-addon sppb-addon-tab ' . $class . '">'; $output .= ($title) ? '<'.$heading_selector.' class="sppb-addon-title">' . $title . '</'.$heading_selector.'>' : ''; $output .= '<div class="sppb-addon-content sppb-tab">'; //Tab Title $output .='<ul class="sppb-nav sppb-nav-' . $style . '">'; foreach ($this->addon->settings->sp_tab_item as $key => $tab) { $title = (isset($tab->icon) && $tab->icon) ? '<i class="fa ' . $tab->icon . '"></i> ' . $tab->title : $tab->title; $output .='<li class="'. ( ($key==0) ? "active" : "").'"><a data-toggle="sppb-tab" href="#sppb-tab-'. ($this->addon->id + $key) .'">'. $title .'</a></li>'; } $output .='</ul>'; //Tab Contnet $output .='<div class="sppb-tab-content sppb-nav-' . $style . '-content">'; foreach ($this->addon->settings->sp_tab_item as $key => $tab) { $output .='<div id="sppb-tab-'. ($this->addon->id + $key) .'" class="sppb-tab-pane sppb-fade'. ( ($key==0) ? " active in" : "").'">' . $tab->content .'</div>'; } $output .='</div>'; $output .= '</div>'; $output .= '</div>'; return $output; } public function css() { $addon_id = '#sppb-addon-' . $this->addon->id; $tab_style = (isset($this->addon->settings->style) && $this->addon->settings->style) ? $this->addon->settings->style : ''; $style = (isset($this->addon->settings->active_tab_color) && $this->addon->settings->active_tab_color) ? 'color: ' . $this->addon->settings->active_tab_color . ';': ''; $css = ''; if($tab_style == 'pills') { $style .= (isset($this->addon->settings->active_tab_bg) && $this->addon->settings->active_tab_bg) ? 'background-color: ' . $this->addon->settings->active_tab_bg . ';': ''; if($style) { $css .= $addon_id . ' .sppb-nav-pills > li.active > a,' . $addon_id . ' .sppb-nav-pills > li.active > a:hover,' . $addon_id . ' .sppb-nav-pills > li.active > a:focus {'; $css .= $style; $css .= '}'; } } else if ($tab_style == 'lines') { $style .= (isset($this->addon->settings->active_tab_bg) && $this->addon->settings->active_tab_bg) ? 'border-bottom-color: ' . $this->addon->settings->active_tab_bg . ';': ''; if($style) { $css .= $addon_id . ' .sppb-nav-lines > li.active > a,' . $addon_id . ' .sppb-nav-lines > li.active > a:hover,' . $addon_id . ' .sppb-nav-lines > li.active > a:focus {'; $css .= $style; $css .= '}'; } } return $css; } }
Java
/* Copyright (C) 1997-2001 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "g_local.h" #ifdef IML_Q2_EXTENSIONS #include <stdio.h> #include "binmsg.h" #endif // IML_Q2_EXTENSIONS void InitTrigger (edict_t *self) { if (!VectorCompare (self->s.angles, vec3_origin)) G_SetMovedir (self->s.angles, self->movedir); self->solid = SOLID_TRIGGER; self->movetype = MOVETYPE_NONE; gi.setmodel (self, self->model); self->svflags = SVF_NOCLIENT; } // the wait time has passed, so set back up for another activation void multi_wait (edict_t *ent) { ent->nextthink = 0; } // the trigger was just activated // ent->activator should be set to the activator so it can be held through a delay // so wait for the delay time before firing void multi_trigger (edict_t *ent) { if (ent->nextthink) return; // already been triggered G_UseTargets (ent, ent->activator); if (ent->wait > 0) { ent->think = multi_wait; ent->nextthink = level.time + ent->wait; } else { // we can't just remove (self) here, because this is a touch function // called while looping through area links... ent->touch = NULL; ent->nextthink = level.time + FRAMETIME; ent->think = G_FreeEdict; } } void Use_Multi (edict_t *ent, edict_t *other, edict_t *activator) { ent->activator = activator; multi_trigger (ent); } void Touch_Multi (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { if(other->client) { if (self->spawnflags & 2) return; } else if (other->svflags & SVF_MONSTER) { if (!(self->spawnflags & 1)) return; } else return; if (!VectorCompare(self->movedir, vec3_origin)) { vec3_t forward; AngleVectors(other->s.angles, forward, NULL, NULL); if (_DotProduct(forward, self->movedir) < 0) return; } self->activator = other; multi_trigger (self); } /*QUAKED trigger_multiple (.5 .5 .5) ? MONSTER NOT_PLAYER TRIGGERED Variable sized repeatable trigger. Must be targeted at one or more entities. If "delay" is set, the trigger waits some time after activating before firing. "wait" : Seconds between triggerings. (.2 default) sounds 1) secret 2) beep beep 3) large switch 4) set "message" to text string */ void trigger_enable (edict_t *self, edict_t *other, edict_t *activator) { self->solid = SOLID_TRIGGER; self->use = Use_Multi; gi.linkentity (self); } void SP_trigger_multiple (edict_t *ent) { if (ent->sounds == 1) ent->noise_index = gi.soundindex ("misc/secret.wav"); else if (ent->sounds == 2) ent->noise_index = gi.soundindex ("misc/talk.wav"); else if (ent->sounds == 3) ent->noise_index = gi.soundindex ("misc/trigger1.wav"); if (!ent->wait) ent->wait = 0.2; ent->touch = Touch_Multi; ent->movetype = MOVETYPE_NONE; ent->svflags |= SVF_NOCLIENT; if (ent->spawnflags & 4) { ent->solid = SOLID_NOT; ent->use = trigger_enable; } else { ent->solid = SOLID_TRIGGER; ent->use = Use_Multi; } if (!VectorCompare(ent->s.angles, vec3_origin)) G_SetMovedir (ent->s.angles, ent->movedir); gi.setmodel (ent, ent->model); gi.linkentity (ent); } /*QUAKED trigger_once (.5 .5 .5) ? x x TRIGGERED Triggers once, then removes itself. You must set the key "target" to the name of another object in the level that has a matching "targetname". If TRIGGERED, this trigger must be triggered before it is live. sounds 1) secret 2) beep beep 3) large switch 4) "message" string to be displayed when triggered */ void SP_trigger_once(edict_t *ent) { // make old maps work because I messed up on flag assignments here // triggered was on bit 1 when it should have been on bit 4 if (ent->spawnflags & 1) { vec3_t v; VectorMA (ent->mins, 0.5, ent->size, v); ent->spawnflags &= ~1; ent->spawnflags |= 4; gi.dprintf("fixed TRIGGERED flag on %s at %s\n", ent->classname, vtos(v)); } ent->wait = -1; SP_trigger_multiple (ent); } /*QUAKED trigger_relay (.5 .5 .5) (-8 -8 -8) (8 8 8) This fixed size trigger cannot be touched, it can only be fired by other events. */ void trigger_relay_use (edict_t *self, edict_t *other, edict_t *activator) { G_UseTargets (self, activator); } void SP_trigger_relay (edict_t *self) { self->use = trigger_relay_use; } /* ============================================================================== trigger_key ============================================================================== */ /*QUAKED trigger_key (.5 .5 .5) (-8 -8 -8) (8 8 8) A relay trigger that only fires it's targets if player has the proper key. Use "item" to specify the required key, for example "key_data_cd" */ void trigger_key_use (edict_t *self, edict_t *other, edict_t *activator) { int index; if (!self->item) return; if (!activator->client) return; index = ITEM_INDEX(self->item); if (!activator->client->pers.inventory[index]) { if (level.time < self->touch_debounce_time) return; self->touch_debounce_time = level.time + 5.0; gi.centerprintf (activator, "You need the %s", self->item->pickup_name); gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/keytry.wav"), 1, ATTN_NORM, 0); return; } gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/keyuse.wav"), 1, ATTN_NORM, 0); if (coop->value) { int player; edict_t *ent; if (strcmp(self->item->classname, "key_power_cube") == 0) { int cube; for (cube = 0; cube < 8; cube++) if (activator->client->pers.power_cubes & (1 << cube)) break; for (player = 1; player <= game.maxclients; player++) { ent = &g_edicts[player]; if (!ent->inuse) continue; if (!ent->client) continue; if (ent->client->pers.power_cubes & (1 << cube)) { ent->client->pers.inventory[index]--; ent->client->pers.power_cubes &= ~(1 << cube); } } } else { for (player = 1; player <= game.maxclients; player++) { ent = &g_edicts[player]; if (!ent->inuse) continue; if (!ent->client) continue; ent->client->pers.inventory[index] = 0; } } } else { activator->client->pers.inventory[index]--; } G_UseTargets (self, activator); self->use = NULL; } void SP_trigger_key (edict_t *self) { if (!st.item) { gi.dprintf("no key item for trigger_key at %s\n", vtos(self->s.origin)); return; } self->item = FindItemByClassname (st.item); if (!self->item) { gi.dprintf("item %s not found for trigger_key at %s\n", st.item, vtos(self->s.origin)); return; } if (!self->target) { gi.dprintf("%s at %s has no target\n", self->classname, vtos(self->s.origin)); return; } gi.soundindex ("misc/keytry.wav"); gi.soundindex ("misc/keyuse.wav"); self->use = trigger_key_use; } /* ============================================================================== trigger_counter ============================================================================== */ /*QUAKED trigger_counter (.5 .5 .5) ? nomessage Acts as an intermediary for an action that takes multiple inputs. If nomessage is not set, t will print "1 more.. " etc when triggered and "sequence complete" when finished. After the counter has been triggered "count" times (default 2), it will fire all of it's targets and remove itself. */ void trigger_counter_use(edict_t *self, edict_t *other, edict_t *activator) { if (self->count == 0) return; self->count--; if (self->count) { if (! (self->spawnflags & 1)) { gi.centerprintf(activator, "%i more to go...", self->count); gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/talk1.wav"), 1, ATTN_NORM, 0); } return; } if (! (self->spawnflags & 1)) { gi.centerprintf(activator, "Sequence completed!"); gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/talk1.wav"), 1, ATTN_NORM, 0); } self->activator = activator; multi_trigger (self); } void SP_trigger_counter (edict_t *self) { self->wait = -1; if (!self->count) self->count = 2; self->use = trigger_counter_use; } /* ============================================================================== trigger_always ============================================================================== */ /*QUAKED trigger_always (.5 .5 .5) (-8 -8 -8) (8 8 8) This trigger will always fire. It is activated by the world. */ void SP_trigger_always (edict_t *ent) { // we must have some delay to make sure our use targets are present if (ent->delay < 0.2) ent->delay = 0.2; G_UseTargets(ent, ent); } /* ============================================================================== trigger_push ============================================================================== */ #define PUSH_ONCE 1 static int windsound; void trigger_push_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { if (strcmp(other->classname, "grenade") == 0) { VectorScale (self->movedir, self->speed * 10, other->velocity); } else if (other->health > 0) { VectorScale (self->movedir, self->speed * 10, other->velocity); if (other->client) { // don't take falling damage immediately from this VectorCopy (other->velocity, other->client->oldvelocity); if (other->fly_sound_debounce_time < level.time) { other->fly_sound_debounce_time = level.time + 1.5; gi.sound (other, CHAN_AUTO, windsound, 1, ATTN_NORM, 0); } } } if (self->spawnflags & PUSH_ONCE) G_FreeEdict (self); } /*QUAKED trigger_push (.5 .5 .5) ? PUSH_ONCE Pushes the player "speed" defaults to 1000 */ void SP_trigger_push (edict_t *self) { InitTrigger (self); windsound = gi.soundindex ("misc/windfly.wav"); self->touch = trigger_push_touch; if (!self->speed) self->speed = 1000; gi.linkentity (self); } /* ============================================================================== trigger_hurt ============================================================================== */ /*QUAKED trigger_hurt (.5 .5 .5) ? START_OFF TOGGLE SILENT NO_PROTECTION SLOW Any entity that touches this will be hurt. It does dmg points of damage each server frame SILENT supresses playing the sound SLOW changes the damage rate to once per second NO_PROTECTION *nothing* stops the damage "dmg" default 5 (whole numbers only) */ void hurt_use (edict_t *self, edict_t *other, edict_t *activator) { if (self->solid == SOLID_NOT) self->solid = SOLID_TRIGGER; else self->solid = SOLID_NOT; gi.linkentity (self); if (!(self->spawnflags & 2)) self->use = NULL; } void hurt_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { int dflags; if (!other->takedamage) return; if (self->timestamp > level.time) return; if (self->spawnflags & 16) self->timestamp = level.time + 1; else self->timestamp = level.time + FRAMETIME; if (!(self->spawnflags & 4)) { if ((level.framenum % 10) == 0) gi.sound (other, CHAN_AUTO, self->noise_index, 1, ATTN_NORM, 0); } if (self->spawnflags & 8) dflags = DAMAGE_NO_PROTECTION; else dflags = 0; T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, self->dmg, dflags, MOD_TRIGGER_HURT); } void SP_trigger_hurt (edict_t *self) { InitTrigger (self); self->noise_index = gi.soundindex ("world/electro.wav"); self->touch = hurt_touch; if (!self->dmg) self->dmg = 5; if (self->spawnflags & 1) self->solid = SOLID_NOT; else self->solid = SOLID_TRIGGER; if (self->spawnflags & 2) self->use = hurt_use; gi.linkentity (self); } /* ============================================================================== trigger_gravity ============================================================================== */ /*QUAKED trigger_gravity (.5 .5 .5) ? Changes the touching entites gravity to the value of "gravity". 1.0 is standard gravity for the level. */ void trigger_gravity_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { other->gravity = self->gravity; } void SP_trigger_gravity (edict_t *self) { if (st.gravity == 0) { gi.dprintf("trigger_gravity without gravity set at %s\n", vtos(self->s.origin)); G_FreeEdict (self); return; } InitTrigger (self); self->gravity = atoi(st.gravity); self->touch = trigger_gravity_touch; } /* ============================================================================== trigger_monsterjump ============================================================================== */ /*QUAKED trigger_monsterjump (.5 .5 .5) ? Walking monsters that touch this will jump in the direction of the trigger's angle "speed" default to 200, the speed thrown forward "height" default to 200, the speed thrown upwards */ void trigger_monsterjump_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { if (other->flags & (FL_FLY | FL_SWIM) ) return; if (other->svflags & SVF_DEADMONSTER) return; if ( !(other->svflags & SVF_MONSTER)) return; // set XY even if not on ground, so the jump will clear lips other->velocity[0] = self->movedir[0] * self->speed; other->velocity[1] = self->movedir[1] * self->speed; if (!other->groundentity) return; other->groundentity = NULL; other->velocity[2] = self->movedir[2]; } void SP_trigger_monsterjump (edict_t *self) { if (!self->speed) self->speed = 200; if (!st.height) st.height = 200; if (self->s.angles[YAW] == 0) self->s.angles[YAW] = 360; InitTrigger (self); self->touch = trigger_monsterjump_touch; self->movedir[2] = st.height; } /* ============================================================================== trigger_region ============================================================================== */ #ifdef IML_Q2_EXTENSIONS static void AddRegion(edict_t *player, edict_t *region) { int i; for (i = 0; i < MAX_REGIONS; i++) { if (player->client->in_regions[i] == region) { break; } else if (player->client->in_regions[i] == NULL) { player->client->in_regions[i] = region; break; } } } void trigger_region_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { if (other->client) AddRegion(other, self); } void SP_trigger_region (edict_t *self) { InitTrigger (self); self->touch = &trigger_region_touch; } static qboolean EntityInList (edict_t *ent, edict_t **list, size_t items) { int i; for (i = 0; i < items; i++) if (list[i] == ent) return true; return false; } static void SendBinMsg_InRegion(edict_t *player, char *region_name, qboolean is_in_region) { char key[MAX_STRING_CHARS]; binmsg_byte buffer[BINMSG_MAX_SIZE]; binmsg_message msg; // Format our key name. _snprintf(key, sizeof(key), "in-region?/%s", region_name); key[MAX_STRING_CHARS-1] = '\0'; // Build and send the message. if (!binmsg_build(&msg, buffer, BINMSG_MAX_SIZE, "state")) return; if (!binmsg_add_string(&msg.args, key)) return; if (!binmsg_add_bool(&msg.args, is_in_region)) return; if (!binmsg_build_done(&msg)) return; SendBinMsg(player, msg.buffer, msg.buffer_size); } static void ExitRegion (edict_t *player, edict_t *region) { if (region->region_name) SendBinMsg_InRegion(player, region->region_name, false); if (region->exit_target) G_UseTargetsByName(region, region->exit_target, player); } static void EnterRegion (edict_t *player, edict_t *region) { if (region->region_name) SendBinMsg_InRegion(player, region->region_name, true); if (region->enter_target) G_UseTargetsByName(region, region->enter_target, player); } void CheckRegions (edict_t *player) { int i; // Send exit messages. for (i = 0; i < MAX_REGIONS; i++) if (!EntityInList(player->client->in_regions_old[i], player->client->in_regions, MAX_REGIONS)) ExitRegion(player, player->client->in_regions_old[i]); // Send enter messages. for (i = 0; i < MAX_REGIONS; i++) if (!EntityInList(player->client->in_regions[i], player->client->in_regions_old, MAX_REGIONS)) EnterRegion(player, player->client->in_regions[i]); // Move in_regions to in_regions_old and clear in_regions. memcpy(player->client->in_regions_old, player->client->in_regions, sizeof(edict_t*) * MAX_REGIONS); memset(player->client->in_regions, 0, sizeof(edict_t*) * MAX_REGIONS); } #endif // IML_Q2_EXTENSIONS
Java
#include "capwap.h" #include "capwap_element.h" /******************************************************************** 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Radio ID | MAC Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | MAC Address | QoS Sub-Element... | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 0 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Reserved|8021p|RSV| DSCP Tag | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Type: 1043 for IEEE 802.11 Update Station QoS Length: 14 ********************************************************************/ /* */ static void capwap_80211_updatestationqos_element_create(void* data, capwap_message_elements_handle handle, struct capwap_write_message_elements_ops* func) { int i; struct capwap_80211_updatestationqos_element* element = (struct capwap_80211_updatestationqos_element*)data; ASSERT(data != NULL); func->write_u8(handle, element->radioid); func->write_block(handle, element->address, MACADDRESS_EUI48_LENGTH); for (i = 0; i < CAPWAP_UPDATE_STATION_QOS_SUBELEMENTS; i++) { func->write_u8(handle, element->qos[i].priority8021p & CAPWAP_UPDATE_STATION_QOS_PRIORIY_MASK); func->write_u8(handle, element->qos[i].dscp & CAPWAP_UPDATE_STATION_QOS_DSCP_MASK); } } /* */ static void* capwap_80211_updatestationqos_element_parsing(capwap_message_elements_handle handle, struct capwap_read_message_elements_ops* func) { int i; struct capwap_80211_updatestationqos_element* data; ASSERT(handle != NULL); ASSERT(func != NULL); if (func->read_ready(handle) != 14) { capwap_logging_debug("Invalid IEEE 802.11 Update Station QoS element"); return NULL; } /* */ data = (struct capwap_80211_updatestationqos_element*)capwap_alloc(sizeof(struct capwap_80211_updatestationqos_element)); memset(data, 0, sizeof(struct capwap_80211_updatestationqos_element)); /* Retrieve data */ func->read_u8(handle, &data->radioid); func->read_block(handle, data->address, MACADDRESS_EUI48_LENGTH); for (i = 0; i < CAPWAP_UPDATE_STATION_QOS_SUBELEMENTS; i++) { func->read_u8(handle, &data->qos[i].priority8021p); data->qos[i].priority8021p &= CAPWAP_UPDATE_STATION_QOS_PRIORIY_MASK; func->read_u8(handle, &data->qos[i].dscp); data->qos[i].dscp &= CAPWAP_UPDATE_STATION_QOS_DSCP_MASK; } return data; } /* */ static void* capwap_80211_updatestationqos_element_clone(void* data) { ASSERT(data != NULL); return capwap_clone(data, sizeof(struct capwap_80211_updatestationqos_element)); } /* */ static void capwap_80211_updatestationqos_element_free(void* data) { ASSERT(data != NULL); capwap_free(data); } /* */ struct capwap_message_elements_ops capwap_element_80211_updatestationqos_ops = { .create_message_element = capwap_80211_updatestationqos_element_create, .parsing_message_element = capwap_80211_updatestationqos_element_parsing, .clone_message_element = capwap_80211_updatestationqos_element_clone, .free_message_element = capwap_80211_updatestationqos_element_free };
Java
/* * This file is part of Libav. * * Libav is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Libav is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * null audio source */ #include <inttypes.h> #include <stdio.h> #include "libavutil/channel_layout.h" #include "libavutil/internal.h" #include "avfilter.h" #include "internal.h" static int request_frame(AVFilterLink *link) { return AVERROR_EOF; } static const AVFilterPad avfilter_asrc_anullsrc_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_AUDIO, .request_frame = request_frame, }, { NULL } }; AVFilter avfilter_asrc_anullsrc = { .name = "anullsrc", .description = NULL_IF_CONFIG_SMALL("Null audio source, never return audio frames."), .inputs = NULL, .outputs = avfilter_asrc_anullsrc_outputs, };
Java
var ajaxManager = (function() { $jq = jQuery.noConflict(); var requests = []; return { addReq: function(opt) { requests.push(opt); }, removeReq: function(opt) { if($jq.inArray(opt, requests) > -1) { requests.splice($jq.inArray(opt, requests), 1); } }, run: function() { var self = this, orgSuc; if(requests.length) { oriSuc = requests[0].complete; requests[0].complete = function() { if(typeof oriSuc === 'function') { oriSuc(); } requests.shift(); self.run.apply(self, []); }; $jq.ajax(requests[0]); } else { self.tid = setTimeout(function() { self.run.apply(self, []); }, 1000); } }, stop: function() { requests = []; clearTimeout(this.tid); } }; }()); ajaxManager.run(); (function($){ $(document).ready(function(){ $('.purAddToCart, .purAddToCartImage').click(function() { $(this).attr('disabled', 'disabled'); }) $('.Cart66AjaxWarning').hide(); // Added to remove error on double-click when add to cart is clicked $('.purAddToCart, .purAddToCartImage').click(function() { $(this).attr('disabled', 'disabled'); }) $('.ajax-button').click(function() { $(this).attr('disabled', true); var id = $(this).attr('id').replace('addToCart_', ''); $('#task_' + id).val('ajax'); var product = C66.products[id]; if(C66.trackInventory) { inventoryCheck(id, C66.ajaxurl, product.ajax, product.name, product.returnUrl, product.addingText); } else { if(product.ajax === 'no') { $('#task_' + id).val('addToCart'); $('#cartButtonForm_' + id).submit(); return false; } else if(product.ajax === 'yes' || product.ajax === 'true') { buttonTransform(id, C66.ajaxurl, product.name, product.returnUrl, product.addingText); } } return false; }); $('.modalClose').click(function() { $('.Cart66Unavailable, .Cart66Warning, .Cart66Error, .alert-message').fadeOut(800); }); $('#Cart66CancelPayPalSubscription').click(function() { return confirm('Are you sure you want to cancel your subscription?\n'); }); var original_methods = $('#shipping_method_id').html(); var selected_country = $('#shipping_country_code').val(); $('.methods-country').each(function() { if(!$(this).hasClass(selected_country) && !$(this).hasClass('all-countries') && !$(this).hasClass('select')) { $(this).remove(); } }); $('#shipping_country_code').change(function() { var selected_country = $(this).val(); $('#shipping_method_id').html(original_methods); $('.methods-country').each(function() { if(!$(this).hasClass(selected_country) && !$(this).hasClass('all-countries') && !$(this).hasClass('select')) { $(this).remove(); } }); $("#shipping_method_id option:eq(1)").attr('selected','selected').change(); }); $('#shipping_method_id').change(function() { $('#Cart66CartForm').submit(); }); $('#live_rates').change(function() { $('#Cart66CartForm').submit(); }); $('.showEntriesLink').click(function() { var panel = $(this).attr('rel'); $('#' + panel).toggle(); return false; }); $('#change_shipping_zip_link').click(function() { $('#set_shipping_zip_row').toggle(); return false; }); }) })(jQuery); function getCartButtonFormData(formId) { $jq = jQuery.noConflict(); var theForm = $jq('#' + formId); var str = ''; $jq('input:not([type=checkbox], :radio), input[type=checkbox]:checked, input:radio:checked, select, textarea', theForm).each( function() { var name = $jq(this).attr('name'); var val = $jq(this).val(); str += name + '=' + encodeURIComponent(val) + '&'; } ); return str.substring(0, str.length-1); } function inventoryCheck(formId, ajaxurl, useAjax, productName, productUrl, addingText) { $jq = jQuery.noConflict(); var mydata = getCartButtonFormData('cartButtonForm_' + formId); ajaxManager.addReq({ type: "POST", url: ajaxurl + '=1', data: mydata, dataType: 'json', success: function(response) { if(response[0]) { $jq('#task_' + formId).val('addToCart'); if(useAjax == 'no') { $jq('#cartButtonForm_' + formId).submit(); } else { buttonTransform(formId, ajaxurl, productName, productUrl, addingText); } } else { $jq('.modalClose').show(); $jq('#stock_message_box_' + formId).fadeIn(300); $jq('#stock_message_' + formId).html(response[1]); $jq('#addToCart_' + formId).removeAttr('disabled'); } }, error: function(xhr,err){ alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status); } }); } function addToCartAjax(formId, ajaxurl, productName, productUrl, buttonText) { $jq = jQuery.noConflict(); var options1 = $jq('#cartButtonForm_' + formId + ' .cart66Options.options_1').val(); var options2 = $jq('#cartButtonForm_' + formId + ' .cart66Options.options_2').val(); var itemQuantity = $jq('#Cart66UserQuantityInput_' + formId).val(); var itemUserPrice = $jq('#Cart66UserPriceInput_' + formId).val(); var cleanProductId = formId.split('_'); cleanProductId = cleanProductId[0]; var data = { cart66ItemId: cleanProductId, itemName: productName, options_1: options1, options_2: options2, item_quantity: itemQuantity, item_user_price: itemUserPrice, product_url: productUrl }; ajaxManager.addReq({ type: "POST", url: ajaxurl + '=2', data: data, dataType: 'json', success: function(response) { $jq('#addToCart_' + formId).removeAttr('disabled'); $jq('#addToCart_' + formId).removeClass('ajaxPurAddToCart'); $jq('#addToCart_' + formId).val(buttonText); $jq.hookExecute('addToCartAjaxHook', response); ajaxUpdateCartWidgets(ajaxurl); if($jq('.customAjaxAddToCartMessage').length > 0) { $jq('.customAjaxAddToCartMessage').show().html(response.msg); $jq.hookExecute('customAjaxAddToCartMessage', response); } else { if((response.msgId) == 0){ $jq('.success_' + formId).fadeIn(300); $jq('.success_message_' + formId).html(response.msg); if(typeof response.msgHeader !== 'undefined') { $jq('.success' + formId + ' .message-header').html(response.msgHeader); } $jq('.success_' + formId).delay(2000).fadeOut(300); } if((response.msgId) == -1){ $jq('.warning_' + formId).fadeIn(300); $jq('.warning_message_' + formId).html(response.msg); if(typeof response.msgHeader !== 'undefined') { $jq('.warning' + formId + ' .message-header').html(response.msgHeader); } } if((response.msgId) == -2){ $jq('.error_' + formId).fadeIn(300); $jq('.error_message_' + formId).html(response.msg); if(typeof response.msgHeader !== 'undefined') { $jq('.error_' + formId + ' .message-header').html(response.msgHeader); } } } } }) } function buttonTransform(formId, ajaxurl, productName, productUrl, addingText) { $jq = jQuery.noConflict(); var buttonText = $jq('#addToCart_' + formId).val(); $jq('#addToCart_' + formId).attr('disabled', 'disabled'); $jq('#addToCart_' + formId).addClass('ajaxPurAddToCart'); $jq('#addToCart_' + formId).val(addingText); addToCartAjax(formId, ajaxurl, productName, productUrl, buttonText); } function ajaxUpdateCartWidgets(ajaxurl) { $jq = jQuery.noConflict(); var widgetId = $jq('.Cart66CartWidget').attr('id'); var data = { action: "ajax_cart_elements" }; ajaxManager.addReq({ type: "POST", url: ajaxurl + '=3', data: data, dataType: 'json', success: function(response) { $jq.hookExecute('cartElementsAjaxHook', response); $jq('#Cart66AdvancedSidebarAjax, #Cart66WidgetCartContents').show(); $jq('.Cart66WidgetViewCartCheckoutEmpty, #Cart66WidgetCartEmpty').hide(); $jq('#Cart66WidgetCartLink').each(function(){ widgetContent = "<span id=\"Cart66WidgetCartCount\">" + response.summary.count + "</span>"; widgetContent += "<span id=\"Cart66WidgetCartCountText\">" + response.summary.items + "</span>"; widgetContent += "<span id=\"Cart66WidgetCartCountDash\"> – </span>" widgetContent += "<span id=\"Cart66WidgetCartPrice\">" + response.summary.amount + "</span>"; $jq(this).html(widgetContent).fadeIn('slow'); }); $jq('.Cart66RequireShipping').each(function(){ if(response.shipping == 1) { $jq(this).show(); } }) $jq('#Cart66WidgetCartEmptyAdvanced').each(function(){ widgetContent = C66.youHave + ' ' + response.summary.count + " " + response.summary.items + " (" + response.summary.amount + ") " + C66.inYourShoppingCart; $jq(this).html(widgetContent).fadeIn('slow'); }); $jq("#Cart66AdvancedWidgetCartTable .product_items").remove(); $jq.each(response.products.reverse(), function(index, array){ widgetContent = "<tr class=\"product_items\"><td>"; widgetContent += "<span class=\"Cart66ProductTitle\">" + array.productName + "</span>"; widgetContent += "<span class=\"Cart66QuanPrice\">"; widgetContent += "<span class=\"Cart66ProductQuantity\">" + array.productQuantity + "</span>"; widgetContent += "<span class=\"Cart66MetaSep\"> x </span>"; widgetContent += "<span class=\"Cart66ProductPrice\">" + array.productPrice + "</span>"; widgetContent += "</span>"; widgetContent += "</td><td class=\"Cart66ProductSubtotalColumn\">"; widgetContent += "<span class=\"Cart66ProductSubtotal\">" + array.productSubtotal + "</span>"; widgetContent += "</td></tr>"; $jq("#Cart66AdvancedWidgetCartTable tbody").prepend(widgetContent).fadeIn("slow"); }); $jq('.Cart66Subtotal').each(function(){ $jq(this).html(response.subtotal) }); $jq('.Cart66Shipping').each(function(){ $jq(this).html(response.shippingAmount) }); } }) } jQuery.extend({ hookExecute: function (function_name, response){ if (typeof window[function_name] == "function"){ window[function_name](response); return true; } else{ return false; } } });
Java
<?php session_start(); ob_start(); include ('connect.php'); if(($_SESSION['LOGIN'] == "NO") or (!$_SESSION['LOGIN'])) header('Location: index.php'); function cssifysize($img) { $dimensions = getimagesize($img); $dimensions = str_replace("=\"", ":", $dimensions['3']); $dimensions = str_replace("\"", "px;", $dimensions); return $dimensions; }; ?> <br /><br /><a href="index.php">RETURN</a><br /><br /> <form action="image_folder.php" method="POST" enctype="multipart/form-data"> <p> Image Name: <input type="text" name="name_image"> </p> <p>Locate Image: <input type="file" name="userfile" id="file"></p> <p><input type="submit" value="Upload"></p> </form> <br /><br /> <?php if(($_POST['name_image'])){ $nameimg = $_POST['name_image']; $uploaddir = 'img/'; $uploadfile = $uploaddir . $nameimg; //basename($_FILES['userfile']['name']); if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { $query=mysql_query("INSERT INTO IMG_NEWSLETTER (NAME_IMG, DELETED) VALUES ('$nameimg', 'NO') ") or die (mysql_error()) ; if($query) header('Location: image_folder?img_upload=success'); } else { echo "<br />Upload failed<br /><br />"; } }; $query=mysql_query("SELECT * FROM IMG_NEWSLETTER WHERE DELETED LIKE 'NO' ") or die (mysql_error()); $count = 0; while($array=mysql_fetch_array($query)){ $count++; ?> <?php $img = "img/".$array['NAME_IMG']; ?> <p><b>Real Size:</b> <?php echo cssifysize($img); ?></p> <p><b>Display below:</b> width:200px; height:150px; </p> <p><a href="<?php echo "img/".$array['NAME_IMG']; ?>" target="_blank" ><img src="<?php echo "img/".$array['NAME_IMG']; ?>" width="200" height="150"></a></p><p><b><font size="+2"> <?php echo $array['NAME_IMG']; ?></b></font><input type="button" value="DELETE" onClick="javascript: document.location.href = 'delimg.php?idimg=<?php echo $array['ID_IMG_NEWSLETTER']; ?>';" /></p> <br />-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=<br /> <?php }; if($count == 0 ) echo "No image found."; if($_GET['delete']) echo "<br />The Image has been deleted successfully."; if($_GET['img_upload']) echo "<br />The Image has been uploaded successfully."; ?> <br /><br /><a href="index.php">RETURN</a><br /><br />
Java
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <errno.h> #include <iostream> #include "ftfilemapper.h" //#define DEBUG_FILEMAPPER ftFileMapper::ftFileMapper(uint64_t file_size,uint32_t chunk_size) : _file_size(file_size),_chunk_size(chunk_size) { int nb_chunks = (int)(file_size / (uint64_t)chunk_size) + ( (file_size % chunk_size)==0 ?0:1 ) ; #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) Creating ftFileMapper for file of size " << file_size << ", with " << nb_chunks << " chunks." << std::endl; #endif _first_free_chunk = 0 ; _mapped_chunks.clear() ; _mapped_chunks.resize(nb_chunks,-1) ; _data_chunks.clear() ; _data_chunks.resize(nb_chunks,-1) ; } bool ftFileMapper::computeStorageOffset(uint64_t offset,uint64_t& storage_offset) const { // Compute the chunk number for this offset // uint32_t cid = (uint32_t)(offset / (uint64_t)_chunk_size) ; // Check that the cid is in the allowed range. That should always be the case. // if(cid < _mapped_chunks.size() && _mapped_chunks[cid] >= 0) { storage_offset = _mapped_chunks[cid]*_chunk_size + (offset % (uint64_t)_chunk_size) ; return true ; } else { #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) ftFileMapper::computeStorageOffset(): offset " << offset << " corresponds to chunk number " << cid << " which is not mapped!!" << std::endl; #endif return false ; } } bool ftFileMapper::writeData(uint64_t offset,uint32_t size,void *data,FILE *fd) const { if (0 != fseeko64(fd, offset, SEEK_SET)) { std::cerr << "(EE) ftFileMapper::ftFileMapper::writeData() Bad fseek at offset " << offset << ", fd=" << (void*)fd << ", size=" << size << ", errno=" << errno << std::endl; return false; } if (1 != fwrite(data, size, 1, fd)) { std::cerr << "(EE) ftFileMapper::ftFileCreator::addFileData() Bad fwrite." << std::endl; std::cerr << "ERRNO: " << errno << std::endl; return false; } fflush(fd) ; return true ; } bool ftFileMapper::storeData(void *data, uint32_t data_size, uint64_t offset,FILE *fd) { uint64_t real_offset = 0; #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) ftFileMapper::storeData(): storing data size " << data_size << " for offset "<< offset << std::endl; #endif // we compute the real place of the data in the mapped file. Several cases: // // 1 - the place corresponds to a mapped place // => write there. // 2 - the place does not correspond to a mapped place. // 2.0 - we allocate a new chunk at the end of the file. // 2.0.1 - the chunk corresponds to a mapped chunk somewhere before // => we move it, and use the other chunk as writing position // 2.0.2 - the chunk does not correspond to a mapped chunk somewhere before // => we use it // 2.1 - the place is in the range of existing data // => we move the existing data at the end of the file, and update the mapping // 2.2 - the place is outside the range of existing data // => we allocate a new chunk at the end of the file, and write there. // 2.2.1 - we look for the first chunk that is not already mapped before. // if(!computeStorageOffset(offset,real_offset)) { uint32_t cid = (uint32_t)(offset / (uint64_t)_chunk_size) ; #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) real offset unknown. chunk id is " << cid << std::endl; #endif uint32_t empty_chunk = allocateNewEmptyChunk(fd) ; #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) allocated new empty chunk " << empty_chunk << std::endl; #endif if(cid < _first_free_chunk && cid != empty_chunk) // the place is already occupied by some data { #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) chunk already in use. " << std::endl; std::cerr << "(DD) swapping with first free chunk: " << empty_chunk << std::endl; #endif if(!moveChunk(cid, empty_chunk,fd)) { std::cerr << "(EE) ftFileMapper::writeData(): cannot move chunk " << empty_chunk << " and " << cid << std::endl ; return false ; } // Get the old chunk id that was mapping to this place // int oid = _data_chunks[cid] ; if(oid < 0) { std::cerr << "(EE) ftFileMapper::writeData(): cannot find chunk that was previously mapped to place " << cid << std::endl ; return false ; } #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) old chunk now pointing to: " << empty_chunk << std::endl; std::cerr << "(DD) new chunk now pointing to: " << cid << std::endl; #endif _mapped_chunks[cid] = cid ; // this one is in place, since we swapped it _mapped_chunks[oid] = empty_chunk ; _data_chunks[cid] = cid ; _data_chunks[empty_chunk] = oid ; } else // allocate a new chunk at end of the file. { #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) allocating new storage place at first free chunk: " << empty_chunk << std::endl; #endif _mapped_chunks[cid] = empty_chunk ; _data_chunks[empty_chunk] = cid ; } real_offset = _mapped_chunks[cid]*_chunk_size + (offset % (uint64_t)_chunk_size) ; } #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) real offset = " << real_offset << ", data size=" << data_size << std::endl; std::cerr << "(DD) writing data " << std::endl; #endif return writeData(real_offset,data_size,data,fd) ; } uint32_t ftFileMapper::allocateNewEmptyChunk(FILE *fd_out) { // look into _first_free_chunk. Is it the place of a chunk already mapped before? // #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) ftFileMapper::getFirstEmptyChunk()" << std::endl; #endif if(_mapped_chunks[_first_free_chunk] >= 0 && _mapped_chunks[_first_free_chunk] < (int)_first_free_chunk) { uint32_t old_chunk = _mapped_chunks[_first_free_chunk] ; #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) first free chunk " << _first_free_chunk << " is actually mapped to " << old_chunk << ". Moving it." << std::endl; #endif moveChunk(_mapped_chunks[_first_free_chunk],_first_free_chunk,fd_out) ; _mapped_chunks[_first_free_chunk] = _first_free_chunk ; _data_chunks[_first_free_chunk] = _first_free_chunk ; _first_free_chunk++ ; #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) Returning " << old_chunk << std::endl; #endif return old_chunk ; } else { #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) first free chunk is fine. Returning " << _first_free_chunk << ", and making room" << std::endl; #endif // We need to wipe the entire chunk, since it might be moved before beign completely written, which would cause // a fread error. // wipeChunk(_first_free_chunk,fd_out) ; return _first_free_chunk++ ; } } bool ftFileMapper::wipeChunk(uint32_t cid,FILE *fd) const { uint32_t size = (cid == _mapped_chunks.size()-1)?(_file_size - cid*_chunk_size) : _chunk_size ; void *buf = malloc(size) ; if(buf == NULL) { std::cerr << "(EE) ftFileMapper::wipeChunk(): cannot allocate temporary buf of size " << size << std::endl; return false ; } if(fseeko64(fd, cid*_chunk_size, SEEK_SET)!= 0) { std::cerr << "(EE) ftFileMapper::wipeChunk(): cannot fseek file at position " << cid*_chunk_size << std::endl; free(buf) ; return false ; } if(1 != fwrite(buf, size, 1, fd)) { std::cerr << "(EE) ftFileMapper::wipeChunk(): cannot write to file" << std::endl; free(buf) ; return false ; } free(buf) ; return true ; } bool ftFileMapper::moveChunk(uint32_t to_move, uint32_t new_place,FILE *fd_out) { // Read the old chunk, write at the new place assert(to_move != new_place) ; fflush(fd_out) ; #ifdef DEBUG_FILEMAPPER std::cerr << "(DD) ftFileMapper::moveChunk(): moving chunk " << to_move << " to place " << new_place << std::endl ; #endif uint32_t new_place_size = (new_place == _mapped_chunks.size()-1)?(_file_size - (_mapped_chunks.size()-1)*_chunk_size) : _chunk_size ; uint32_t to_move_size = (new_place == _mapped_chunks.size()-1)?(_file_size - (_mapped_chunks.size()-1)*_chunk_size) : _chunk_size ; uint32_t size = std::min(new_place_size,to_move_size) ; void *buff = malloc(size) ; if(buff == NULL) { std::cerr << "(EE) ftFileMapper::moveChunk(): cannot open temporary buffer. Out of memory??" << std::endl; return false ; } if(fseeko64(fd_out, to_move*_chunk_size, SEEK_SET) != 0) { std::cerr << "(EE) ftFileMapper::moveChunk(): cannot fseek file at position " << to_move*_chunk_size << std::endl; return false ; } size_t rd ; if(size != (rd = fread(buff, 1, size, fd_out))) { std::cerr << "(EE) ftFileMapper::moveChunk(): cannot read from file" << std::endl; std::cerr << "(EE) errno = " << errno << std::endl; std::cerr << "(EE) feof = " << feof(fd_out) << std::endl; std::cerr << "(EE) size = " << size << std::endl; std::cerr << "(EE) rd = " << rd << std::endl; return false ; } if(fseeko64(fd_out, new_place*_chunk_size, SEEK_SET)!= 0) { std::cerr << "(EE) ftFileMapper::moveChunk(): cannot fseek file at position " << new_place*_chunk_size << std::endl; return false ; } if(1 != fwrite(buff, size, 1, fd_out)) { std::cerr << "(EE) ftFileMapper::moveChunk(): cannot write to file" << std::endl; return false ; } free(buff) ; return true ; } void ftFileMapper::print() const { std::cerr << "ftFileMapper:: [ " ; for(uint32_t i=0;i<_mapped_chunks.size();++i) { std::cerr << _mapped_chunks[i] << " " ; } std::cerr << "] - ffc = " << _first_free_chunk << " - [ "; for(uint32_t i=0;i<_data_chunks.size();++i) std::cerr << _data_chunks[i] << " " ; std::cerr << " ] " << std::endl; }
Java
# Endpoints for user to control the home. from datetime import datetime from flask import Blueprint, jsonify, request from services import elements_services, home_services home_api = Blueprint('/home_api', __name__) elements_services = elements_services.ElementsServices() home_services = home_services.HomeServices() @home_api.route('/profiles') def profiles(): """Gets all profiles for all elements for user application to display and manipulate elements""" return jsonify(home_services.get_profiles()) @home_api.route('/element', methods=['POST']) def update_element(): """Updates single element with all new values received from the user application""" received_element = request.get_json() home_services.update_element(received_element) return 'OK' @home_api.route('/elements', methods=['POST']) def update_elements(): """Updates all elements with all new values received from the user application""" received_elements = request.get_json() home_services.update_elements(received_elements) return 'OK' @home_api.route('/elementdelete', methods=['POST']) def delete_element(): """Deletes a single element with given hid""" element = request.get_json() home_services.delete_element(element['hid']) return 'OK' @home_api.route('/timerules', methods=['POST']) def timerules(): """Adds, Updates or deletes time rule for the given element""" rules = request.get_json() if len(rules) == 0: raise Exception("No elements in the list") for rule in rules: if 'id' not in rule: rule['id'] = None home_services.save_time_rules(rules) return 'OK' @home_api.route('/timerules/<string:hid>') def get_timerules(hid): """Gets list of timerules for given hid""" timerules= home_services.read_time_rules(hid) return jsonify(timerules)
Java
#include "stdafx.h" #include "Utilities/Log.h" #include "Utilities/File.h" #include "git-version.h" #include "rpcs3/Ini.h" #include "Emu/Memory/Memory.h" #include "Emu/System.h" #include "Emu/GameInfo.h" #include "Emu/SysCalls/ModuleManager.h" #include "Emu/Cell/PPUThread.h" #include "Emu/Cell/SPUThread.h" #include "Emu/Cell/PPUInstrTable.h" #include "Emu/FS/vfsFile.h" #include "Emu/FS/vfsLocalFile.h" #include "Emu/FS/vfsDeviceLocalFile.h" #include "Emu/DbgCommand.h" #include "Emu/CPU/CPUThreadManager.h" #include "Emu/SysCalls/Callback.h" #include "Emu/IdManager.h" #include "Emu/Io/Pad.h" #include "Emu/Io/Keyboard.h" #include "Emu/Io/Mouse.h" #include "Emu/RSX/GSManager.h" #include "Emu/Audio/AudioManager.h" #include "Emu/FS/VFS.h" #include "Emu/Event.h" #include "Loader/PSF.h" #include "Loader/ELF64.h" #include "Loader/ELF32.h" #include "../Crypto/unself.h" #include <fstream> using namespace PPU_instr; static const std::string& BreakPointsDBName = "BreakPoints.dat"; static const u16 bpdb_version = 0x1000; extern std::atomic<u32> g_thread_count; extern u64 get_system_time(); extern void finalize_psv_modules(); Emulator::Emulator() : m_status(Stopped) , m_mode(DisAsm) , m_rsx_callback(0) , m_thread_manager(new CPUThreadManager()) , m_pad_manager(new PadManager()) , m_keyboard_manager(new KeyboardManager()) , m_mouse_manager(new MouseManager()) , m_gs_manager(new GSManager()) , m_audio_manager(new AudioManager()) , m_callback_manager(new CallbackManager()) , m_event_manager(new EventManager()) , m_module_manager(new ModuleManager()) , m_vfs(new VFS()) { m_loader.register_handler(new loader::handlers::elf32); m_loader.register_handler(new loader::handlers::elf64); } Emulator::~Emulator() { } void Emulator::Init() { } void Emulator::SetPath(const std::string& path, const std::string& elf_path) { m_path = path; m_elf_path = elf_path; } void Emulator::SetTitleID(const std::string& id) { m_title_id = id; } void Emulator::SetTitle(const std::string& title) { m_title = title; } bool Emulator::BootGame(const std::string& path, bool direct) { static const char* elf_path[6] = { "/PS3_GAME/USRDIR/BOOT.BIN", "/USRDIR/BOOT.BIN", "/BOOT.BIN", "/PS3_GAME/USRDIR/EBOOT.BIN", "/USRDIR/EBOOT.BIN", "/EBOOT.BIN" }; auto curpath = path; if (direct) { if (fs::is_file(curpath)) { SetPath(curpath); Load(); return true; } } for (int i = 0; i < sizeof(elf_path) / sizeof(*elf_path); i++) { curpath = path + elf_path[i]; if (fs::is_file(curpath)) { SetPath(curpath); Load(); return true; } } return false; } void Emulator::Load() { m_status = Ready; GetModuleManager().Init(); if (!fs::is_file(m_path)) { m_status = Stopped; return; } const std::string elf_dir = m_path.substr(0, m_path.find_last_of("/\\", std::string::npos, 2) + 1); if (IsSelf(m_path)) { const std::string full_name = m_path.substr(elf_dir.length()); const std::string base_name = full_name.substr(0, full_name.find_last_of('.', std::string::npos)); const std::string ext = full_name.substr(base_name.length()); if (fmt::toupper(full_name) == "EBOOT.BIN") { m_path = elf_dir + "BOOT.BIN"; } else if (fmt::toupper(ext) == ".SELF") { m_path = elf_dir + base_name + ".elf"; } else if (fmt::toupper(ext) == ".SPRX") { m_path = elf_dir + base_name + ".prx"; } else { m_path = elf_dir + base_name + ".decrypted" + ext; } LOG_NOTICE(LOADER, "Decrypting '%s%s'...", elf_dir, full_name); if (!DecryptSelf(m_path, elf_dir + full_name)) { m_status = Stopped; return; } } LOG_NOTICE(LOADER, "Loading '%s'...", m_path.c_str()); ResetInfo(); GetVFS().Init(elf_dir); // /dev_bdvd/ mounting vfsFile f("/app_home/../dev_bdvd.path"); if (f.IsOpened()) { // load specified /dev_bdvd/ directory and mount it std::string bdvd; bdvd.resize(f.GetSize()); f.Read(&bdvd[0], bdvd.size()); Emu.GetVFS().Mount("/dev_bdvd/", bdvd, new vfsDeviceLocalFile()); } else if (fs::is_file(elf_dir + "../../PS3_DISC.SFB")) // guess loading disc game { const auto dir_list = fmt::split(elf_dir, { "/", "\\" }); // check latest two directories if (dir_list.size() >= 2 && dir_list.back() == "USRDIR" && *(dir_list.end() - 2) == "PS3_GAME") { // mount detected /dev_bdvd/ directory Emu.GetVFS().Mount("/dev_bdvd/", elf_dir.substr(0, elf_dir.length() - 17), new vfsDeviceLocalFile()); } } LOG_NOTICE(LOADER, ""); LOG_NOTICE(LOADER, "Mount info:"); for (uint i = 0; i < GetVFS().m_devices.size(); ++i) { LOG_NOTICE(LOADER, "%s -> %s", GetVFS().m_devices[i]->GetPs3Path().c_str(), GetVFS().m_devices[i]->GetLocalPath().c_str()); } LOG_NOTICE(LOADER, ""); LOG_NOTICE(LOADER, "RPCS3 version: %s", RPCS3_GIT_VERSION); LOG_NOTICE(LOADER, ""); LOG_NOTICE(LOADER, "Settings:"); LOG_NOTICE(LOADER, "CPU: %s", Ini.CPUIdToString(Ini.CPUDecoderMode.GetValue())); LOG_NOTICE(LOADER, "SPU: %s", Ini.SPUIdToString(Ini.SPUDecoderMode.GetValue())); LOG_NOTICE(LOADER, "Renderer: %s", Ini.RendererIdToString(Ini.GSRenderMode.GetValue())); if (Ini.GSRenderMode.GetValue() == 2) { LOG_NOTICE(LOADER, "D3D Adapter: %s", Ini.AdapterIdToString(Ini.GSD3DAdaptater.GetValue())); } LOG_NOTICE(LOADER, "Resolution: %s", Ini.ResolutionIdToString(Ini.GSResolution.GetValue())); LOG_NOTICE(LOADER, "Write Depth Buffer: %s", Ini.GSDumpDepthBuffer.GetValue() ? "Yes" : "No"); LOG_NOTICE(LOADER, "Write Color Buffers: %s", Ini.GSDumpColorBuffers.GetValue() ? "Yes" : "No"); LOG_NOTICE(LOADER, "Read Color Buffer: %s", Ini.GSReadColorBuffer.GetValue() ? "Yes" : "No"); LOG_NOTICE(LOADER, "Audio Out: %s", Ini.AudioOutIdToString(Ini.AudioOutMode.GetValue())); LOG_NOTICE(LOADER, "Log Everything: %s", Ini.HLELogging.GetValue() ? "Yes" : "No"); LOG_NOTICE(LOADER, "RSX Logging: %s", Ini.RSXLogging.GetValue() ? "Yes" : "No"); LOG_NOTICE(LOADER, ""); f.Open("/app_home/../PARAM.SFO"); const PSFLoader psf(f); std::string title = psf.GetString("TITLE"); std::string title_id = psf.GetString("TITLE_ID"); LOG_NOTICE(LOADER, "Title: %s", title.c_str()); LOG_NOTICE(LOADER, "Serial: %s", title_id.c_str()); title.length() ? SetTitle(title) : SetTitle(m_path); SetTitleID(title_id); if (m_elf_path.empty()) { GetVFS().GetDeviceLocal(m_path, m_elf_path); LOG_NOTICE(LOADER, "Elf path: %s", m_elf_path); LOG_NOTICE(LOADER, ""); } f.Open(m_elf_path); if (!f.IsOpened()) { LOG_ERROR(LOADER, "Opening '%s' failed", m_path.c_str()); m_status = Stopped; return; } if (!m_loader.load(f)) { LOG_ERROR(LOADER, "Loading '%s' failed", m_path.c_str()); LOG_NOTICE(LOADER, ""); m_status = Stopped; vm::close(); return; } LoadPoints(BreakPointsDBName); GetGSManager().Init(); GetCallbackManager().Init(); GetAudioManager().Init(); GetEventManager().Init(); SendDbgCommand(DID_READY_EMU); } void Emulator::Run() { if (!IsReady()) { Load(); if(!IsReady()) return; } if (IsRunning()) Stop(); if (IsPaused()) { Resume(); return; } SendDbgCommand(DID_START_EMU); m_pause_start_time = 0; m_pause_amend_time = 0; m_status = Running; GetCPU().Exec(); SendDbgCommand(DID_STARTED_EMU); } void Emulator::Pause() { const u64 start = get_system_time(); // try to set Paused status if (!sync_bool_compare_and_swap(&m_status, Running, Paused)) { return; } // update pause start time if (m_pause_start_time.exchange(start)) { LOG_ERROR(GENERAL, "Emulator::Pause() error: concurrent access"); } SendDbgCommand(DID_PAUSE_EMU); for (auto& t : GetCPU().GetAllThreads()) { t->sleep(); // trigger status check } SendDbgCommand(DID_PAUSED_EMU); } void Emulator::Resume() { // get pause start time const u64 time = m_pause_start_time.exchange(0); // try to increment summary pause time if (time) { m_pause_amend_time += get_system_time() - time; } // try to resume if (!sync_bool_compare_and_swap(&m_status, Paused, Running)) { return; } if (!time) { LOG_ERROR(GENERAL, "Emulator::Resume() error: concurrent access"); } SendDbgCommand(DID_RESUME_EMU); for (auto& t : GetCPU().GetAllThreads()) { t->awake(); // untrigger status check and signal } SendDbgCommand(DID_RESUMED_EMU); } extern std::map<u32, std::string> g_armv7_dump; void Emulator::Stop() { LOG_NOTICE(GENERAL, "Stopping emulator..."); if (sync_lock_test_and_set(&m_status, Stopped) == Stopped) { return; } SendDbgCommand(DID_STOP_EMU); { LV2_LOCK; // notify all threads for (auto& t : GetCPU().GetAllThreads()) { std::lock_guard<std::mutex> lock(t->mutex); t->sleep(); // trigger status check t->cv.notify_one(); // signal } } LOG_NOTICE(GENERAL, "All threads signaled..."); while (g_thread_count) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } LOG_NOTICE(GENERAL, "All threads stopped..."); idm::clear(); fxm::clear(); LOG_NOTICE(GENERAL, "Objects cleared..."); finalize_psv_modules(); for (auto& v : decltype(g_armv7_dump)(std::move(g_armv7_dump))) { LOG_NOTICE(ARMv7, v.second); } m_rsx_callback = 0; // TODO: check finalization order SavePoints(BreakPointsDBName); m_break_points.clear(); m_marked_points.clear(); GetVFS().UnMountAll(); GetGSManager().Close(); GetAudioManager().Close(); GetEventManager().Clear(); GetCPU().Close(); GetPadManager().Close(); GetKeyboardManager().Close(); GetMouseManager().Close(); GetCallbackManager().Clear(); GetModuleManager().Close(); CurGameInfo.Reset(); RSXIOMem.Clear(); vm::close(); SendDbgCommand(DID_STOPPED_EMU); } void Emulator::SavePoints(const std::string& path) { std::ofstream f(path, std::ios::binary | std::ios::trunc); u32 break_count = (u32)m_break_points.size(); u32 marked_count = (u32)m_marked_points.size(); f.write((char*)(&bpdb_version), sizeof(bpdb_version)); f.write((char*)(&break_count), sizeof(break_count)); f.write((char*)(&marked_count), sizeof(marked_count)); if (break_count) { f.write((char*)(m_break_points.data()), sizeof(u64) * break_count); } if (marked_count) { f.write((char*)(m_marked_points.data()), sizeof(u64) * marked_count); } } bool Emulator::LoadPoints(const std::string& path) { if (!fs::is_file(path)) return false; std::ifstream f(path, std::ios::binary); if (!f.is_open()) return false; f.seekg(0, std::ios::end); u64 length = (u64)f.tellg(); f.seekg(0, std::ios::beg); u16 version; u32 break_count, marked_count; u64 expected_length = sizeof(bpdb_version) + sizeof(break_count) + sizeof(marked_count); if (length < expected_length) { LOG_ERROR(LOADER, "'%s' breakpoint db is broken (file is too short, length=0x%x)", path, length); return false; } f.read((char*)(&version), sizeof(version)); if (version != bpdb_version) { LOG_ERROR(LOADER, "'%s' breakpoint db version is unsupported (version=0x%x, length=0x%x)", path, version, length); return false; } f.read((char*)(&break_count), sizeof(break_count)); f.read((char*)(&marked_count), sizeof(marked_count)); expected_length += break_count * sizeof(u64) + marked_count * sizeof(u64); if (expected_length != length) { LOG_ERROR(LOADER, "'%s' breakpoint db format is incorrect " "(version=0x%x, break_count=0x%x, marked_count=0x%x, length=0x%x)", path, version, break_count, marked_count, length); return false; } if (break_count > 0) { m_break_points.resize(break_count); f.read((char*)(m_break_points.data()), sizeof(u64) * break_count); } if (marked_count > 0) { m_marked_points.resize(marked_count); f.read((char*)(m_marked_points.data()), sizeof(u64) * marked_count); } return true; } Emulator Emu; CallAfterCbType CallAfterCallback = nullptr; void CallAfter(std::function<void()> func) { CallAfterCallback(func); } void SetCallAfterCallback(CallAfterCbType cb) { CallAfterCallback = cb; }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><head> <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/> <meta name="keywords" content="TEMU, dynamic analysis, binary analysis, dynamic taint analysis"/> <meta name="description" content="C/C++/OCaml Source Code Documentation for the TEMU Project."/> <title>TEMU: xed-encoder-hl.h Source File</title> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head><body> <p class="title">TEMU: Dynamic Binary Analysis Platform</p> <!-- Generated by Doxygen 1.5.8 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&nbsp;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li><a href="dirs.html"><span>Directories</span></a></li> <li> <form action="search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul> </div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <div class="navpath"><a class="el" href="dir_4f22f3fd3d3cce94a331ff7cdf0bf085.html">temu-1.0</a>&nbsp;&raquo&nbsp;<a class="el" href="dir_3b6767f6be6ef802b0654406f3e74d86.html">shared</a>&nbsp;&raquo&nbsp;<a class="el" href="dir_0277bd4601ee6c31034924754cae7495.html">xed2</a>&nbsp;&raquo&nbsp;<a class="el" href="dir_05e0ad34a2706acb4f73624c38c2a107.html">xed2-ia32</a>&nbsp;&raquo&nbsp;<a class="el" href="dir_f86fba19af9dbb3e8d51a2bdea785276.html">include</a> </div> </div> <div class="contents"> <h1>xed2-ia32/include/xed-encoder-hl.h</h1><a href="xed2-ia32_2include_2xed-encoder-hl_8h.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*BEGIN_LEGAL </span> <a name="l00002"></a>00002 <span class="comment">Intel Open Source License </span> <a name="l00003"></a>00003 <span class="comment"></span> <a name="l00004"></a>00004 <span class="comment">Copyright (c) 2002-2008 Intel Corporation </span> <a name="l00005"></a>00005 <span class="comment">All rights reserved. </span> <a name="l00006"></a>00006 <span class="comment">Redistribution and use in source and binary forms, with or without</span> <a name="l00007"></a>00007 <span class="comment">modification, are permitted provided that the following conditions are</span> <a name="l00008"></a>00008 <span class="comment">met:</span> <a name="l00009"></a>00009 <span class="comment"></span> <a name="l00010"></a>00010 <span class="comment">Redistributions of source code must retain the above copyright notice,</span> <a name="l00011"></a>00011 <span class="comment">this list of conditions and the following disclaimer. Redistributions</span> <a name="l00012"></a>00012 <span class="comment">in binary form must reproduce the above copyright notice, this list of</span> <a name="l00013"></a>00013 <span class="comment">conditions and the following disclaimer in the documentation and/or</span> <a name="l00014"></a>00014 <span class="comment">other materials provided with the distribution. Neither the name of</span> <a name="l00015"></a>00015 <span class="comment">the Intel Corporation nor the names of its contributors may be used to</span> <a name="l00016"></a>00016 <span class="comment">endorse or promote products derived from this software without</span> <a name="l00017"></a>00017 <span class="comment">specific prior written permission.</span> <a name="l00018"></a>00018 <span class="comment"> </span> <a name="l00019"></a>00019 <span class="comment">THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS</span> <a name="l00020"></a>00020 <span class="comment">``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT</span> <a name="l00021"></a>00021 <span class="comment">LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR</span> <a name="l00022"></a>00022 <span class="comment">A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR</span> <a name="l00023"></a>00023 <span class="comment">ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,</span> <a name="l00024"></a>00024 <span class="comment">SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT</span> <a name="l00025"></a>00025 <span class="comment">LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,</span> <a name="l00026"></a>00026 <span class="comment">DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY</span> <a name="l00027"></a>00027 <span class="comment">THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT</span> <a name="l00028"></a>00028 <span class="comment">(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE</span> <a name="l00029"></a>00029 <span class="comment">OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</span> <a name="l00030"></a>00030 <span class="comment">END_LEGAL */</span> <a name="l00031"></a>00031 <a name="l00032"></a>00032 <span class="preprocessor">#ifndef _XED_ENCODER_HL_H_</span> <a name="l00033"></a>00033 <span class="preprocessor"></span><span class="preprocessor"># define _XED_ENCODER_HL_H_</span> <a name="l00034"></a>00034 <span class="preprocessor"></span><span class="preprocessor">#include "xed-types.h"</span> <a name="l00035"></a>00035 <span class="preprocessor">#include "xed-reg-enum.h"</span> <a name="l00036"></a>00036 <span class="preprocessor">#include "xed-state.h"</span> <a name="l00037"></a>00037 <span class="preprocessor">#include "xed-iclass-enum.h"</span> <a name="l00038"></a>00038 <span class="preprocessor">#include "xed-portability.h"</span> <a name="l00039"></a>00039 <span class="preprocessor">#include "xed-encode.h"</span> <a name="l00040"></a>00040 <a name="l00041"></a>00041 <a name="l00042"></a><a class="code" href="structxed__enc__displacement__t.html">00042</a> <span class="keyword">typedef</span> <span class="keyword">struct </span>{ <a name="l00043"></a><a class="code" href="structxed__enc__displacement__t.html#c983d8e2ceacd11fce421ac110c65bd8">00043</a> xed_uint64_t displacement; <a name="l00044"></a><a class="code" href="structxed__enc__displacement__t.html#3fd0ffc7c9929f49bfc795fe01bf1798">00044</a> xed_uint32_t displacement_width; <a name="l00045"></a>00045 } <a class="code" href="structxed__enc__displacement__t.html">xed_enc_displacement_t</a>; <span class="comment">/* fixme bad name */</span> <a name="l00046"></a>00046 <span class="comment"></span> <a name="l00047"></a>00047 <span class="comment">/// @name Memory Displacement</span> <a name="l00048"></a>00048 <span class="comment"></span><span class="comment">//@{</span> <a name="l00049"></a>00049 <span class="comment"></span><span class="comment">/// @ingroup ENCHL</span> <a name="l00050"></a>00050 <span class="comment"></span><span class="comment">/// a memory displacement (not for branches)</span> <a name="l00051"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#c8a806e9c0ba578adcb5aa2ee7cdb394">00051</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__enc__displacement__t.html">xed_enc_displacement_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#c8a806e9c0ba578adcb5aa2ee7cdb394">xdisp</a>(xed_uint64_t displacement, <a name="l00052"></a>00052 xed_uint32_t displacement_width ) { <a name="l00053"></a>00053 <a class="code" href="structxed__enc__displacement__t.html">xed_enc_displacement_t</a> x; <a name="l00054"></a>00054 x.<a class="code" href="structxed__enc__displacement__t.html#c983d8e2ceacd11fce421ac110c65bd8">displacement</a> = displacement; <a name="l00055"></a>00055 x.<a class="code" href="structxed__enc__displacement__t.html#3fd0ffc7c9929f49bfc795fe01bf1798">displacement_width</a> = displacement_width; <a name="l00056"></a>00056 <span class="keywordflow">return</span> x; <a name="l00057"></a>00057 }<span class="comment"></span> <a name="l00058"></a>00058 <span class="comment">//@}</span> <a name="l00059"></a>00059 <span class="comment"></span> <a name="l00060"></a><a class="code" href="structxed__memop__t.html">00060</a> <span class="keyword">typedef</span> <span class="keyword">struct </span>{ <a name="l00061"></a><a class="code" href="structxed__memop__t.html#d07ef1ac72ff572e65e78b3653c43c1d">00061</a> <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> seg; <a name="l00062"></a><a class="code" href="structxed__memop__t.html#b33f5fd03ddbc01a1795e85978b32c61">00062</a> <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> base; <a name="l00063"></a><a class="code" href="structxed__memop__t.html#451ae2fcc3acdff8a10543b18f19f84e">00063</a> <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> index; <a name="l00064"></a><a class="code" href="structxed__memop__t.html#d801bcd3961aa78d30caaca98489dd36">00064</a> xed_uint32_t scale; <a name="l00065"></a><a class="code" href="structxed__memop__t.html#1fd26bd97ff3565101e7e79ccf1d5a53">00065</a> <a class="code" href="structxed__enc__displacement__t.html">xed_enc_displacement_t</a> disp; <a name="l00066"></a>00066 } <a class="code" href="structxed__memop__t.html">xed_memop_t</a>; <a name="l00067"></a>00067 <a name="l00068"></a>00068 <a name="l00069"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638">00069</a> <span class="keyword">typedef</span> <span class="keyword">enum</span> { <a name="l00070"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638cbc8d93653c02e76eac8d019f449d88b">00070</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638cbc8d93653c02e76eac8d019f449d88b">XED_ENCODER_OPERAND_TYPE_INVALID</a>, <a name="l00071"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d126383bea84e3495457e582cd5533b3b67b43">00071</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d126383bea84e3495457e582cd5533b3b67b43">XED_ENCODER_OPERAND_TYPE_BRDISP</a>, <a name="l00072"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638c7e137bec55ec1ebaf1b3269cbf8d35b">00072</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638c7e137bec55ec1ebaf1b3269cbf8d35b">XED_ENCODER_OPERAND_TYPE_REG</a>, <a name="l00073"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638ec1aab94e9a39cad7281722d72f4c074">00073</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638ec1aab94e9a39cad7281722d72f4c074">XED_ENCODER_OPERAND_TYPE_IMM0</a>, <a name="l00074"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d126386010b70490d8deb87248988db4851991">00074</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d126386010b70490d8deb87248988db4851991">XED_ENCODER_OPERAND_TYPE_SIMM0</a>, <a name="l00075"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d1263839d2ecbd06732c86c9be27e5697513e4">00075</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d1263839d2ecbd06732c86c9be27e5697513e4">XED_ENCODER_OPERAND_TYPE_IMM1</a>, <a name="l00076"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638fb6bee5a0fcf154e71397defed76ed88">00076</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638fb6bee5a0fcf154e71397defed76ed88">XED_ENCODER_OPERAND_TYPE_MEM</a>, <a name="l00077"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638617ca23d3a043d05c07435199e768b88">00077</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638617ca23d3a043d05c07435199e768b88">XED_ENCODER_OPERAND_TYPE_PTR</a>, <a name="l00078"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d126385a7a43348b1552de102211c4d76ca72d">00078</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d126385a7a43348b1552de102211c4d76ca72d">XED_ENCODER_OPERAND_TYPE_SEG0</a>, <span class="comment">/* special for things with suppressed implicit memops */</span> <a name="l00079"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638acd0df30646ec7115ac403e2dc7bf2ff">00079</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638acd0df30646ec7115ac403e2dc7bf2ff">XED_ENCODER_OPERAND_TYPE_SEG1</a>, <span class="comment">/* special for things with suppressed implicit memops */</span> <a name="l00080"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638263eeedf98d73a93dd619bc0b2359d79">00080</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638263eeedf98d73a93dd619bc0b2359d79">XED_ENCODER_OPERAND_TYPE_OTHER</a> <span class="comment">/* specific operand storage fields -- must supply a name */</span> <a name="l00081"></a>00081 } <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638">xed_encoder_operand_type_t</a>; <a name="l00082"></a>00082 <a name="l00083"></a><a class="code" href="structxed__encoder__operand__t.html">00083</a> <span class="keyword">typedef</span> <span class="keyword">struct </span>{ <a name="l00084"></a><a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">00084</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638">xed_encoder_operand_type_t</a> type; <a name="l00085"></a>00085 <span class="keyword">union </span>{ <a name="l00086"></a><a class="code" href="structxed__encoder__operand__t.html#e5eeb0d5e528568c4335f3e1232b1c74">00086</a> <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> reg; <a name="l00087"></a><a class="code" href="structxed__encoder__operand__t.html#248b7401faf495144a60aed3e033de28">00087</a> xed_int32_t brdisp; <a name="l00088"></a><a class="code" href="structxed__encoder__operand__t.html#5dce7d3756139b85189dad3a9156c082">00088</a> xed_uint64_t <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#e90462df43d77847591b28317121a7f0">imm0</a>; <a name="l00089"></a><a class="code" href="structxed__encoder__operand__t.html#14f433f92d67d3bed1e912dfaec7478c">00089</a> xed_uint8_t <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#c6d077d7c8bd6d603c46554caf4eac8b">imm1</a>; <a name="l00090"></a>00090 <span class="keyword">struct </span>{ <a name="l00091"></a><a class="code" href="structxed__encoder__operand__t.html#82618f4d775f0f34a11ff4374bcb8ce7">00091</a> <a class="code" href="xed2-ia32_2include_2xed-operand-enum_8h.html#09c2a35d8bb7bfe68bb3d34b0a5e011a">xed_operand_enum_t</a> operand_name; <a name="l00092"></a><a class="code" href="structxed__encoder__operand__t.html#676f6026a5ba7d95e2dd4ce2b730a48d">00092</a> xed_uint32_t value; <a name="l00093"></a>00093 } s; <a name="l00094"></a><a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">00094</a> <a class="code" href="structxed__memop__t.html">xed_memop_t</a> mem; <a name="l00095"></a>00095 } u; <a name="l00096"></a><a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">00096</a> xed_uint32_t width; <a name="l00097"></a>00097 } <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a>; <a name="l00098"></a>00098 <span class="comment"></span> <a name="l00099"></a>00099 <span class="comment">/// @name Branch Displacement</span> <a name="l00100"></a>00100 <span class="comment"></span><span class="comment">//@{</span> <a name="l00101"></a>00101 <span class="comment"></span><span class="comment">/// @ingroup ENCHL</span> <a name="l00102"></a>00102 <span class="comment"></span><span class="comment">/// a relative branch displacement operand</span> <a name="l00103"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#cdb37097d0759178bb58ed9a09def08d">00103</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#cdb37097d0759178bb58ed9a09def08d">xrelbr</a>(xed_int32_t brdisp, <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00104"></a>00104 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00105"></a>00105 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d126383bea84e3495457e582cd5533b3b67b43">XED_ENCODER_OPERAND_TYPE_BRDISP</a>; <a name="l00106"></a>00106 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#248b7401faf495144a60aed3e033de28">brdisp</a> = brdisp; <a name="l00107"></a>00107 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00108"></a>00108 <span class="keywordflow">return</span> o; <a name="l00109"></a>00109 }<span class="comment"></span> <a name="l00110"></a>00110 <span class="comment">//@}</span> <a name="l00111"></a>00111 <span class="comment"></span><span class="comment"></span> <a name="l00112"></a>00112 <span class="comment">/// @name Pointer Displacement</span> <a name="l00113"></a>00113 <span class="comment"></span><span class="comment">//@{</span> <a name="l00114"></a>00114 <span class="comment"></span><span class="comment">/// @ingroup ENCHL</span> <a name="l00115"></a>00115 <span class="comment"></span><span class="comment">/// a relative displacement for a PTR operand -- the subsequent imm0 holds the 16b selector</span> <a name="l00116"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#ba429e1d2123dacf780e53c57b743ff6">00116</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#ba429e1d2123dacf780e53c57b743ff6">xptr</a>(xed_int32_t brdisp, <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00117"></a>00117 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00118"></a>00118 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638617ca23d3a043d05c07435199e768b88">XED_ENCODER_OPERAND_TYPE_PTR</a>; <a name="l00119"></a>00119 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#248b7401faf495144a60aed3e033de28">brdisp</a> = brdisp; <a name="l00120"></a>00120 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00121"></a>00121 <span class="keywordflow">return</span> o; <a name="l00122"></a>00122 }<span class="comment"></span> <a name="l00123"></a>00123 <span class="comment">//@}</span> <a name="l00124"></a>00124 <span class="comment"></span><span class="comment"></span> <a name="l00125"></a>00125 <span class="comment">/// @name Register and Immmediate Operands</span> <a name="l00126"></a>00126 <span class="comment"></span><span class="comment">//@{</span> <a name="l00127"></a>00127 <span class="comment"></span><span class="comment">/// @ingroup ENCHL</span> <a name="l00128"></a>00128 <span class="comment"></span><span class="comment">/// a register operand</span> <a name="l00129"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#3ebdabca7dc139c49b31bcc86635298e">00129</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#3ebdabca7dc139c49b31bcc86635298e">xreg</a>(<a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> reg) { <a name="l00130"></a>00130 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00131"></a>00131 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638c7e137bec55ec1ebaf1b3269cbf8d35b">XED_ENCODER_OPERAND_TYPE_REG</a>; <a name="l00132"></a>00132 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#e5eeb0d5e528568c4335f3e1232b1c74">reg</a> = reg; <a name="l00133"></a>00133 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = 0; <a name="l00134"></a>00134 <span class="keywordflow">return</span> o; <a name="l00135"></a>00135 } <a name="l00136"></a>00136 <span class="comment"></span> <a name="l00137"></a>00137 <span class="comment">/// @ingroup ENCHL</span> <a name="l00138"></a>00138 <span class="comment">/// a first immediate operand (known as IMM0)</span> <a name="l00139"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#e90462df43d77847591b28317121a7f0">00139</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#e90462df43d77847591b28317121a7f0">imm0</a>(xed_uint64_t v, <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00140"></a>00140 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00141"></a>00141 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638ec1aab94e9a39cad7281722d72f4c074">XED_ENCODER_OPERAND_TYPE_IMM0</a>; <a name="l00142"></a>00142 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#5dce7d3756139b85189dad3a9156c082">imm0</a> = v; <a name="l00143"></a>00143 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00144"></a>00144 <span class="keywordflow">return</span> o; <a name="l00145"></a>00145 }<span class="comment"></span> <a name="l00146"></a>00146 <span class="comment">/// @ingroup ENCHL</span> <a name="l00147"></a>00147 <span class="comment">/// an 32b signed immediate operand</span> <a name="l00148"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#224148173f630a050658a41d82e1806f">00148</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#224148173f630a050658a41d82e1806f">simm0</a>(xed_int32_t v, <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00149"></a>00149 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00150"></a>00150 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d126386010b70490d8deb87248988db4851991">XED_ENCODER_OPERAND_TYPE_SIMM0</a>; <a name="l00151"></a>00151 <span class="comment">/* sign conversion: we store the int32 in an uint64. It gets sign</span> <a name="l00152"></a>00152 <span class="comment"> extended. Later we convert it to the right width for the</span> <a name="l00153"></a>00153 <span class="comment"> instruction. The maximum width of a signed immediate is currently</span> <a name="l00154"></a>00154 <span class="comment"> 32b. */</span> <a name="l00155"></a>00155 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#5dce7d3756139b85189dad3a9156c082">imm0</a> = v; <a name="l00156"></a>00156 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00157"></a>00157 <span class="keywordflow">return</span> o; <a name="l00158"></a>00158 } <a name="l00159"></a>00159 <span class="comment"></span> <a name="l00160"></a>00160 <span class="comment">/// @ingroup ENCHL</span> <a name="l00161"></a>00161 <span class="comment">/// an second immediate operand (known as IMM1)</span> <a name="l00162"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#c6d077d7c8bd6d603c46554caf4eac8b">00162</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#c6d077d7c8bd6d603c46554caf4eac8b">imm1</a>(xed_uint8_t v) { <a name="l00163"></a>00163 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00164"></a>00164 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d1263839d2ecbd06732c86c9be27e5697513e4">XED_ENCODER_OPERAND_TYPE_IMM1</a>; <a name="l00165"></a>00165 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#14f433f92d67d3bed1e912dfaec7478c">imm1</a> = v; <a name="l00166"></a>00166 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = 8; <a name="l00167"></a>00167 <span class="keywordflow">return</span> o; <a name="l00168"></a>00168 } <a name="l00169"></a>00169 <a name="l00170"></a>00170 <span class="comment"></span> <a name="l00171"></a>00171 <span class="comment">/// @ingroup ENCHL</span> <a name="l00172"></a>00172 <span class="comment">/// an operand storage field name and value</span> <a name="l00173"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#6e3a5790c41207ef4b7c1f2fb1153b46">00173</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#6e3a5790c41207ef4b7c1f2fb1153b46">xother</a>(<a class="code" href="xed2-ia32_2include_2xed-operand-enum_8h.html#09c2a35d8bb7bfe68bb3d34b0a5e011a">xed_operand_enum_t</a> operand_name, <a name="l00174"></a>00174 xed_int32_t value) { <a name="l00175"></a>00175 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00176"></a>00176 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638263eeedf98d73a93dd619bc0b2359d79">XED_ENCODER_OPERAND_TYPE_OTHER</a>; <a name="l00177"></a>00177 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#e0848586a721bdf0be7381053b9e9925">s</a>.operand_name = operand_name; <a name="l00178"></a>00178 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#e0848586a721bdf0be7381053b9e9925">s</a>.value = value; <a name="l00179"></a>00179 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = 0; <a name="l00180"></a>00180 <span class="keywordflow">return</span> o; <a name="l00181"></a>00181 }<span class="comment"></span> <a name="l00182"></a>00182 <span class="comment">//@}</span> <a name="l00183"></a>00183 <span class="comment"></span> <a name="l00184"></a>00184 <span class="comment"></span> <a name="l00185"></a>00185 <span class="comment">//@}</span> <a name="l00186"></a>00186 <span class="comment"></span><span class="comment"></span> <a name="l00187"></a>00187 <span class="comment">/// @name Memory and Segment-releated Operands</span> <a name="l00188"></a>00188 <span class="comment"></span><span class="comment">//@{</span> <a name="l00189"></a>00189 <span class="comment"></span><span class="comment"></span> <a name="l00190"></a>00190 <span class="comment">/// @ingroup ENCHL</span> <a name="l00191"></a>00191 <span class="comment">/// seg reg override for implicit suppressed memory ops</span> <a name="l00192"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#793653db3198f72eb18d140e25dde653">00192</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#793653db3198f72eb18d140e25dde653">xseg0</a>(<a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> seg0) { <a name="l00193"></a>00193 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00194"></a>00194 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d126385a7a43348b1552de102211c4d76ca72d">XED_ENCODER_OPERAND_TYPE_SEG0</a>; <a name="l00195"></a>00195 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#e5eeb0d5e528568c4335f3e1232b1c74">reg</a> = seg0; <a name="l00196"></a>00196 <span class="keywordflow">return</span> o; <a name="l00197"></a>00197 } <a name="l00198"></a>00198 <span class="comment"></span> <a name="l00199"></a>00199 <span class="comment">/// @ingroup ENCHL</span> <a name="l00200"></a>00200 <span class="comment">/// seg reg override for implicit suppressed memory ops</span> <a name="l00201"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#b67610fd9da5d421558105f820cbd27b">00201</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#b67610fd9da5d421558105f820cbd27b">xseg1</a>(<a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> seg1) { <a name="l00202"></a>00202 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00203"></a>00203 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638acd0df30646ec7115ac403e2dc7bf2ff">XED_ENCODER_OPERAND_TYPE_SEG1</a>; <a name="l00204"></a>00204 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#e5eeb0d5e528568c4335f3e1232b1c74">reg</a> = seg1; <a name="l00205"></a>00205 <span class="keywordflow">return</span> o; <a name="l00206"></a>00206 } <a name="l00207"></a>00207 <span class="comment"></span> <a name="l00208"></a>00208 <span class="comment">/// @ingroup ENCHL</span> <a name="l00209"></a>00209 <span class="comment">/// memory operand - base only </span> <a name="l00210"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7a36b028c6ec7d4e1dc84011cc6787d0">00210</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7a36b028c6ec7d4e1dc84011cc6787d0">xmem_b</a>(<a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> base, <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00211"></a>00211 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00212"></a>00212 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638fb6bee5a0fcf154e71397defed76ed88">XED_ENCODER_OPERAND_TYPE_MEM</a>; <a name="l00213"></a>00213 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#b33f5fd03ddbc01a1795e85978b32c61">base</a> = base; <a name="l00214"></a>00214 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d07ef1ac72ff572e65e78b3653c43c1d">seg</a> = <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61fac474058f0819d415285511086bf219">XED_REG_INVALID</a>; <a name="l00215"></a>00215 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#451ae2fcc3acdff8a10543b18f19f84e">index</a>= <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61fac474058f0819d415285511086bf219">XED_REG_INVALID</a>; <a name="l00216"></a>00216 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d801bcd3961aa78d30caaca98489dd36">scale</a> = 0; <a name="l00217"></a>00217 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#1fd26bd97ff3565101e7e79ccf1d5a53">disp</a>.<a class="code" href="structxed__enc__displacement__t.html#c983d8e2ceacd11fce421ac110c65bd8">displacement</a> = 0; <a name="l00218"></a>00218 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#1fd26bd97ff3565101e7e79ccf1d5a53">disp</a>.<a class="code" href="structxed__enc__displacement__t.html#3fd0ffc7c9929f49bfc795fe01bf1798">displacement_width</a> = 0; <a name="l00219"></a>00219 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00220"></a>00220 <span class="keywordflow">return</span> o; <a name="l00221"></a>00221 } <a name="l00222"></a>00222 <span class="comment"></span> <a name="l00223"></a>00223 <span class="comment">/// @ingroup ENCHL</span> <a name="l00224"></a>00224 <span class="comment">/// memory operand - base and displacement only </span> <a name="l00225"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#6a7e5ee43079588be0649fc0af9f317e">00225</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#6a7e5ee43079588be0649fc0af9f317e">xmem_bd</a>(<a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> base, <a name="l00226"></a>00226 <a class="code" href="structxed__enc__displacement__t.html">xed_enc_displacement_t</a> disp, <a name="l00227"></a>00227 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00228"></a>00228 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00229"></a>00229 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638fb6bee5a0fcf154e71397defed76ed88">XED_ENCODER_OPERAND_TYPE_MEM</a>; <a name="l00230"></a>00230 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#b33f5fd03ddbc01a1795e85978b32c61">base</a> = base; <a name="l00231"></a>00231 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d07ef1ac72ff572e65e78b3653c43c1d">seg</a> = <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61fac474058f0819d415285511086bf219">XED_REG_INVALID</a>; <a name="l00232"></a>00232 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#451ae2fcc3acdff8a10543b18f19f84e">index</a>= <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61fac474058f0819d415285511086bf219">XED_REG_INVALID</a>; <a name="l00233"></a>00233 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d801bcd3961aa78d30caaca98489dd36">scale</a> = 0; <a name="l00234"></a>00234 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#1fd26bd97ff3565101e7e79ccf1d5a53">disp</a> =disp; <a name="l00235"></a>00235 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00236"></a>00236 <span class="keywordflow">return</span> o; <a name="l00237"></a>00237 } <a name="l00238"></a>00238 <span class="comment"></span> <a name="l00239"></a>00239 <span class="comment">/// @ingroup ENCHL</span> <a name="l00240"></a>00240 <span class="comment">/// memory operand - base, index, scale, displacement</span> <a name="l00241"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#59d7b50dfd23d11b89be56686d6bdd63">00241</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#59d7b50dfd23d11b89be56686d6bdd63">xmem_bisd</a>(<a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> base, <a name="l00242"></a>00242 <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> index, <a name="l00243"></a>00243 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> scale, <a name="l00244"></a>00244 <a class="code" href="structxed__enc__displacement__t.html">xed_enc_displacement_t</a> disp, <a name="l00245"></a>00245 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00246"></a>00246 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00247"></a>00247 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638fb6bee5a0fcf154e71397defed76ed88">XED_ENCODER_OPERAND_TYPE_MEM</a>; <a name="l00248"></a>00248 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#b33f5fd03ddbc01a1795e85978b32c61">base</a> = base; <a name="l00249"></a>00249 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d07ef1ac72ff572e65e78b3653c43c1d">seg</a> = <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61fac474058f0819d415285511086bf219">XED_REG_INVALID</a>; <a name="l00250"></a>00250 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#451ae2fcc3acdff8a10543b18f19f84e">index</a>= index; <a name="l00251"></a>00251 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d801bcd3961aa78d30caaca98489dd36">scale</a> = scale; <a name="l00252"></a>00252 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#1fd26bd97ff3565101e7e79ccf1d5a53">disp</a> = disp; <a name="l00253"></a>00253 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00254"></a>00254 <span class="keywordflow">return</span> o; <a name="l00255"></a>00255 } <a name="l00256"></a>00256 <a name="l00257"></a>00257 <span class="comment"></span> <a name="l00258"></a>00258 <span class="comment">/// @ingroup ENCHL</span> <a name="l00259"></a>00259 <span class="comment">/// memory operand - segment and base only</span> <a name="l00260"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#03dcdbf44f52401301bf7e1f037a4ba0">00260</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#03dcdbf44f52401301bf7e1f037a4ba0">xmem_gb</a>(<a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> seg, <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> base, <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00261"></a>00261 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00262"></a>00262 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638fb6bee5a0fcf154e71397defed76ed88">XED_ENCODER_OPERAND_TYPE_MEM</a>; <a name="l00263"></a>00263 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#b33f5fd03ddbc01a1795e85978b32c61">base</a> = base; <a name="l00264"></a>00264 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d07ef1ac72ff572e65e78b3653c43c1d">seg</a> = seg; <a name="l00265"></a>00265 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#451ae2fcc3acdff8a10543b18f19f84e">index</a>= <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61fac474058f0819d415285511086bf219">XED_REG_INVALID</a>; <a name="l00266"></a>00266 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d801bcd3961aa78d30caaca98489dd36">scale</a> = 0; <a name="l00267"></a>00267 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#1fd26bd97ff3565101e7e79ccf1d5a53">disp</a>.<a class="code" href="structxed__enc__displacement__t.html#c983d8e2ceacd11fce421ac110c65bd8">displacement</a> = 0; <a name="l00268"></a>00268 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#1fd26bd97ff3565101e7e79ccf1d5a53">disp</a>.<a class="code" href="structxed__enc__displacement__t.html#3fd0ffc7c9929f49bfc795fe01bf1798">displacement_width</a> = 0; <a name="l00269"></a>00269 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00270"></a>00270 <span class="keywordflow">return</span> o; <a name="l00271"></a>00271 } <a name="l00272"></a>00272 <span class="comment"></span> <a name="l00273"></a>00273 <span class="comment">/// @ingroup ENCHL</span> <a name="l00274"></a>00274 <span class="comment">/// memory operand - segment, base and displacement only</span> <a name="l00275"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#1ec05f0acc4469fe82b3c2824c4a366d">00275</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#1ec05f0acc4469fe82b3c2824c4a366d">xmem_gbd</a>(<a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> seg, <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> base, <a name="l00276"></a>00276 <a class="code" href="structxed__enc__displacement__t.html">xed_enc_displacement_t</a> disp, <a name="l00277"></a>00277 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00278"></a>00278 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00279"></a>00279 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638fb6bee5a0fcf154e71397defed76ed88">XED_ENCODER_OPERAND_TYPE_MEM</a>; <a name="l00280"></a>00280 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#b33f5fd03ddbc01a1795e85978b32c61">base</a> = base; <a name="l00281"></a>00281 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d07ef1ac72ff572e65e78b3653c43c1d">seg</a> = seg; <a name="l00282"></a>00282 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#451ae2fcc3acdff8a10543b18f19f84e">index</a>= <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61fac474058f0819d415285511086bf219">XED_REG_INVALID</a>; <a name="l00283"></a>00283 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d801bcd3961aa78d30caaca98489dd36">scale</a> = 0; <a name="l00284"></a>00284 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#1fd26bd97ff3565101e7e79ccf1d5a53">disp</a> = disp; <a name="l00285"></a>00285 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00286"></a>00286 <span class="keywordflow">return</span> o; <a name="l00287"></a>00287 } <a name="l00288"></a>00288 <span class="comment"></span> <a name="l00289"></a>00289 <span class="comment">/// @ingroup ENCHL</span> <a name="l00290"></a>00290 <span class="comment">/// memory operand - segment and displacement only</span> <a name="l00291"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#1515d8567dd24b840528e94ef45d5cd1">00291</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#1515d8567dd24b840528e94ef45d5cd1">xmem_gd</a>(<a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> seg, <a name="l00292"></a>00292 <a class="code" href="structxed__enc__displacement__t.html">xed_enc_displacement_t</a> disp, <a name="l00293"></a>00293 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00294"></a>00294 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00295"></a>00295 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638fb6bee5a0fcf154e71397defed76ed88">XED_ENCODER_OPERAND_TYPE_MEM</a>; <a name="l00296"></a>00296 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#b33f5fd03ddbc01a1795e85978b32c61">base</a> = <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61fac474058f0819d415285511086bf219">XED_REG_INVALID</a>; <a name="l00297"></a>00297 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d07ef1ac72ff572e65e78b3653c43c1d">seg</a> = seg; <a name="l00298"></a>00298 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#451ae2fcc3acdff8a10543b18f19f84e">index</a>= <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61fac474058f0819d415285511086bf219">XED_REG_INVALID</a>; <a name="l00299"></a>00299 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d801bcd3961aa78d30caaca98489dd36">scale</a> = 0; <a name="l00300"></a>00300 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#1fd26bd97ff3565101e7e79ccf1d5a53">disp</a> = disp; <a name="l00301"></a>00301 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00302"></a>00302 <span class="keywordflow">return</span> o; <a name="l00303"></a>00303 } <a name="l00304"></a>00304 <span class="comment"></span> <a name="l00305"></a>00305 <span class="comment">/// @ingroup ENCHL</span> <a name="l00306"></a>00306 <span class="comment">/// memory operand - segment, base, index, scale, and displacement</span> <a name="l00307"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#00fc1e423b20d24b1843e502cc4d39a3">00307</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#00fc1e423b20d24b1843e502cc4d39a3">xmem_gbisd</a>(<a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> seg, <a name="l00308"></a>00308 <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> base, <a name="l00309"></a>00309 <a class="code" href="xed2-ia32_2include_2xed-reg-enum_8h.html#f05c33c5a68e9304d1d8ac0408ae3f61">xed_reg_enum_t</a> index, <a name="l00310"></a>00310 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> scale, <a name="l00311"></a>00311 <a class="code" href="structxed__enc__displacement__t.html">xed_enc_displacement_t</a> disp, <a name="l00312"></a>00312 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00313"></a>00313 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> o; <a name="l00314"></a>00314 o.<a class="code" href="structxed__encoder__operand__t.html#15b522f5fb9447f7bbea3ae6baf328a9">type</a> = <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#7621255aeac26b5e78f7a0dc72d12638fb6bee5a0fcf154e71397defed76ed88">XED_ENCODER_OPERAND_TYPE_MEM</a>; <a name="l00315"></a>00315 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#b33f5fd03ddbc01a1795e85978b32c61">base</a> = base; <a name="l00316"></a>00316 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d07ef1ac72ff572e65e78b3653c43c1d">seg</a> = seg; <a name="l00317"></a>00317 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#451ae2fcc3acdff8a10543b18f19f84e">index</a>= index; <a name="l00318"></a>00318 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#d801bcd3961aa78d30caaca98489dd36">scale</a> = scale; <a name="l00319"></a>00319 o.<a class="code" href="structxed__encoder__operand__t.html#01d174f19e13511270eefe522bc61248">u</a>.<a class="code" href="structxed__encoder__operand__t.html#7874f7a5284ff2064ba6b9bf032e25ff">mem</a>.<a class="code" href="structxed__memop__t.html#1fd26bd97ff3565101e7e79ccf1d5a53">disp</a> = disp; <a name="l00320"></a>00320 o.<a class="code" href="structxed__encoder__operand__t.html#ea2d8c884cca697c2dbc9807dfbdd139">width</a> = width; <a name="l00321"></a>00321 <span class="keywordflow">return</span> o; <a name="l00322"></a>00322 }<span class="comment"></span> <a name="l00323"></a>00323 <span class="comment">//@}</span> <a name="l00324"></a>00324 <span class="comment"></span> <a name="l00325"></a><a class="code" href="unionxed__encoder__prefixes__t.html">00325</a> <span class="keyword">typedef</span> <span class="keyword">union </span>{ <a name="l00326"></a>00326 <span class="keyword">struct </span>{ <a name="l00327"></a><a class="code" href="unionxed__encoder__prefixes__t.html#c8dc70af0c2333374574b71ee91d66aa">00327</a> xed_uint32_t rep :1; <a name="l00328"></a><a class="code" href="unionxed__encoder__prefixes__t.html#d6e7f53ef6fc3cdd9cb45089e7978c86">00328</a> xed_uint32_t repne :1; <a name="l00329"></a><a class="code" href="unionxed__encoder__prefixes__t.html#045a7a7fb9c564bb2d14a71f22356a47">00329</a> xed_uint32_t lock :1; <a name="l00330"></a><a class="code" href="unionxed__encoder__prefixes__t.html#1f154d5ebf743d7d2220705a7d554a89">00330</a> xed_uint32_t br_hint_taken :1; <a name="l00331"></a><a class="code" href="unionxed__encoder__prefixes__t.html#bd09ac7e3aa0de912b2150a3f2000396">00331</a> xed_uint32_t br_hint_not_taken :1; <a name="l00332"></a>00332 } s; <a name="l00333"></a><a class="code" href="unionxed__encoder__prefixes__t.html#15762219ece938eca0db01a735121dbe">00333</a> xed_uint32_t i; <a name="l00334"></a>00334 } <a class="code" href="unionxed__encoder__prefixes__t.html">xed_encoder_prefixes_t</a>; <a name="l00335"></a>00335 <a name="l00336"></a>00336 <span class="preprocessor">#define XED_ENCODER_OPERANDS_MAX 5 </span><span class="comment">/* FIXME */</span> <a name="l00337"></a><a class="code" href="structxed__encoder__instruction__t.html">00337</a> <span class="keyword">typedef</span> <span class="keyword">struct </span>{ <a name="l00338"></a><a class="code" href="structxed__encoder__instruction__t.html#1647966dc2ac0f213f9674e6c1e7e336">00338</a> <a class="code" href="group__INIT.html#g58af142456a133c3df29c763216a85cf">xed_state_t</a> mode; <a name="l00339"></a><a class="code" href="structxed__encoder__instruction__t.html#bdc1758a5dc07d92701e95617d539909">00339</a> <a class="code" href="xed2-ia32_2include_2xed-iclass-enum_8h.html#d318511ae9cc50f102251b3c91a1ab9f">xed_iclass_enum_t</a> iclass; <span class="comment">/*FIXME: use iform instead? or allow either */</span> <a name="l00340"></a><a class="code" href="structxed__encoder__instruction__t.html#2b23c8d18171f9a4699744992b5cc026">00340</a> xed_uint32_t effective_operand_width; <a name="l00341"></a>00341 <a name="l00342"></a>00342 <span class="comment">/* the effective_address_width is only requires to be set for</span> <a name="l00343"></a>00343 <span class="comment"> * instructions * with implicit suppressed memops or memops with no</span> <a name="l00344"></a>00344 <span class="comment"> * base or index regs. When base or index regs are present, XED pick</span> <a name="l00345"></a>00345 <span class="comment"> * this up automatically from the register names.</span> <a name="l00346"></a>00346 <span class="comment"></span> <a name="l00347"></a>00347 <span class="comment"> * FIXME: make effective_address_width required by all encodes for</span> <a name="l00348"></a>00348 <span class="comment"> * unifority. Add to xed_inst[0123]() APIs??? */</span> <a name="l00349"></a><a class="code" href="structxed__encoder__instruction__t.html#d829df66320029ad521451b2896b18f3">00349</a> xed_uint32_t effective_address_width; <a name="l00350"></a>00350 <a name="l00351"></a><a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">00351</a> <a class="code" href="unionxed__encoder__prefixes__t.html">xed_encoder_prefixes_t</a> prefixes; <a name="l00352"></a><a class="code" href="structxed__encoder__instruction__t.html#10c44c5cf064364003d1d4f6f4bbb7da">00352</a> xed_uint32_t noperands; <a name="l00353"></a><a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">00353</a> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> operands[XED_ENCODER_OPERANDS_MAX]; <a name="l00354"></a>00354 } <a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>; <a name="l00355"></a>00355 <span class="comment"></span> <a name="l00356"></a>00356 <span class="comment">/// @name Instruction Properties and prefixes</span> <a name="l00357"></a>00357 <span class="comment"></span><span class="comment">//@{</span> <a name="l00358"></a>00358 <span class="comment"></span><span class="comment">/// @ingroup ENCHL</span> <a name="l00359"></a>00359 <span class="comment"></span><span class="comment">/// This is to specify effective address size different than the</span> <a name="l00360"></a>00360 <span class="comment"></span><span class="comment">/// default. For things with base or index regs, XED picks it up from the</span> <a name="l00361"></a>00361 <span class="comment"></span><span class="comment">/// registers. But for things that have implicit memops, or no base or index</span> <a name="l00362"></a>00362 <span class="comment"></span><span class="comment">/// reg, we must allow the user to set the address width directly.</span> <a name="l00363"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#3dcef3e2652fa12f63eecd6fa29d2f48">00363</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#3dcef3e2652fa12f63eecd6fa29d2f48">xaddr</a>(<a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* x, <a name="l00364"></a>00364 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> width) { <a name="l00365"></a>00365 x-&gt;<a class="code" href="structxed__encoder__instruction__t.html#d829df66320029ad521451b2896b18f3">effective_address_width</a> = width; <a name="l00366"></a>00366 } <a name="l00367"></a>00367 <a name="l00368"></a>00368 <span class="comment"></span> <a name="l00369"></a>00369 <span class="comment">/// @ingroup ENCHL</span> <a name="l00370"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#089c068bfc4e04fe9571d1af267af068">00370</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#089c068bfc4e04fe9571d1af267af068">xrep</a>(<a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* x) { <a name="l00371"></a>00371 x-&gt;<a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">prefixes</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#2f01cb0ecd47fddfa9a0e4bc67d6f18c">s</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#c8dc70af0c2333374574b71ee91d66aa">rep</a>=1; <a name="l00372"></a>00372 } <a name="l00373"></a>00373 <span class="comment"></span> <a name="l00374"></a>00374 <span class="comment">/// @ingroup ENCHL</span> <a name="l00375"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#139f196ef758eabea56fc3c12bc04008">00375</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#139f196ef758eabea56fc3c12bc04008">xrepne</a>(<a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* x) { <a name="l00376"></a>00376 x-&gt;<a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">prefixes</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#2f01cb0ecd47fddfa9a0e4bc67d6f18c">s</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#d6e7f53ef6fc3cdd9cb45089e7978c86">repne</a>=1; <a name="l00377"></a>00377 } <a name="l00378"></a>00378 <span class="comment"></span> <a name="l00379"></a>00379 <span class="comment">/// @ingroup ENCHL</span> <a name="l00380"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#2bddb61d7cc4980ad081933603a98bf4">00380</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#2bddb61d7cc4980ad081933603a98bf4">xlock</a>(<a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* x) { <a name="l00381"></a>00381 x-&gt;<a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">prefixes</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#2f01cb0ecd47fddfa9a0e4bc67d6f18c">s</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#045a7a7fb9c564bb2d14a71f22356a47">lock</a>=1; <a name="l00382"></a>00382 } <a name="l00383"></a>00383 <a name="l00384"></a>00384 <a name="l00385"></a>00385 <a name="l00386"></a>00386 <span class="comment"></span> <a name="l00387"></a>00387 <span class="comment">/// @ingroup ENCHL</span> <a name="l00388"></a>00388 <span class="comment">/// convert a #xed_encoder_instruction_t to a #xed_encoder_request_t for encoding</span> <a name="l00389"></a>00389 <span class="comment"></span><a class="code" href="xed2-ia32_2include_2xed-types_8h.html#d355c921b747945a82d62233a599c7b5">xed_bool_t</a> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#22b6ec424e2b07c28f7094196c039172">xed_convert_to_encoder_request</a>(<a class="code" href="xed2-ia32_2include_2xed-encode_8h.html#6f914541ddfa1ffe609acebff72d0b5f">xed_encoder_request_t</a>* out, <a name="l00390"></a>00390 <a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* in); <a name="l00391"></a>00391 <span class="comment"></span> <a name="l00392"></a>00392 <span class="comment">//@}</span> <a name="l00393"></a>00393 <span class="comment"></span><span class="comment"></span> <a name="l00394"></a>00394 <span class="comment">////////////////////////////////////////////////////////////////////////////</span> <a name="l00395"></a>00395 <span class="comment"></span><span class="comment">/* FIXME: rather than return the xed_encoder_instruction_t I can make</span> <a name="l00396"></a>00396 <span class="comment"> * another version that returns a xed_encoder_request_t. Saves silly</span> <a name="l00397"></a>00397 <span class="comment"> * copying. Although the xed_encoder_instruction_t might be handy for</span> <a name="l00398"></a>00398 <span class="comment"> * having code templates that get customized &amp; passed to encoder later. */</span><span class="comment"></span> <a name="l00399"></a>00399 <span class="comment">////////////////////////////////////////////////////////////////////////////</span> <a name="l00400"></a>00400 <span class="comment">/// @name Creating instructions from operands</span> <a name="l00401"></a>00401 <span class="comment"></span><span class="comment">//@{</span> <a name="l00402"></a>00402 <span class="comment"></span><span class="comment"></span> <a name="l00403"></a>00403 <span class="comment">/// @ingroup ENCHL</span> <a name="l00404"></a>00404 <span class="comment">/// instruction with no operands</span> <a name="l00405"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#8d463fe5834dfc1dd4e4664fbf897528">00405</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#8d463fe5834dfc1dd4e4664fbf897528">xed_inst0</a>( <a name="l00406"></a>00406 <a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* inst, <a name="l00407"></a>00407 <a class="code" href="group__INIT.html#g58af142456a133c3df29c763216a85cf">xed_state_t</a> mode, <a name="l00408"></a>00408 <a class="code" href="xed2-ia32_2include_2xed-iclass-enum_8h.html#d318511ae9cc50f102251b3c91a1ab9f">xed_iclass_enum_t</a> iclass, <a name="l00409"></a>00409 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> effective_operand_width) { <a name="l00410"></a>00410 <a name="l00411"></a>00411 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#1647966dc2ac0f213f9674e6c1e7e336">mode</a>=mode; <a name="l00412"></a>00412 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#bdc1758a5dc07d92701e95617d539909">iclass</a> = iclass; <a name="l00413"></a>00413 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#2b23c8d18171f9a4699744992b5cc026">effective_operand_width</a> = effective_operand_width; <a name="l00414"></a>00414 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#d829df66320029ad521451b2896b18f3">effective_address_width</a> = 0; <a name="l00415"></a>00415 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">prefixes</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#15762219ece938eca0db01a735121dbe">i</a> = 0; <a name="l00416"></a>00416 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#10c44c5cf064364003d1d4f6f4bbb7da">noperands</a> = 0; <a name="l00417"></a>00417 } <a name="l00418"></a>00418 <span class="comment"></span> <a name="l00419"></a>00419 <span class="comment">/// @ingroup ENCHL</span> <a name="l00420"></a>00420 <span class="comment">/// instruction with one operand</span> <a name="l00421"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#605a860a788e8ba6d7342783be23a093">00421</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#605a860a788e8ba6d7342783be23a093">xed_inst1</a>( <a name="l00422"></a>00422 <a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* inst, <a name="l00423"></a>00423 <a class="code" href="group__INIT.html#g58af142456a133c3df29c763216a85cf">xed_state_t</a> mode, <a name="l00424"></a>00424 <a class="code" href="xed2-ia32_2include_2xed-iclass-enum_8h.html#d318511ae9cc50f102251b3c91a1ab9f">xed_iclass_enum_t</a> iclass, <a name="l00425"></a>00425 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> effective_operand_width, <a name="l00426"></a>00426 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op0) { <a name="l00427"></a>00427 <a name="l00428"></a>00428 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#1647966dc2ac0f213f9674e6c1e7e336">mode</a>=mode; <a name="l00429"></a>00429 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#bdc1758a5dc07d92701e95617d539909">iclass</a> = iclass; <a name="l00430"></a>00430 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#2b23c8d18171f9a4699744992b5cc026">effective_operand_width</a> = effective_operand_width; <a name="l00431"></a>00431 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#d829df66320029ad521451b2896b18f3">effective_address_width</a> = 0; <a name="l00432"></a>00432 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">prefixes</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#15762219ece938eca0db01a735121dbe">i</a> = 0; <a name="l00433"></a>00433 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[0] = op0; <a name="l00434"></a>00434 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#10c44c5cf064364003d1d4f6f4bbb7da">noperands</a> = 1; <a name="l00435"></a>00435 } <a name="l00436"></a>00436 <span class="comment"></span> <a name="l00437"></a>00437 <span class="comment">/// @ingroup ENCHL</span> <a name="l00438"></a>00438 <span class="comment">/// instruction with two operands</span> <a name="l00439"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#d2669ef272ad5c97d0e5070b50cce5ec">00439</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#d2669ef272ad5c97d0e5070b50cce5ec">xed_inst2</a>( <a name="l00440"></a>00440 <a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* inst, <a name="l00441"></a>00441 <a class="code" href="group__INIT.html#g58af142456a133c3df29c763216a85cf">xed_state_t</a> mode, <a name="l00442"></a>00442 <a class="code" href="xed2-ia32_2include_2xed-iclass-enum_8h.html#d318511ae9cc50f102251b3c91a1ab9f">xed_iclass_enum_t</a> iclass, <a name="l00443"></a>00443 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> effective_operand_width, <a name="l00444"></a>00444 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op0, <a name="l00445"></a>00445 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op1) { <a name="l00446"></a>00446 <a name="l00447"></a>00447 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#1647966dc2ac0f213f9674e6c1e7e336">mode</a>=mode; <a name="l00448"></a>00448 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#bdc1758a5dc07d92701e95617d539909">iclass</a> = iclass; <a name="l00449"></a>00449 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#2b23c8d18171f9a4699744992b5cc026">effective_operand_width</a> = effective_operand_width; <a name="l00450"></a>00450 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#d829df66320029ad521451b2896b18f3">effective_address_width</a> = 0; <a name="l00451"></a>00451 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">prefixes</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#15762219ece938eca0db01a735121dbe">i</a> = 0; <a name="l00452"></a>00452 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[0] = op0; <a name="l00453"></a>00453 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[1] = op1; <a name="l00454"></a>00454 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#10c44c5cf064364003d1d4f6f4bbb7da">noperands</a> = 2; <a name="l00455"></a>00455 } <a name="l00456"></a>00456 <span class="comment"></span> <a name="l00457"></a>00457 <span class="comment">/// @ingroup ENCHL</span> <a name="l00458"></a>00458 <span class="comment">/// instruction with three operands</span> <a name="l00459"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#5bf8b6ae6bb2bfd07725c1acfea2ac2b">00459</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#5bf8b6ae6bb2bfd07725c1acfea2ac2b">xed_inst3</a>( <a name="l00460"></a>00460 <a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* inst, <a name="l00461"></a>00461 <a class="code" href="group__INIT.html#g58af142456a133c3df29c763216a85cf">xed_state_t</a> mode, <a name="l00462"></a>00462 <a class="code" href="xed2-ia32_2include_2xed-iclass-enum_8h.html#d318511ae9cc50f102251b3c91a1ab9f">xed_iclass_enum_t</a> iclass, <a name="l00463"></a>00463 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> effective_operand_width, <a name="l00464"></a>00464 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op0, <a name="l00465"></a>00465 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op1, <a name="l00466"></a>00466 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op2) { <a name="l00467"></a>00467 <a name="l00468"></a>00468 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#1647966dc2ac0f213f9674e6c1e7e336">mode</a>=mode; <a name="l00469"></a>00469 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#bdc1758a5dc07d92701e95617d539909">iclass</a> = iclass; <a name="l00470"></a>00470 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#2b23c8d18171f9a4699744992b5cc026">effective_operand_width</a> = effective_operand_width; <a name="l00471"></a>00471 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#d829df66320029ad521451b2896b18f3">effective_address_width</a> = 0; <a name="l00472"></a>00472 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">prefixes</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#15762219ece938eca0db01a735121dbe">i</a> = 0; <a name="l00473"></a>00473 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[0] = op0; <a name="l00474"></a>00474 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[1] = op1; <a name="l00475"></a>00475 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[2] = op2; <a name="l00476"></a>00476 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#10c44c5cf064364003d1d4f6f4bbb7da">noperands</a> = 3; <a name="l00477"></a>00477 } <a name="l00478"></a>00478 <a name="l00479"></a>00479 <span class="comment"></span> <a name="l00480"></a>00480 <span class="comment">/// @ingroup ENCHL</span> <a name="l00481"></a>00481 <span class="comment">/// instruction with four operands</span> <a name="l00482"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#49825c9af03114c82b10b61aefa8ce93">00482</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#49825c9af03114c82b10b61aefa8ce93">xed_inst4</a>( <a name="l00483"></a>00483 <a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* inst, <a name="l00484"></a>00484 <a class="code" href="group__INIT.html#g58af142456a133c3df29c763216a85cf">xed_state_t</a> mode, <a name="l00485"></a>00485 <a class="code" href="xed2-ia32_2include_2xed-iclass-enum_8h.html#d318511ae9cc50f102251b3c91a1ab9f">xed_iclass_enum_t</a> iclass, <a name="l00486"></a>00486 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> effective_operand_width, <a name="l00487"></a>00487 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op0, <a name="l00488"></a>00488 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op1, <a name="l00489"></a>00489 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op2, <a name="l00490"></a>00490 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op3) { <a name="l00491"></a>00491 <a name="l00492"></a>00492 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#1647966dc2ac0f213f9674e6c1e7e336">mode</a>=mode; <a name="l00493"></a>00493 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#bdc1758a5dc07d92701e95617d539909">iclass</a> = iclass; <a name="l00494"></a>00494 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#2b23c8d18171f9a4699744992b5cc026">effective_operand_width</a> = effective_operand_width; <a name="l00495"></a>00495 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#d829df66320029ad521451b2896b18f3">effective_address_width</a> = 0; <a name="l00496"></a>00496 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">prefixes</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#15762219ece938eca0db01a735121dbe">i</a> = 0; <a name="l00497"></a>00497 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[0] = op0; <a name="l00498"></a>00498 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[1] = op1; <a name="l00499"></a>00499 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[2] = op2; <a name="l00500"></a>00500 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[3] = op3; <a name="l00501"></a>00501 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#10c44c5cf064364003d1d4f6f4bbb7da">noperands</a> = 4; <a name="l00502"></a>00502 } <a name="l00503"></a>00503 <span class="comment"></span> <a name="l00504"></a>00504 <span class="comment">/// @ingroup ENCHL</span> <a name="l00505"></a>00505 <span class="comment">/// instruction with five operands</span> <a name="l00506"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#3a745d122221c6039c4aad0c2e61bc68">00506</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#3a745d122221c6039c4aad0c2e61bc68">xed_inst5</a>( <a name="l00507"></a>00507 <a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* inst, <a name="l00508"></a>00508 <a class="code" href="group__INIT.html#g58af142456a133c3df29c763216a85cf">xed_state_t</a> mode, <a name="l00509"></a>00509 <a class="code" href="xed2-ia32_2include_2xed-iclass-enum_8h.html#d318511ae9cc50f102251b3c91a1ab9f">xed_iclass_enum_t</a> iclass, <a name="l00510"></a>00510 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> effective_operand_width, <a name="l00511"></a>00511 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op0, <a name="l00512"></a>00512 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op1, <a name="l00513"></a>00513 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op2, <a name="l00514"></a>00514 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op3, <a name="l00515"></a>00515 <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a> op4) { <a name="l00516"></a>00516 <a name="l00517"></a>00517 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#1647966dc2ac0f213f9674e6c1e7e336">mode</a>=mode; <a name="l00518"></a>00518 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#bdc1758a5dc07d92701e95617d539909">iclass</a> = iclass; <a name="l00519"></a>00519 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#2b23c8d18171f9a4699744992b5cc026">effective_operand_width</a> = effective_operand_width; <a name="l00520"></a>00520 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#d829df66320029ad521451b2896b18f3">effective_address_width</a> = 0; <a name="l00521"></a>00521 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">prefixes</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#15762219ece938eca0db01a735121dbe">i</a> = 0; <a name="l00522"></a>00522 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[0] = op0; <a name="l00523"></a>00523 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[1] = op1; <a name="l00524"></a>00524 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[2] = op2; <a name="l00525"></a>00525 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[3] = op3; <a name="l00526"></a>00526 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[4] = op4; <a name="l00527"></a>00527 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#10c44c5cf064364003d1d4f6f4bbb7da">noperands</a> = 5; <a name="l00528"></a>00528 } <a name="l00529"></a>00529 <a name="l00530"></a>00530 <span class="comment"></span> <a name="l00531"></a>00531 <span class="comment">/// @ingroup ENCHL</span> <a name="l00532"></a>00532 <span class="comment">/// instruction with an array of operands. The maximum number is</span> <a name="l00533"></a>00533 <span class="comment">/// XED_ENCODER_OPERANDS_MAX. The array's contents are copied.</span> <a name="l00534"></a><a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#0b2f5d72a7c89397c9eb011280d4b001">00534</a> <span class="comment"></span>XED_INLINE <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="xed2-ia32_2include_2xed-encoder-hl_8h.html#0b2f5d72a7c89397c9eb011280d4b001">xed_inst</a>( <a name="l00535"></a>00535 <a class="code" href="structxed__encoder__instruction__t.html">xed_encoder_instruction_t</a>* inst, <a name="l00536"></a>00536 <a class="code" href="group__INIT.html#g58af142456a133c3df29c763216a85cf">xed_state_t</a> mode, <a name="l00537"></a>00537 <a class="code" href="xed2-ia32_2include_2xed-iclass-enum_8h.html#d318511ae9cc50f102251b3c91a1ab9f">xed_iclass_enum_t</a> iclass, <a name="l00538"></a>00538 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> effective_operand_width, <a name="l00539"></a>00539 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> number_of_operands, <a name="l00540"></a>00540 <span class="keyword">const</span> <a class="code" href="structxed__encoder__operand__t.html">xed_encoder_operand_t</a>* operand_array) { <a name="l00541"></a>00541 <a name="l00542"></a>00542 <a class="code" href="xed2-ia32_2include_2xed-types_8h.html#0c92e8263b7ca02d8e4826ae5b79bb30">xed_uint_t</a> i; <a name="l00543"></a>00543 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#1647966dc2ac0f213f9674e6c1e7e336">mode</a>=mode; <a name="l00544"></a>00544 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#bdc1758a5dc07d92701e95617d539909">iclass</a> = iclass; <a name="l00545"></a>00545 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#2b23c8d18171f9a4699744992b5cc026">effective_operand_width</a> = effective_operand_width; <a name="l00546"></a>00546 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#d829df66320029ad521451b2896b18f3">effective_address_width</a> = 0; <a name="l00547"></a>00547 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#76abfb9a09afa6474a8c673db06a3839">prefixes</a>.<a class="code" href="unionxed__encoder__prefixes__t.html#15762219ece938eca0db01a735121dbe">i</a> = 0; <a name="l00548"></a>00548 xed_assert(number_of_operands &lt; XED_ENCODER_OPERANDS_MAX); <a name="l00549"></a>00549 <span class="keywordflow">for</span>(i=0;i&lt;number_of_operands;i++) { <a name="l00550"></a>00550 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#0cc465ba90570b77abcc6e2833b43673">operands</a>[i] = operand_array[i]; <a name="l00551"></a>00551 } <a name="l00552"></a>00552 inst-&gt;<a class="code" href="structxed__encoder__instruction__t.html#10c44c5cf064364003d1d4f6f4bbb7da">noperands</a> = number_of_operands; <a name="l00553"></a>00553 } <a name="l00554"></a>00554 <span class="comment"></span> <a name="l00555"></a>00555 <span class="comment">//@}</span> <a name="l00556"></a>00556 <span class="comment"></span> <a name="l00557"></a>00557 <span class="comment">/*</span> <a name="l00558"></a>00558 <span class="comment"> xed_encoder_instruction_t x,y;</span> <a name="l00559"></a>00559 <span class="comment"></span> <a name="l00560"></a>00560 <span class="comment"> xed_inst2(&amp;x, state, XED_ICLASS_ADD, 32, </span> <a name="l00561"></a>00561 <span class="comment"> xreg(XED_REG_EAX), </span> <a name="l00562"></a>00562 <span class="comment"> xmem_bd(XED_REG_EDX, xdisp(0x11223344, 32), 32));</span> <a name="l00563"></a>00563 <span class="comment"> </span> <a name="l00564"></a>00564 <span class="comment"> xed_inst2(&amp;y, state, XED_ICLASS_ADD, 32, </span> <a name="l00565"></a>00565 <span class="comment"> xreg(XED_REG_EAX), </span> <a name="l00566"></a>00566 <span class="comment"> xmem_gbisd(XED_REG_FS, XED_REG_EAX, XED_REG_ESI,4, xdisp(0x11223344, 32), 32));</span> <a name="l00567"></a>00567 <span class="comment"></span> <a name="l00568"></a>00568 <span class="comment"> */</span> <a name="l00569"></a>00569 <a name="l00570"></a>00570 <span class="preprocessor">#endif</span> </pre></div></div> <hr> <p class="footer"> Generated on Fri Mar 30 16:18:24 2012 for <a href="http://bitblaze.cs.berkeley.edu/temu.html">TEMU</a> by <a href="http://www.doxygen.org"><img src="doxygen.png" alt="Doxygen" align="middle" border="0"/>1.5.8</a><br/> Copyright &copy; 2008-2009, BitBlaze Project. All Rights Reserved.</p> <hr> <!--#include virtual="/attrib.incl" --> </body> </html>
Java
BoardConnetServer ================= server application that run on embedded linux based development boards ( Begalbone Bone, Beagleboard, Altera SocKit, Xilinx ZedBoard ) connects to android app
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>Luayats: src/src/bssrc.h Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.6.1 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul> </div> <h1>src/src/bssrc.h</h1><a href="bssrc_8h.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*************************************************************************</span> <a name="l00002"></a>00002 <span class="comment">*</span> <a name="l00003"></a>00003 <span class="comment">* YATS - Yet Another Tiny Simulator</span> <a name="l00004"></a>00004 <span class="comment">*</span> <a name="l00005"></a>00005 <span class="comment">**************************************************************************</span> <a name="l00006"></a>00006 <span class="comment">*</span> <a name="l00007"></a>00007 <span class="comment">* Copyright (C) 1995-1997 Chair for Telecommunications</span> <a name="l00008"></a>00008 <span class="comment">* Dresden University of Technology</span> <a name="l00009"></a>00009 <span class="comment">* D-01062 Dresden</span> <a name="l00010"></a>00010 <span class="comment">* Germany</span> <a name="l00011"></a>00011 <span class="comment">*</span> <a name="l00012"></a>00012 <span class="comment">**************************************************************************</span> <a name="l00013"></a>00013 <span class="comment">*</span> <a name="l00014"></a>00014 <span class="comment">* This program is free software; you can redistribute it and/or modify</span> <a name="l00015"></a>00015 <span class="comment">* it under the terms of the GNU General Public License as published by</span> <a name="l00016"></a>00016 <span class="comment">* the Free Software Foundation; either version 2 of the License, or</span> <a name="l00017"></a>00017 <span class="comment">* (at your option) any later version.</span> <a name="l00018"></a>00018 <span class="comment">*</span> <a name="l00019"></a>00019 <span class="comment">* This program is distributed in the hope that it will be useful,</span> <a name="l00020"></a>00020 <span class="comment">* but WITHOUT ANY WARRANTY; without even the implied warranty of</span> <a name="l00021"></a>00021 <span class="comment">* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</span> <a name="l00022"></a>00022 <span class="comment">* GNU General Public License for more details.</span> <a name="l00023"></a>00023 <span class="comment">*</span> <a name="l00024"></a>00024 <span class="comment">* You should have received a copy of the GNU General Public License</span> <a name="l00025"></a>00025 <span class="comment">* along with this program; if not, write to the Free Software</span> <a name="l00026"></a>00026 <span class="comment">* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.</span> <a name="l00027"></a>00027 <span class="comment">*</span> <a name="l00028"></a>00028 <span class="comment">*************************************************************************/</span> <a name="l00029"></a>00029 <a name="l00030"></a>00030 <span class="comment">// changed 2004-10-15: included deterministic_behaviour variable.</span> <a name="l00031"></a>00031 <span class="comment">// If deterministic_behaviour is set to 1, the burst and silence</span> <a name="l00032"></a>00032 <span class="comment">// lengths are fix, not chosen from a distribution</span> <a name="l00033"></a>00033 <a name="l00034"></a>00034 <span class="preprocessor">#ifndef _BSSRC_H_</span> <a name="l00035"></a>00035 <span class="preprocessor"></span><span class="preprocessor">#define _BSSRC_H_</span> <a name="l00036"></a>00036 <span class="preprocessor"></span> <a name="l00037"></a>00037 <span class="preprocessor">#include &quot;<a class="code" href="in1out_8h.html">in1out.h</a>&quot;</span> <a name="l00038"></a>00038 <a name="l00039"></a>00039 <span class="comment">//tolua_begin</span> <a name="l00040"></a><a class="code" href="classbssrc.html">00040</a> <span class="keyword">class </span><a class="code" href="classbssrc.html">bssrc</a>: <span class="keyword">public</span> <a class="code" href="classin1out.html">in1out</a> { <a name="l00041"></a>00041 <span class="keyword">typedef</span> <a class="code" href="classin1out.html">in1out</a> <a class="code" href="classino.html">baseclass</a>; <a name="l00042"></a>00042 <a name="l00043"></a>00043 <span class="keyword">public</span>: <a name="l00044"></a>00044 <a class="code" href="classbssrc.html#a798d93c795807f551b5089105cc7f4ba">bssrc</a>(); <a name="l00045"></a>00045 <a class="code" href="classbssrc.html#ae3dea53e1cc3d34c19ee0b212d1a7903">~bssrc</a>(); <a name="l00046"></a>00046 <a name="l00047"></a>00047 <span class="keywordtype">void</span> <a class="code" href="classbssrc.html#a7125cf14df4e4eacf34134f9ddeec2dd">SetDeterministicEx</a>(<span class="keywordtype">int</span> det); <span class="comment">// included 2004-10-29</span> <a name="l00048"></a>00048 <span class="keywordtype">void</span> <a class="code" href="classbssrc.html#a999b5f13126c9a57815002241d1046fa">SetDeterministicEs</a>(<span class="keywordtype">int</span> det); <span class="comment">// included 2004-10-29</span> <a name="l00049"></a>00049 <a name="l00050"></a>00050 <span class="keywordtype">int</span> <a class="code" href="classbssrc.html#a042da540921e8918b2e3f6aa8a95e41b">act</a>(<span class="keywordtype">void</span>); <a name="l00051"></a>00051 <a name="l00052"></a><a class="code" href="classbssrc.html#a56cddf2f5d2321cfbd22689acc41dc30">00052</a> <span class="keywordtype">double</span> <a class="code" href="classbssrc.html#a56cddf2f5d2321cfbd22689acc41dc30">ex</a>; <a name="l00053"></a><a class="code" href="classbssrc.html#afa70bb6a8176a4e761f524ac6f9851d8">00053</a> <span class="keywordtype">double</span> <a class="code" href="classbssrc.html#afa70bb6a8176a4e761f524ac6f9851d8">es</a>; <a name="l00054"></a><a class="code" href="classbssrc.html#a39990a2f8d7eefaa07e793a264a1a444">00054</a> <span class="keywordtype">int</span> <a class="code" href="classbssrc.html#a39990a2f8d7eefaa07e793a264a1a444">delta</a>; <a name="l00055"></a><a class="code" href="classbssrc.html#afc8a6c1a6dff3b90684114fa96ac9c6c">00055</a> <span class="keywordtype">int</span> <a class="code" href="classbssrc.html#afc8a6c1a6dff3b90684114fa96ac9c6c">dist_burst</a>; <a name="l00056"></a><a class="code" href="classbssrc.html#a67611af2013faadc2ab2b6e475eb09dd">00056</a> <span class="keywordtype">int</span> <a class="code" href="classbssrc.html#a67611af2013faadc2ab2b6e475eb09dd">dist_silence</a>; <a name="l00057"></a><a class="code" href="classbssrc.html#a5653d81a51400e9a730882941c77f864">00057</a> <span class="keywordtype">int</span> <a class="code" href="classbssrc.html#a5653d81a51400e9a730882941c77f864">state</a>; <span class="comment">/* current state:</span> <a name="l00058"></a>00058 <span class="comment"> * is decremented with each sent cell. If</span> <a name="l00059"></a>00059 <span class="comment"> * state = 0, the current burst is finished</span> <a name="l00060"></a>00060 <span class="comment"> */</span> <a name="l00061"></a><a class="code" href="classbssrc.html#a7ec09a637098664b8759de51fc5f56f1">00061</a> <span class="keywordtype">int</span> <a class="code" href="classbssrc.html#a7ec09a637098664b8759de51fc5f56f1">deterministic_ex</a>; <span class="comment">// included 2004-10-15</span> <a name="l00062"></a><a class="code" href="classbssrc.html#a23ea6616e620b70f9b6283fdc0f7a6f2">00062</a> <span class="keywordtype">int</span> <a class="code" href="classbssrc.html#a23ea6616e620b70f9b6283fdc0f7a6f2">deterministic_es</a>; <span class="comment">// included 2004-10-15</span> <a name="l00063"></a>00063 <span class="comment">//tolua_end</span> <a name="l00064"></a>00064 <a name="l00065"></a>00065 <span class="keywordtype">void</span> <a class="code" href="classbssrc.html#ac90d250944f3fdcc7b7cda6ff917f9ea">early</a>(<a class="code" href="classevent.html">event</a> *); <a name="l00066"></a>00066 }; <span class="comment">//tolua_export</span> <a name="l00067"></a>00067 <a name="l00068"></a>00068 <span class="preprocessor">#endif // _BSSRC_H_</span> </pre></div></div> <hr size="1"/><address style="text-align: right;"><small>Generated on Sun Feb 14 12:31:42 2010 for Luayats by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.1 </small></address> </body> </html>
Java
<?php /** * @version 3.2.11 September 8, 2011 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2011 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ defined('GANTRY_VERSION') or die; gantry_import('core.config.gantryformgroup'); gantry_import('core.config.gantryformfield'); class GantryFormGroupEnabledGroup extends GantryFormGroup { protected $type = 'enabledgroup'; protected $baseetype = 'group'; protected $sets = array(); protected $enabler; public function getInput() { global $gantry; $buffer = ''; // get the sets just below foreach ($this->fields as $field) { if ($field->type == 'set') { $this->sets[] = $field; } } $buffer .= "<div class='wrapper'>\n"; foreach ($this->fields as $field) { if ((string)$field->type != 'set') { $enabler = false; if ($field->element['enabler'] && (string)$field->element['enabler'] == true){ $this->enabler = $field; $enabler = true; } $itemName = $this->fieldname . "-" . $field->fieldname; $buffer .= '<div class="chain ' . $itemName . ' chain-' . strtolower($field->type) . '">' . "\n"; if (strlen($field->getLabel())) $buffer .= '<span class="chain-label">' . JText::_($field->getLabel()) . '</span>' . "\n"; if ($enabler) $buffer .= '<div class="enabledset-enabler">'."\n"; $buffer .= $field->getInput(); if ($enabler) $buffer .= '</div>'."\n"; $buffer .= "</div>" . "\n"; } } $buffer .= "</div>" . "\n"; return $buffer; } public function render($callback) { $buffer = parent::render($callback); $cls = ' enabledset-hidden-field'; if (!empty($this->sets)){ $set = array_shift($this->sets); if (isset($this->enabler) && (int)$this->enabler->value == 0){ $cls = ' enabledset-hidden-field'; } $buffer .= '<div class="enabledset-fields'.$cls.'" id="set-'.(string)$set->element['name'].'">'; foreach ($set->fields as $field) { if ($field->type == 'hidden') $buffer .= $field->getInput(); else { $buffer .= $field->render($callback); } } $buffer .= '</div>'; } return $buffer; } }
Java
# -*- coding: utf-8 -*- import time import EafIO import warnings class Eaf: """Read and write Elan's Eaf files. .. note:: All times are in milliseconds and can't have decimals. :var dict annotation_document: Annotation document TAG entries. :var dict licences: Licences included in the file. :var dict header: XML header. :var list media_descriptors: Linked files, where every file is of the form: ``{attrib}``. :var list properties: Properties, where every property is of the form: ``(value, {attrib})``. :var list linked_file_descriptors: Secondary linked files, where every linked file is of the form: ``{attrib}``. :var dict timeslots: Timeslot data of the form: ``{TimslotID -> time(ms)}``. :var dict tiers: Tier data of the form: ``{tier_name -> (aligned_annotations, reference_annotations, attributes, ordinal)}``, aligned_annotations of the form: ``[{annotation_id -> (begin_ts, end_ts, value, svg_ref)}]``, reference annotations of the form: ``[{annotation_id -> (reference, value, previous, svg_ref)}]``. :var list linguistic_types: Linguistic types, where every type is of the form: ``{id -> attrib}``. :var list locales: Locales, where every locale is of the form: ``{attrib}``. :var dict constraints: Constraint data of the form: ``{stereotype -> description}``. :var dict controlled_vocabularies: Controlled vocabulary data of the form: ``{id -> (descriptions, entries, ext_ref)}``, descriptions of the form: ``[(lang_ref, text)]``, entries of the form: ``{id -> (values, ext_ref)}``, values of the form: ``[(lang_ref, description, text)]``. :var list external_refs: External references, where every reference is of the form ``[id, type, value]``. :var list lexicon_refs: Lexicon references, where every reference is of the form: ``[{attribs}]``. """ def __init__(self, file_path=None, author='pympi'): """Construct either a new Eaf file or read on from a file/stream. :param str file_path: Path to read from, - for stdin. If ``None`` an empty Eaf file will be created. :param str author: Author of the file. """ self.naive_gen_ann, self.naive_gen_ts = False, False self.annotation_document = { 'AUTHOR': author, 'DATE': time.strftime("%Y-%m-%dT%H:%M:%S%z"), 'VERSION': '2.8', 'FORMAT': '2.8', 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:noNamespaceSchemaLocation': 'http://www.mpi.nl/tools/elan/EAFv2.8.xsd'} self.constraints = {} self.controlled_vocabularies = {} self.header = {} self.licences = {} self.linguistic_types = {} self.tiers = {} self.timeslots = {} self.external_refs = [] self.lexicon_refs = [] self.linked_file_descriptors = [] self.locales = [] self.media_descriptors = [] self.properties = [] self.new_time, self.new_ann = 0, 0 if file_path is None: self.add_linguistic_type('default-lt', None) self.constraints = {'Time_Subdivision': 'Time subdivision of paren' 't annotation\'s time interval, no time gaps a' 'llowed within this interval', 'Symbolic_Subdivision': 'Symbolic subdivision ' 'of a parent annotation. Annotations refering ' 'to the same parent are ordered', 'Symbolic_Association': '1-1 association with ' 'a parent annotation', 'Included_In': 'Time alignable annotations wit' 'hin the parent annotation\'s time interval, g' 'aps are allowed'} self.properties.append(('0', {'NAME': 'lastUsedAnnotation'})) self.add_tier('default') else: EafIO.parse_eaf(file_path, self) def to_file(self, file_path, pretty=True): """Write the object to a file, if the file already exists a backup will be created with the ``.bak`` suffix. :param str file_path: Path to write to, - for stdout. :param bool pretty: Flag for pretty XML printing. """ EafIO.to_eaf(file_path, self, pretty) def to_textgrid(self, excluded_tiers=[], included_tiers=[]): """Convert the object to a :class:`pympi.Praat.TextGrid` object. :param list excluded_tiers: Specifically exclude these tiers. :param list included_tiers: Only include this tiers, when empty all are included. :returns: :class:`pympi.Praat.TextGrid` object :raises ImportError: If the pympi.Praat module can't be loaded. """ from Praat import TextGrid tgout = TextGrid() tiers = [a for a in self.tiers if a not in excluded_tiers] if included_tiers: tiers = [a for a in tiers if a in included_tiers] for tier in tiers: currentTier = tgout.add_tier(tier) for interval in self.get_annotation_data_for_tier(tier): if interval[0] == interval[1]: continue currentTier.add_interval(interval[0]/1000.0, interval[1]/1000.0, interval[2]) return tgout def extract(self, start, end): """Extracts the selected time frame as a new object. :param int start: Start time. :param int end: End time. :returns: The extracted frame in a new object. """ from copy import deepcopy eaf_out = deepcopy(self) for tier in eaf_out.tiers.itervalues(): rems = [] for ann in tier[0]: if eaf_out.timeslots[tier[0][ann][1]] > end or\ eaf_out.timeslots[tier[0][ann][0]] < start: rems.append(ann) for r in rems: del tier[0][r] return eaf_out def get_linked_files(self): """Give all linked files.""" return self.media_descriptors def add_linked_file(self, file_path, relpath=None, mimetype=None, time_origin=None, ex_from=None): """Add a linked file. :param str file_path: Path of the file. :param str relpath: Relative path of the file. :param str mimetype: Mimetype of the file, if ``None`` it tries to guess it according to the file extension which currently only works for wav, mpg, mpeg and xml. :param int time_origin: Time origin for the media file. :param str ex_from: Extracted from field. :raises KeyError: If mimetype had to be guessed and a non standard extension or an unknown mimetype. """ if mimetype is None: mimes = {'wav': 'audio/x-wav', 'mpg': 'video/mpeg', 'mpeg': 'video/mpg', 'xml': 'text/xml'} mimetype = mimes[file_path.split('.')[-1]] self.media_descriptors.append({ 'MEDIA_URL': file_path, 'RELATIVE_MEDIA_URL': relpath, 'MIME_TYPE': mimetype, 'TIME_ORIGIN': time_origin, 'EXTRACTED_FROM': ex_from}) def copy_tier(self, eaf_obj, tier_name): """Copies a tier to another :class:`pympi.Elan.Eaf` object. :param pympi.Elan.Eaf eaf_obj: Target Eaf object. :param str tier_name: Name of the tier. :raises KeyError: If the tier doesn't exist. """ eaf_obj.remove_tier(tier_name) eaf_obj.add_tier(tier_name, tier_dict=self.tiers[tier_name][3]) for ann in self.get_annotation_data_for_tier(tier_name): eaf_obj.insert_annotation(tier_name, ann[0], ann[1], ann[2]) def add_tier(self, tier_id, ling='default-lt', parent=None, locale=None, part=None, ann=None, tier_dict=None): """Add a tier. :param str tier_id: Name of the tier. :param str ling: Linguistic type, if the type is not available it will warn and pick the first available type. :param str parent: Parent tier name. :param str locale: Locale. :param str part: Participant. :param str ann: Annotator. :param dict tier_dict: TAG attributes, when this is not ``None`` it will ignore all other options. """ if ling not in self.linguistic_types: warnings.warn( 'add_tier: Linguistic type non existent, choosing the first') ling = self.linguistic_types.keys()[0] if tier_dict is None: self.tiers[tier_id] = ({}, {}, { 'TIER_ID': tier_id, 'LINGUISTIC_TYPE_REF': ling, 'PARENT_REF': parent, 'PARTICIPANT': part, 'DEFAULT_LOCALE': locale, 'ANNOTATOR': ann}, len(self.tiers)) else: self.tiers[tier_id] = ({}, {}, tier_dict, len(self.tiers)) def remove_tiers(self, tiers): """Remove multiple tiers, note that this is a lot faster then removing them individually because of the delayed cleaning of timeslots. :param list tiers: Names of the tier to remove. :raises KeyError: If a tier is non existent. """ for a in tiers: self.remove_tier(a, check=False, clean=False) self.clean_time_slots() def remove_tier(self, id_tier, clean=True): """Remove tier. :param str id_tier: Name of the tier. :param bool clean: Flag to also clean the timeslots. :raises KeyError: If tier is non existent. """ del(self.tiers[id_tier]) if clean: self.clean_time_slots() def get_tier_names(self): """List all the tier names. :returns: List of all tier names """ return self.tiers.keys() def get_parameters_for_tier(self, id_tier): """Give the parameter dictionary, this is usaable in :func:`add_tier`. :param str id_tier: Name of the tier. :returns: Dictionary of parameters. :raises KeyError: If the tier is non existent. """ return self.tiers[id_tier][2] def child_tiers_for(self, id_tier): """Give all child tiers for a tier. :param str id_tier: Name of the tier. :returns: List of all children :raises KeyError: If the tier is non existent. """ return [m for m in self.tiers if 'PARENT_REF' in self.tiers[m][2] and self.tiers[m][2]['PARENT_REF'] == id_tier] def get_annotation_data_for_tier(self, id_tier): """Gives a list of annotations of the form: ``(begin, end, value)`` :param str id_tier: Name of the tier. :raises KeyError: If the tier is non existent. """ a = self.tiers[id_tier][0] return [(self.timeslots[a[b][0]], self.timeslots[a[b][1]], a[b][2]) for b in a] def get_annotation_data_at_time(self, id_tier, time): """Give the annotations at the given time. :param str id_tier: Name of the tier. :param int time: Time of the annotation. :returns: List of annotations at that time. :raises KeyError: If the tier is non existent. """ anns = self.tiers[id_tier][0] return sorted( [(self.timeslots[m[0]], self.timeslots[m[1]], m[2]) for m in anns.itervalues() if self.timeslots[m[0]] <= time and self.timeslots[m[1]] >= time]) def get_annotation_datas_between_times(self, id_tier, start, end): """Gives the annotations within the times. :param str id_tier: Name of the tier. :param int start: Start time of the annotation. :param int end: End time of the annotation. :returns: List of annotations within that time. :raises KeyError: If the tier is non existent. """ anns = self.tiers[id_tier][0] return sorted([ (self.timeslots[m[0]], self.timeslots[m[1]], m[2]) for m in anns.itervalues() if self.timeslots[m[1]] >= start and self.timeslots[m[0]] <= end]) def remove_all_annotations_from_tier(self, id_tier): """remove all annotations from a tier :param str id_tier: Name of the tier. :raises KeyError: If the tier is non existent. """ self.tiers[id_tier][0], self.tiers[id_tier][1] = {}, {} self.clean_time_slots() def insert_annotation(self, id_tier, start, end, value='', svg_ref=None): """Insert an annotation. :param str id_tier: Name of the tier. :param int start: Start time of the annotation. :param int end: End time of the annotation. :param str value: Value of the annotation. :param str svg_ref: Svg reference. :raises KeyError: If the tier is non existent. """ start_ts = self.generate_ts_id(start) end_ts = self.generate_ts_id(end) self.tiers[id_tier][0][self.generate_annotation_id()] =\ (start_ts, end_ts, value, svg_ref) def remove_annotation(self, id_tier, time, clean=True): """Remove an annotation in a tier, if you need speed the best thing is to clean the timeslots after the last removal. :param str id_tier: Name of the tier. :param int time: Timepoint within the annotation. :param bool clean: Flag to clean the timeslots afterwards. :raises KeyError: If the tier is non existent. """ for b in [a for a in self.tiers[id_tier][0].iteritems() if a[1][0] >= time and a[1][1] <= time]: del(self.tiers[id_tier][0][b[0]]) if clean: self.clean_time_slots() def insert_ref_annotation(self, id_tier, ref, value, prev, svg_ref=None): """Insert a reference annotation. :param str id_tier: Name of the tier. :param str ref: Id of the referenced annotation. :param str value: Value of the annotation. :param str prev: Id of the previous annotation. :param str svg_ref: Svg reference. :raises KeyError: If the tier is non existent. """ self.tiers[id_tier][1][self.generate_annotation_id()] =\ (ref, value, prev, svg_ref) def get_ref_annotation_data_for_tier(self, id_tier): """"Give a list of all reference annotations of the form: ``[{id -> (ref, value, previous, svg_ref}]`` :param str id_tier: Name of the tier. :raises KeyError: If the tier is non existent. """ return self.tiers[id_tier][1] def remove_controlled_vocabulary(self, cv): """Remove a controlled vocabulary. :param str cv: Controlled vocabulary id. :raises KeyError: If the controlled vocabulary is non existent. """ del(self.controlled_vocabularies[cv]) def generate_annotation_id(self): """Generate the next annotation id, this function is mainly used internally. """ if self.naive_gen_ann: new = self.last_ann+1 self.last_ann = new else: new = 1 anns = {int(ann[1:]) for tier in self.tiers.itervalues() for ann in tier[0]} if len(anns) > 0: newann = set(xrange(1, max(anns))).difference(anns) if len(newann) == 0: new = max(anns)+1 self.naive_gen_ann = True self.last_ann = new else: new = sorted(newann)[0] return 'a%d' % new def generate_ts_id(self, time=None): """Generate the next timeslot id, this function is mainly used internally :param int time: Initial time to assign to the timeslot """ if self.naive_gen_ts: new = self.last_ts+1 self.last_ts = new else: new = 1 tss = {int(x[2:]) for x in self.timeslots} if len(tss) > 0: newts = set(xrange(1, max(tss))).difference(tss) if len(newts) == 0: new = max(tss)+1 self.naive_gen_ts = True self.last_ts = new else: new = sorted(newts)[0] ts = 'ts%d' % new self.timeslots[ts] = time return ts def clean_time_slots(self): """Clean up all unused timeslots. .. warning:: This can and will take time for larger tiers. When you want to do a lot of operations on a lot of tiers please unset the flags for cleaning in the functions so that the cleaning is only performed afterwards. """ ts_in_tier = set(sum([a[0:2] for tier in self.tiers.itervalues() for a in tier[0].itervalues()], ())) ts_avail = set(self.timeslots) for a in ts_in_tier.symmetric_difference(ts_avail): del(self.timeslots[a]) self.naive_gen_ts = False self.naive_gen_ann = False def generate_annotation_concat(self, tiers, start, end, sep='-'): """Give a string of concatenated annotation values for annotations within a timeframe. :param list tiers: List of tier names. :param int start: Start time. :param int end: End time. :param str sep: Separator string to use. :returns: String containing a concatenation of annotation values. :raises KeyError: If a tier is non existent. """ return sep.join( set(d[2] for t in tiers if t in self.tiers for d in self.get_annotation_datas_between_times(t, start, end))) def merge_tiers(self, tiers, tiernew=None, gaptresh=1): """Merge tiers into a new tier and when the gap is lower then the threshhold glue the annotations together. :param list tiers: List of tier names. :param str tiernew: Name for the new tier, if ``None`` the name will be generated. :param int gapthresh: Threshhold for the gaps. :raises KeyError: If a tier is non existent. :raises TypeError: If there are no annotations within the tiers. """ if tiernew is None: tiernew = '%s_Merged' % '_'.join(tiers) self.remove_tier(tiernew) self.add_tier(tiernew) timepts = sorted(set.union( *[set(j for j in xrange(d[0], d[1])) for d in [ann for tier in tiers for ann in self.get_annotation_data_for_tier(tier)]])) if len(timepts) > 1: start = timepts[0] for i in xrange(1, len(timepts)): if timepts[i]-timepts[i-1] > gaptresh: self.insert_annotation( tiernew, start, timepts[i-1], self.generate_annotation_concat(tiers, start, timepts[i-1])) start = timepts[i] self.insert_annotation( tiernew, start, timepts[i-1], self.generate_annotation_concat(tiers, start, timepts[i-1])) def shift_annotations(self, time): """Shift all annotations in time, this creates a new object. :param int time: Time shift width, negative numbers make a right shift. :returns: Shifted :class:`pympi.Elan.Eaf' object. """ e = self.extract( -1*time, self.get_full_time_interval()[1]) if time < 0 else\ self.extract(0, self.get_full_time_interval()[1]-time) for tier in e.tiers.itervalues(): for ann in tier[0].itervalues(): e.timeslots[ann[0]] = e.timeslots[ann[0]]+time e.timeslots[ann[1]] = e.timeslots[ann[1]]+time e.clean_time_slots() return e def filterAnnotations(self, tier, tier_name=None, filtin=None, filtex=None): """Filter annotations in a tier :param str tier: Name of the tier: :param str tier_name: Name of the new tier, when ``None`` the name will be generated. :param list filtin: List of strings to be included, if None all annotations all is included. :param list filtex: List of strings to be excluded, if None no strings are excluded. :raises KeyError: If the tier is non existent. """ if tier_name is None: tier_name = '%s_filter' % tier self.remove_tier(tier_name) self.add_tier(tier_name) for a in [b for b in self.get_annotation_data_for_tier(tier) if (filtex is None or b[2] not in filtex) and (filtin is None or b[2] in filtin)]: self.insert_annotation(tier_name, a[0], a[1], a[2]) def glue_annotations_in_tier(self, tier, tier_name=None, treshhold=85, filtin=None, filtex=None): """Glue annotatotions together in a tier. :param str tier: Name of the tier. :param str tier_name: Name of the new tier, if ``None`` the name will be generated. :param int threshhold: Threshhold for the maximum gap to still glue. :param list filtin: List of strings to be included, if None all annotations all is included. :param list filtex: List of strings to be excluded, if None no strings are excluded. :raises KeyError: If the tier is non existent. """ if tier_name is None: tier_name = '%s_glued' % tier self.remove_tier(tier_name) self.add_tier(tier_name) tier_data = sorted(self.get_annotation_data_for_tier(tier)) tier_data = [t for t in tier_data if (filtin is None or t[2] in filtin) and (filtex is None or t[2] not in filtex)] currentAnn = None for i in xrange(0, len(tier_data)): if currentAnn is None: currentAnn = (tier_data[i][0], tier_data[i][1], tier_data[i][2]) elif tier_data[i][0] - currentAnn[1] < treshhold: currentAnn = (currentAnn[0], tier_data[i][1], '%s_%s' % (currentAnn[2], tier_data[i][2])) else: self.insert_annotation(tier_name, currentAnn[0], currentAnn[1], currentAnn[2]) currentAnn = tier_data[i] if currentAnn is not None: self.insert_annotation(tier_name, currentAnn[0], tier_data[len(tier_data)-1][1], currentAnn[2]) def get_full_time_interval(self): """Give the full time interval of the file. :returns: Tuple of the form: ``(min_time, max_time``. """ return (min(self.timeslots.itervalues()), max(self.timeslots.itervalues())) def create_gaps_and_overlaps_tier(self, tier1, tier2, tier_name=None, maxlen=-1): """Create a tier with the gaps and overlaps of the annotations. For types see :func:`get_gaps_and_overlaps_duration` :param str tier1: Name of the first tier. :param str tier2: Name of the second tier. :param str tier_name: Name of the new tier, if ``None`` the name will be generated. :param int maxlen: Maximum length of gaps (skip longer ones), if ``-1`` no maximum will be used. :returns: List of gaps and overlaps of the form: ``[(type, start, end)]``. :raises KeyError: If a tier is non existent. :raises IndexError: If no annotations are available in the tiers. """ if tier_name is None: tier_name = '%s_%s_ftos' % (tier1, tier2) self.remove_tier(tier_name) self.add_tier(tier_name) ftos = self.get_gaps_and_overlaps_duration(tier1, tier2, maxlen) for fto in ftos: self.insert_annotation(tier_name, fto[1], fto[2], fto[0]) return ftos def get_gaps_and_overlaps_duration(self, tier1, tier2, maxlen=-1, progressbar=False): """Give gaps and overlaps. The return types are shown in the table below. The string will be of the format: ``id_tiername_tiername``. For example when a gap occurs between tier1 and tier2 and they are called ``speakerA`` and ``speakerB`` the annotation value of that gap will be ``G12_speakerA_speakerB``. | The gaps and overlaps are calculated using Heldner and Edlunds method found in: | *Heldner, M., & Edlund, J. (2010). Pauses, gaps and overlaps in conversations. Journal of Phonetics, 38(4), 555–568. doi:10.1016/j.wocn.2010.08.002* +-----+--------------------------------------------+ | id | Description | +=====+============================================+ | O12 | Overlap from tier1 to tier2 | +-----+--------------------------------------------+ | O21 | Overlap from tier2 to tier1 | +-----+--------------------------------------------+ | G12 | Gap from tier1 to tier2 | +-----+--------------------------------------------+ | G21 | Gap from tier2 to tier1 | +-----+--------------------------------------------+ | P1 | Pause for tier1 | +-----+--------------------------------------------+ | P2 | Pause for tier2 | +-----+--------------------------------------------+ | B12 | Within speaker overlap from tier1 to tier2 | +-----+--------------------------------------------+ | B21 | Within speaker overlap from tier2 to tier1 | +-----+--------------------------------------------+ :param str tier1: Name of the first tier. :param str tier2: Name of the second tier. :param int maxlen: Maximum length of gaps (skip longer ones), if ``-1`` no maximum will be used. :param bool progressbar: Flag for debugging purposes that shows the progress during the process. :returns: List of gaps and overlaps of the form: ``[(type, start, end)]``. :raises KeyError: If a tier is non existent. :raises IndexError: If no annotations are available in the tiers. """ spkr1anns = sorted((self.timeslots[a[0]], self.timeslots[a[1]]) for a in self.tiers[tier1][0].values()) spkr2anns = sorted((self.timeslots[a[0]], self.timeslots[a[1]]) for a in self.tiers[tier2][0].values()) line1 = [] isin = lambda x, lst: False if\ len([i for i in lst if i[0] <= x and i[1] >= x]) == 0 else True minmax = (min(spkr1anns[0][0], spkr2anns[0][0]), max(spkr1anns[-1][1], spkr2anns[-1][1])) last = (1, minmax[0]) lastP = 0 for ts in xrange(*minmax): in1, in2 = isin(ts, spkr1anns), isin(ts, spkr2anns) if in1 and in2: # Both speaking if last[0] == 'B': continue ty = 'B' elif in1: # Only 1 speaking if last[0] == '1': continue ty = '1' elif in2: # Only 2 speaking if last[0] == '2': continue ty = '2' else: # None speaking if last[0] == 'N': continue ty = 'N' line1.append((last[0], last[1], ts)) last = (ty, ts) if progressbar and int((ts*1.0/minmax[1])*100) > lastP: lastP = int((ts*1.0/minmax[1])*100) print '%d%%' % lastP line1.append((last[0], last[1], minmax[1])) ftos = [] for i in xrange(len(line1)): if line1[i][0] == 'N': if i != 0 and i < len(line1) - 1 and\ line1[i-1][0] != line1[i+1][0]: ftos.append(('G12_%s_%s' % (tier1, tier2) if line1[i-1][0] == '1' else 'G21_%s_%s' % (tier2, tier1), line1[i][1], line1[i][2])) else: ftos.append(('P_%s' % (tier1 if line1[i-1][0] == '1' else tier2), line1[i][1], line1[i][2])) elif line1[i][0] == 'B': if i != 0 and i < len(line1) - 1 and\ line1[i-1][0] != line1[i+1][0]: ftos.append(('O12_%s_%s' % ((tier1, tier2) if line1[i-1][0] else 'O21_%s_%s' % (tier2, tier1)), line1[i][1], line1[i][2])) else: ftos.append(('B_%s_%s' % ((tier1, tier2) if line1[i-1][0] == '1' else (tier2, tier1)), line1[i][1], line1[i][2])) return [f for f in ftos if maxlen == -1 or abs(f[2] - f[1]) < maxlen] def create_controlled_vocabulary(self, cv_id, descriptions, entries, ext_ref=None): """Create a controlled vocabulary. .. warning:: This is a very raw implementation and you should check the Eaf file format specification for the entries. :param str cv_id: Name of the controlled vocabulary. :param list descriptions: List of descriptions. :param dict entries: Entries dictionary. :param str ext_ref: External reference. """ self.controlledvocabularies[cv_id] = (descriptions, entries, ext_ref) def get_tier_ids_for_linguistic_type(self, ling_type, parent=None): """Give a list of all tiers matching a linguistic type. :param str ling_type: Name of the linguistic type. :param str parent: Only match tiers from this parent, when ``None`` this option will be ignored. :returns: List of tiernames. :raises KeyError: If a tier or linguistic type is non existent. """ return [t for t in self.tiers if self.tiers[t][2]['LINGUISTIC_TYPE_REF'] == ling_type and (parent is None or self.tiers[t][2]['PARENT_REF'] == parent)] def remove_linguistic_type(self, ling_type): """Remove a linguistic type. :param str ling_type: Name of the linguistic type. """ del(self.linguistic_types[ling_type]) def add_linguistic_type(self, lingtype, constraints=None, timealignable=True, graphicreferences=False, extref=None): """Add a linguistic type. :param str lingtype: Name of the linguistic type. :param list constraints: Constraint names. :param bool timealignable: Flag for time alignable. :param bool graphicreferences: Flag for graphic references. :param str extref: External reference. """ self.linguistic_types[lingtype] = { 'LINGUISTIC_TYPE_ID': lingtype, 'TIME_ALIGNABLE': str(timealignable).lower(), 'GRAPHIC_REFERENCES': str(graphicreferences).lower(), 'CONSTRAINTS': constraints} if extref is not None: self.linguistic_types[lingtype]['EXT_REF'] = extref def get_linguistic_types(self): """Give a list of available linguistic types. :returns: List of linguistic type names. """ return self.linguistic_types.keys()
Java
<div class="form-horizontal"> <h3>Create a new Data</h3> <div class="form-group"> <div class="col-md-offset-2 col-sm-2"> <a id="Create" name="Create" class="btn btn-primary" href="#/DataConfig/new"><span class="glyphicon glyphicon-plus-sign"></span> Create</a> </div> </div> </div> <hr /> <div> <h3>Search for Data</h3> <form id="DataConfigSearch" class="form-horizontal"> <div class="form-group"> <label for="project" class="col-sm-2 control-label">Project</label> <div class="col-sm-10"> <input id="project" name="project" class="form-control" type="text" ng-model="search.baseConfig.id.project" placeholder="Enter the Project Name"></input> </div> </div> <div class="form-group"> <label for="buildVersion" class="col-sm-2 control-label">Build Version</label> <div class="col-sm-10"> <input id="buildVersion" name="buildVersion" class="form-control" type="text" ng-model="search.baseConfig.id.buildVersion" placeholder="Enter the Build Version"></input> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-sm-10"> <a id="Search" name="Search" class="btn btn-primary" ng-click="performSearch()"><span class="glyphicon glyphicon-search"></span> Search</a> </div> </div> </form> </div> <div id="search-results"> <div class="table-responsive"> <table class="table table-responsive table-bordered table-striped clearfix"> <thead> <tr> <th>Name</th> <th>Browser</th> <th>Status</th> <th>Description</th> </tr> </thead> <tbody id="search-results-body"> <tr ng-repeat="result in searchResults | searchFilter:searchResults | startFrom:currentPage*pageSize | limitTo:pageSize"> <td><a href="#/DataConfig/edit/{{result.id}}">{{result.scriptName}}</a></td> <td><a href="#/DataConfig/edit/{{result.id}}">{{result.browser}}</a></td> <td><a href="#/DataConfig/edit/{{result.id}}">{{result.status}}</a></td> <td><a href="#/DataConfig/edit/{{result.id}}">{{result.description}}</a></td> </tr> </tbody> </table> </div> <ul class="pagination pagination-centered"> <li ng-class="{disabled:currentPage == 0}"><a id="prev" href ng-click="previous()">«</a></li> <li ng-repeat="n in pageRange" ng-class="{active:currentPage == n}" ng-click="setPage(n)"><a href ng-bind="n + 1">1</a></li> <li ng-class="{disabled: currentPage == (numberOfPages() - 1)}"> <a id="next" href ng-click="next()">»</a> </li> </ul> </div>
Java
% custom packages \usepackage{config/textpos} \setlength{\TPHorizModule}{1cm} \setlength{\TPVertModule}{1cm} \newcommand\crule[1][black]{\textcolor{#1}{\rule{2cm}{2cm}}} \newcommand{\hugetextsc}[1]{ { \begin{spacing}{\linespaceone} \textsc{\fontsize{\fontsizeone}{\fontsizeone}{\notosansfont #1}} \end{spacing} } } \newcommand{\btVFill}{\vskip0pt plus 1filll} \newcommand{\frameanimation}[4]{ { \usebackgroundtemplate{% \setbeamercolor{background canvas}{bg=black} \tikz[overlay,remember picture] \node[opacity=1, at=(current page.center)] { \animategraphics[loop,width=\paperwidth,autoplay]{#4}{#1}{#2}{#3} }; } \begin{frame}[plain] \end{frame} } } \usepackage{animate} \usepackage{graphicx} \usepackage{multimedia} \usepackage{media9}[2013/11/04] % Partial derivatives \newcommand*{\pd}[3][]{\ensuremath{\frac{\partial^{#1} #2}{\partial #3}}} % Letters \newcommand{\R}{\mathbb{R}} % Algorithms \usepackage{algorithm} \usepackage[noend]{algpseudocode}
Java
/* -*- c++ -*- Kvalobs - Free Quality Control Software for Meteorological Observations $Id: decodermgr.h,v 1.1.2.2 2007/09/27 09:02:27 paule Exp $ Copyright (C) 2007 met.no Contact information: Norwegian Meteorological Institute Box 43 Blindern 0313 OSLO NORWAY email: kvalobs-dev@met.no This file is part of KVALOBS KVALOBS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. KVALOBS 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 KVALOBS; if not, write to the Free Software Foundation Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __dnmi_decoder_DecoderMgr_h__ #define __dnmi_decoder_DecoderMgr_h__ #include <list> #include <string> #include <kvdb/kvdb.h> #include <fileutil/dso.h> #include <decoderbase/decoder.h> #include <kvalobs/kvTypes.h> #include <boost/noncopyable.hpp> #include <miconfparser/miconfparser.h> /** * \addtogroup kvdecoder * * @{ */ extern "C" { typedef kvalobs::decoder::DecoderBase* (*decoderFactory)(dnmi::db::Connection &con_, const ParamList &params, const std::list<kvalobs::kvTypes> &typeList, int decoderId_, const std::string &observationType_, const std::string &observation_); typedef void (*releaseDecoderFunc)(kvalobs::decoder::DecoderBase* decoder); typedef std::list<std::string> (*getObsTypes)(); typedef std::list<std::string> (*getObsTypesExt)( miutil::conf::ConfSection *theKvConf); typedef void (*setKvConf)(kvalobs::decoder::DecoderBase* decoder, miutil::conf::ConfSection *theKvConf); } namespace kvalobs { namespace decoder { /** * \brief DecoderMgr is responsible for loading of decoders. */ class DecoderMgr { struct DecoderItem : public boost::noncopyable { decoderFactory factory; releaseDecoderFunc releaseFunc; setKvConf setConf; dnmi::file::DSO *dso; time_t modTime; int decoderCount; int decoderId; std::list<std::string> obsTypes; DecoderItem(decoderFactory factory_, releaseDecoderFunc releaseFunc_, setKvConf setKvConf_, dnmi::file::DSO *dso_, time_t mTime) : factory(factory_), releaseFunc(releaseFunc_), setConf(setKvConf_), dso(dso_), modTime(mTime), decoderCount(0), decoderId(-1) { } ~DecoderItem() { delete dso; } }; typedef std::list<DecoderItem*> DecoderList; typedef std::list<DecoderItem*>::iterator IDecoderList; typedef std::list<DecoderItem*>::const_iterator CIDecoderList; DecoderList decoders; std::string decoderPath; std::string soVersion; miutil::conf::ConfSection *theKvConf; public: DecoderMgr(const std::string &decoderPath_, miutil::conf::ConfSection *theKvConf); DecoderMgr() : theKvConf(0) { } ; ~DecoderMgr(); std::string fixDecoderName(const std::string &driver); void setTheKvConf(miutil::conf::ConfSection *theKvConf); void setDecoderPath(const std::string &decoderPath_); /** * returns true when all decoder has a decoderCount of 0. */ bool readyForUpdate(); void updateDecoders(miutil::conf::ConfSection *theKvConf); void updateDecoders(); DecoderBase *findDecoder(dnmi::db::Connection &connection, const ParamList &params, const std::list<kvalobs::kvTypes> &typeList, const std::string &obsType, const std::string &obs, std::string &errorMsg); void releaseDecoder(DecoderBase *dec); int numberOfDecoders() const { return decoders.size(); } void obsTypes(std::list<std::string> &list); private: void clearDecoders(); }; /** @} */ } } #endif
Java
// <copyright file="Collision.cs" company="LeagueSharp"> // Copyright (c) 2015 LeagueSharp. // // 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/ // </copyright> namespace LeagueSharp.SDK { using System; using System.Collections.Generic; using System.Linq; using LeagueSharp.Data.Enumerations; using LeagueSharp.SDK.Polygons; using LeagueSharp.SDK.Utils; using SharpDX; /// <summary> /// Collision class, calculates collision for moving objects. /// </summary> public static class Collision { #region Static Fields private static MissileClient yasuoWallLeft, yasuoWallRight; private static RectanglePoly yasuoWallPoly; #endregion #region Constructors and Destructors /// <summary> /// Initializes static members of the <see cref="Collision" /> class. /// Static Constructor /// </summary> static Collision() { GameObject.OnCreate += (sender, args) => { var missile = sender as MissileClient; var spellCaster = missile?.SpellCaster as Obj_AI_Hero; if (spellCaster == null || spellCaster.ChampionName != "Yasuo" || spellCaster.Team == GameObjects.Player.Team) { return; } switch (missile.SData.Name) { case "YasuoWMovingWallMisL": yasuoWallLeft = missile; break; case "YasuoWMovingWallMisR": yasuoWallRight = missile; break; case "YasuoWMovingWallMisVis": yasuoWallRight = missile; break; } }; GameObject.OnDelete += (sender, args) => { var missile = sender as MissileClient; if (missile == null) { return; } if (missile.Compare(yasuoWallLeft)) { yasuoWallLeft = null; } else if (missile.Compare(yasuoWallRight)) { yasuoWallRight = null; } }; } #endregion #region Public Methods and Operators /// <summary> /// Returns the list of the units that the skill-shot will hit before reaching the set positions. /// </summary> /// <param name="positions"> /// The positions. /// </param> /// <param name="input"> /// The input. /// </param> /// <returns> /// A list of <c>Obj_AI_Base</c>s which the input collides with. /// </returns> public static List<Obj_AI_Base> GetCollision(List<Vector3> positions, PredictionInput input) { var result = new List<Obj_AI_Base>(); foreach (var position in positions) { if (input.CollisionObjects.HasFlag(CollisionableObjects.Minions)) { result.AddRange( GameObjects.EnemyMinions.Where(i => i.IsMinion() || i.IsPet()) .Concat(GameObjects.Jungle) .Where( minion => minion.IsValidTarget( Math.Min(input.Range + input.Radius + 100, 2000), true, input.RangeCheckFrom) && IsHitCollision(minion, input, position, 20))); } if (input.CollisionObjects.HasFlag(CollisionableObjects.Heroes)) { result.AddRange( GameObjects.EnemyHeroes.Where( hero => hero.IsValidTarget( Math.Min(input.Range + input.Radius + 100, 2000), true, input.RangeCheckFrom) && IsHitCollision(hero, input, position, 50))); } if (input.CollisionObjects.HasFlag(CollisionableObjects.Walls)) { var step = position.Distance(input.From) / 20; for (var i = 0; i < 20; i++) { if (input.From.ToVector2().Extend(position, step * i).IsWall()) { result.Add(GameObjects.Player); } } } if (input.CollisionObjects.HasFlag(CollisionableObjects.YasuoWall)) { if (yasuoWallLeft == null || yasuoWallRight == null) { continue; } yasuoWallPoly = new RectanglePoly(yasuoWallLeft.Position, yasuoWallRight.Position, 75); var intersections = new List<Vector2>(); for (var i = 0; i < yasuoWallPoly.Points.Count; i++) { var inter = yasuoWallPoly.Points[i].Intersection( yasuoWallPoly.Points[i != yasuoWallPoly.Points.Count - 1 ? i + 1 : 0], input.From.ToVector2(), position.ToVector2()); if (inter.Intersects) { intersections.Add(inter.Point); } } if (intersections.Count > 0) { result.Add(GameObjects.Player); } } } return result.Distinct().ToList(); } #endregion #region Methods private static bool IsHitCollision(Obj_AI_Base collision, PredictionInput input, Vector3 pos, float extraRadius) { var inputSub = input.Clone() as PredictionInput; if (inputSub == null) { return false; } inputSub.Unit = collision; var predPos = Movement.GetPrediction(inputSub, false, false).UnitPosition.ToVector2(); return predPos.Distance(input.From) < input.Radius + input.Unit.BoundingRadius / 2 || predPos.Distance(pos) < input.Radius + input.Unit.BoundingRadius / 2 || predPos.DistanceSquared(input.From.ToVector2(), pos.ToVector2(), true) <= Math.Pow(input.Radius + input.Unit.BoundingRadius + extraRadius, 2); } #endregion } }
Java
/* * Copyright (c) 1990,1993 Regents of The University of Michigan. * All Rights Reserved. See COPYRIGHT. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <sys/param.h> #include <sys/uio.h> #include <sys/time.h> #include <sys/socket.h> #include <sys/poll.h> #include <errno.h> #include <sys/wait.h> #include <sys/resource.h> #include <atalk/logger.h> #include <atalk/adouble.h> #include <atalk/compat.h> #include <atalk/dsi.h> #include <atalk/afp.h> #include <atalk/paths.h> #include <atalk/util.h> #include <atalk/server_child.h> #include <atalk/server_ipc.h> #include <atalk/errchk.h> #include <atalk/globals.h> #include <atalk/netatalk_conf.h> #include "afp_config.h" #include "status.h" #include "fork.h" #include "uam_auth.h" #include "afp_zeroconf.h" #define AFP_LISTENERS 32 #define FDSET_SAFETY 5 unsigned char nologin = 0; static AFPObj obj; static server_child *server_children; static sig_atomic_t reloadconfig = 0; static sig_atomic_t gotsigchld = 0; /* Two pointers to dynamic allocated arrays which store pollfds and associated data */ static struct pollfd *fdset; static struct polldata *polldata; static int fdset_size; /* current allocated size */ static int fdset_used; /* number of used elements */ static int disasociated_ipc_fd; /* disasociated sessions uses this fd for IPC */ static afp_child_t *dsi_start(AFPObj *obj, DSI *dsi, server_child *server_children); static void afp_exit(int ret) { exit(ret); } /* ------------------ initialize fd set we are waiting for. */ static void fd_set_listening_sockets(const AFPObj *config) { DSI *dsi; for (dsi = config->dsi; dsi; dsi = dsi->next) { fdset_add_fd(config->options.connections + AFP_LISTENERS + FDSET_SAFETY, &fdset, &polldata, &fdset_used, &fdset_size, dsi->serversock, LISTEN_FD, dsi); } if (config->options.flags & OPTION_KEEPSESSIONS) fdset_add_fd(config->options.connections + AFP_LISTENERS + FDSET_SAFETY, &fdset, &polldata, &fdset_used, &fdset_size, disasociated_ipc_fd, DISASOCIATED_IPC_FD, NULL); } static void fd_reset_listening_sockets(const AFPObj *config) { const DSI *dsi; for (dsi = config->dsi; dsi; dsi = dsi->next) { fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, dsi->serversock); } if (config->options.flags & OPTION_KEEPSESSIONS) fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, disasociated_ipc_fd); } /* ------------------ */ static void afp_goaway(int sig) { switch( sig ) { case SIGTERM: case SIGQUIT: switch (sig) { case SIGTERM: LOG(log_note, logtype_afpd, "AFP Server shutting down on SIGTERM"); break; case SIGQUIT: if (obj.options.flags & OPTION_KEEPSESSIONS) { LOG(log_note, logtype_afpd, "AFP Server shutting down on SIGQUIT, NOT disconnecting clients"); } else { LOG(log_note, logtype_afpd, "AFP Server shutting down on SIGQUIT"); sig = SIGTERM; } break; } if (server_children) server_child_kill(server_children, CHILD_DSIFORK, sig); _exit(0); break; case SIGUSR1 : nologin++; auth_unload(); LOG(log_info, logtype_afpd, "disallowing logins"); if (server_children) server_child_kill(server_children, CHILD_DSIFORK, sig); break; case SIGHUP : /* w/ a configuration file, we can force a re-read if we want */ reloadconfig = 1; break; case SIGCHLD: /* w/ a configuration file, we can force a re-read if we want */ gotsigchld = 1; break; default : LOG(log_error, logtype_afpd, "afp_goaway: bad signal" ); } return; } static void child_handler(void) { int fd; int status, i; pid_t pid; #ifndef WAIT_ANY #define WAIT_ANY (-1) #endif /* ! WAIT_ANY */ while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) > 0) { for (i = 0; i < server_children->nforks; i++) { if ((fd = server_child_remove(server_children, i, pid)) != -1) { fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, fd); break; } } if (WIFEXITED(status)) { if (WEXITSTATUS(status)) LOG(log_info, logtype_afpd, "child[%d]: exited %d", pid, WEXITSTATUS(status)); else LOG(log_info, logtype_afpd, "child[%d]: done", pid); } else { if (WIFSIGNALED(status)) LOG(log_info, logtype_afpd, "child[%d]: killed by signal %d", pid, WTERMSIG(status)); else LOG(log_info, logtype_afpd, "child[%d]: died", pid); } } } static int setlimits(void) { struct rlimit rlim; if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { LOG(log_warning, logtype_afpd, "setlimits: reading current limits failed: %s", strerror(errno)); return -1; } if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < 65535) { rlim.rlim_cur = 65535; if (rlim.rlim_max != RLIM_INFINITY && rlim.rlim_max < 65535) rlim.rlim_max = 65535; if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { LOG(log_warning, logtype_afpd, "setlimits: increasing limits failed: %s", strerror(errno)); return -1; } } return 0; } int main(int ac, char **av) { fd_set rfds; void *ipc; struct sigaction sv; sigset_t sigs; int ret; /* Parse argv args and initialize default options */ afp_options_parse_cmdline(&obj, ac, av); if (!(obj.cmdlineflags & OPTION_DEBUG) && (daemonize(0, 0) != 0)) exit(EXITERR_SYS); /* Log SIGBUS/SIGSEGV SBT */ fault_setup(NULL); if (afp_config_parse(&obj, "afpd") != 0) afp_exit(EXITERR_CONF); /* Save the user's current umask */ obj.options.save_mask = umask(obj.options.umask); /* install child handler for asp and dsi. we do this before afp_goaway * as afp_goaway references stuff from here. * XXX: this should really be setup after the initial connections. */ if (!(server_children = server_child_alloc(obj.options.connections, CHILD_NFORKS))) { LOG(log_error, logtype_afpd, "main: server_child alloc: %s", strerror(errno) ); afp_exit(EXITERR_SYS); } sigemptyset(&sigs); pthread_sigmask(SIG_SETMASK, &sigs, NULL); memset(&sv, 0, sizeof(sv)); /* linux at least up to 2.4.22 send a SIGXFZ for vfat fs, even if the file is open with O_LARGEFILE ! */ #ifdef SIGXFSZ sv.sa_handler = SIG_IGN; sigemptyset( &sv.sa_mask ); if (sigaction(SIGXFSZ, &sv, NULL ) < 0 ) { LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) ); afp_exit(EXITERR_SYS); } #endif sv.sa_handler = afp_goaway; /* handler for all sigs */ sigemptyset( &sv.sa_mask ); sigaddset(&sv.sa_mask, SIGALRM); sigaddset(&sv.sa_mask, SIGHUP); sigaddset(&sv.sa_mask, SIGTERM); sigaddset(&sv.sa_mask, SIGUSR1); sigaddset(&sv.sa_mask, SIGQUIT); sv.sa_flags = SA_RESTART; if ( sigaction( SIGCHLD, &sv, NULL ) < 0 ) { LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) ); afp_exit(EXITERR_SYS); } sigemptyset( &sv.sa_mask ); sigaddset(&sv.sa_mask, SIGALRM); sigaddset(&sv.sa_mask, SIGTERM); sigaddset(&sv.sa_mask, SIGHUP); sigaddset(&sv.sa_mask, SIGCHLD); sigaddset(&sv.sa_mask, SIGQUIT); sv.sa_flags = SA_RESTART; if ( sigaction( SIGUSR1, &sv, NULL ) < 0 ) { LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) ); afp_exit(EXITERR_SYS); } sigemptyset( &sv.sa_mask ); sigaddset(&sv.sa_mask, SIGALRM); sigaddset(&sv.sa_mask, SIGTERM); sigaddset(&sv.sa_mask, SIGUSR1); sigaddset(&sv.sa_mask, SIGCHLD); sigaddset(&sv.sa_mask, SIGQUIT); sv.sa_flags = SA_RESTART; if ( sigaction( SIGHUP, &sv, NULL ) < 0 ) { LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) ); afp_exit(EXITERR_SYS); } sigemptyset( &sv.sa_mask ); sigaddset(&sv.sa_mask, SIGALRM); sigaddset(&sv.sa_mask, SIGHUP); sigaddset(&sv.sa_mask, SIGUSR1); sigaddset(&sv.sa_mask, SIGCHLD); sigaddset(&sv.sa_mask, SIGQUIT); sv.sa_flags = SA_RESTART; if ( sigaction( SIGTERM, &sv, NULL ) < 0 ) { LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) ); afp_exit(EXITERR_SYS); } sigemptyset( &sv.sa_mask ); sigaddset(&sv.sa_mask, SIGALRM); sigaddset(&sv.sa_mask, SIGHUP); sigaddset(&sv.sa_mask, SIGUSR1); sigaddset(&sv.sa_mask, SIGCHLD); sigaddset(&sv.sa_mask, SIGTERM); sv.sa_flags = SA_RESTART; if (sigaction(SIGQUIT, &sv, NULL ) < 0 ) { LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) ); afp_exit(EXITERR_SYS); } /* afp.conf: not in config file: lockfile, configfile * preference: command-line provides defaults. * config file over-writes defaults. * * we also need to make sure that killing afpd during startup * won't leave any lingering registered names around. */ sigemptyset(&sigs); sigaddset(&sigs, SIGALRM); sigaddset(&sigs, SIGHUP); sigaddset(&sigs, SIGUSR1); #if 0 /* don't block SIGTERM */ sigaddset(&sigs, SIGTERM); #endif sigaddset(&sigs, SIGCHLD); pthread_sigmask(SIG_BLOCK, &sigs, NULL); if (configinit(&obj) != 0) { LOG(log_error, logtype_afpd, "main: no servers configured"); afp_exit(EXITERR_CONF); } pthread_sigmask(SIG_UNBLOCK, &sigs, NULL); /* Initialize */ cnid_init(); /* watch atp, dsi sockets and ipc parent/child file descriptor. */ if (obj.options.flags & OPTION_KEEPSESSIONS) { LOG(log_note, logtype_afpd, "Activating continous service"); disasociated_ipc_fd = ipc_server_uds(_PATH_AFP_IPC); } fd_set_listening_sockets(&obj); /* set limits */ (void)setlimits(); afp_child_t *child; int recon_ipc_fd; pid_t pid; int saveerrno; /* wait for an appleshare connection. parent remains in the loop * while the children get handled by afp_over_{asp,dsi}. this is * currently vulnerable to a denial-of-service attack if a * connection is made without an actual login attempt being made * afterwards. establishing timeouts for logins is a possible * solution. */ while (1) { LOG(log_maxdebug, logtype_afpd, "main: polling %i fds", fdset_used); pthread_sigmask(SIG_UNBLOCK, &sigs, NULL); ret = poll(fdset, fdset_used, -1); pthread_sigmask(SIG_BLOCK, &sigs, NULL); saveerrno = errno; if (gotsigchld) { gotsigchld = 0; child_handler(); continue; } if (reloadconfig) { nologin++; auth_unload(); fd_reset_listening_sockets(&obj); LOG(log_info, logtype_afpd, "re-reading configuration file"); configfree(&obj, NULL); if (configinit(&obj) != 0) { LOG(log_error, logtype_afpd, "config re-read: no servers configured"); afp_exit(EXITERR_CONF); } fd_set_listening_sockets(&obj); nologin = 0; reloadconfig = 0; errno = saveerrno; continue; } if (ret == 0) continue; if (ret < 0) { if (errno == EINTR) continue; LOG(log_error, logtype_afpd, "main: can't wait for input: %s", strerror(errno)); break; } for (int i = 0; i < fdset_used; i++) { if (fdset[i].revents & (POLLIN | POLLERR | POLLHUP | POLLNVAL)) { switch (polldata[i].fdtype) { case LISTEN_FD: if (child = dsi_start(&obj, (DSI *)polldata[i].data, server_children)) { /* Add IPC fd to select fd set */ fdset_add_fd(obj.options.connections + AFP_LISTENERS + FDSET_SAFETY, &fdset, &polldata, &fdset_used, &fdset_size, child->ipc_fd, IPC_FD, child); } break; case IPC_FD: child = (afp_child_t *)polldata[i].data; LOG(log_debug, logtype_afpd, "main: IPC request from child[%u]", child->pid); if (ipc_server_read(server_children, child->ipc_fd) != 0) { fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, child->ipc_fd); close(child->ipc_fd); child->ipc_fd = -1; if ((obj.options.flags & OPTION_KEEPSESSIONS) && child->disasociated) { LOG(log_note, logtype_afpd, "main: removing reattached child[%u]", child->pid); server_child_remove(server_children, CHILD_DSIFORK, child->pid); } } break; case DISASOCIATED_IPC_FD: LOG(log_debug, logtype_afpd, "main: IPC reconnect request"); if ((recon_ipc_fd = accept(disasociated_ipc_fd, NULL, NULL)) == -1) { LOG(log_error, logtype_afpd, "main: accept: %s", strerror(errno)); break; } if (readt(recon_ipc_fd, &pid, sizeof(pid_t), 0, 1) != sizeof(pid_t)) { LOG(log_error, logtype_afpd, "main: readt: %s", strerror(errno)); close(recon_ipc_fd); break; } LOG(log_note, logtype_afpd, "main: IPC reconnect from pid [%u]", pid); if ((child = server_child_add(server_children, CHILD_DSIFORK, pid, recon_ipc_fd)) == NULL) { LOG(log_error, logtype_afpd, "main: server_child_add"); close(recon_ipc_fd); break; } child->disasociated = 1; fdset_add_fd(obj.options.connections + AFP_LISTENERS + FDSET_SAFETY, &fdset, &polldata, &fdset_used, &fdset_size, recon_ipc_fd, IPC_FD, child); break; default: LOG(log_debug, logtype_afpd, "main: IPC request for unknown type"); break; } /* switch */ } /* if */ } /* for (i)*/ } /* while (1) */ return 0; } static afp_child_t *dsi_start(AFPObj *obj, DSI *dsi, server_child *server_children) { afp_child_t *child = NULL; if (dsi_getsession(dsi, server_children, obj->options.tickleval, &child) != 0) { LOG(log_error, logtype_afpd, "dsi_start: session error: %s", strerror(errno)); return NULL; } /* we've forked. */ if (child == NULL) { configfree(obj, dsi); afp_over_dsi(obj); /* start a session */ exit (0); } return child; }
Java
var express = require('express'); var path = require('path'); var tilestrata = require('tilestrata'); var disk = require('tilestrata-disk'); var mapnik = require('tilestrata-mapnik'); var dependency = require('tilestrata-dependency'); var strata = tilestrata(); var app = express(); // define layers strata.layer('hillshade') .route('shade.png') .use(disk.cache({dir: './tiles/shade/'})) .use(mapnik({ pathname: './styles/hillshade.xml', tileSize: 256, scale: 1 })); strata.layer('dem') .route('dem.png') .use(disk.cache({dir: './tiles/dem/'})) .use(mapnik({ pathname: './styles/dem.xml', tileSize: 256, scale: 1 })); strata.layer('sim1') .route('sim1.png') .use(disk.cache({dir: './tiles/sim1/'})) .use(mapnik({ pathname: './styles/sim1.xml', tileSize: 256, scale: 1 })); strata.layer('sim2') .route('sim2.png') .use(disk.cache({dir: './tiles/sim2/'})) .use(mapnik({ pathname: './styles/sim2.xml', tileSize: 256, scale: 1 })); strata.layer('sim3') .route('sim3.png') .use(disk.cache({dir: './tiles/sim3/'})) .use(mapnik({ pathname: './styles/sim3.xml', tileSize: 256, scale: 1 })); strata.layer('slope') .route('slope.png') .use(disk.cache({dir: './tiles/slope/'})) .use(mapnik({ pathname: './styles/slope.xml', tileSize: 256, scale: 1 })); var staticPath = path.resolve(__dirname, './public/'); app.use(express.static(staticPath)); app.use(tilestrata.middleware({ server: strata, prefix: '' })); app.listen(8080, function() { console.log('Express server running on port 8080.'); });
Java
/* * synergy -- mouse and keyboard sharing utility * Copyright (C) 2016 Symless Ltd. * * This package is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * found in the file LICENSE that should have accompanied this file. * * This package 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 "platform/OSXUchrKeyResource.h" #include <Carbon/Carbon.h> // // OSXUchrKeyResource // OSXUchrKeyResource::OSXUchrKeyResource(const void* resource, UInt32 keyboardType) : m_m(NULL), m_cti(NULL), m_sdi(NULL), m_sri(NULL), m_st(NULL) { m_resource = reinterpret_cast<const UCKeyboardLayout*>(resource); if (m_resource == NULL) { return; } // find the keyboard info for the current keyboard type const UCKeyboardTypeHeader* th = NULL; const UCKeyboardLayout* r = m_resource; for (ItemCount i = 0; i < r->keyboardTypeCount; ++i) { if (keyboardType >= r->keyboardTypeList[i].keyboardTypeFirst && keyboardType <= r->keyboardTypeList[i].keyboardTypeLast) { th = r->keyboardTypeList + i; break; } if (r->keyboardTypeList[i].keyboardTypeFirst == 0) { // found the default. use it unless we find a match. th = r->keyboardTypeList + i; } } if (th == NULL) { // cannot find a suitable keyboard type return; } // get tables for keyboard type const UInt8* base = reinterpret_cast<const UInt8*>(m_resource); m_m = reinterpret_cast<const UCKeyModifiersToTableNum*>(base + th->keyModifiersToTableNumOffset); m_cti = reinterpret_cast<const UCKeyToCharTableIndex*>(base + th->keyToCharTableIndexOffset); m_sdi = reinterpret_cast<const UCKeySequenceDataIndex*>(base + th->keySequenceDataIndexOffset); if (th->keyStateRecordsIndexOffset != 0) { m_sri = reinterpret_cast<const UCKeyStateRecordsIndex*>(base + th->keyStateRecordsIndexOffset); } if (th->keyStateTerminatorsOffset != 0) { m_st = reinterpret_cast<const UCKeyStateTerminators*>(base + th->keyStateTerminatorsOffset); } // find the space key, but only if it can combine with dead keys. // a dead key followed by a space yields the non-dead version of // the dead key. m_spaceOutput = 0xffffu; UInt32 table = getTableForModifier(0); for (UInt32 button = 0, n = getNumButtons(); button < n; ++button) { KeyID id = getKey(table, button); if (id == 0x20) { UCKeyOutput c = reinterpret_cast<const UCKeyOutput*>(base + m_cti->keyToCharTableOffsets[table])[button]; if ((c & kUCKeyOutputTestForIndexMask) == kUCKeyOutputStateIndexMask) { m_spaceOutput = (c & kUCKeyOutputGetIndexMask); break; } } } } bool OSXUchrKeyResource::isValid() const { return (m_m != NULL); } UInt32 OSXUchrKeyResource::getNumModifierCombinations() const { // only 32 (not 256) because the righthanded modifier bits are ignored return 32; } UInt32 OSXUchrKeyResource::getNumTables() const { return m_cti->keyToCharTableCount; } UInt32 OSXUchrKeyResource::getNumButtons() const { return m_cti->keyToCharTableSize; } UInt32 OSXUchrKeyResource::getTableForModifier(UInt32 mask) const { if (mask >= m_m->modifiersCount) { return m_m->defaultTableNum; } else { return m_m->tableNum[mask]; } } KeyID OSXUchrKeyResource::getKey(UInt32 table, UInt32 button) const { assert(table < getNumTables()); assert(button < getNumButtons()); const UInt8* base = reinterpret_cast<const UInt8*>(m_resource); const UCKeyOutput* cPtr = reinterpret_cast<const UCKeyOutput*>(base + m_cti->keyToCharTableOffsets[table]); const UCKeyOutput c = cPtr[button]; KeySequence keys; switch (c & kUCKeyOutputTestForIndexMask) { case kUCKeyOutputStateIndexMask: if (!getDeadKey(keys, c & kUCKeyOutputGetIndexMask)) { return kKeyNone; } break; case kUCKeyOutputSequenceIndexMask: default: if (!addSequence(keys, c)) { return kKeyNone; } break; } // XXX -- no support for multiple characters if (keys.size() != 1) { return kKeyNone; } return keys.front(); } bool OSXUchrKeyResource::getDeadKey( KeySequence& keys, UInt16 index) const { if (m_sri == NULL || index >= m_sri->keyStateRecordCount) { // XXX -- should we be using some other fallback? return false; } UInt16 state = 0; if (!getKeyRecord(keys, index, state)) { return false; } if (state == 0) { // not a dead key return true; } // no dead keys if we couldn't find the space key if (m_spaceOutput == 0xffffu) { return false; } // the dead key should not have put anything in the key list if (!keys.empty()) { return false; } // get the character generated by pressing the space key after the // dead key. if we're still in a compose state afterwards then we're // confused so we bail. if (!getKeyRecord(keys, m_spaceOutput, state) || state != 0) { return false; } // convert keys to their dead counterparts for (KeySequence::iterator i = keys.begin(); i != keys.end(); ++i) { *i = synergy::KeyMap::getDeadKey(*i); } return true; } bool OSXUchrKeyResource::getKeyRecord( KeySequence& keys, UInt16 index, UInt16& state) const { const UInt8* base = reinterpret_cast<const UInt8*>(m_resource); const UCKeyStateRecord* sr = reinterpret_cast<const UCKeyStateRecord*>(base + m_sri->keyStateRecordOffsets[index]); const UCKeyStateEntryTerminal* kset = reinterpret_cast<const UCKeyStateEntryTerminal*>(sr->stateEntryData); UInt16 nextState = 0; bool found = false; if (state == 0) { found = true; nextState = sr->stateZeroNextState; if (!addSequence(keys, sr->stateZeroCharData)) { return false; } } else { // we have a next entry switch (sr->stateEntryFormat) { case kUCKeyStateEntryTerminalFormat: for (UInt16 j = 0; j < sr->stateEntryCount; ++j) { if (kset[j].curState == state) { if (!addSequence(keys, kset[j].charData)) { return false; } nextState = 0; found = true; break; } } break; case kUCKeyStateEntryRangeFormat: // XXX -- not supported yet break; default: // XXX -- unknown format return false; } } if (!found) { // use a terminator if (m_st != NULL && state < m_st->keyStateTerminatorCount) { if (!addSequence(keys, m_st->keyStateTerminators[state - 1])) { return false; } } nextState = sr->stateZeroNextState; if (!addSequence(keys, sr->stateZeroCharData)) { return false; } } // next state = nextState; return true; } bool OSXUchrKeyResource::addSequence( KeySequence& keys, UCKeyCharSeq c) const { if ((c & kUCKeyOutputTestForIndexMask) == kUCKeyOutputSequenceIndexMask) { UInt16 index = (c & kUCKeyOutputGetIndexMask); if (index < m_sdi->charSequenceCount && m_sdi->charSequenceOffsets[index] != m_sdi->charSequenceOffsets[index + 1]) { // XXX -- sequences not supported yet return false; } } if (c != 0xfffe && c != 0xffff) { KeyID id = unicharToKeyID(c); if (id != kKeyNone) { keys.push_back(id); } } return true; }
Java
<?php include_once "srcPHP/View/View.php"; include_once "srcPHP/Model/ResearchModel.php"; class Mosaic implements View{ var $model = NULL; var $array = NULL; function Mosaic(){ $this->model = new ResearchModel("dbserver", "xjouveno", "xjouveno", "pdp"); $this->array = $this->model->getAllVideo(); } function linkCSS(){ echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/mosaic.css\">"; } function linkJS(){ } function onLoadJS(){ } function draw(){ echo "<section>"; echo "<ul class=\"patients\">"; echo $tmp = NULL; for($i=0; $i<count($this->array); $i++){ // Patient suivant if($tmp != $this->array[$i]["IdPatient"]){ $tmp = $this->array[$i]["IdPatient"]; if($i != 0){ echo "</ul>"; echo "</li>"; } echo "<li>"; echo "<h3>".$this->array[$i]["Name"]." - ".$this->array[$i]["IdPatient"]."</h3>"; echo "<ul>"; } //Video Suivante echo "<li>"; echo "<span>"; // echo "<a href=\"index.php?play=".$this->array[$i]["IdVideo"]."\" ><img src=\"modules/jQuery-File-Upload/server/php/files/video_thumbnails/video.png\" /></a>"; echo "<a href=\"index.php?play=".$this->array[$i]["IdVideo"]."\" ><img src=\"modules/jQuery-File-Upload/server/php/files/video_thumbnails/".$this->array[$i]["IdVideo"].".jpg\" /></a>"; echo "<label>".$this->array[$i]["Title"]."</label>"; echo "</span>"; echo "</li>"; } echo "</ul>"; echo "</section>"; } } ?>
Java
<?php /** * Description of Resume * * @author greg * @package */ class Wpjb_Form_Abstract_Resume extends Daq_Form_ObjectAbstract { protected $_custom = "wpjb_form_resume"; protected $_key = "resume"; protected $_model = "Wpjb_Model_Resume"; public function _exclude() { if($this->_object->getId()) { return array("id" => $this->_object->getId()); } else { return array(); } } public function init() { $this->_upload = array( "path" => wpjb_upload_dir("{object}", "{field}", "{id}", "basedir"), "object" => "resume", "field" => null, "id" => wpjb_upload_id($this->getId()) ); $this->addGroup("_internal", ""); $this->addGroup("default", __("Account Information", "wpjobboard")); $this->addGroup("location", __("Address", "wpjobboard")); $this->addGroup("resume", __("Resume", "wpjobboard")); $this->addGroup("experience", __("Experience", "wpjobboard")); $this->addGroup("education", __("Education", "wpjobboard")); $this->_group["experience"]->setAlwaysVisible(true); $this->_group["education"]->setAlwaysVisible(true); $user = new WP_User($this->getObject()->user_id); $e = $this->create("first_name"); $e->setLabel(__("First Name", "wpjobboard")); $e->setRequired(true); $e->setValue($user->first_name); $this->addElement($e, "default"); $e = $this->create("last_name"); $e->setLabel(__("Last Name", "wpjobboard")); $e->setRequired(true); $e->setValue($user->last_name); $this->addElement($e, "default"); $def = wpjb_locale(); $e = $this->create("candidate_country", "select"); $e->setLabel(__("Country", "wpjobboard")); $e->setValue(($this->_object->candidate_country) ? $this->_object->candidate_country : $def); $e->addOptions(wpjb_form_get_countries()); $e->addClass("wpjb-location-country"); $this->addElement($e, "location"); $e = $this->create("candidate_state"); $e->setLabel(__("State", "wpjobboard")); $e->setValue($this->_object->candidate_state); $e->addClass("wpjb-location-state"); $this->addElement($e, "location"); $e = $this->create("candidate_zip_code"); $e->setLabel(__("Zip-Code", "wpjobboard")); $e->addValidator(new Daq_Validate_StringLength(null, 20)); $e->setValue($this->_object->candidate_zip_code); $this->addElement($e, "location"); $e = $this->create("candidate_location"); $e->setValue($this->_object->candidate_location); $e->setRequired(true); $e->setLabel(__("City", "wpjobboard")); $e->setHint(__('For example: "Chicago", "London", "Anywhere" or "Telecommute".', "wpjobboard")); $e->addValidator(new Daq_Validate_StringLength(null, 120)); $e->addClass("wpjb-location-city"); $this->addElement($e, "location"); $e = $this->create("user_email"); $e->setRequired(true); $e->setLabel(__("Email Address", "wpjobboard")); $e->setHint(__('This field will be shown only to registered employers.', "wpjobboard")); $e->addValidator(new Daq_Validate_Email(array("exclude"=>$user->ID))); $e->setValue($user->user_email); $this->addElement($e, "default"); $e = $this->create("phone"); $e->setLabel(__("Phone Number", "wpjobboard")); $e->setHint(__('This field will be shown only to registered employers.', "wpjobboard")); $e->setValue($this->_object->phone); $this->addElement($e, "default"); $e = $this->create("user_url"); $e->setLabel(__("Website", "wpjobboard")); $e->setHint(__('This field will be shown only to registered employers.', "wpjobboard")); $e->addFilter(new Daq_Filter_WP_Url()); $e->addValidator(new Daq_Validate_Url()); $e->setValue($user->user_url); $this->addElement($e, "default"); $e = $this->create("is_public", "checkbox"); $e->setLabel(__("Privacy", "wpjobboard")); $e->addOption(1, 1, __("Show my resume in search results.", "wpjobboard")); $e->setValue($this->_object->is_public); $e->addFilter(new Daq_Filter_Int()); $this->addElement($e, "default"); $e = $this->create("is_active", "checkbox"); $e->setValue($this->_object->is_active); $e->setLabel(__("Status", "wpjobboard")); $e->addOption(1, 1, __("Resume is approved.", "wpjobboard")); $this->addElement($e, "_internal"); $e = $this->create("modified_at", "text_date"); $e->setDateFormat(wpjb_date_format()); $e->setValue($this->ifNew(date("Y-m-d"), $this->_object->modified_at)); $this->addElement($e, "_internal"); $e = $this->create("created_at", "text_date"); $e->setDateFormat(wpjb_date_format()); $e->setValue($this->ifNew(date("Y-m-d"), $this->_object->created_at)); $this->addElement($e, "_internal"); $e = $this->create("image", "file"); $e->setLabel(__("Your Photo", "wpjobboard"));; $e->addValidator(new Daq_Validate_File_Default()); $e->addValidator(new Daq_Validate_File_Ext("jpg,jpeg,gif,png")); $e->addValidator(new Daq_Validate_File_Size(300000)); $e->setUploadPath($this->_upload); $e->setRenderer("wpjb_form_field_upload"); $this->addElement($e, "default"); $e = $this->create("category", "select"); $e->setLabel(__("Category", "wpjobboard")); $e->setValue($this->_object->getTagIds("category")); $e->addOptions(wpjb_form_get_categories()); $this->addElement($e, "resume"); $this->addTag($e); $e = $this->create("headline"); $e->setLabel(__("Professional Headline", "wpjobboard")); $e->setHint(__("Describe yourself in few words, for example: Experienced Web Developer", "wpjobboard")); $e->addValidator(new Daq_Validate_StringLength(1, 120)); $e->setValue($this->_object->headline); $this->addElement($e, "resume"); $e = $this->create("description", "textarea"); $e->setLabel(__("Profile Summary", "wpjobboard")); $e->setHint(__("Use this field to list your skills, specialities, experience or goals", "wpjobboard")); $e->setValue($this->_object->description); $e->setEditor(Daq_Form_Element_Textarea::EDITOR_TINY); $this->addElement($e, "resume"); } public function save($append = array()) { parent::save($append); $user = $this->getObject()->getUser(true); $names = array_merge($user->getFieldNames(), array("first_name", "last_name")); $userdata = array("ID"=>$user->ID); $user = new WP_User($this->getObject(true)->ID); $update = false; foreach($names as $key) { if($this->hasElement($key) && !in_array($key, array("user_login", "user_pass"))) { $userdata[$key] = $this->value($key); $update = true; } } if($update) { wp_update_user($userdata); } $temp = wpjb_upload_dir("resume", "", null, "basedir"); $finl = dirname($temp)."/".$this->getId(); wpjb_rename_dir($temp, $finl); } public function dump() { $dump = parent::dump(); $count = count($dump); for($i=0; $i<$count; $i++) { if(in_array($dump[$i]->name, array("experience", "education"))) { $dump[$i]->editable = false; } } return $dump; } } ?>
Java
/* * This file is part of PowerDNS or dnsdist. * Copyright -- PowerDNS.COM B.V. and its contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * In addition, for the avoidance of any doubt, permission is granted to * link this program with OpenSSL and to (re)distribute the binaries * produced as the result of such linking. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "utility.hh" #include "packetcache.hh" #include "logger.hh" #include "arguments.hh" #include "statbag.hh" #include <map> #include <boost/algorithm/string.hpp> extern StatBag S; PacketCache::PacketCache() { d_ops=0; d_maps.resize(1024); for(auto& mc : d_maps) { pthread_rwlock_init(&mc.d_mut, 0); } d_ttl=-1; d_recursivettl=-1; S.declare("packetcache-hit"); S.declare("packetcache-miss"); S.declare("packetcache-size"); d_statnumhit=S.getPointer("packetcache-hit"); d_statnummiss=S.getPointer("packetcache-miss"); d_statnumentries=S.getPointer("packetcache-size"); d_doRecursion=false; } PacketCache::~PacketCache() { // WriteLock l(&d_mut); vector<WriteLock*> locks; for(auto& mc : d_maps) { locks.push_back(new WriteLock(&mc.d_mut)); } for(auto wl : locks) { delete wl; } } int PacketCache::get(DNSPacket *p, DNSPacket *cached, bool recursive) { extern StatBag S; if(d_ttl<0) getTTLS(); cleanupIfNeeded(); if(d_doRecursion && p->d.rd) { // wants recursion if(!d_recursivettl) { (*d_statnummiss)++; return 0; } } else { // does not if(!d_ttl) { (*d_statnummiss)++; return 0; } } if(ntohs(p->d.qdcount)!=1) // we get confused by packets with more than one question return 0; unsigned int age=0; string value; bool haveSomething; { auto& mc=getMap(p->qdomain); TryReadLock l(&mc.d_mut); // take a readlock here if(!l.gotIt()) { S.inc("deferred-cache-lookup"); return 0; } uint16_t maxReplyLen = p->d_tcp ? 0xffff : p->getMaxReplyLen(); haveSomething=getEntryLocked(p->qdomain, p->qtype, PacketCache::PACKETCACHE, value, -1, recursive, maxReplyLen, p->d_dnssecOk, p->hasEDNS(), &age); } if(haveSomething) { (*d_statnumhit)++; if (recursive) ageDNSPacket(value, age); if(cached->noparse(value.c_str(), value.size()) < 0) return 0; cached->spoofQuestion(p); // for correct case cached->qdomain=p->qdomain; cached->qtype=p->qtype; return 1; } // cerr<<"Packet cache miss for '"<<p->qdomain<<"', merits: "<<packetMeritsRecursion<<endl; (*d_statnummiss)++; return 0; // bummer } void PacketCache::getTTLS() { d_ttl=::arg().asNum("cache-ttl"); d_recursivettl=::arg().asNum("recursive-cache-ttl"); d_doRecursion=::arg().mustDo("recursor"); } void PacketCache::insert(DNSPacket *q, DNSPacket *r, bool recursive, unsigned int maxttl) { if(d_ttl < 0) getTTLS(); if(ntohs(q->d.qdcount)!=1) { return; // do not try to cache packets with multiple questions } if(q->qclass != QClass::IN) // we only cache the INternet return; uint16_t maxReplyLen = q->d_tcp ? 0xffff : q->getMaxReplyLen(); unsigned int ourttl = recursive ? d_recursivettl : d_ttl; if(!recursive) { if(maxttl<ourttl) ourttl=maxttl; } else { unsigned int minttl = r->getMinTTL(); if(minttl<ourttl) ourttl=minttl; } insert(q->qdomain, q->qtype, PacketCache::PACKETCACHE, r->getString(), ourttl, -1, recursive, maxReplyLen, q->d_dnssecOk, q->hasEDNS()); } // universal key appears to be: qname, qtype, kind (packet, query cache), optionally zoneid, meritsRecursion void PacketCache::insert(const DNSName &qname, const QType& qtype, CacheEntryType cet, const string& value, unsigned int ttl, int zoneID, bool meritsRecursion, unsigned int maxReplyLen, bool dnssecOk, bool EDNS) { cleanupIfNeeded(); if(!ttl) return; //cerr<<"Inserting qname '"<<qname<<"', cet: "<<(int)cet<<", qtype: "<<qtype.getName()<<", ttl: "<<ttl<<", maxreplylen: "<<maxReplyLen<<", hasEDNS: "<<EDNS<<endl; CacheEntry val; val.created=time(0); val.ttd=val.created+ttl; val.qname=qname; val.qtype=qtype.getCode(); val.value=value; val.ctype=cet; val.meritsRecursion=meritsRecursion; val.maxReplyLen = maxReplyLen; val.dnssecOk = dnssecOk; val.zoneID = zoneID; val.hasEDNS = EDNS; auto& mc = getMap(val.qname); TryWriteLock l(&mc.d_mut); if(l.gotIt()) { bool success; cmap_t::iterator place; tie(place, success)=mc.d_map.insert(val); if(!success) mc.d_map.replace(place, val); } else S.inc("deferred-cache-inserts"); } void PacketCache::insert(const DNSName &qname, const QType& qtype, CacheEntryType cet, const vector<DNSZoneRecord>& value, unsigned int ttl, int zoneID) { cleanupIfNeeded(); if(!ttl) return; //cerr<<"Inserting qname '"<<qname<<"', cet: "<<(int)cet<<", qtype: "<<qtype.getName()<<", ttl: "<<ttl<<", maxreplylen: "<<maxReplyLen<<", hasEDNS: "<<EDNS<<endl; CacheEntry val; val.created=time(0); val.ttd=val.created+ttl; val.qname=qname; val.qtype=qtype.getCode(); val.drs=value; val.ctype=cet; val.meritsRecursion=false; val.maxReplyLen = 0; val.dnssecOk = false; val.zoneID = zoneID; val.hasEDNS = false; auto& mc = getMap(val.qname); TryWriteLock l(&mc.d_mut); if(l.gotIt()) { bool success; cmap_t::iterator place; tie(place, success)=mc.d_map.insert(val); if(!success) mc.d_map.replace(place, val); } else S.inc("deferred-cache-inserts"); } /* clears the entire packetcache. */ int PacketCache::purge() { int delcount=0; for(auto& mc : d_maps) { WriteLock l(&mc.d_mut); delcount+=mc.d_map.size(); mc.d_map.clear(); } d_statnumentries->store(0); return delcount; } int PacketCache::purgeExact(const DNSName& qname) { int delcount=0; auto& mc = getMap(qname); WriteLock l(&mc.d_mut); auto range = mc.d_map.equal_range(tie(qname)); if(range.first != range.second) { delcount+=distance(range.first, range.second); mc.d_map.erase(range.first, range.second); } *d_statnumentries-=delcount; // XXX FIXME NEEDS TO BE ADJUSTED (for packetcache shards) return delcount; } /* purges entries from the packetcache. If match ends on a $, it is treated as a suffix */ int PacketCache::purge(const string &match) { if(ends_with(match, "$")) { int delcount=0; string prefix(match); prefix.resize(prefix.size()-1); DNSName dprefix(prefix); for(auto& mc : d_maps) { WriteLock l(&mc.d_mut); cmap_t::const_iterator iter = mc.d_map.lower_bound(tie(dprefix)); auto start=iter; for(; iter != mc.d_map.end(); ++iter) { if(!iter->qname.isPartOf(dprefix)) { break; } delcount++; } mc.d_map.erase(start, iter); } *d_statnumentries-=delcount; // XXX FIXME NEEDS TO BE ADJUSTED (for packetcache shards) return delcount; } else { return purgeExact(DNSName(match)); } } // called from ueberbackend bool PacketCache::getEntry(const DNSName &qname, const QType& qtype, CacheEntryType cet, vector<DNSZoneRecord>& value, int zoneID) { if(d_ttl<0) getTTLS(); cleanupIfNeeded(); auto& mc=getMap(qname); TryReadLock l(&mc.d_mut); // take a readlock here if(!l.gotIt()) { S.inc( "deferred-cache-lookup"); return false; } return getEntryLocked(qname, qtype, cet, value, zoneID); } bool PacketCache::getEntryLocked(const DNSName &qname, const QType& qtype, CacheEntryType cet, string& value, int zoneID, bool meritsRecursion, unsigned int maxReplyLen, bool dnssecOK, bool hasEDNS, unsigned int *age) { uint16_t qt = qtype.getCode(); //cerr<<"Lookup for maxReplyLen: "<<maxReplyLen<<endl; auto& mc=getMap(qname); // cmap_t::const_iterator i=mc.d_map.find(tie(qname, qt, cet, zoneID, meritsRecursion, maxReplyLen, dnssecOK, hasEDNS, *age)); auto& idx = boost::multi_index::get<UnorderedNameTag>(mc.d_map); auto range=idx.equal_range(tie(qname, qt, cet, zoneID)); if(range.first == range.second) return false; time_t now=time(0); for(auto iter = range.first ; iter != range.second; ++iter) { if(meritsRecursion == iter->meritsRecursion && maxReplyLen == iter->maxReplyLen && dnssecOK == iter->dnssecOk && hasEDNS == iter->hasEDNS ) { if(iter->ttd > now) { if (age) *age = now - iter->created; value = iter->value; return true; } } } return false; } bool PacketCache::getEntryLocked(const DNSName &qname, const QType& qtype, CacheEntryType cet, vector<DNSZoneRecord>& value, int zoneID) { uint16_t qt = qtype.getCode(); //cerr<<"Lookup for maxReplyLen: "<<maxReplyLen<<endl; auto& mc=getMap(qname); auto& idx = boost::multi_index::get<UnorderedNameTag>(mc.d_map); auto i=idx.find(tie(qname, qt, cet, zoneID)); if(i==idx.end()) return false; time_t now=time(0); if(i->ttd > now) { value = i->drs; return true; } return false; } map<char,int> PacketCache::getCounts() { int recursivePackets=0, nonRecursivePackets=0, queryCacheEntries=0, negQueryCacheEntries=0; for(auto& mc : d_maps) { ReadLock l(&mc.d_mut); for(cmap_t::const_iterator iter = mc.d_map.begin() ; iter != mc.d_map.end(); ++iter) { if(iter->ctype == PACKETCACHE) if(iter->meritsRecursion) recursivePackets++; else nonRecursivePackets++; else if(iter->ctype == QUERYCACHE) { if(iter->value.empty()) negQueryCacheEntries++; else queryCacheEntries++; } } } map<char,int> ret; ret['!']=negQueryCacheEntries; ret['Q']=queryCacheEntries; ret['n']=nonRecursivePackets; ret['r']=recursivePackets; return ret; } int PacketCache::size() { uint64_t ret=0; for(auto& mc : d_maps) { ReadLock l(&mc.d_mut); ret+=mc.d_map.size(); } return ret; } /** readlock for figuring out which iterators to delete, upgrade to writelock when actually cleaning */ void PacketCache::cleanup() { d_statnumentries->store(0); for(auto& mc : d_maps) { ReadLock l(&mc.d_mut); *d_statnumentries+=mc.d_map.size(); } unsigned int maxCached=::arg().asNum("max-cache-entries"); unsigned int toTrim=0; unsigned long cacheSize=*d_statnumentries; if(maxCached && cacheSize > maxCached) { toTrim = cacheSize - maxCached; } unsigned int lookAt=0; // two modes - if toTrim is 0, just look through 10% of the cache and nuke everything that is expired // otherwise, scan first 5*toTrim records, and stop once we've nuked enough if(toTrim) lookAt=5*toTrim; else lookAt=cacheSize/10; // cerr<<"cacheSize: "<<cacheSize<<", lookAt: "<<lookAt<<", toTrim: "<<toTrim<<endl; time_t now=time(0); DLOG(L<<"Starting cache clean"<<endl); //unsigned int totErased=0; for(auto& mc : d_maps) { WriteLock wl(&mc.d_mut); typedef cmap_t::nth_index<1>::type sequence_t; sequence_t& sidx=mc.d_map.get<1>(); unsigned int erased=0, lookedAt=0; for(sequence_t::iterator i=sidx.begin(); i != sidx.end(); lookedAt++) { if(i->ttd < now) { sidx.erase(i++); erased++; } else { ++i; } if(toTrim && erased > toTrim / d_maps.size()) break; if(lookedAt > lookAt / d_maps.size()) break; } //totErased += erased; } // if(totErased) // cerr<<"erased: "<<totErased<<endl; d_statnumentries->store(0); for(auto& mc : d_maps) { ReadLock l(&mc.d_mut); *d_statnumentries+=mc.d_map.size(); } DLOG(L<<"Done with cache clean"<<endl); }
Java
<?php /** * BackPress Styles Procedural API * * @since 2.6.0 * * @package WordPress * @subpackage BackPress */ /** * Initialize $wp_styles if it has not been set. * * @global WP_Styles $wp_styles * * @since 4.2.0 * * @return WP_Styles WP_Styles instance. */ function wp_styles() { global $wp_styles; if ( ! ( $wp_styles instanceof WP_Styles ) ) { $wp_styles = new WP_Styles(); } return $wp_styles; } /** * Display styles that are in the $handles queue. * * Passing an empty array to $handles prints the queue, * passing an array with one string prints that style, * and passing an array of strings prints those styles. * * @global WP_Styles $wp_styles The WP_Styles object for printing styles. * * @since 2.6.0 * * @param string|bool|array $handles Styles to be printed. Default 'false'. * @return array On success, a processed array of WP_Dependencies items; otherwise, an empty array. */ function wp_print_styles( $handles = false ) { if ( '' === $handles ) { // for wp_head $handles = false; } /** * Fires before styles in the $handles queue are printed. * * @since 2.6.0 */ if ( ! $handles ) { do_action( 'wp_print_styles' ); } _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ ); global $wp_styles; if ( ! ( $wp_styles instanceof WP_Styles ) ) { if ( ! $handles ) { return array(); // No need to instantiate if nothing is there. } } return wp_styles()->do_items( $handles ); } /** * Add extra CSS styles to a registered stylesheet. * * Styles will only be added if the stylesheet in already in the queue. * Accepts a string $data containing the CSS. If two or more CSS code blocks * are added to the same stylesheet $handle, they will be printed in the order * they were added, i.e. the latter added styles can redeclare the previous. * * @see WP_Styles::add_inline_style() * * @since 3.3.0 * * @param string $handle Name of the stylesheet to add the extra styles to. Must be lowercase. * @param string $data String containing the CSS styles to be added. * @return bool True on success, false on failure. */ function wp_add_inline_style( $handle, $data ) { _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ ); if ( false !== stripos( $data, '</style>' ) ) { _doing_it_wrong( __FUNCTION__, __( 'Do not pass style tags to wp_add_inline_style().' ), '3.7' ); $data = trim( preg_replace( '#<style[^>]*>(.*)</style>#is', '$1', $data ) ); } return wp_styles()->add_inline_style( $handle, $data ); } /** * Register a CSS stylesheet. * * @see WP_Dependencies::add() * @link http://www.w3.org/TR/CSS2/media.html#media-types List of CSS media types. * * @since 2.6.0 * @since 4.3.0 A return value was added. * * @param string $handle Name of the stylesheet. * @param string|bool $src Path to the stylesheet from the WordPress root directory. Example: '/css/mystyle.css'. * @param array $deps An array of registered style handles this stylesheet depends on. Default empty array. * @param string|bool $ver String specifying the stylesheet version number. Used to ensure that the correct version * is sent to the client regardless of caching. Default 'false'. Accepts 'false', 'null', or 'string'. * @param string $media Optional. The media for which this stylesheet has been defined. * Default 'all'. Accepts 'all', 'aural', 'braille', 'handheld', 'projection', 'print', * 'screen', 'tty', or 'tv'. * @return bool Whether the style has been registered. True on success, false on failure. */ function wp_register_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' ) { _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ ); return wp_styles()->add( $handle, $src, $deps, $ver, $media ); } /** * Remove a registered stylesheet. * * @see WP_Dependencies::remove() * * @since 2.1.0 * * @param string $handle Name of the stylesheet to be removed. */ function wp_deregister_style( $handle ) { _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ ); wp_styles()->remove( $handle ); } /** * Enqueue a CSS stylesheet. * * Registers the style if source provided (does NOT overwrite) and enqueues. * * @see WP_Dependencies::add(), WP_Dependencies::enqueue() * @link http://www.w3.org/TR/CSS2/media.html#media-types List of CSS media types. * * @since 2.6.0 * * @param string $handle Name of the stylesheet. * @param string|bool $src Path to the stylesheet from the root directory of WordPress. Example: '/css/mystyle.css'. * @param array $deps An array of registered style handles this stylesheet depends on. Default empty array. * @param string|bool $ver String specifying the stylesheet version number, if it has one. This parameter is used * to ensure that the correct version is sent to the client regardless of caching, and so * should be included if a version number is available and makes sense for the stylesheet. * @param string $media Optional. The media for which this stylesheet has been defined. * Default 'all'. Accepts 'all', 'aural', 'braille', 'handheld', 'projection', 'print', * 'screen', 'tty', or 'tv'. */ function wp_enqueue_style( $handle, $src = false, $deps = array(), $ver = false, $media = 'all' ) { _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ ); $wp_styles = wp_styles(); if ( $src ) { $_handle = explode('?', $handle); $wp_styles->add( $_handle[0], $src, $deps, $ver, $media ); } $wp_styles->enqueue( $handle ); } /** * Remove a previously enqueued CSS stylesheet. * * @see WP_Dependencies::dequeue() * * @since 3.1.0 * * @param string $handle Name of the stylesheet to be removed. */ function wp_dequeue_style( $handle ) { _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ ); wp_styles()->dequeue( $handle ); } /** * Check whether a CSS stylesheet has been added to the queue. * * @since 2.8.0 * * @param string $handle Name of the stylesheet. * @param string $list Optional. Status of the stylesheet to check. Default 'enqueued'. * Accepts 'enqueued', 'registered', 'queue', 'to_do', and 'done'. * @return bool Whether style is queued. */ function wp_style_is( $handle, $list = 'enqueued' ) { _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ ); return (bool) wp_styles()->query( $handle, $list ); } /** * Add metadata to a CSS stylesheet. * * Works only if the stylesheet has already been added. * * Possible values for $key and $value: * 'conditional' string Comments for IE 6, lte IE 7 etc. * 'rtl' bool|string To declare an RTL stylesheet. * 'suffix' string Optional suffix, used in combination with RTL. * 'alt' bool For rel="alternate stylesheet". * 'title' string For preferred/alternate stylesheets. * * @see WP_Dependency::add_data() * * @since 3.6.0 * * @param string $handle Name of the stylesheet. * @param string $key Name of data point for which we're storing a value. * Accepts 'conditional', 'rtl' and 'suffix', 'alt' and 'title'. * @param mixed $value String containing the CSS data to be added. * @return bool True on success, false on failure. */ function wp_style_add_data( $handle, $key, $value ) { return wp_styles()->add_data( $handle, $key, $value ); }
Java
cmd_drivers/mmc/core/built-in.o := /home/ar/android/aosp/prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi-ld -EL -r -o drivers/mmc/core/built-in.o drivers/mmc/core/mmc_core.o
Java
// TransformPatternDlg.cpp : implementation file #include <psycle/host/detail/project.private.hpp> #include "TransformPatternDlg.hpp" #include "Song.hpp" #include "ChildView.hpp" #include "MainFrm.hpp" namespace psycle { namespace host { static const char notes[12][3]={"C-","C#","D-","D#","E-","F-","F#","G-","G#","A-","A#","B-"}; static const char *empty ="Empty"; static const char *nonempty="Nonempty"; static const char *all="All"; static const char *same="Same"; static const char *off="off"; static const char *twk="twk"; static const char *tws="tws"; static const char *mcm="mcm"; // CTransformPatternDlg dialog IMPLEMENT_DYNAMIC(CTransformPatternDlg, CDialog) CTransformPatternDlg::CTransformPatternDlg(Song& _pSong, CChildView& _cview, CWnd* pParent /*=NULL*/) : CDialog(CTransformPatternDlg::IDD, pParent) , song(_pSong), cview(_cview), m_applyto(0) { } CTransformPatternDlg::~CTransformPatternDlg() { } void CTransformPatternDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_SEARCHNOTECOMB, m_searchnote); DDX_Control(pDX, IDC_SEARCHINSTCOMB, m_searchinst); DDX_Control(pDX, IDC_SEARCHMACHCOMB, m_searchmach); DDX_Control(pDX, IDC_REPLNOTECOMB, m_replacenote); DDX_Control(pDX, IDC_REPLINSTCOMB, m_replaceinst); DDX_Control(pDX, IDC_REPLMACHCOMB, m_replacemach); DDX_Control(pDX, IDC_REPLTWEAKCHECK, m_replacetweak); DDX_Radio(pDX,IDC_APPLYTOSONG, m_applyto); DDX_Control(pDX, IDC_CH_INCLUDEPAT, m_includePatNotInSeq); } BEGIN_MESSAGE_MAP(CTransformPatternDlg, CDialog) ON_BN_CLICKED(IDD_SEARCH, &CTransformPatternDlg::OnBnClickedSearch) ON_BN_CLICKED(IDD_REPLACE, &CTransformPatternDlg::OnBnClickedReplace) END_MESSAGE_MAP() BOOL CTransformPatternDlg::OnInitDialog() { CDialog::OnInitDialog(); //Note (search and replace) m_searchnote.AddString(all); m_searchnote.SetItemData(0,1003); m_searchnote.AddString(empty); m_searchnote.SetItemData(1,1001); m_searchnote.AddString(nonempty); m_searchnote.SetItemData(2,1002); m_replacenote.AddString(same); m_replacenote.SetItemData(0,1002); m_replacenote.AddString(empty); m_replacenote.SetItemData(1,1001); bool is440 = PsycleGlobal::conf().patView().showA440; for (int i=notecommands::c0; i <= notecommands::b9;i++) { std::ostringstream os; os << notes[i%12]; if (is440) os << (i/12)-1; else os << (i/12); m_searchnote.AddString(os.str().c_str()); m_searchnote.SetItemData(3+i,i); m_replacenote.AddString(os.str().c_str()); m_replacenote.SetItemData(2+i,i); } m_searchnote.AddString(off); m_searchnote.SetItemData(123,notecommands::release); m_searchnote.AddString(twk); m_searchnote.SetItemData(124,notecommands::tweak); m_searchnote.AddString(tws); m_searchnote.SetItemData(125,notecommands::tweakslide); m_searchnote.AddString(mcm); m_searchnote.SetItemData(126,notecommands::midicc); m_replacenote.AddString(off); m_replacenote.SetItemData(122,notecommands::release); m_replacenote.AddString(twk); m_replacenote.SetItemData(123,notecommands::tweak); m_replacenote.AddString(tws); m_replacenote.SetItemData(124,notecommands::tweakslide); m_replacenote.AddString(mcm); m_replacenote.SetItemData(125,notecommands::midicc); m_searchnote.SetCurSel(0); m_replacenote.SetCurSel(0); //Inst (search and replace) m_searchinst.AddString(all); m_searchinst.SetItemData(0,1003); m_searchinst.AddString(empty); m_searchinst.SetItemData(1,1001); m_searchinst.AddString(nonempty); m_searchinst.SetItemData(2,1002); m_replaceinst.AddString(same); m_replaceinst.SetItemData(0,1002); m_replaceinst.AddString(empty); m_replaceinst.SetItemData(1,1001); for (int i=0; i < 0xFF; i++) { std::ostringstream os; if (i < 16) os << "0"; os << std::uppercase << std::hex << i; m_searchinst.AddString(os.str().c_str()); m_searchinst.SetItemData(3+i,i); m_replaceinst.AddString(os.str().c_str()); m_replaceinst.SetItemData(2+i,i); } m_searchinst.SetCurSel(0); m_replaceinst.SetCurSel(0); //Mach (search and replace) m_searchmach.AddString(all); m_searchmach.SetItemData(0,1003); m_searchmach.AddString(empty); m_searchmach.SetItemData(1,1001); m_searchmach.AddString(nonempty); m_searchmach.SetItemData(2,1002); m_replacemach.AddString(same); m_replacemach.SetItemData(0,1002); m_replacemach.AddString(empty); m_replacemach.SetItemData(1,1001); for (int i=0; i < 0xFF; i++) { std::ostringstream os; if (i < 16) os << "0"; os << std::uppercase << std::hex << i; m_searchmach.AddString(os.str().c_str()); m_searchmach.SetItemData(3+i,i); m_replacemach.AddString(os.str().c_str()); m_replacemach.SetItemData(2+i,i); } m_searchmach.SetCurSel(0); m_replacemach.SetCurSel(0); if (cview.blockSelected) m_applyto = 2; UpdateData(FALSE); return true; // return true unless you set the focus to a control // EXCEPTION: OCX Property Pages should return false } // CTransformPatternDlg message handlers void CTransformPatternDlg::OnBnClickedSearch() { CSearchReplaceMode mode = cview.SetupSearchReplaceMode( m_searchnote.GetItemData(m_searchnote.GetCurSel()), m_searchinst.GetItemData(m_searchinst.GetCurSel()), m_searchmach.GetItemData(m_searchmach.GetCurSel())); CCursor cursor; cursor.line = -1; int pattern = -1; UpdateData (TRUE); if (m_applyto == 0) { bool includeOther = m_includePatNotInSeq.GetCheck() > 0; int lastPatternUsed = (includeOther )? song.GetHighestPatternIndexInSequence() : MAX_PATTERNS; for (int currentPattern = 0; currentPattern <= lastPatternUsed; currentPattern++) { if (song.IsPatternUsed(currentPattern, !includeOther)) { CSelection sel; sel.start.line = 0; sel.start.track = 0; sel.end.line = song.patternLines[currentPattern]; sel.end.track = MAX_TRACKS; cursor = cview.SearchInPattern(currentPattern, sel , mode); if (cursor.line != -1) { pattern=currentPattern; break; } } } } else if (m_applyto == 1) { CSelection sel; sel.start.line = 0; sel.start.track = 0; sel.end.line = song.patternLines[cview._ps()]; sel.end.track = MAX_TRACKS; cursor = cview.SearchInPattern(cview._ps(), sel , mode); pattern = cview._ps(); } else if (m_applyto == 2 && cview.blockSelected) { cursor = cview.SearchInPattern(cview._ps(), cview.blockSel , mode); pattern = cview._ps(); } else { MessageBox("No block selected for action","Search and replace",MB_ICONWARNING); return; } if (cursor.line == -1) { MessageBox("Nothing found that matches the selected options","Search and replace",MB_ICONINFORMATION); } else { cview.editcur = cursor; if (cview._ps() != pattern) { int pos = -1; for (int i=0; i < MAX_SONG_POSITIONS; i++) { if (song.playOrder[i] == pattern) { pos = i; break; } } if (pos == -1){ pos = song.playLength; ++song.playLength; song.playOrder[pos]=pattern; ((CMainFrame*)cview.pParentFrame)->UpdateSequencer(); } cview.editPosition = pos; memset(song.playOrderSel,0,MAX_SONG_POSITIONS*sizeof(bool)); song.playOrderSel[cview.editPosition]=true; ((CMainFrame*)cview.pParentFrame)->UpdatePlayOrder(true); cview.Repaint(draw_modes::pattern); } else { cview.Repaint(draw_modes::cursor); } } } void CTransformPatternDlg::OnBnClickedReplace() { CSearchReplaceMode mode = cview.SetupSearchReplaceMode( m_searchnote.GetItemData(m_searchnote.GetCurSel()), m_searchinst.GetItemData(m_searchinst.GetCurSel()), m_searchmach.GetItemData(m_searchmach.GetCurSel()), m_replacenote.GetItemData(m_replacenote.GetCurSel()), m_replaceinst.GetItemData(m_replaceinst.GetCurSel()), m_replacemach.GetItemData(m_replacemach.GetCurSel()), m_replacetweak.GetCheck()); bool replaced=false; UpdateData (TRUE); if (m_applyto == 0) { bool includeOther = m_includePatNotInSeq.GetCheck() > 0; int lastPatternUsed = (includeOther )? song.GetHighestPatternIndexInSequence() : MAX_PATTERNS; for (int currentPattern = 0; currentPattern <= lastPatternUsed; currentPattern++) { if (song.IsPatternUsed(currentPattern, !includeOther)) { CSelection sel; sel.start.line = 0; sel.start.track = 0; sel.end.line = song.patternLines[currentPattern]; sel.end.track = MAX_TRACKS; replaced=cview.SearchReplace(currentPattern, sel , mode); } } } else if (m_applyto == 1) { CSelection sel; sel.start.line = 0; sel.start.track = 0; sel.end.line = song.patternLines[cview._ps()]; sel.end.track = MAX_TRACKS; replaced=cview.SearchReplace(cview._ps(), sel, mode); } else if (m_applyto == 2 && cview.blockSelected) { replaced=cview.SearchReplace(cview._ps(), cview.blockSel , mode); } else { MessageBox("No block selected for action","Search and replace",MB_ICONWARNING); return; } if (replaced) { cview.Repaint(draw_modes::pattern); } else { MessageBox("Nothing found that matches the selected options","Search and replace",MB_ICONINFORMATION); } } } // namespace } // namespace
Java
/* ======================================================================== * Bootstrap: alert.js v3.0.3 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function($) { "use strict"; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function(element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.DEFAULTS = { animation: true , placement: 'top' , selector: false , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' , trigger: 'hover focus' , title: '' , delay: 0 , html: false , container: false } Tooltip.prototype.init = function(type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--; ) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, {trigger: 'manual', selector: ''})) : this.fixTitle() } Tooltip.prototype.getDefaults = function() { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function(options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function() { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function(key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function(obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function() { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function(obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function() { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function() { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return var $tip = this.tip() this.setContent() if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({top: 0, left: 0, display: 'block'}) .addClass(placement) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var $parent = this.$element.parent() var orgPlacement = placement var docScroll = document.documentElement.scrollTop || document.body.scrollTop var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth() var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight() var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) this.$element.trigger('shown.bs.' + this.type) } } Tooltip.prototype.applyPlacement = function(offset, placement) { var replace var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft $tip .offset(offset) .addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { replace = true offset.top = offset.top + height - actualHeight } if (/bottom|top/.test(placement)) { var delta = 0 if (offset.left < 0) { delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } else { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } Tooltip.prototype.replaceArrow = function(delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } Tooltip.prototype.setContent = function() { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function() { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() this.$element.trigger('hidden.bs.' + this.type) return this } Tooltip.prototype.fixTitle = function() { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function() { return this.getTitle() } Tooltip.prototype.getPosition = function() { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth , height: el.offsetHeight }, this.$element.offset()) } Tooltip.prototype.getCalculatedOffset = function(placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} : placement == 'top' ? {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} : placement == 'left' ? {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} : /* placement == 'right' */ {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width} } Tooltip.prototype.getTitle = function() { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.tip = function() { return this.$tip = this.$tip || $(this.options.template) } Tooltip.prototype.arrow = function() { return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow') } Tooltip.prototype.validate = function() { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function() { this.enabled = true } Tooltip.prototype.disable = function() { this.enabled = false } Tooltip.prototype.toggleEnabled = function() { this.enabled = !this.enabled } Tooltip.prototype.toggle = function(e) { var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function() { this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= var old = $.fn.tooltip $.fn.tooltip = function(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function() { $.fn.tooltip = old return this } // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function(el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function(e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent.trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one($.support.transition.end, removeElement) .emulateTransitionEnd(150) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= var old = $.fn.alert $.fn.alert = function(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function() { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.0.3 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function($) { "use strict"; // TAB CLASS DEFINITION // ==================== var Tab = function(element) { this.element = $(element) } Tab.prototype.show = function() { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ($this.parent('li').hasClass('active')) return var previous = $ul.find('.active:last a')[0] var e = $.Event('show.bs.tab', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return var $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function() { $this.trigger({ type: 'shown.bs.tab' , relatedTarget: previous }) }) } Tab.prototype.activate = function(element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active .one($.support.transition.end, next) .emulateTransitionEnd(150) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== var old = $.fn.tab $.fn.tab = function(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function() { $.fn.tab = old return this } // TAB DATA-API // ============ $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function(e) { e.preventDefault() $(this).tab('show') }) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.0.3 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function($) { "use strict"; // AFFIX CLASS DEFINITION // ====================== var Affix = function(element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$window = $(window) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = null this.checkPosition() } Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0 } Affix.prototype.checkPositionWithEventLoop = function() { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function() { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$window.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin) this.$element.css('top', '') this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : '')) if (affix == 'bottom') { this.$element.offset({top: document.body.offsetHeight - offsetBottom - this.$element.height()}) } } // AFFIX PLUGIN DEFINITION // ======================= var old = $.fn.affix $.fn.affix = function(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function() { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function() { $('[data-spy="affix"]').each(function() { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop $spy.affix(data) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.0.3 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function($) { "use strict"; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function(element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function() { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function() { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing') [dimension](0) this.transitioning = 1 var complete = function() { this.$element .removeClass('collapsing') .addClass('in') [dimension]('auto') this.transitioning = 0 this.$element.trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) [dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function() { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element [dimension](this.$element[dimension]()) [0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function() { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function() { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== var old = $.fn.collapse $.fn.collapse = function(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function() { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function(e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $target.collapse(option) }) }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.0.3 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function($) { "use strict"; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var href var process = $.proxy(this.process, this) this.$element = $(element).is('body') ? $(window) : $(element) this.$body = $('body') this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.offsets = $([]) this.targets = $([]) this.activeTarget = null this.refresh() this.process() } ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.refresh = function() { var offsetMethod = this.$element[0] == window ? 'offset' : 'position' this.offsets = $([]) this.targets = $([]) var self = this var $targets = this.$body .find(this.selector) .map(function() { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#\w/.test(href) && $(href) return ($href && $href.length && [[$href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href]]) || null }) .sort(function(a, b) { return a[0] - b[0] }) .each(function() { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function() { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight var maxScroll = scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate(i) } for (i = offsets.length; i--; ) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function(target) { this.activeTarget = target $(this.selector) .parents('.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } // SCROLLSPY PLUGIN DEFINITION // =========================== var old = $.fn.scrollspy $.fn.scrollspy = function(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function() { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load', function() { $('[data-spy="scroll"]').each(function() { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.0.3 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function($) { "use strict"; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd' , 'MozTransition': 'transitionend' , 'OTransition': 'oTransitionEnd otransitionend' , 'transition': 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return {end: transEndEventNames[name]} } } } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function(duration) { var called = false, $el = this $(this).one($.support.transition.end, function() { called = true }) var callback = function() { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function() { $.support.transition = transitionEnd() }) }(jQuery);
Java
/** * Copyright (C) 2008-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. * */ /******************** (c) Marvell Semiconductor, Inc., 2001 ******************* * * Purpose: * This file contains the definitions of the fragment module * *****************************************************************************/ #ifndef __FRAGMENT_H__ #define __FRAGMENT_H__ #include "StaDb.h" //============================================================================= // INCLUDE FILES //============================================================================= //============================================================================= // DEFINITIONS //============================================================================= //============================================================================= // PUBLIC TYPE DEFINITIONS //============================================================================= //============================================================================= // PUBLIC PROCEDURES (ANSI Prototypes) //============================================================================= extern struct sk_buff *DeFragPck(struct net_device *dev,struct sk_buff *skb, extStaDb_StaInfo_t **pStaInfo); #endif/* __FRAGMENT_H__ */
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_67) on Thu Apr 09 10:31:52 MDT 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.lucene.analysis.custom.CustomAnalyzer (Lucene 5.1.0 API)</title> <meta name="date" content="2015-04-09"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.lucene.analysis.custom.CustomAnalyzer (Lucene 5.1.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/lucene/analysis/custom/class-use/CustomAnalyzer.html" target="_top">Frames</a></li> <li><a href="CustomAnalyzer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.lucene.analysis.custom.CustomAnalyzer" class="title">Uses of Class<br>org.apache.lucene.analysis.custom.CustomAnalyzer</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">CustomAnalyzer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.lucene.analysis.custom">org.apache.lucene.analysis.custom</a></td> <td class="colLast"> <div class="block">A general-purpose Analyzer that can be created with a builder-style API.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.lucene.analysis.custom"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">CustomAnalyzer</a> in <a href="../../../../../../org/apache/lucene/analysis/custom/package-summary.html">org.apache.lucene.analysis.custom</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/apache/lucene/analysis/custom/package-summary.html">org.apache.lucene.analysis.custom</a> that return <a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">CustomAnalyzer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">CustomAnalyzer</a></code></td> <td class="colLast"><span class="strong">CustomAnalyzer.Builder.</span><code><strong><a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.Builder.html#build()">build</a></strong>()</code> <div class="block">Builds the analyzer.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/lucene/analysis/custom/class-use/CustomAnalyzer.html" target="_top">Frames</a></li> <li><a href="CustomAnalyzer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2015 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
Java
var express = require('express'), Weapon = require('../models/Weapon'), router = express.Router(); // HOMEPAGE router.get('/', function(req, res) { res.render('index', { title:'Weapons Guide | Fire Emblem | Awakening', credit: 'Matt.Dodson.Digital', msg: 'Hello Word!' }); }); // WEAPON router.get('/weapon', function(req, res) { var schema = {}; Weapon.schema.eachPath(function (pathname, schemaType) { schema[pathname] = schemaType.instance; }); res.render('weapon', { title:'Weapons Guide | Fire Emblem | Awakening', credit: 'Matt.Dodson.Digital', msg: 'This is a form.', schema: schema }); }); module.exports = router;
Java
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2013 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ #include <stdio.h> #pragma data_seg("dsec") static char greeting[] = "Hello"; #pragma code_seg("asection") void report() { printf("%s, world\n", greeting); } #pragma code_seg(".text") int main () { report(); return 0; }
Java
function isCompatible(){if(navigator.appVersion.indexOf('MSIE')!==-1&&parseFloat(navigator.appVersion.split('MSIE')[1])<6){return false;}return true;}var startUp=function(){mw.config=new mw.Map(true);mw.loader.addSource({"local":{"loadScript":"//bits.wikimedia.org/he.wikipedia.org/load.php","apiScript":"/w/api.php"}});mw.loader.register([["site","1349976191",[],"site"],["noscript","1347062400",[],"noscript"],["startup","1351588618",[],"startup"],["filepage","1347062400"],["user.groups","1347062400",[],"user"],["user","1347062400",[],"user"],["user.cssprefs","1347062400",["mediawiki.user"],"private"],["user.options","1347062400",[],"private"],["user.tokens","1347062400",[],"private"],["mediawiki.language.data","1351588618",["mediawiki.language.init"]],["skins.chick","1350311539"],["skins.cologneblue","1350311539"],["skins.modern","1350311539"],["skins.monobook","1350311539"],["skins.nostalgia","1350311539"],["skins.simple","1350311539"],["skins.standard","1350311539"],["skins.vector", "1350311539"],["jquery","1350311539"],["jquery.appear","1350311539"],["jquery.arrowSteps","1350311539"],["jquery.async","1350311539"],["jquery.autoEllipsis","1350334340",["jquery.highlightText"]],["jquery.badge","1350311539"],["jquery.byteLength","1350311539"],["jquery.byteLimit","1350311539",["jquery.byteLength"]],["jquery.checkboxShiftClick","1350311539"],["jquery.client","1350311539"],["jquery.collapsibleTabs","1350311539"],["jquery.color","1350311539",["jquery.colorUtil"]],["jquery.colorUtil","1350311539"],["jquery.cookie","1350311539"],["jquery.delayedBind","1350311539"],["jquery.expandableField","1350311539",["jquery.delayedBind"]],["jquery.farbtastic","1350311539",["jquery.colorUtil"]],["jquery.footHovzer","1350311539"],["jquery.form","1350311539"],["jquery.getAttrs","1350311539"],["jquery.hidpi","1350311539"],["jquery.highlightText","1350334340",["jquery.mwExtension"]],["jquery.hoverIntent","1350311539"],["jquery.json","1350311539"],["jquery.localize","1350311539"],[ "jquery.makeCollapsible","1351565405"],["jquery.mockjax","1350311539"],["jquery.mw-jump","1350311539"],["jquery.mwExtension","1350311539"],["jquery.placeholder","1350311539"],["jquery.qunit","1350311539"],["jquery.qunit.completenessTest","1350311539",["jquery.qunit"]],["jquery.spinner","1350311539"],["jquery.jStorage","1350311539",["jquery.json"]],["jquery.suggestions","1350311539",["jquery.autoEllipsis"]],["jquery.tabIndex","1350311539"],["jquery.tablesorter","1351565484",["jquery.mwExtension"]],["jquery.textSelection","1350311539",["jquery.client"]],["jquery.validate","1350311539"],["jquery.xmldom","1350311539"],["jquery.tipsy","1350311539"],["jquery.ui.core","1350311539",["jquery"],"jquery.ui"],["jquery.ui.widget","1350311539",[],"jquery.ui"],["jquery.ui.mouse","1350311539",["jquery.ui.widget"],"jquery.ui"],["jquery.ui.position","1350311539",[],"jquery.ui"],["jquery.ui.draggable","1350311539",["jquery.ui.core","jquery.ui.mouse","jquery.ui.widget"],"jquery.ui"],["jquery.ui.droppable" ,"1350311539",["jquery.ui.core","jquery.ui.mouse","jquery.ui.widget","jquery.ui.draggable"],"jquery.ui"],["jquery.ui.resizable","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.mouse"],"jquery.ui"],["jquery.ui.selectable","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.mouse"],"jquery.ui"],["jquery.ui.sortable","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.mouse"],"jquery.ui"],["jquery.ui.accordion","1350311539",["jquery.ui.core","jquery.ui.widget"],"jquery.ui"],["jquery.ui.autocomplete","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.position"],"jquery.ui"],["jquery.ui.button","1350311539",["jquery.ui.core","jquery.ui.widget"],"jquery.ui"],["jquery.ui.datepicker","1350311539",["jquery.ui.core"],"jquery.ui"],["jquery.ui.dialog","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.button","jquery.ui.draggable","jquery.ui.mouse","jquery.ui.position","jquery.ui.resizable"],"jquery.ui"],["jquery.ui.progressbar","1350311539",[ "jquery.ui.core","jquery.ui.widget"],"jquery.ui"],["jquery.ui.slider","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.mouse"],"jquery.ui"],["jquery.ui.tabs","1350311539",["jquery.ui.core","jquery.ui.widget"],"jquery.ui"],["jquery.effects.core","1350311539",["jquery"],"jquery.ui"],["jquery.effects.blind","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.bounce","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.clip","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.drop","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.explode","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.fade","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.fold","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.highlight","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.pulsate","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.scale", "1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.shake","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.slide","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.transfer","1350311539",["jquery.effects.core"],"jquery.ui"],["mediawiki","1350311539"],["mediawiki.api","1350311539",["mediawiki.util"]],["mediawiki.api.category","1350311539",["mediawiki.api","mediawiki.Title"]],["mediawiki.api.edit","1350311539",["mediawiki.api","mediawiki.Title"]],["mediawiki.api.parse","1350311539",["mediawiki.api"]],["mediawiki.api.titleblacklist","1350311539",["mediawiki.api","mediawiki.Title"]],["mediawiki.api.watch","1350311539",["mediawiki.api","user.tokens"]],["mediawiki.debug","1350311539",["jquery.footHovzer"]],["mediawiki.debug.init","1350311539",["mediawiki.debug"]],["mediawiki.feedback","1350311539",["mediawiki.api.edit","mediawiki.Title","mediawiki.jqueryMsg","jquery.ui.dialog"]],["mediawiki.hidpi","1350311539",["jquery.hidpi"]],[ "mediawiki.htmlform","1350311539"],["mediawiki.notification","1350311539",["mediawiki.page.startup"]],["mediawiki.notify","1350311539"],["mediawiki.searchSuggest","1351565405",["jquery.autoEllipsis","jquery.client","jquery.placeholder","jquery.suggestions"]],["mediawiki.Title","1350311539",["mediawiki.util"]],["mediawiki.Uri","1350311539"],["mediawiki.user","1350311539",["jquery.cookie","mediawiki.api","user.options","user.tokens"]],["mediawiki.util","1351565428",["jquery.client","jquery.cookie","jquery.mwExtension","mediawiki.notify"]],["mediawiki.action.edit","1350311539",["jquery.textSelection","jquery.byteLimit"]],["mediawiki.action.edit.preview","1350311539",["jquery.form","jquery.spinner"]],["mediawiki.action.history","1350311539",[],"mediawiki.action.history"],["mediawiki.action.history.diff","1350311539",[],"mediawiki.action.history"],["mediawiki.action.view.dblClickEdit","1350311539",["mediawiki.util","mediawiki.page.startup"]],["mediawiki.action.view.metadata","1351565405"],[ "mediawiki.action.view.rightClickEdit","1350311539"],["mediawiki.action.watch.ajax","1347062400",["mediawiki.page.watch.ajax"]],["mediawiki.language","1350311539",["mediawiki.language.data","mediawiki.cldr"]],["mediawiki.cldr","1350311539",["mediawiki.libs.pluralruleparser"]],["mediawiki.libs.pluralruleparser","1350311539"],["mediawiki.language.init","1350311539"],["mediawiki.jqueryMsg","1350311539",["mediawiki.util","mediawiki.language"]],["mediawiki.libs.jpegmeta","1350311539"],["mediawiki.page.ready","1350311539",["jquery.checkboxShiftClick","jquery.makeCollapsible","jquery.placeholder","jquery.mw-jump","mediawiki.util"]],["mediawiki.page.startup","1350311539",["jquery.client","mediawiki.util"]],["mediawiki.page.watch.ajax","1351565428",["mediawiki.page.startup","mediawiki.api.watch","mediawiki.util","mediawiki.notify","jquery.mwExtension"]],["mediawiki.special","1350311539"],["mediawiki.special.block","1350311539",["mediawiki.util"]],["mediawiki.special.changeemail","1350311539",[ "mediawiki.util"]],["mediawiki.special.changeslist","1350311539",["jquery.makeCollapsible"]],["mediawiki.special.movePage","1350311539",["jquery.byteLimit"]],["mediawiki.special.preferences","1350311539"],["mediawiki.special.recentchanges","1350311539",["mediawiki.special"]],["mediawiki.special.search","1351565552"],["mediawiki.special.undelete","1350311539"],["mediawiki.special.upload","1351573522",["mediawiki.libs.jpegmeta","mediawiki.util"]],["mediawiki.special.javaScriptTest","1350311539",["jquery.qunit"]],["mediawiki.tests.qunit.testrunner","1350311539",["jquery.qunit","jquery.qunit.completenessTest","mediawiki.page.startup","mediawiki.page.ready"]],["mediawiki.legacy.ajax","1350311539",["mediawiki.util","mediawiki.legacy.wikibits"]],["mediawiki.legacy.commonPrint","1350311539"],["mediawiki.legacy.config","1350311539",["mediawiki.legacy.wikibits"]],["mediawiki.legacy.IEFixes","1350311539",["mediawiki.legacy.wikibits"]],["mediawiki.legacy.protect","1350311539",[ "mediawiki.legacy.wikibits","jquery.byteLimit"]],["mediawiki.legacy.shared","1350311539"],["mediawiki.legacy.oldshared","1350311539"],["mediawiki.legacy.upload","1350311539",["mediawiki.legacy.wikibits","mediawiki.util"]],["mediawiki.legacy.wikibits","1350311539",["mediawiki.util"]],["mediawiki.legacy.wikiprintable","1350311539"],["ext.gadget.Checkty","1349240575",["jquery.ui.button","jquery.ui.dialog"]],["ext.gadget.SubsetMenu","1347062400",["mediawiki.api"]],["ext.gadget.OrphanCheck","1347062400"],["ext.gadget.Revert","1347062400"],["ext.gadget.autocomplete","1347062400",["jquery.ui.widget","jquery.ui.autocomplete","jquery.textSelection"]],["ext.gadget.TemplateParamWizard","1349813783",["jquery.ui.widget","jquery.tipsy","jquery.textSelection","jquery.ui.autocomplete","jquery.ui.dialog"]],["ext.gadget.TemplatesExternalLinks","1351381284",["jquery.ui.dialog","jquery.textSelection"]],["ext.gadget.Summarieslist","1347062400"],["ext.gadget.ReferencesWarn","1347062400"],[ "ext.gadget.CustomSideBarLinks","1347062400"],["ext.gadget.Dwim","1351288385",["jquery.suggestions","mediawiki.user"]],["ext.gadget.mySandbox","1347062400",["mediawiki.util"]],["ext.gadget.alignEditsectionToRight","1347062400"],["ext.gadget.FixedMenu","1347062400"],["ext.gadget.FixedSidebar","1347062400"],["ext.gadget.refStyle","1347062400"],["ext.gadget.CiteTooltip","1350413007",["jquery.tipsy","mediawiki.user"]],["ext.gadget.ExternalLinkIcon","1347062400"],["ext.gadget.updateMarker","1348209888"],["ext.gadget.watchlistMark","1347062400"],["ext.gadget.DeleteRequest","1347062400",["mediawiki.util"]],["ext.gadget.rollBackSummary","1347062400"],["ext.gadget.ajaxRC","1347062400"],["ext.gadget.patrolAlarm","1347062400"],["ext.gadget.disableFeedback","1347062400"],["ext.gadget.microblog","1347062400"],["ext.gadget.mychat","1347062400"],["ext.gadget.MoveToCommons","1351028833"],["mobile.device.default","1350311691"],["mobile.device.webkit","1351099404"],["mobile.device.android","1351099404"] ,["mobile.device.iphone","1351099404"],["mobile.device.iphone2","1351099404"],["mobile.device.palm_pre","1350311691"],["mobile.device.kindle","1350311691"],["mobile.device.blackberry","1351099404"],["mobile.device.simple","1350311691"],["mobile.device.psp","1350311691"],["mobile.device.wii","1350311691"],["mobile.device.operamini","1350311691"],["mobile.device.operamobile","1350311691"],["mobile.device.nokia","1350311691"],["ext.wikihiero","1350311861"],["ext.wikihiero.Special","1350311861",["jquery.spinner"]],["ext.cite","1350311592",["jquery.tooltip"]],["jquery.tooltip","1350311592"],["ext.specialcite","1350311592"],["ext.geshi.local","1347062400"],["ext.categoryTree","1351565722"],["ext.categoryTree.css","1350311573"],["ext.nuke","1350311699"],["ext.centralauth","1351583215"],["ext.centralauth.noflash","1350311583"],["ext.centralauth.globalusers","1350311583"],["ext.centralauth.globalgrouppermissions","1350311583"],["ext.centralNotice.interface","1350311586",["jquery.ui.datepicker"] ],["ext.centralNotice.bannerStats","1350311586"],["ext.centralNotice.bannerController","1351218499"],["ext.collection.jquery.jstorage","1350311605",["jquery.json"]],["ext.collection.suggest","1350311605",["ext.collection.bookcreator"]],["ext.collection","1350311605",["ext.collection.bookcreator","jquery.ui.sortable"]],["ext.collection.bookcreator","1350311605",["ext.collection.jquery.jstorage"]],["ext.collection.checkLoadFromLocalStorage","1350311605",["ext.collection.jquery.jstorage"]],["ext.abuseFilter","1350311550"],["ext.abuseFilter.edit","1351260433",["mediawiki.util","jquery.textSelection","jquery.spinner"]],["ext.abuseFilter.tools","1351261611",["mediawiki.util","jquery.spinner"]],["ext.abuseFilter.examine","1351261611",["mediawiki.util"]],["ext.vector.collapsibleNav","1351565552",["mediawiki.util","jquery.client","jquery.cookie","jquery.tabIndex"],"ext.vector"],["ext.vector.collapsibleTabs","1350311790",["jquery.collapsibleTabs","jquery.delayedBind"],"ext.vector"],[ "ext.vector.editWarning","1351565552",[],"ext.vector"],["ext.vector.expandableSearch","1350311790",["jquery.client","jquery.expandableField","jquery.delayedBind"],"ext.vector"],["ext.vector.footerCleanup","1351196615",["mediawiki.jqueryMsg","jquery.cookie"],"ext.vector"],["ext.vector.sectionEditLinks","1350311790",["jquery.cookie","jquery.clickTracking"],"ext.vector"],["contentCollector","1350311833",[],"ext.wikiEditor"],["jquery.wikiEditor","1351565399",["jquery.client","jquery.textSelection","jquery.delayedBind"],"ext.wikiEditor"],["jquery.wikiEditor.iframe","1350311833",["jquery.wikiEditor","contentCollector"],"ext.wikiEditor"],["jquery.wikiEditor.dialogs","1350311833",["jquery.wikiEditor","jquery.wikiEditor.toolbar","jquery.ui.dialog","jquery.ui.button","jquery.ui.draggable","jquery.ui.resizable","jquery.tabIndex"],"ext.wikiEditor"],["jquery.wikiEditor.dialogs.config","1351565399",["jquery.wikiEditor","jquery.wikiEditor.dialogs","jquery.wikiEditor.toolbar.i18n","jquery.suggestions" ,"mediawiki.Title"],"ext.wikiEditor"],["jquery.wikiEditor.highlight","1350311833",["jquery.wikiEditor","jquery.wikiEditor.iframe"],"ext.wikiEditor"],["jquery.wikiEditor.preview","1350311833",["jquery.wikiEditor"],"ext.wikiEditor"],["jquery.wikiEditor.previewDialog","1350311833",["jquery.wikiEditor","jquery.wikiEditor.dialogs"],"ext.wikiEditor"],["jquery.wikiEditor.publish","1350311833",["jquery.wikiEditor","jquery.wikiEditor.dialogs"],"ext.wikiEditor"],["jquery.wikiEditor.templateEditor","1350311833",["jquery.wikiEditor","jquery.wikiEditor.iframe","jquery.wikiEditor.dialogs"],"ext.wikiEditor"],["jquery.wikiEditor.templates","1350311833",["jquery.wikiEditor","jquery.wikiEditor.iframe"],"ext.wikiEditor"],["jquery.wikiEditor.toc","1350311833",["jquery.wikiEditor","jquery.wikiEditor.iframe","jquery.ui.draggable","jquery.ui.resizable","jquery.autoEllipsis","jquery.color"],"ext.wikiEditor"],["jquery.wikiEditor.toolbar","1350311833",["jquery.wikiEditor","jquery.wikiEditor.toolbar.i18n"], "ext.wikiEditor"],["jquery.wikiEditor.toolbar.config","1350311833",["jquery.wikiEditor","jquery.wikiEditor.toolbar.i18n","jquery.wikiEditor.toolbar","jquery.cookie","jquery.async"],"ext.wikiEditor"],["jquery.wikiEditor.toolbar.i18n","1347062400",[],"ext.wikiEditor"],["ext.wikiEditor","1350311833",["jquery.wikiEditor"],"ext.wikiEditor"],["ext.wikiEditor.dialogs","1350311833",["ext.wikiEditor","ext.wikiEditor.toolbar","jquery.wikiEditor.dialogs","jquery.wikiEditor.dialogs.config"],"ext.wikiEditor"],["ext.wikiEditor.highlight","1350311833",["ext.wikiEditor","jquery.wikiEditor.highlight"],"ext.wikiEditor"],["ext.wikiEditor.preview","1350311833",["ext.wikiEditor","jquery.wikiEditor.preview"],"ext.wikiEditor"],["ext.wikiEditor.previewDialog","1350311833",["ext.wikiEditor","jquery.wikiEditor.previewDialog"],"ext.wikiEditor"],["ext.wikiEditor.publish","1350311833",["ext.wikiEditor","jquery.wikiEditor.publish"],"ext.wikiEditor"],["ext.wikiEditor.templateEditor","1350311833",["ext.wikiEditor", "ext.wikiEditor.highlight","jquery.wikiEditor.templateEditor"],"ext.wikiEditor"],["ext.wikiEditor.templates","1350311833",["ext.wikiEditor","ext.wikiEditor.highlight","jquery.wikiEditor.templates"],"ext.wikiEditor"],["ext.wikiEditor.toc","1350311833",["ext.wikiEditor","ext.wikiEditor.highlight","jquery.wikiEditor.toc"],"ext.wikiEditor"],["ext.wikiEditor.tests.toolbar","1350311833",["ext.wikiEditor.toolbar"],"ext.wikiEditor"],["ext.wikiEditor.toolbar","1350311833",["ext.wikiEditor","jquery.wikiEditor.toolbar","jquery.wikiEditor.toolbar.config"],"ext.wikiEditor"],["ext.wikiEditor.toolbar.hideSig","1350311833",[],"ext.wikiEditor"],["ext.wikiLove.icon","1350311835"],["ext.wikiLove.defaultOptions","1351566772"],["ext.wikiLove.startup","1351566772",["ext.wikiLove.defaultOptions","jquery.ui.dialog","jquery.ui.button","jquery.localize","jquery.elastic"]],["ext.wikiLove.local","1351571152"],["ext.wikiLove.init","1350311835",["ext.wikiLove.startup"]],["jquery.elastic","1350311835"],[ "mobile.head","1351099404"],["mobile","1351190119"],["mobile.beta.jquery","1351187517"],["mobile.beta.jquery.eventlog","1351099404"],["mobile.production-only","1351190119"],["mobile.beta","1351190119"],["mobile.filePage","1351037747"],["mobile.references","1351187517"],["mobile.site","1347062400",[],"site"],["mobile.desktop","1351037747",["jquery.cookie"]],["ext.math.mathjax","1350311683",[],"ext.math.mathjax"],["ext.math.mathjax.enabler","1350311683"],["ext.babel","1350311571"],["ext.apiSandbox","1350311555",["mediawiki.util","jquery.ui.button"]],["ext.interwiki.specialpage","1350311669",["jquery.makeCollapsible"]],["ext.postEdit","1351565462",["jquery.cookie"]],["ext.checkUser","1350311590",["mediawiki.util"]]]);mw.config.set({"wgLoadScript":"//bits.wikimedia.org/he.wikipedia.org/load.php","debug":false,"skin":"vector","stylepath":"//bits.wikimedia.org/static-1.21wmf2/skins","wgUrlProtocols": "http\\:\\/\\/|https\\:\\/\\/|ftp\\:\\/\\/|irc\\:\\/\\/|ircs\\:\\/\\/|gopher\\:\\/\\/|telnet\\:\\/\\/|nntp\\:\\/\\/|worldwind\\:\\/\\/|mailto\\:|news\\:|svn\\:\\/\\/|git\\:\\/\\/|mms\\:\\/\\/|\\/\\/","wgArticlePath":"/wiki/$1","wgScriptPath":"/w","wgScriptExtension":".php","wgScript":"/w/index.php","wgVariantArticlePath":false,"wgActionPaths":{},"wgServer":"//he.wikipedia.org","wgUserLanguage":"he","wgContentLanguage":"he","wgVersion":"1.21wmf2","wgEnableAPI":true,"wgEnableWriteAPI":true,"wgMainPageTitle":"עמוד ראשי","wgFormattedNamespaces":{"-2":"מדיה","-1":"מיוחד","0":"","1":"שיחה","2":"משתמש","3":"שיחת משתמש","4":"ויקיפדיה","5":"שיחת ויקיפדיה","6":"קובץ","7":"שיחת קובץ","8":"מדיה ויקי","9":"שיחת מדיה ויקי","10":"תבנית","11":"שיחת תבנית","12":"עזרה","13":"שיחת עזרה","14":"קטגוריה","15":"שיחת קטגוריה","100":"פורטל","101":"שיחת פורטל","108": "ספר","109":"שיחת ספר"},"wgNamespaceIds":{"מדיה":-2,"מיוחד":-1,"":0,"שיחה":1,"משתמש":2,"שיחת_משתמש":3,"ויקיפדיה":4,"שיחת_ויקיפדיה":5,"קובץ":6,"שיחת_קובץ":7,"מדיה_ויקי":8,"שיחת_מדיה_ויקי":9,"תבנית":10,"שיחת_תבנית":11,"עזרה":12,"שיחת_עזרה":13,"קטגוריה":14,"שיחת_קטגוריה":15,"פורטל":100,"שיחת_פורטל":101,"ספר":108,"שיחת_ספר":109,"תמונה":6,"שיחת_תמונה":7,"משתמשת":2,"שיחת_משתמשת":3,"image":6,"image_talk":7,"media":-2,"special":-1,"talk":1,"user":2,"user_talk":3,"project":4,"project_talk":5,"file":6,"file_talk":7,"mediawiki":8,"mediawiki_talk":9,"template":10,"template_talk":11,"help":12,"help_talk":13,"category":14,"category_talk":15},"wgSiteName":"ויקיפדיה","wgFileExtensions":["png","gif","jpg","jpeg","xcf","pdf","mid","ogg","ogv","svg","djvu","tiff","tif","oga"],"wgDBname":"hewiki","wgFileCanRotate" :true,"wgAvailableSkins":{"chick":"Chick","cologneblue":"CologneBlue","modern":"Modern","monobook":"MonoBook","myskin":"MySkin","nostalgia":"Nostalgia","simple":"Simple","standard":"Standard","vector":"Vector"},"wgExtensionAssetsPath":"//bits.wikimedia.org/static-1.21wmf2/extensions","wgCookiePrefix":"hewiki","wgResourceLoaderMaxQueryLength":-1,"wgCaseSensitiveNamespaces":[],"wgCollectionVersion":"1.6.1","wgCollapsibleNavBucketTest":false,"wgCollapsibleNavForceNewVersion":false,"wgWikiEditorToolbarClickTracking":false,"wgWikiEditorMagicWords":{"redirect":"#הפניה","img_right":"ימין","img_left":"שמאל","img_none":"ללא","img_center":"מרכז","img_thumbnail":"ממוזער","img_framed":"ממוסגר","img_frameless":"לא ממוסגר"},"wgNoticeFundraisingUrl":"https://donate.wikimedia.org/wiki/Special:LandingCheck","wgCentralPagePath":"//meta.wikimedia.org/w/index.php","wgNoticeBannerListLoader":"מיוחד:BannerListLoader","wgCentralBannerDispatcher": "//meta.wikimedia.org/wiki/Special:BannerLoader","wgCookiePath":"/","wgMFStopRedirectCookieHost":".wikipedia.org"});};if(isCompatible()){document.write("\x3cscript src=\"//bits.wikimedia.org/he.wikipedia.org/load.php?debug=false\x26amp;lang=he\x26amp;modules=jquery%2Cmediawiki\x26amp;only=scripts\x26amp;skin=vector\x26amp;version=20121015T143219Z\"\x3e\x3c/script\x3e");}delete isCompatible; /* cache key: hewiki:resourceloader:filter:minify-js:7:60f4df8e133ee65d1c188b18b6f0e1b4 */
Java
{- hpodder component Copyright (C) 2006 John Goerzen <jgoerzen@complete.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : FeedParser Copyright : Copyright (C) 2006 John Goerzen License : GNU GPL, version 2 or above Maintainer : John Goerzen <jgoerzen@complete.org> Stability : provisional Portability: portable Written by John Goerzen, jgoerzen\@complete.org -} module FeedParser where import Types import Text.XML.HaXml import Text.XML.HaXml.Parse import Text.XML.HaXml.Posn import Utils import Data.Maybe.Utils import Data.Char import Data.Either.Utils import Data.List import System.IO data Item = Item {itemtitle :: String, itemguid :: Maybe String, enclosureurl :: String, enclosuretype :: String, enclosurelength :: String } deriving (Eq, Show, Read) data Feed = Feed {channeltitle :: String, items :: [Item]} deriving (Eq, Show, Read) item2ep pc item = Episode {podcast = pc, epid = 0, eptitle = sanitize_basic (itemtitle item), epurl = sanitize_basic (enclosureurl item), epguid = fmap sanitize_basic (itemguid item), eptype = sanitize_basic (enclosuretype item), epstatus = Pending, eplength = case reads . sanitize_basic . enclosurelength $ item of [] -> 0 [(x, [])] -> x _ -> 0, epfirstattempt = Nothing, eplastattempt = Nothing, epfailedattempts = 0} parse :: FilePath -> String -> IO (Either String Feed) parse fp name = do h <- openBinaryFile fp ReadMode c <- hGetContents h case xmlParse' name (unifrob c) of Left x -> return (Left x) Right y -> do let doc = getContent y let title = getTitle doc let feeditems = getEnclosures doc return $ Right $ (Feed {channeltitle = title, items = feeditems}) where getContent (Document _ _ e _) = CElem e noPos unifrob ('\xfeff':x) = x -- Strip off unicode BOM unifrob x = x unesc = xmlUnEscape stdXmlEscaper getTitle doc = forceEither $ strofm "title" (channel doc) getEnclosures doc = concat . map procitem $ item doc where procitem i = map (procenclosure title guid) enclosure where title = case strofm "title" [i] of Left x -> "Untitled" Right x -> x guid = case strofm "guid" [i] of Left _ -> Nothing Right x -> Just x enclosure = tag "enclosure" `o` children $ i procenclosure title guid e = Item {itemtitle = title, itemguid = guid, enclosureurl = head0 $ forceMaybe $ stratt "url" e, enclosuretype = head0 $ case stratt "type" e of Nothing -> ["application/octet-stream"] Just x -> x, enclosurelength = head $ case stratt "length" e of Nothing -> ["0"] Just [] -> ["0"] Just x -> x } head0 [] = "" head0 (x:xs) = x item = tag "item" `o` children `o` channel channel = tag "channel" `o` children `o` tag "rss" -------------------------------------------------- -- Utilities -------------------------------------------------- attrofelem :: String -> Content Posn -> Maybe AttValue attrofelem attrname (CElem inelem _) = case unesc inelem of Elem name al _ -> lookup attrname al attrofelem _ _ = error "attrofelem: called on something other than a CElem" stratt :: String -> Content Posn -> Maybe [String] stratt attrname content = case attrofelem attrname content of Just (AttValue x) -> Just (concat . map mapfunc $ x) Nothing -> Nothing where mapfunc (Left x) = [x] mapfunc (Right _) = [] -- Finds the literal children of the named tag, and returns it/them tagof :: String -> CFilter Posn tagof x = keep /> tag x -- /> txt -- Retruns the literal string that tagof would find strof :: String -> Content Posn -> String strof x y = forceEither $ strof_either x y strof_either :: String -> Content Posn -> Either String String strof_either x y = case tagof x $ y of [CElem elem pos] -> Right $ verbatim $ tag x /> txt $ CElem (unesc elem) pos z -> Left $ "strof: expecting CElem in " ++ x ++ ", got " ++ verbatim z ++ " at " ++ verbatim y strofm x y = if length errors /= 0 then Left errors else Right (concat plainlist) where mapped = map (strof_either x) $ y (errors, plainlist) = conveithers mapped isright (Left _) = False isright (Right _) = True conveithers :: [Either a b] -> ([a], [b]) conveithers inp = worker inp ([], []) where worker [] y = y worker (Left x:xs) (lefts, rights) = worker xs (x:lefts, rights) worker (Right x:xs) (lefts, rights) = worker xs (lefts, x:rights)
Java
/* * Copyright (c) 1997 Enterprise Systems Management Corp. * * This file is part of UName*It. * * UName*It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2, or (at your option) any later * version. * * UName*It 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 UName*It; see the file COPYING. If not, write to the Free * Software Foundation, 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ /* $Id: transaction.h,v 1.13 1997/05/28 23:19:52 viktor Exp $ */ #ifndef _TRANSACTION_H #define _TRANSACTION_H #include <dbi.h> #include <tcl.h> typedef enum {NORESTORE, RESTOREDATA, RESTORESCHEMA} RestoreMode; /* * item_class NON-NULL iff template is for a 'unameit_item' */ extern DB_OBJECT *Udb_Finish_Object( DB_OBJECT *item_class, DB_OTMPL *template, int item_deleted ); extern RestoreMode Udb_Restore_Mode(RestoreMode *new); extern Tcl_CmdProc Udb_Syscall; extern Tcl_CmdProc Udb_Transaction; extern Tcl_CmdProc Udb_Version; extern Tcl_CmdProc Udb_Rollback; extern Tcl_CmdProc Udb_Commit; extern void Udb_OpenLog(const char *logPrefix); extern void Udb_CloseLog(void); extern void Udb_Force_Rollback(Tcl_Interp *interp); extern int Udb_Do_Rollback(Tcl_Interp *interp); extern int Udb_Do_Commit(Tcl_Interp *interp, const char *logEntry); #endif
Java
<?php /* Icinga Web 2 | (c) 2013-2015 Icinga Development Team | GPLv2+ */ namespace Icinga\Module\Monitoring\DataView; class Contactgroup extends DataView { /** * {@inheritdoc} */ public function isValidFilterTarget($column) { if ($column[0] === '_' && preg_match('/^_(?:host|service)_/', $column)) { return true; } return parent::isValidFilterTarget($column); } /** * {@inheritdoc} */ public function getColumns() { return array( 'contactgroup_name', 'contactgroup_alias', 'contact_object_id', 'contact_id', 'contact_name', 'contact_alias', 'contact_email', 'contact_pager', 'contact_has_host_notfications', 'contact_has_service_notfications', 'contact_can_submit_commands', 'contact_notify_service_recovery', 'contact_notify_service_warning', 'contact_notify_service_critical', 'contact_notify_service_unknown', 'contact_notify_service_flapping', 'contact_notify_service_downtime', 'contact_notify_host_recovery', 'contact_notify_host_down', 'contact_notify_host_unreachable', 'contact_notify_host_flapping', 'contact_notify_host_downtime', 'contact_notify_host_timeperiod', 'contact_notify_service_timeperiod' ); } /** * {@inheritdoc} */ public function getSortRules() { return array( 'contactgroup_name' => array( 'order' => self::SORT_ASC ), 'contactgroup_alias' => array( 'order' => self::SORT_ASC ) ); } /** * {@inheritdoc} */ public function getFilterColumns() { return array( 'contactgroup', 'contact', 'host', 'host_name', 'host_display_name', 'host_alias', 'hostgroup', 'hostgroup_alias', 'hostgroup_name', 'service', 'service_description', 'service_display_name', 'servicegroup', 'servicegroup_alias', 'servicegroup_name' ); } /** * {@inheritdoc} */ public function getSearchColumns() { return array('contactgroup_alias'); } }
Java
import configparser CONFIG_PATH = 'accounting.conf' class MyConfigParser(): def __init__(self, config_path=CONFIG_PATH): self.config = configparser.ConfigParser(allow_no_value=True) self.config.read(config_path) def config_section_map(self, section): """ returns all configuration options in 'section' in a dict with key: config_option and value: the read value in the file""" dict1 = {} options = self.config.options(section) for option in options: try: dict1[option] = self.config.get(section, option) if dict1[option] == -1: DebugPrint("skip: %s" % option) except: dict1[option] = None return dict1 # getint(section, option) # getboolean(section, option)
Java
///////////////////////////////////////////////////////////////////////////// // Name: imagpnm.h // Purpose: wxImage PNM handler // Author: Sylvain Bougnoux // RCS-ID: $Id: imagpnm.h,v 1.1 1999/12/15 22:37:51 VS Exp $ // Copyright: (c) Sylvain Bougnoux // Licence: wxWindows licence // Modified by: Chris M. Christoudias // read/write pnm image ///////////////////////////////////////////////////////////////////////////// #ifndef _BG_IMAGPNM_H_ #define _BG_IMAGPNM_H_ #ifdef __GNUG__ #pragma interface "BgImagPNM.h" #endif #include <wx/image.h> //----------------------------------------------------------------------------- // bgPGMHandler //----------------------------------------------------------------------------- class bgPNMHandler : public wxImageHandler { DECLARE_DYNAMIC_CLASS(bgPNMHandler) public: inline bgPNMHandler() { m_name = "PNM file"; m_extension = "pnm"; m_type = wxBITMAP_TYPE_PNM; m_mime = "image/pnm"; }; virtual bool LoadFile( wxImage *image, wxInputStream& stream, bool verbose=TRUE, int index=0 ); virtual bool SaveFile( wxImage *image, wxOutputStream& stream, bool verbose=TRUE ); virtual bool DoCanRead( wxInputStream& stream ); void Skip_Comment(wxInputStream &stream); }; #endif
Java
# codingInPython Github space for my experiments with programming, learning Python and git alongside. Much of what I have in here are some code examples of exercies I have been trying to complete. As of 4/6, most of the effort has been on data manipulation or rather list manipulation. 4/7 : Updated files :
Java
<h2><?php print $node->title; ?></h2> <h3><?php print content_format('field_subtitle', $field_subtitle[0]); ?></h3> <? print l('Back', 'node/'.$node->field_case_project[0]['nid'], array('html'=>TRUE, 'attributes'=>array('class'=>'back-link'))); ?> <? print content_format('field_case_intro_title', $field_case_intro_title[0]); ?> <? print content_format('field_case_intro_body', $field_case_intro_body[0]); ?> <? print content_format('field_case_video', $field_case_video[0]); ?> <? $distribution_body = strip_tags($field_case_distribution_body[0]['value']); if (!empty($distribution_body)) print content_format('field_case_distribution_body', $field_case_distribution_body[0]); ?> <? if (!empty($field_case_distribution_image[0]['filename'])) print content_format('field_case_distribution_image', $field_case_distribution_image[0], 'image_plain'); ?> <? $finance_body = strip_tags($field_case_finance_body[0]['value']); if (!empty($finance_body)) print content_format('field_case_finance_body', $field_case_finance_body[0]); ?> <? if (!empty($field_case_finance_image[0]['filename'])) print content_format('field_case_finance_image', $field_case_finance_image[0], 'image_plain'); ?> <? $multiplatform_body = strip_tags($field_case_multiplatform_body[0]['value']); if (!empty($multiplatform_body)) print content_format('field_case_multiplatform_body', $field_case_multiplatform_body[0]); ?> <? if (!empty($field_case_multiplatform_image[0]['filename'])) print content_format('field_case_multiplatform_image', $field_case_multiplatform_image[0], 'image_plain'); ?> <? $ad_body = strip_tags($field_case_ad_body[0]['value']); if (!empty($ad_body)) print content_format('field_case_ad_body', $field_case_ad_body[0]); ?> <? if (!empty($field_case_ad_image[0]['filename'])) print content_format('field_case_ad_image', $field_case_ad_image[0], 'image_plain'); ?> <? $international_body = strip_tags($field_case_international_body[0]['value']); if (!empty($international_body)) print content_format('field_case_international_body', $field_case_international_body[0]); ?> <? if (!empty($field_case_international_image[0]['filename'])) print content_format('field_case_international_image', $field_case_international_image[0], 'image_plain'); ?> <? $format_body = strip_tags($field_case_format_body[0]['value']); if (!empty($format_body)) print content_format('field_case_format_body', $field_case_format_body[0]); ?> <? if (!empty($field_case_format_image[0]['filename'])) print content_format('field_case_format_image', $field_case_format_image[0], 'image_plain'); ?> <? print content_format('field_case_whitepaper', $field_case_whitepaper[0]); ?> <div class="sponsor-logos"> <? print views_embed_view('sponsor_logos', 'block_1', $field_case_project[0]['nid']); ?> </div>
Java
package ms.aurora.browser.wrapper; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.tidy.Tidy; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * A parser / access layer for HTML pages * @author Rick */ public final class HTML { private static Logger logger = Logger.getLogger(HTML.class); private Document dom; public HTML(Document dom) { this.dom = dom; } public Document getDOM() { return dom; } public List<Node> searchXPath(String expression) { List<Node> matchingElements = new ArrayList<Node>(); try { XPathExpression expressionObj = getExpression(expression); NodeList resultingNodeList = (NodeList) expressionObj.evaluate(dom, XPathConstants.NODESET); for (int index = 0; index < resultingNodeList.getLength(); index++) { matchingElements.add(resultingNodeList.item(index)); } } catch (XPathExpressionException e) { logger.error("Incorrect XPath expression", e); } return matchingElements; } public List<Node> searchXPath(Node base, String expression) { List<Node> matchingElements = new ArrayList<Node>(); try { XPathExpression expressionObj = getExpression(expression); NodeList resultingNodeList = (NodeList) expressionObj.evaluate(base, XPathConstants.NODESET); for (int index = 0; index < resultingNodeList.getLength(); index++) { matchingElements.add(resultingNodeList.item(index)); } } catch (XPathExpressionException e) { logger.error("Incorrect XPath expression", e); } return matchingElements; } private XPathExpression getExpression(String expression) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); return xpath.compile(expression); } public static HTML fromStream(InputStream stream) { try { /* * UGLY ASS W3C API IS UGLY */ Tidy tidy = new Tidy(); tidy.setXHTML(true); Document dom = tidy.parseDOM(stream, null); dom.getDocumentElement().normalize(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Source xmlSource = new DOMSource(dom); Result outputTarget = new StreamResult(outputStream); TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget); InputStream is = new ByteArrayInputStream(outputStream.toByteArray()); return new HTML(db.parse(is)); } catch (Exception e) { logger.error("Failed to parse HTML properly", e); } return null; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_43) on Tue Dec 15 22:07:49 NZDT 2015 --> <TITLE> weka.core.stemmers </TITLE> <META NAME="date" CONTENT="2015-12-15"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="weka.core.stemmers"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="http://www.cs.waikato.ac.nz/ml/weka/" target="_blank"><FONT CLASS="NavBarFont1"><B>Weka's home</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../weka/core/pmml/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../weka/core/tokenizers/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?weka/core/stemmers/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package weka.core.stemmers </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/Stemmer.html" title="interface in weka.core.stemmers">Stemmer</A></B></TD> <TD>Interface for all stemming algorithms.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/IteratedLovinsStemmer.html" title="class in weka.core.stemmers">IteratedLovinsStemmer</A></B></TD> <TD>An iterated version of the Lovins stemmer.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/LovinsStemmer.html" title="class in weka.core.stemmers">LovinsStemmer</A></B></TD> <TD>A stemmer based on the Lovins stemmer, described here:<br/> <br/> Julie Beth Lovins (1968).</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/NullStemmer.html" title="class in weka.core.stemmers">NullStemmer</A></B></TD> <TD>A dummy stemmer that performs no stemming at all.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/SnowballStemmer.html" title="class in weka.core.stemmers">SnowballStemmer</A></B></TD> <TD>A wrapper class for the Snowball stemmers.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/Stemming.html" title="class in weka.core.stemmers">Stemming</A></B></TD> <TD>A helper class for using the stemmers.</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="http://www.cs.waikato.ac.nz/ml/weka/" target="_blank"><FONT CLASS="NavBarFont1"><B>Weka's home</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../weka/core/pmml/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../weka/core/tokenizers/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?weka/core/stemmers/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
<html> <head> <title>Transverse Ray Aberration Diagram</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="generator" content="HelpNDoc Personal Edition 4.3.1.364"> <link type="text/css" rel="stylesheet" media="all" href="css/reset.css" /> <link type="text/css" rel="stylesheet" media="all" href="css/base.css" /> <link type="text/css" rel="stylesheet" media="all" href="css/hnd.css" /> <!--[if lte IE 8]> <link type="text/css" rel="stylesheet" media="all" href="css/ielte8.css" /> <![endif]--> <style type="text/css"> #topic_header { background-color: #EFEFEF; } </style> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/hnd.js"></script> <script type="text/javascript"> $(document).ready(function() { if (top.frames.length == 0) { var sTopicUrl = top.location.href.substring(top.location.href.lastIndexOf("/") + 1, top.location.href.length); top.location.href = "Programming and Algorithms Reference MATLAB Based Optical Analysis Toolbox V 3.0.html?" + sTopicUrl; } else if (top && top.FrameTOC && top.FrameTOC.SelectTocItem) { top.FrameTOC.SelectTocItem("TransverseRayAberrationDiagram"); } }); </script> </head> <body> <div id="topic_header"> <div id="topic_header_content"> <h1 id="topic_header_text">Transverse Ray Aberration Diagram</h1> <div id="topic_breadcrumb"> <a href="ExamplesofExtendingtheToolbox.html">Examples of Extending the Toolbox</a> &rsaquo;&rsaquo; <a href="Method1Aspartofthetoolbox.html">Method 1: As part of the toolbox</a> &rsaquo;&rsaquo; </div> </div> <div id="topic_header_nav"> <a href="Method1Aspartofthetoolbox.html"><img src="img/arrow_up.png" alt="Parent"/></a> <a href="Method1Aspartofthetoolbox.html"><img src="img/arrow_left.png" alt="Previous"/></a> <a href="Procedures.html"><img src="img/arrow_right.png" alt="Next"/></a> </div> <div class="clear"></div> </div> <div id="topic_content"> <p></p> <h1 class="rvps11"><span class="rvts0"><span class="rvts59">Toolbox Extension Example: Transverse Ray Aberration Diagram</span></span></h1> <p class="rvps10"><span class="rvts37">Purpose:</span></p> <p class="rvps10"><span class="rvts38">To add an analysis window to the toolbox which shows ray aberrations as a function of pupil coordinate. </span></p> <p class="rvps10"><span class="rvts38"><br/></span></p> <p></p> <p class="rvps6"><span class="rvts20">Created with the Personal Edition of HelpNDoc: </span><a class="rvts21" href="http://www.helpndoc.com/help-authoring-tool">Create HTML Help, DOC, PDF and print manuals from 1 single source</a></p> </div> <div id="topic_footer"> <div id="topic_footer_content"> Copyright &copy; &lt;2014&gt; by &lt;Norman G. Worku (normangirma2012@gmail.com), Optical System Design Research Group, FSU, Jena&gt;. All Rights Reserved.</div> </div> </body> </html>
Java
/* * Read-Copy Update mechanism for mutual exclusion * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Copyright IBM Corporation, 2001 * * Author: Dipankar Sarma <dipankar@in.ibm.com> * * Based on the original work by Paul McKenney <paulmck@us.ibm.com> * and inputs from Rusty Russell, Andrea Arcangeli and Andi Kleen. * Papers: * http://www.rdrop.com/users/paulmck/paper/rclockpdcsproof.pdf * http://lse.sourceforge.net/locking/rclock_OLS.2001.05.01c.sc.pdf (OLS2001) * * For detailed explanation of Read-Copy Update mechanism see - * http://lse.sourceforge.net/locking/rcupdate.html * */ #ifndef __LINUX_RCUPDATE_H #define __LINUX_RCUPDATE_H #include <linux/cache.h> #include <linux/spinlock.h> #include <linux/threads.h> #include <linux/cpumask.h> #include <linux/seqlock.h> #include <linux/lockdep.h> #include <linux/completion.h> /** * struct rcu_head - callback structure for use with RCU * @next: next update requests in a list * @func: actual update function to call after the grace period. */ struct rcu_head { struct rcu_head *next; void (*func)(struct rcu_head *head); }; /* Exported common interfaces */ #ifdef CONFIG_TREE_PREEMPT_RCU extern void synchronize_rcu(void); #else /* #ifdef CONFIG_TREE_PREEMPT_RCU */ #define synchronize_rcu synchronize_sched #endif /* #else #ifdef CONFIG_TREE_PREEMPT_RCU */ extern void synchronize_rcu_bh(void); extern void synchronize_sched(void); extern void rcu_barrier(void); extern void rcu_barrier_bh(void); extern void rcu_barrier_sched(void); extern void synchronize_sched_expedited(void); extern int sched_expedited_torture_stats(char *page); /* Internal to kernel */ extern void rcu_init(void); extern void rcu_scheduler_starting(void); #ifndef CONFIG_TINY_RCU extern int rcu_needs_cpu(int cpu); #else static inline int rcu_needs_cpu(int cpu) { return 0; } #endif extern int rcu_scheduler_active; #include "rcutiny.h" /* Figure out why later. */ // #if defined(CONFIG_TREE_RCU) || defined(CONFIG_TREE_PREEMPT_RCU) // #include <linux/rcutree.h> #ifdef CONFIG_TINY_RCU #include <linux/rcutiny.h> #else #error "Unknown RCU implementation specified to kernel configuration" #endif #define RCU_HEAD_INIT { .next = NULL, .func = NULL } #define RCU_HEAD(head) struct rcu_head head = RCU_HEAD_INIT #define INIT_RCU_HEAD(ptr) do { \ (ptr)->next = NULL; (ptr)->func = NULL; \ } while (0) #ifdef CONFIG_DEBUG_LOCK_ALLOC extern struct lockdep_map rcu_lock_map; # define rcu_read_acquire() \ lock_acquire(&rcu_lock_map, 0, 0, 2, 1, NULL, _THIS_IP_) # define rcu_read_release() lock_release(&rcu_lock_map, 1, _THIS_IP_) #else # define rcu_read_acquire() do { } while (0) # define rcu_read_release() do { } while (0) #endif /** * rcu_read_lock - mark the beginning of an RCU read-side critical section. * * When synchronize_rcu() is invoked on one CPU while other CPUs * are within RCU read-side critical sections, then the * synchronize_rcu() is guaranteed to block until after all the other * CPUs exit their critical sections. Similarly, if call_rcu() is invoked * on one CPU while other CPUs are within RCU read-side critical * sections, invocation of the corresponding RCU callback is deferred * until after the all the other CPUs exit their critical sections. * * Note, however, that RCU callbacks are permitted to run concurrently * with RCU read-side critical sections. One way that this can happen * is via the following sequence of events: (1) CPU 0 enters an RCU * read-side critical section, (2) CPU 1 invokes call_rcu() to register * an RCU callback, (3) CPU 0 exits the RCU read-side critical section, * (4) CPU 2 enters a RCU read-side critical section, (5) the RCU * callback is invoked. This is legal, because the RCU read-side critical * section that was running concurrently with the call_rcu() (and which * therefore might be referencing something that the corresponding RCU * callback would free up) has completed before the corresponding * RCU callback is invoked. * * RCU read-side critical sections may be nested. Any deferred actions * will be deferred until the outermost RCU read-side critical section * completes. * * It is illegal to block while in an RCU read-side critical section. */ static inline void rcu_read_lock(void) { __rcu_read_lock(); __acquire(RCU); rcu_read_acquire(); } /* * So where is rcu_write_lock()? It does not exist, as there is no * way for writers to lock out RCU readers. This is a feature, not * a bug -- this property is what provides RCU's performance benefits. * Of course, writers must coordinate with each other. The normal * spinlock primitives work well for this, but any other technique may be * used as well. RCU does not care how the writers keep out of each * others' way, as long as they do so. */ /** * rcu_read_unlock - marks the end of an RCU read-side critical section. * * See rcu_read_lock() for more information. */ static inline void rcu_read_unlock(void) { rcu_read_release(); __release(RCU); __rcu_read_unlock(); } /** * rcu_read_lock_bh - mark the beginning of a softirq-only RCU critical section * * This is equivalent of rcu_read_lock(), but to be used when updates * are being done using call_rcu_bh(). Since call_rcu_bh() callbacks * consider completion of a softirq handler to be a quiescent state, * a process in RCU read-side critical section must be protected by * disabling softirqs. Read-side critical sections in interrupt context * can use just rcu_read_lock(). * */ static inline void rcu_read_lock_bh(void) { __rcu_read_lock_bh(); __acquire(RCU_BH); rcu_read_acquire(); } /* * rcu_read_unlock_bh - marks the end of a softirq-only RCU critical section * * See rcu_read_lock_bh() for more information. */ static inline void rcu_read_unlock_bh(void) { rcu_read_release(); __release(RCU_BH); __rcu_read_unlock_bh(); } /** * rcu_read_lock_sched - mark the beginning of a RCU-classic critical section * * Should be used with either * - synchronize_sched() * or * - call_rcu_sched() and rcu_barrier_sched() * on the write-side to insure proper synchronization. */ static inline void rcu_read_lock_sched(void) { preempt_disable(); __acquire(RCU_SCHED); rcu_read_acquire(); } /* Used by lockdep and tracing: cannot be traced, cannot call lockdep. */ static inline notrace void rcu_read_lock_sched_notrace(void) { preempt_disable_notrace(); __acquire(RCU_SCHED); } /* * rcu_read_unlock_sched - marks the end of a RCU-classic critical section * * See rcu_read_lock_sched for more information. */ static inline void rcu_read_unlock_sched(void) { rcu_read_release(); __release(RCU_SCHED); preempt_enable(); } /* Used by lockdep and tracing: cannot be traced, cannot call lockdep. */ static inline notrace void rcu_read_unlock_sched_notrace(void) { __release(RCU_SCHED); preempt_enable_notrace(); } /** * rcu_dereference - fetch an RCU-protected pointer in an * RCU read-side critical section. This pointer may later * be safely dereferenced. * * Inserts memory barriers on architectures that require them * (currently only the Alpha), and, more importantly, documents * exactly which pointers are protected by RCU. */ #define rcu_dereference(p) ({ \ typeof(p) _________p1 = ACCESS_ONCE(p); \ smp_read_barrier_depends(); \ (_________p1); \ }) /** * rcu_assign_pointer - assign (publicize) a pointer to a newly * initialized structure that will be dereferenced by RCU read-side * critical sections. Returns the value assigned. * * Inserts memory barriers on architectures that require them * (pretty much all of them other than x86), and also prevents * the compiler from reordering the code that initializes the * structure after the pointer assignment. More importantly, this * call documents which pointers will be dereferenced by RCU read-side * code. */ #define rcu_assign_pointer(p, v) \ ({ \ if (!__builtin_constant_p(v) || \ ((v) != NULL)) \ smp_wmb(); \ (p) = (v); \ }) /* Infrastructure to implement the synchronize_() primitives. */ struct rcu_synchronize { struct rcu_head head; struct completion completion; }; extern void wakeme_after_rcu(struct rcu_head *head); /** * call_rcu - Queue an RCU callback for invocation after a grace period. * @head: structure to be used for queueing the RCU updates. * @func: actual update function to be invoked after the grace period * * The update function will be invoked some time after a full grace * period elapses, in other words after all currently executing RCU * read-side critical sections have completed. RCU read-side critical * sections are delimited by rcu_read_lock() and rcu_read_unlock(), * and may be nested. */ extern void call_rcu(struct rcu_head *head, void (*func)(struct rcu_head *head)); /** * call_rcu_bh - Queue an RCU for invocation after a quicker grace period. * @head: structure to be used for queueing the RCU updates. * @func: actual update function to be invoked after the grace period * * The update function will be invoked some time after a full grace * period elapses, in other words after all currently executing RCU * read-side critical sections have completed. call_rcu_bh() assumes * that the read-side critical sections end on completion of a softirq * handler. This means that read-side critical sections in process * context must not be interrupted by softirqs. This interface is to be * used when most of the read-side critical sections are in softirq context. * RCU read-side critical sections are delimited by : * - rcu_read_lock() and rcu_read_unlock(), if in interrupt context. * OR * - rcu_read_lock_bh() and rcu_read_unlock_bh(), if in process context. * These may be nested. */ extern void call_rcu_bh(struct rcu_head *head, void (*func)(struct rcu_head *head)); #endif /* __LINUX_RCUPDATE_H */
Java
<?php /** * Plugin Name: Custom Register Form Plugin * Plugin URI: http://tamanhquyen.com/register-form-for-wordpress.html * Description: Create Custom Register Form Frontend Page * Version: 1.0 * Author: TA MANH QUYEN * Author URI: http://tamanhquyen.com */ global $wp_version; if(version_compare($wp_version,'3.6.1','<')) { exit('This is plugin requice Wordpress Version 3.6 on highter. Please update now!'); } register_activation_hook(__FILE__,'mq_register_setting'); register_deactivation_hook(__FILE__,'mq_delete_setting'); function enque_register() { wp_register_script('mq_register_ajax',plugins_url('inc/js/init.js',__FILE__),array('jquery'),true); wp_localize_script('mq_register_ajax','mq_register_ajax',array('mq_ajax_url' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script('mq_register_ajax'); } add_action('wp_enqueue_scripts','enque_register'); function mq_registerform_menu() { add_menu_page('Register Form Setting','Register Form','update_plugins','register-form-setting','mq_registerform_set','',1); } add_action('admin_menu','mq_registerform_menu'); function mq_register_setting() { add_option('mq_register_form_title','','255','yes'); add_option('mq_register_form_setting','','255','yes'); add_option('mq_register_form_css','','255','yes'); add_option('mq_register_form_intro','','255','yes'); add_option('mq_register_facelink','','255','yes'); } function mq_delete_setting() { delete_option('mq_register_form_setting'); delete_option('mq_register_form_title'); delete_option('mq_register_form_css'); delete_option('mq_register_facelink'); delete_option('mq_register_form_intro'); remove_shortcode('mq_register'); } include_once('inc/mq_shortcode.php'); include_once('inc/mq_ajax.php'); include_once('inc/form_setting.php'); include_once('inc/form_create.php'); include_once('inc/script/register_action.php');
Java
<?php class grid_assignments_progress{ private $db = false; private $user; private $edit_color = '#FFFFFF'; public function __construct(){ $this->db = Connection::getDB(); $this->user = new administrator(); if($this->user->role=='pupil' || $this->user->role=='parent'){ $this->edit_color = '#AAAAAA'; } $this->db->query("START TRANSACTION"); error_reporting(E_ALL ^ E_NOTICE); switch ($_POST['action']) { case 'editresult': $this->editResult($_POST['id'],$_POST['value'],$_POST['pass']); break; case 'editgrade': $this->editGrade($_POST['id'],$_POST['value'],$_POST['pass']); break; case 'editassessment': $this->editAssessment($_POST['id'],$_POST['assessment']); break; case 'deactive': $this->deactivePerformance($_POST['id']); break; case 'reactive': $this->reactivePerformance($_POST['id']); break; case 'editstatus': $this->editStutus($_POST['assid'],$_POST['pid'],$_POST['value']); break; case 'makeassubmitted': $this->makeAsSubmitted($_POST['assid'],$_POST['pid']); break; case 'makeasnotsubmitted': $this->makeAsNotSubmitted($_POST['assid'],$_POST['pid']); break; case 'activate': $this->activate($_POST['assid'],$_POST['pid'],$_POST['type']); break; case 'remove': $this->remove($_POST['assid'],$_POST['pid'],$_POST['type']); break; case 'deactivate': $this->deactivate($_POST['assid'],$_POST['pid'],$_POST['type']); break; default: $this->getAssignmentsGrid(); break; } $this->db->query("COMMIT"); } private function editStutus($id,$pid,$val){ $result = $this->db->query("UPDATE pupli_submission_slot SET status='$val' WHERE assignment_id=$id AND pupil_id=$pid"); } private function makeAsSubmitted($id,$pid){ $result = $this->db->query("UPDATE pupli_submission_slot SET status='1', submission_date = NOW() WHERE assignment_id=$id AND pupil_id=$pid"); } private function makeAsNotSubmitted($id,$pid){ $ns = dlang("grids_not_subm_text","Not subm."); $result = $this->db->query("UPDATE pupli_submission_slot SET status='$ns' WHERE assignment_id=$id AND pupil_id=$pid"); } private function editResult($id,$val,$pass){ @session_start(); $_SESSION['submissions_update']=$this->user->id; session_write_close(); $this->db->query("UPDATE pupil_submission_result SET result='$val', pass='$pass' WHERE pupil_submission_result_id=$id"); if($val=='A' || $val=='B'|| $val=='C'||$val=='D'||$val=='E'||$val=='F'||$val=='Fx'||$val==dlang("passvalue","Pass")||$val==dlang("npassvalue","NPass")){ $result = $this->db->query("UPDATE pupil_submission_result SET assessment='$val' WHERE pupil_submission_result_id=$id"); } $this->db->query("UPDATE pupli_submission_slot,pupil_submission_result SET pupli_submission_slot.status='1' WHERE pupli_submission_slot.submission_slot_id = pupil_submission_result.submission_slot_id AND pupil_submission_result.pupil_submission_result_id = $id"); echo 1; } private function editGrade($id,$val,$pass){ $result = $this->db->query("UPDATE pupil_submission_result SET assessment='$assess', pass=$val WHERE pupil_submission_result_id=$id"); } private function editAssessment($id, $assess){ $result = $this->db->query("UPDATE pupil_performance_assessment SET assessment='$assess' WHERE pupil_performance_assessment_id=$id"); } private function remove($id,$pid,$type){ if($type=="performance"){ $result = $this->db->query("DELETE FROM pupil_performance_assessment WHERE pupil_id=$pid AND performance_id=$id"); }else{ $result = $this->db->query("DELETE FROM pupli_submission_slot WHERE pupil_id=$pid AND assignment_id=$id"); } } private function activate($id,$pid,$type){ if($type=="performance"){ $this->db->query("UPDATE pupil_performance_assessment SET active=1, activation_date=NOW() WHERE pupil_id=$pid AND performance_id=$id"); }else{ $this->db->query("UPDATE pupli_submission_slot SET active=1, activation_date=NOW() WHERE pupil_id=$pid AND assignment_id=$id"); } } private function deactivate($id,$pid,$type){ if($type=="performance"){ $this->db->query("UPDATE pupil_performance_assessment SET active=0 WHERE pupil_id=$pid AND performance_id=$id"); }else{ $this->db->query("UPDATE pupli_submission_slot SET active=0 WHERE pupil_id=$pid AND assignment_id=$id"); } } private function getPerformanceArray($result,$rows){ //$rows = array(); while($row = mysql_fetch_assoc($result)){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][12] = $row['performance_id']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][1] = $row['perf_title']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][7] = $row['sid']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][8] = $row['s_id']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][11] = $row['active']?"1":"0.5"; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][13] = $row['active']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][10] = $row['active']?"#FFFFFF":"#F5F5F5"; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][0] = $row['pid']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][3]= $row['ass']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][13] = $row['active']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][10] = $row['active']?"#FFFFFF":"#F5F5F5"; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][11] = $row['active']?"1":"0.5"; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][4][] = $row['obj_title']; if($row['ass'] == "" || $row['ass'] == "na"){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][5] = $this->edit_color; }elseif($row['ass'] == "F" || $row['ass'] == "Fx"){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][5] = "#ff8888"; }else{ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][5] = "#88ff88"; } } //print_r($rows); return $rows; } private function getAssignmentsGrid(){ header("Content-type:text/xml"); print('<?xml version="1.0" encoding="UTF-8"?>'); $id = $_GET['id']; $and = ""; if(isset($_GET['stg']) && $_GET['stg']!=""){ $and = "AND studygroups.studygroup_id = ".$_GET['stg']; } $result = $this->db->query(" SELECT course_rooms_assignments.number as numb, course_rooms_assignments.title_en as title_assignment, course_rooms_assignments.assignment_id as aid, DATEDIFF(course_rooms_assignments.deadline_date, CURDATE()) as dl_date, DATEDIFF(course_rooms_assignments.deadline_date, pupli_submission_slot.submission_date) as submission_date, course_rooms_assignments.deadline_date as deadline_date2, pupli_submission_slot.submission_date as submission_date2, course_objectives.title_en as title_course_obj, course_rooms_assignments.deadline as deadline, course_rooms_assignments.deadline_passed as dp, pupli_submission_slot.content_en as pcont, pupli_submission_slot.status as status, pupli_submission_slot.active as active, resultsets.result_max as max_rs, resultsets.result_pass as pass_rs, resultsets.studygroup_ids as studygroup_ids, result_units.result_unit_en as unit_rs, pupil_submission_result.result as subm_result, pupil_submission_result.assessment as assessment, pupil_submission_result.pupil_submission_result_id as psr, studygroups.title_en as sid, studygroups.studygroup_id as s_id, result_units.result_unit_id as result_unit_id, academic_years.title_en as acyear, subjects.title_en as subject, academic_years.academic_year_id as acyear_id, subjects.subject_id as subject_id, resultsets.castom_name as castom_name FROM course_rooms,pupli_submission_slot, course_rooms_assignments, resultsets, studygroups, course_objectives, result_units, pupil_submission_result, resultset_to_course_objectives, academic_years, subjects WHERE pupli_submission_slot.assignment_id = course_rooms_assignments.assignment_id AND course_rooms_assignments.course_room_id = course_rooms.course_room_id AND course_rooms.course_room_id = studygroups.course_room_id AND resultsets.assignment_id = pupli_submission_slot.assignment_id AND resultset_to_course_objectives.resultset_id = resultsets.resultset_id AND course_objectives.objective_id = resultset_to_course_objectives.objective_id AND result_units.result_unit_id = resultsets.result_unit_id AND pupil_submission_result.result_set_id = resultsets.resultset_id AND pupil_submission_result.submission_slot_id = pupli_submission_slot.submission_slot_id AND pupli_submission_slot.pupil_id=$id AND studygroups.subject_id=subjects.subject_id AND subjects.academic_year_id = academic_years.academic_year_id AND resultset_to_course_objectives.type = 'assignment' {$and} "); $result_perf = $this->db->query(" SELECT performance.title_en as perf_title, pupil_performance_assessment.pupil_performance_assessment_id as pid, course_objectives.title_en as obj_title,pupil_performance_assessment.assessment as ass, pupil_performance_assessment.passed as passed, pupil_performance_assessment.active as active, studygroups.title_en as sid, studygroups.studygroup_id as s_id, pupil_performance_assessment.performance_id as performance_id, resultsets.resultset_id as resultset_id, academic_years.title_en as acyear, subjects.title_en as subject, academic_years.academic_year_id as acyear_id, subjects.subject_id as subject_id FROM course_rooms, pupil_performance_assessment, performance, studygroups,resultsets,course_objectives,resultset_to_course_objectives, academic_years, subjects WHERE pupil_performance_assessment.performance_id = performance.performance_id AND performance.course_room_id = course_rooms.course_room_id AND course_rooms.course_room_id = studygroups.course_room_id AND resultsets.resultset_id = pupil_performance_assessment.resultset_id AND resultset_to_course_objectives.resultset_id = resultsets.resultset_id AND course_objectives.objective_id = resultset_to_course_objectives.objective_id AND pupil_performance_assessment.pupil_id = $id AND studygroups.subject_id=subjects.subject_id AND subjects.academic_year_id = academic_years.academic_year_id AND resultset_to_course_objectives.type = 'performance' "); echo '<rows>'; $assarr = $this->getAssignmentsArray($result); $perfarr = $this->getPerformanceArray($result_perf,$assarr); //$perform = $this->outPerformanceArray($this->getPerformanceArray($result_perf)); $this->outAssignmentsArray($perfarr); echo '</rows>'; } private function outPerformanceArray($value2){ $perf_xml = ' <row id="performance_'.$value2[12].'"> <cell bgColor="'.$value2[10].'" style="opacity: '.$value2[11].';" sid="performance_'.$value2[12].'" image="assessment.png">'.$value2[1].'</cell> <cell bgColor="'.$value2[10].'" style="opacity: '.$value2[11].';"/><cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/> <cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/><cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/> <cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/><cell bgColor="'.$value2[10].'"/>'; foreach ($value2[14] as $value3) { $perf_xml.= ' <row id="p_'.$value3[0].'" style="opacity: '.$value3[11].';"> <cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$value3[11].';" image="objective.png" >'.$value2[7].': '.implode(', ',$value3[4]).'</cell> <cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell> <cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell> <cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell> <cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell> <cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';">'.$value3[6].'</cell> <cell style="opacity: '.$value3[11].';" xmlcontent="1" bgColor="'.$value3[5].'">'.$value3[3].'<option value="A">'."A".'</option> <option value="B">'."B".'</option> <option value="C">'."C".'</option> <option value="D">'."D".'</option> <option value="E">'."E".'</option> <option value="F">'."F".'</option> <option value="Fx">'."Fx".'</option> <option value="">'."".'</option> </cell> </row> '; } $perf_xml.= '<userdata name="activate">'.$value2[13].'</userdata></row>'; return $perf_xml; } private function getAssignmentsArray($result){ $rows = array(); $graeds = array('A','B','C','D','E','F'); while($row = mysql_fetch_assoc($result)){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']][0] = $row['sid']; $rows[$row['acyear_id']][0] = $row['acyear']; $rows[$row['acyear_id']][$row['subject_id']][0] = $row['subject']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][0] = $row['aid']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][2] = $row['title_assignment']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][3] = $row['dp']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][4] = $row['pcont']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][5] = $row['dl_date']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][20] = $row['deadline_date2']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][21] = $row['submission_date2']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][16] = $row['deadline']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][6] = $row['status']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][7] = $row['title_course']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][9] = $row['sid']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][10] = $row['active']?"#FFFFFF":"#F5F5F5"; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][11] = $row['active']?"1":"0.5"; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][12] = $row['active']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][15] = $row['submission_date']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][0] = $row['psr']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][1] = $row['castom_name']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][2] = $row['max_rs']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][3] = $row['pass_rs']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][4] = $row['subm_result']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][6] = $row['dl_date']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][7] = $row['sid']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][8] = $row['s_id']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][9] = $row['assessment']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][12] = $row['result_unit_id']; $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][14] = $row['studygroup_ids']; if($row['assessment']=="p"){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][9] = dlang("passvalue","Pass"); } if($row['assessment']=="np"){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][9] = dlang("npassvalue","NPass"); } $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][10] = $row['title_course']; $pass = $row['pass_rs']; $res = $row['subm_result']; switch ($row['result_unit_id']) { case '1': if((int)$pass <= (int)$res){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88"; }else{ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888"; } break; case '2': if((int)$pass <= (int)$res){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88"; }else{ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888"; } break; case '3': if(array_search($pass,$graeds)>=array_search($res,$graeds)){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88"; }else{ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888"; } break; case '4': if(strtolower($res)==dlang("passvalue","Pass")){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88"; }else{ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888"; } break; } if($res==""){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = $this->edit_color; } if($row['assessment']!=""){ if($row['assessment']=='F' || $row['assessment']=="Fx" || $row['assessment']==dlang("npassvalue","NPass")){ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888"; }else{ $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88"; } } $rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][5][] = $row['title_course_obj']; } // print_r($rows); return $rows; } private function outStgsArray($stg){ foreach ($stg as $key => $group){ if($key=="0") continue; echo ' <row id="stg_'.$key.'"> <cell style="color:rgb(73, 74, 75);" sid="stg_'.$key.'" image="studygroup.png">'.$group[0].'</cell>'; foreach ($group as $key2 => $assignment){ if($key2=="0"){ continue; } $tkey2 = explode('_',$key2); if($tkey2[0] == 'performancep'){ echo $this->outPerformanceArray($assignment); continue; } echo '<row style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';" bgColor="'.$assignment[10].'" id="assignment_'.$assignment[0].'"><cell bgColor="'.$assignment[10].'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';" image="submission.png">'.$assignment[2].'</cell>'; if($assignment[6]!="1" && $assignment[6]!=dlang("grids_not_subm_text","Not subm.") && $assignment[6]!="Not subm."){ echo '<cell bgColor="'.$this->edit_color.'" style="color:#006699; opacity: '.$assignment[11].';">'.$assignment[6].'</cell>'; }else{ if($assignment[5]>=0 && ($assignment[6]==dlang("grids_not_subm_text","Not subm.") || $assignment[6]=="Not subm.") ){ echo '<cell bgColor="'.$this->edit_color.'" style="color:#6495ED; opacity: '.$assignment[11].';">'.dlang("grids_not_subm_text","Not subm.").'</cell>'; }elseif($assignment[5]<0 && ($assignment[6]==dlang("grids_not_subm_text","Not subm."))){ echo '<cell bgColor="'.$this->edit_color.'" style="color:#EE6A50; opacity: '.$assignment[11].';">'.dlang("grids_not_subm_text","Not subm.").'</cell>'; }else{ if($assignment[16]=='No deadline'){ echo '<cell bgColor="'.$this->edit_color.'" style="color:green; opacity: '.$assignment[9].';">'.dlang("grids_subm_text","Subm.").'</cell>'; }else{ if($assignment[15]>=0){ if($assignment[21]<=$assignment[20]){ echo '<cell bgColor="'.$this->edit_color.'" style="color:green; opacity: '.$assignment[13].';">'.abs($assignment[15]).' '.dlang("grids_not_subm_daye","day early").'</cell>'; }else{ echo '<cell bgColor="'.$this->edit_color.'" style="color:red; opacity: '.$assignment[13].';">'.abs($assignment[15]).' '.dlang("grids_not_subm_dayl","day late").'</cell>'; } }else{ echo '<cell bgColor="'.$this->edit_color.'" style="color:red; opacity: '.$assignment[13].';">'.abs($assignment[15]).' '.dlang("grids_not_subm_dayl","day late").'</cell>'; } } } } echo '<cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/>'; foreach ($assignment[8] as $key3 => $rset) { $sql = "SELECT title_en FROM studygroups WHERE studygroup_id IN (".$rset[14].")"; $result = $this->db->query($sql); $sgids = null; while($row = mysql_fetch_assoc($result)){ $sgids[] = $row['title_en']; } echo ' <row id="a_'.$rset[0].'" style="opacity: '.$assignment[11].';"> <cell image="objective.png" bgColor="#FFFFFF" style="opacity: '.$assignment[11].'; color:rgb(73, 74, 75);">'.implode(', ', $sgids).': '.implode(', ',$rset[5]).'</cell> <cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';"></cell> <cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[1].'</cell> <cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[2].'</cell> <cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[3].'</cell> '; switch ($rset[12]) { case '1': echo '<cell type="ed" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[4].'</cell>'; break; case '2': echo '<cell type="ed" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[4].'</cell>'; break; case '3': echo '<cell type="co" xmlcontent="1" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[4].'<option value="'."A".'">'."A".'</option> <option value="B">'."B".'</option> <option value="C">'."C".'</option> <option value="D">'."D".'</option> <option value="E">'."E".'</option> <option value="F">'."F".'</option> <option value="Fx">'."Fx".'</option> </cell> '; break; case '4': echo '<cell type="co" xmlcontent="1" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.dlang($rset[4]).'<option value="'.dlang("passvalue","Pass").'">'.dlang("passvalue","Pass").'</option> <option value="'.dlang("npassvalue","NPass").'">'.dlang("npassvalue","NPass").'</option> <option value="">'."".'</option> </cell>'; break; default: break; } if($rset[12]=='4'){ echo '<cell xmlcontent="1" bgColor="'.$rset[11].'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[9].'<option value="'.dlang("passvalue","Pass").'">'.dlang("passvalue","Pass").'</option> <option value="'.dlang("npassvalue","NPass").'">'.dlang("npassvalue","NPass").'</option> <option value="">'."".'</option> </cell><userdata name="unit">'.$rset[12].'</userdata></row>'; }else{ echo '<cell xmlcontent="1" bgColor="'.$rset[11].'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[9].'<option value="'."A".'">'."A".'</option> <option value="B">'."B".'</option> <option value="C">'."C".'</option> <option value="D">'."D".'</option> <option value="E">'."E".'</option> <option value="F">'."F".'</option> <option value="Fx">'."Fx".'</option> <option value="">'."".'</option> </cell><userdata name="unit">'.$rset[12].'</userdata></row>'; } } echo "<userdata name='submitted'>".($assignment[6]=="1"?1:0)."</userdata>"; echo "<userdata name='activate'>".$assignment[12]."</userdata>"; echo '</row>'; } echo '</row>'; } } private function outAssignmentsArray($acyears){ foreach($acyears as $yid => $year){ if($yid=="0") continue; echo '<row id="year_'.$yid.'"> <cell style="color:rgb(73, 74, 75);" sid="year_'.$yid.'" image="folder_closed.png">'.$year[0].'</cell>'; foreach($year as $subid => $subject){ if($subid=="0" || !$subject[0]) continue; echo '<row id="subject_'.$subid.'"> <cell style="color:rgb(73, 74, 75);" sid="subject_'.$subid.'" image="folder_closed.png">'.$subject[0].'</cell>'; $this->outStgsArray($subject); echo '</row>'; } echo '</row>'; } } } ?>
Java
.admanage-img p img{ width: 300px; height:100px; display: block; float: left; }
Java
/* * ircd-hybrid: an advanced Internet Relay Chat Daemon(ircd). * s_misc.c: Yet another miscellaneous functions file. * * Copyright (C) 2002 by the past and present ircd coders, and others. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * $Id: s_misc.c 33 2005-10-02 20:50:00Z knight $ */ #include "stdinc.h" #include "s_misc.h" #include "client.h" #include "common.h" #include "irc_string.h" #include "sprintf_irc.h" #include "ircd.h" #include "numeric.h" #include "irc_res.h" #include "fdlist.h" #include "s_bsd.h" #include "s_conf.h" #include "s_serv.h" #include "send.h" #include "memory.h" static const char *months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November","December" }; static const char *weekdays[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; char * date(time_t lclock) { static char buf[80], plus; struct tm *lt, *gm; struct tm gmbuf; int minswest; if (!lclock) lclock = CurrentTime; gm = gmtime(&lclock); memcpy(&gmbuf, gm, sizeof(gmbuf)); gm = &gmbuf; lt = localtime(&lclock); /* * There is unfortunately no clean portable way to extract time zone * offset information, so do ugly things. */ minswest = (gm->tm_hour - lt->tm_hour) * 60 + (gm->tm_min - lt->tm_min); if (lt->tm_yday != gm->tm_yday) { if ((lt->tm_yday > gm->tm_yday && lt->tm_year == gm->tm_year) || (lt->tm_yday < gm->tm_yday && lt->tm_year != gm->tm_year)) minswest -= 24 * 60; else minswest += 24 * 60; } plus = (minswest > 0) ? '-' : '+'; if (minswest < 0) minswest = -minswest; ircsprintf(buf, "%s %s %d %d -- %02u:%02u:%02u %c%02u:%02u", weekdays[lt->tm_wday], months[lt->tm_mon],lt->tm_mday, lt->tm_year + 1900, lt->tm_hour, lt->tm_min, lt->tm_sec, plus, minswest/60, minswest%60); return buf; } const char * smalldate(time_t lclock) { static char buf[MAX_DATE_STRING]; struct tm *lt, *gm; struct tm gmbuf; if (!lclock) lclock = CurrentTime; gm = gmtime(&lclock); memcpy(&gmbuf, gm, sizeof(gmbuf)); gm = &gmbuf; lt = localtime(&lclock); ircsprintf(buf, "%d/%d/%d %02d.%02d", lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min); return buf; } /* small_file_date() * Make a small YYYYMMDD formatted string suitable for a * dated file stamp. */ char * small_file_date(time_t lclock) { static char timebuffer[MAX_DATE_STRING]; struct tm *tmptr; if (!lclock) time(&lclock); tmptr = localtime(&lclock); strftime(timebuffer, MAX_DATE_STRING, "%Y%m%d", tmptr); return timebuffer; } #ifdef HAVE_LIBCRYPTO char * ssl_get_cipher(SSL *ssl) { static char buffer[128]; const char *name = NULL; int bits; switch (ssl->session->ssl_version) { case SSL2_VERSION: name = "SSLv2"; break; case SSL3_VERSION: name = "SSLv3"; break; case TLS1_VERSION: name = "TLSv1"; break; default: name = "UNKNOWN"; } SSL_CIPHER_get_bits(SSL_get_current_cipher(ssl), &bits); snprintf(buffer, sizeof(buffer), "%s %s-%d", name, SSL_get_cipher(ssl), bits); return buffer; } #endif
Java
/* * Copyright (C) 2004 * Swiss Federal Institute of Technology, Lausanne. All rights reserved. * * Developed at the Autonomous Systems Lab. * Visit our homepage at http://asl.epfl.ch/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ #ifndef NPM_TRAJECTORYDRAWING_HPP #define NPM_TRAJECTORYDRAWING_HPP #include <npm/gfx/Drawing.hpp> namespace npm { class RobotServer; class TrajectoryDrawing : public Drawing { public: TrajectoryDrawing(const RobotServer * owner); virtual void Draw(); private: const RobotServer * m_owner; }; } #endif // NPM_TRAJECTORYDRAWING_HPP
Java
/* sort.c Ruby/GSL: Ruby extension library for GSL (GNU Scientific Library) (C) Copyright 2001-2006 by Yoshiki Tsunesada Ruby/GSL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. */ #include <extconf.h> #include "rb_gsl_array.h" #include <gsl/gsl_heapsort.h> #include <gsl/gsl_sort.h> EXTERN ID RBGSL_ID_call; EXTERN VALUE cgsl_complex; int rb_gsl_comparison_double(const void *aa, const void *bb); int rb_gsl_comparison_complex(const void *aa, const void *bb); int rb_gsl_comparison_double(const void *aa, const void *bb) { double *a = NULL, *b = NULL; a = (double *) aa; b = (double *) bb; return FIX2INT(rb_funcall(RB_GSL_MAKE_PROC, RBGSL_ID_call, 2, rb_float_new(*a), rb_float_new(*b))); } int rb_gsl_comparison_complex(const void *aa, const void *bb) { gsl_complex *a = NULL, *b = NULL; a = (gsl_complex *) aa; b = (gsl_complex *) bb; return FIX2INT(rb_funcall(RB_GSL_MAKE_PROC, RBGSL_ID_call, 2, Data_Wrap_Struct(cgsl_complex, 0, NULL, a), Data_Wrap_Struct(cgsl_complex, 0, NULL, b))); } static VALUE rb_gsl_heapsort_vector(VALUE obj) { gsl_vector *v = NULL; if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given"); Data_Get_Struct(obj, gsl_vector, v); gsl_heapsort(v->data, v->size, sizeof(double), rb_gsl_comparison_double); return obj; } static VALUE rb_gsl_heapsort_vector2(VALUE obj) { gsl_vector *v = NULL, *vnew = NULL; if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given"); Data_Get_Struct(obj, gsl_vector, v); vnew = gsl_vector_alloc(v->size); gsl_vector_memcpy(vnew, v); gsl_heapsort(vnew->data, vnew->size, sizeof(double), rb_gsl_comparison_double); return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew); } static VALUE rb_gsl_heapsort_index_vector(VALUE obj) { gsl_vector *v = NULL; gsl_permutation *p = NULL; if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given"); Data_Get_Struct(obj, gsl_vector, v); p = gsl_permutation_alloc(v->size); gsl_heapsort_index(p->data, v->data, v->size, sizeof(double), rb_gsl_comparison_double); return Data_Wrap_Struct(cgsl_permutation, 0, gsl_permutation_free, p); } static VALUE rb_gsl_heapsort_vector_complex(VALUE obj) { gsl_vector_complex *v = NULL; if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given"); Data_Get_Struct(obj, gsl_vector_complex, v); gsl_heapsort(v->data, v->size, sizeof(gsl_complex), rb_gsl_comparison_complex); return obj; } static VALUE rb_gsl_heapsort_vector_complex2(VALUE obj) { gsl_vector_complex *v = NULL, *vnew = NULL; if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given"); Data_Get_Struct(obj, gsl_vector_complex, v); vnew = gsl_vector_complex_alloc(v->size); gsl_vector_complex_memcpy(vnew, v); gsl_heapsort(vnew->data, vnew->size, sizeof(gsl_complex), rb_gsl_comparison_complex); return Data_Wrap_Struct(cgsl_vector_complex, 0, gsl_vector_complex_free, vnew); } static VALUE rb_gsl_heapsort_index_vector_complex(VALUE obj) { gsl_vector_complex *v = NULL; gsl_permutation *p = NULL; if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given"); Data_Get_Struct(obj, gsl_vector_complex, v); p = gsl_permutation_alloc(v->size); gsl_heapsort_index(p->data, v->data, v->size, sizeof(gsl_complex), rb_gsl_comparison_complex); return Data_Wrap_Struct(cgsl_permutation, 0, gsl_permutation_free, p); } /* singleton */ static VALUE rb_gsl_heapsort(VALUE obj, VALUE vv) { if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given"); if (rb_obj_is_kind_of(vv, cgsl_vector_complex)) { return rb_gsl_heapsort_vector_complex(vv); } else if (rb_obj_is_kind_of(vv, cgsl_vector)) { return rb_gsl_heapsort_vector(vv); } else { rb_raise(rb_eTypeError, "wrong argument type %s (Vector or Vector::Complex expected)", rb_class2name(CLASS_OF(vv))); } return vv; } static VALUE rb_gsl_heapsort2(VALUE obj, VALUE vv) { if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given"); if (rb_obj_is_kind_of(vv, cgsl_vector_complex)) { return rb_gsl_heapsort_vector_complex2(vv); } else if (rb_obj_is_kind_of(vv, cgsl_vector)) { return rb_gsl_heapsort_vector2(vv); } else { rb_raise(rb_eTypeError, "wrong argument type %s (Vector or Vector::Complex expected)", rb_class2name(CLASS_OF(vv))); } return vv; } static VALUE rb_gsl_heapsort_index(VALUE obj, VALUE vv) { if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given"); if (rb_obj_is_kind_of(vv, cgsl_vector_complex)) { return rb_gsl_heapsort_index_vector_complex(vv); } else if (rb_obj_is_kind_of(vv, cgsl_vector)) { return rb_gsl_heapsort_index_vector(vv); } else { rb_raise(rb_eTypeError, "wrong argument type %s (Vector or Vector::Complex expected)", rb_class2name(CLASS_OF(vv))); } return vv; } /*****/ #ifdef HAVE_NARRAY_H #include "narray.h" static VALUE rb_gsl_sort_narray(VALUE obj) { struct NARRAY *na; size_t size, stride; double *ptr1, *ptr2; VALUE ary; GetNArray(obj, na); ptr1 = (double*) na->ptr; size = na->total; stride = 1; ary = na_make_object(NA_DFLOAT, na->rank, na->shape, CLASS_OF(obj)); ptr2 = NA_PTR_TYPE(ary, double*); memcpy(ptr2, ptr1, sizeof(double)*size); gsl_sort(ptr2, stride, size); return ary; } static VALUE rb_gsl_sort_narray_bang(VALUE obj) { struct NARRAY *na; size_t size, stride; double *ptr1; GetNArray(obj, na); ptr1 = (double*) na->ptr; size = na->total; stride = 1; gsl_sort(ptr1, stride, size); return obj; } static VALUE rb_gsl_sort_index_narray(VALUE obj) { struct NARRAY *na; size_t size, stride; double *ptr1; gsl_permutation *p; GetNArray(obj, na); ptr1 = (double*) na->ptr; size = na->total; stride = 1; p = gsl_permutation_alloc(size); gsl_sort_index(p->data, ptr1, stride, size); return Data_Wrap_Struct(cgsl_permutation, 0, gsl_permutation_free, p); } #endif void Init_gsl_sort(VALUE module) { rb_define_singleton_method(module, "heapsort!", rb_gsl_heapsort, 1); rb_define_singleton_method(module, "heapsort", rb_gsl_heapsort2, 1); rb_define_singleton_method(module, "heapsort_index", rb_gsl_heapsort_index, 1); rb_define_method(cgsl_vector, "heapsort!", rb_gsl_heapsort_vector, 0); rb_define_method(cgsl_vector, "heapsort", rb_gsl_heapsort_vector2, 0); rb_define_method(cgsl_vector, "heapsort_index", rb_gsl_heapsort_index_vector, 0); rb_define_method(cgsl_vector_complex, "heapsort!", rb_gsl_heapsort_vector_complex, 0); rb_define_method(cgsl_vector_complex, "heapsort", rb_gsl_heapsort_vector_complex2, 0); rb_define_method(cgsl_vector_complex, "heapsort_index", rb_gsl_heapsort_index_vector_complex, 0); #ifdef HAVE_NARRAY_H rb_define_method(cNArray, "gsl_sort", rb_gsl_sort_narray, 0); rb_define_method(cNArray, "gsl_sort!", rb_gsl_sort_narray_bang, 0); rb_define_method(cNArray, "gsl_sort_index", rb_gsl_sort_index_narray, 0); #endif }
Java
/* * This file is part of Soprano Project. * * Copyright (C) 2007-2010 Sebastian Trueg <trueg@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "servercore.h" #include "servercore_p.h" #include "soprano-server-config.h" #include "serverconnection.h" #ifdef BUILD_DBUS_SUPPORT #include "dbus/dbuscontroller.h" #endif #include "modelpool.h" #include "localserver.h" #include "tcpserver.h" #include "backend.h" #include "storagemodel.h" #include "global.h" #include "asyncmodel.h" #include <QtCore/QHash> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtNetwork/QTcpServer> #include <QtNetwork/QHostAddress> #include <QtNetwork/QTcpSocket> #include <QtDBus/QtDBus> const quint16 Soprano::Server::ServerCore::DEFAULT_PORT = 5000; void Soprano::Server::ServerCorePrivate::addConnection( ServerConnection* conn ) { connections.append( conn ); QObject::connect( conn, SIGNAL(destroyed(QObject*)), q, SLOT(serverConnectionFinished(QObject*)) ); conn->start(); qDebug() << Q_FUNC_INFO << "New connection. New count:" << connections.count(); } Soprano::Server::ServerCore::ServerCore( QObject* parent ) : QObject( parent ), d( new ServerCorePrivate() ) { d->q = this; // default backend d->backend = Soprano::usedBackend(); d->modelPool = new ModelPool( this ); } Soprano::Server::ServerCore::~ServerCore() { #ifdef BUILD_DBUS_SUPPORT delete d->dbusController; #endif // We avoid using qDeleteAll because d->connections is modified by each delete operation foreach(const Soprano::Server::ServerConnection* con, d->connections) { delete con; } qDeleteAll( d->models ); delete d->modelPool; delete d; } void Soprano::Server::ServerCore::setBackend( const Backend* backend ) { d->backend = backend; } const Soprano::Backend* Soprano::Server::ServerCore::backend() const { return d->backend; } void Soprano::Server::ServerCore::setBackendSettings( const QList<BackendSetting>& settings ) { d->settings = settings; } QList<Soprano::BackendSetting> Soprano::Server::ServerCore::backendSettings() const { return d->settings; } void Soprano::Server::ServerCore::setMaximumConnectionCount( int max ) { d->maxConnectionCount = max; } int Soprano::Server::ServerCore::maximumConnectionCount() const { return d->maxConnectionCount; } Soprano::Model* Soprano::Server::ServerCore::model( const QString& name ) { QHash<QString, Model*>::const_iterator it = d->models.constFind( name ); if ( it == d->models.constEnd() ) { BackendSettings settings = d->createBackendSettings( name ); if ( isOptionInSettings( settings, BackendOptionStorageDir ) ) { QDir().mkpath( valueInSettings( settings, BackendOptionStorageDir ).toString() ); } Model* model = createModel( settings ); d->models.insert( name, model ); return model; } else { return *it; } } void Soprano::Server::ServerCore::removeModel( const QString& name ) { clearError(); QHash<QString, Model*>::iterator it = d->models.find( name ); if ( it == d->models.end() ) { setError( QString( "Could not find model with name %1" ).arg( name ) ); } else { Model* model = *it; d->models.erase( it ); // delete the model, removing any cached data delete model; if ( isOptionInSettings( d->settings, BackendOptionStorageDir ) ) { // remove the data on disk backend()->deleteModelData( d->createBackendSettings( name ) ); // remove the dir which should now be empty QDir( valueInSettings( d->settings, BackendOptionStorageDir ).toString() ).rmdir( name ); } } } bool Soprano::Server::ServerCore::listen( quint16 port ) { clearError(); if ( !d->tcpServer ) { d->tcpServer = new TcpServer( d, this ); } if ( !d->tcpServer->listen( QHostAddress::Any, port ) ) { setError( QString( "Failed to start listening at port %1 on localhost." ).arg( port ) ); qDebug() << "Failed to start listening at port " << port; return false; } else { qDebug() << "Listening on port " << port; return true; } } void Soprano::Server::ServerCore::stop() { qDebug() << "Stopping and deleting"; // We avoid using qDeleteAll because d->connections is modified by each delete operation foreach(const Soprano::Server::ServerConnection* con, d->connections) { delete con; } qDeleteAll( d->models ); delete d->tcpServer; d->tcpServer = 0; delete d->socketServer; d->socketServer = 0; #ifdef BUILD_DBUS_SUPPORT delete d->dbusController; d->dbusController = 0; #endif } quint16 Soprano::Server::ServerCore::serverPort() const { if ( d->tcpServer ) { return d->tcpServer->serverPort(); } else { return 0; } } bool Soprano::Server::ServerCore::start( const QString& name ) { clearError(); if ( !d->socketServer ) { d->socketServer = new LocalServer( d, this ); } QString path( name ); if ( path.isEmpty() ) { path = QDir::homePath() + QLatin1String( "/.soprano/socket" ); } if ( !d->socketServer->listen( path ) ) { setError( QString( "Failed to start listening at %1." ).arg( path ) ); return false; } else { return true; } } void Soprano::Server::ServerCore::registerAsDBusObject( const QString& objectPath ) { #ifdef BUILD_DBUS_SUPPORT if ( !d->dbusController ) { QString path( objectPath ); if ( path.isEmpty() ) { path = "/org/soprano/Server"; } d->dbusController = new Soprano::Server::DBusController( this, path ); } #else qFatal("Soprano has been built without D-Bus support!" ); #endif } void Soprano::Server::ServerCore::serverConnectionFinished(QObject* obj) { qDebug() << Q_FUNC_INFO << d->connections.count(); // We use static_cast cause qobject_case will fail since the object has been destroyed ServerConnection* conn = static_cast<ServerConnection*>( obj ); d->connections.removeAll( conn ); qDebug() << Q_FUNC_INFO << "Connection removed. Current count:" << d->connections.count(); } Soprano::Model* Soprano::Server::ServerCore::createModel( const QList<BackendSetting>& settings ) { Model* m = backend()->createModel( settings ); if ( m ) { clearError(); } else if ( backend()->lastError() ) { setError( backend()->lastError() ); } else { setError( "Could not create new Model for unknown reason" ); } return m; } QStringList Soprano::Server::ServerCore::allModels() const { return d->models.keys(); }
Java
package es.uniovi.asw.gui.util.form.validator.specific; import es.uniovi.asw.gui.util.form.validator.composite.CheckAllValidator; import es.uniovi.asw.gui.util.form.validator.simple.LengthValidator; import es.uniovi.asw.gui.util.form.validator.simple.NumberValidator; public class TelephoneValidator extends CheckAllValidator { public TelephoneValidator() { super(new NumberValidator(), new LengthValidator(9)); } @Override public String help() { return "S�lo n�meros, 9 caracteres."; } }
Java
Package.describe({ summary: "Next bike list package" }); Package.on_use(function (api) { api.use(['nb','underscore', 'templating', 'nb-autocomplete', 'nb-markers', 'nb-infowindow', 'nb-directions', 'nb-geocoder', 'nb-markerlabel', 'nb-citypicker'], ['client']); api.add_files(['list.html', 'list.js'], ['client']); });
Java
<?php /** * * @package phpBB Extension - Senky Post Links * @copyright (c) 2014 Jakub Senko * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2 * Swedish translation by/ * Svensk översättning av: Tage Strandell, Webmaster vulcanriders-sweden.org * */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } $lang = array_merge($lang, array( 'ACP_POST_LINKS' => 'Post links', 'PL_ENABLE' => 'Tillåt inläggslänkar', 'PL_ENABLE_EXPLAIN' => 'Om tillåtna, varje länk kommer att innehålla kopierbara av de typer som tillåts nedan.', 'PL_LINK_ENABLE' => 'Tillåt normallänk', 'PL_BBCODE_ENABLE' => 'Tillåt BB-kodlänk', 'PL_HTML_ENABLE' => 'Tillåt HTML-länk', ));
Java
/** * \ingroup devices * \defgroup TapBridgeModel Tap Bridge Model * * \section TapBridgeModelOverview TapBridge Model Overview * * The Tap Bridge is designed to integrate "real" internet hosts (or more * precisely, hosts that support Tun/Tap devices) into ns-3 simulations. The * goal is to make it appear to a "real" host node in that it has an ns-3 net * device as a local device. The concept of a "real host" is a bit slippery * since the "real host" may actually be virtualized using readily avialable * technologies such as VMware or OpenVZ. * * Since we are, in essence, connecting the inputs and outputs of an ns-3 net * device to the inputs and outputs of a Linux Tap net device, we call this * arrangement a Tap Bridge. * * There are two basic operating modes of this device available to users. * Basic functionality is essentially identical, but the two modes are * different in details regarding how the arrangement is configured. In the * first mode, the configuration is ns-3 configuration-centric. Configuration * information is taken from the ns-3 simulation and a tap device matching * the ns-3 attributes is created for you. In this mode, which we call * LocalDevice mode, an ns-3 net device is made to appear to be directly * connected to a real host. * * This is illustrated below * * \verbatim * +--------+ * | Linux | * | host | +----------+ * | ------ | | ghost | * | apps | | node | * | ------ | | -------- | * | stack | | IP | +----------+ * | ------ | | stack | | node | * | TAP | |==========| | -------- | * | device | <-- IPC Bridge --> | tap | | IP | * +--------+ | bridge | | stack | * | -------- | | -------- | * | ns-3 | | ns-3 | * | net | | net | * | device | | device | * +----------+ +----------+ * || || * +---------------------------+ * | ns-3 channel | * +---------------------------+ *\endverbatim * * In this case, the ns-3 net device in the ghost node appears as if it were * actually replacing the TAP device in the Linux host. The ns-3 process * creates the TAP device configures the IP address and MAC address of the * TAP device to match the values assigned to the ns-3 net device. The IPC * link is via the network tap mechanism in the underlying OS and acts as a * conventional bridge; but a bridge between devices that happen to have the * same shared MAC address. * * The LocalDevice mode is the default operating mode of the Tap Bridge. * * The second mode, BridgedDevice mode, is more oriented toward allowing existing * host configurations. This allows ns-3 net devices to appear as part of a host * operating system bridge (in Linux, we make the ns-3 device part of a "brctl" * bridge. This mode is especially useful in the case of virtualization where * the configuration of the virtual hosts may be dictated by another system and * not be changable to suit ns-3. For example, a particular VM scheme may create * virtual "vethx" or "vmnetx" devices that appear local to virtual hosts. In * order to connect to such systems, one would need to manually create TAP devices * on the host system and brigde these TAP devices to the existing (VM) virtual * devices. The job of the Tap Bridge in this case is to extend the bridge to * join the ns-3 net device. * * This is illustrated below: * * \verbatim * +---------+ * | Linux | * | VM | +----------+ * | ------- | | ghost | * | apps | | node | * | ------- | | -------- | * | stack | | IP | +----------+ * | ------- | +--------+ | stack | | node | * | Virtual | | TAP | |==========| | -------- | * | Device | | Device | <-- IPC Bridge-> | tap | | IP | * +---------+ +--------+ | bridge | | stack | * || || | -------- | | -------- | * +--------------------+ | ns-3 | | ns-3 | * | OS (brctl) Bridge | | net | | net | * +--------------------+ | device | | device | * +----------+ +----------+ * || || * +---------------------------+ * | ns-3 channel | * +---------------------------+ *\endverbatim * * In this case, a collection of virtual machines with associated Virtual * Devices is created in the virtualization environment (for exampe, OpenVZ * or VMware). A TAP device (with a specific name) is then manually created * for each Virtual Device that will be bridged into the ns-3 simulation. * These created TAP devices are then bridged together with the Virtual Devices * using a native OS bridge mechanism shown as "OS (brctl) Bridge" in the * illustration above. * * In the ns-3 simulation, a Tap Bridge is created to match each TAP Device. * The name of the TAP Device is assigned to the Tap Bridge using the * "DeviceName" attribute. The Tap Bridge then opens a network tap to the TAP * Device and logically extends the bridge to encompass the ns-3 net device. * This makes it appear as if an ns-3 simulated net device is a member of the * "OS (brctl) Bridge" and allows the Virtual Machines to communicate with the * ns-3 simulation.. * * \subsection TapBridgeLocalDeviceMode TapBridge LocalDevice Mode * * In LocalDevice mode, the TapBridge and therefore its associated ns-3 net * device appears to the Linux host computer as a network device just like any * arbitrary "eth0" or "ath0" might appear. The creation and configuration * of the TAP device is done by the ns-3 simulation and no manual configuration * is required by the user. The IP addresses, MAC addresses, gateways, etc., * for created TAP devices are extracted from the simulation itself by querying * the configuration of the ns-3 device and the TapBridge Attributes. * * The TapBridge appears to an ns-3 simulation as a channel-less net device. * This device must not have an IP address associated with it, but the bridged * (ns-3) net device must have an IP adress. Be aware that this is the inverse * of an ns-3 BridgeNetDevice (or a conventional bridge in general) which * demands that its bridge ports not have IP addresses, but allows the bridge * device itself to have an IP address. * * The host computer will appear in a simulation as a "ghost" node that contains * one TapBridge for each NetDevice that is being bridged. From the perspective * of a simulation, the only difference between a ghost node and any other node * will be the presence of the TapBridge devices. Note however, that the * presence of the TapBridge does affect the connectivity of the net device to * the IP stack of the ghost node. * * Configuration of address information and the ns-3 devices is not changed in * any way if a TapBridge is present. A TapBridge will pick up the addressing * information from the ns-3 net device to which it is connected (its "bridged" * net device) and use that information to create and configure the TAP device * on the real host. * * The end result of this is a situation where one can, for example, use the * standard ping utility on a real host to ping a simulated ns-3 node. If * correct routes are added to the internet host (this is expected to be done * automatically in future ns-3 releases), the routing systems in ns-3 will * enable correct routing of the packets across simulated ns-3 networks. * For an example of this, see the example program, tap-wifi-dumbbell.cc in * the ns-3 distribution. * * \subsection TapBridgeLocalDeviceModeOperation TapBridge LocalDevice Mode Operation * * The Tap Bridge lives in a kind of a gray world somewhere between a Linux host * and an ns-3 bridge device. From the Linux perspective, this code appears as * the user mode handler for a TAP net device. In LocalDevice mode, this TAP * device is automatically created by the ns-3 simulation. When the Linux host * writes to one of these automatically created /dev/tap devices, the write is * redirected into the TapBridge that lives in the ns-3 world; and from this * perspective, the packet write on Linux becomes a packet read in the Tap Bridge. * In other words, a Linux process writes a packet to a tap device and this packet * is redirected by the network tap mechanism toan ns-3 process where it is * received by the TapBridge as a result of a read operation there. The TapBridge * then writes the packet to the ns-3 net device to which it is bridged; and * therefore it appears as if the Linux host sent a packet directly through an * ns-3 net device onto an ns-3 network. * * In the other direction, a packet received by the ns-3 net device connected to * the Tap Bridge is sent via promiscuous callback to the TapBridge. The * TapBridge then takes that packet and writes it back to the host using the * network tap mechanism. This write to the device will appear to the Linux * host as if a packet has arrived on its device; and therefore as if a packet * received by the ns-3 net device has appeared on a Linux net device. * * The upshot is that the Tap Bridge appears to bridge a tap device on a * Linux host in the "real world" to an ns-3 net device in the simulation. * Because the TAP device and the bridged ns-3 net device have the same MAC * address and the network tap IPC link is not exernalized, this particular * kind of bridge makes ti appear that a ns-3 net device is actually installed * in the Linux host. * * In order to implement this on the ns-3 side, we need a "ghost node" in the * simulation to hold the bridged ns-3 net device and the TapBridge. This node * should not actually do anything else in the simulation since its job is * simply to make the net device appear in Linux. This is not just arbitrary * policy, it is because: * * - Bits sent to the Tap Bridge from higher layers in the ghost node (using * the TapBridge Send method) are completely ignored. The Tap Bridge is * not, itself, connected to any network, neither in Linux nor in ns-3. You * can never send nor receive data over a Tap Bridge from the ghost node. * * - The bridged ns-3 net device has its receive callback disconnected * from the ns-3 node and reconnected to the Tap Bridge. All data received * by a bridged device will then be sent to the Linux host and will not be * received by the node. From the perspective of the ghost node, you can * send over this device but you cannot ever receive. * * Of course, if you understand all of the issues you can take control of * your own destiny and do whatever you want -- we do not actively * prevent you from using the ghost node for anything you decide. You * will be able to perform typical ns-3 operations on the ghost node if * you so desire. The internet stack, for example, must be there and * functional on that node in order to participate in IP address * assignment and global routing. However, as mentioned above, * interfaces talking any Tap Bridge or associated bridged net devices * will not work completely. If you understand exactly what you are * doing, you can set up other interfaces and devices on the ghost node * and use them; or take advantage of the operational send side of the * bridged devices to create traffic generators. We generally recommend * that you treat this node as a ghost of the Linux host and leave it to * itself, though. * * \subsection TapBridgeBridgedDeviceMode TapBridge BridgedDevice Mode * * In BridgedDevice mode, the TapBridge and its associated ns-3 net device are * arranged in a fundamentally similar was as in LocalDevice mode. The TAP * device is bridged to the ns-3 net device in the same way. The description * of LocalDevice mode applies except as noted below. * * The most user-visible difference in modes is how the creation and * configuration of the underlying TAP device is done. In LocalDevice mode, * both creation and configuration of the underlying TAP device are handled * completely by ns-3. In BridgedDevice mode, creation and configuration is * delegated (due to requirements) to the user. No configuration is done in * ns-3 other than settting the operating mode of the TapBridge to * "BridgedDevice" and specifying the name of a pre-configured TAP device * using ns-3 Attributes of the TapBridge. * * The primary conceptual difference between modes is due to the fact that in * BridgedDevice mode the MAC addresses of the user-created TAPs will be pre- * configured and will therefore be different than those in the bridged device. * As in LocalDevice mode, the Tap Bridge functions as IPC bridge between the * TAP device and the ns-3 net device, but in BridgedDevice configurations the * two devices will have different MAC addresses and the bridging functionality * will be fundamentally the same as in any bridge. Since this implies MAC * address spoofing, the only ns-3 devices which may paritcipate in a bridge * in BridgedDevice mode must support SendFrom (i.e., a call to the method * SupportsSendFrom in the bridged net device must return true). * * \subsection TapBridgeBridgedDeviceModeOperation TapBridge BridgedDevice Mode Operation * * As described in the LocalDevice mode section, when the Linux host writes to * one of the /dev/tap devices, the write is redirected into the TapBridge * that lives in the ns-3 world. In the case of the BridgedDevice mode, these * packets will need to be sent out on the ns-3 network as if they were sent on * the Linux network. This means calling the SendFrom method on the bridged * device and providing the source and destination MAC addresses found in the * packet. * * In the other direction, a packet received by an ns-3 net device is hooked * via callback to the TapBridge. This must be done in promiscuous mode since * the goal is to bridge the ns-3 net device onto the OS (brctl) bridge of * which the TAP device is a part. * * There is no functional difference between modes at this level, even though * the configuration and conceptual models regarding what is going on are quite * different -- the Tap Bridge is just acting like a bridge. In the LocalDevice * mode, the bridge is between devices having the same MAC address and in the * BridgedDevice model the bridge is between devices having different MAC * addresses. * * \subsection TapBridgeSingleSourceModeOperation TapBridge SingleSource Mode Operation * * As described in above, the Tap Bridge acts like a bridge. Just like every * other bridge, there is a requirement that participating devices must have * the ability to receive promiscuously and to spoof the source MAC addresses * of packets. * * We do, however, have a specific requirement to be able to bridge Virtual * Machines onto wireless STA nodes. Unfortunately, the 802.11 spec doesn't * provide a good way to implement SendFrom. So we have to work around this. * * To this end, we provice the SingleSource mode of the Tap Bridge. This * mode allows you to create a bridge as described in BridgedDevice mode, but * only allows one source of packets on the Linux side of the bridge. The * address on the Linux side is remembered in the Tap Bridge, and all packets * coming from the Linux side are repeated out the ns-3 side using the ns-3 device * MAC source address. All packets coming in from the ns-3 side are repeated * out the Linux side using the remembered MAC address. This allows us to use * SendFrom on the ns-3 device side which is available on all ns-3 net devices. * * \section TapBridgeChannelModel Tap Bridge Channel Model * * There is no channel model associated with the Tap Bridge. In fact, the * intention is make it appear that the real internet host is connected to * the channel of the bridged net device. * * \section TapBridgeTracingModel Tap Bridge Tracing Model * * Unlike most ns-3 devices, the TapBridge does not provide any standard trace * sources. This is because the bridge is an intermediary that is essentially * one function call away from the bridged device. We expect that the trace * hooks in the bridged device will be sufficient for most users, * * \section TapBridgeUsage Using the Tap Bridge * * We expect that most users will interact with the TapBridge device through * the TapBridgeHelper. Users of other helper classes, such as CSMA or Wifi, * should be comfortable with the idioms used. */
Java
package com.greenpineyu.fel.function.operator; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.greenpineyu.fel.Expression; import com.greenpineyu.fel.common.ArrayUtils; import com.greenpineyu.fel.common.Null; import com.greenpineyu.fel.common.ReflectUtil; import com.greenpineyu.fel.compile.FelMethod; import com.greenpineyu.fel.compile.SourceBuilder; import com.greenpineyu.fel.context.FelContext; import com.greenpineyu.fel.function.CommonFunction; import com.greenpineyu.fel.function.Function; import com.greenpineyu.fel.parser.FelNode; import com.greenpineyu.fel.security.SecurityMgr; public class Dot implements Function { private static final Logger logger = LoggerFactory.getLogger(Dot.class); private SecurityMgr securityMgr; public SecurityMgr getSecurityMgr() { return securityMgr; } public void setSecurityMgr(SecurityMgr securityMgr) { this.securityMgr = securityMgr; } static final Map<Class<?>, Class<?>> PRIMITIVE_TYPES; static { PRIMITIVE_TYPES = new HashMap<Class<?>, Class<?>>(); PRIMITIVE_TYPES.put(Boolean.class, Boolean.TYPE); PRIMITIVE_TYPES.put(Byte.class, Byte.TYPE); PRIMITIVE_TYPES.put(Character.class, Character.TYPE); PRIMITIVE_TYPES.put(Double.class, Double.TYPE); PRIMITIVE_TYPES.put(Float.class, Float.TYPE); PRIMITIVE_TYPES.put(Integer.class, Integer.TYPE); PRIMITIVE_TYPES.put(Long.class, Long.TYPE); PRIMITIVE_TYPES.put(Short.class, Short.TYPE); } public static final String DOT = "."; @Override public String getName() { return DOT; } @Override public Object call(FelNode node, FelContext context) { List<FelNode> children = node.getChildren(); Object left = children.get(0); if (left instanceof Expression) { Expression exp = (Expression) left; left = exp.eval(context); } FelNode right = children.get(1); FelNode exp = right; Class<?>[] argsType = new Class<?>[0]; Object[] args = CommonFunction.evalArgs(right, context); if (!ArrayUtils.isEmpty(args)) { argsType = new Class[args.length]; for (int i = 0; i < args.length; i++) { if (args[i] == null) { argsType[i] = Null.class; continue; } argsType[i] = args[i].getClass(); } } Method method = null; Class<?> cls = left instanceof Class<?> ? (Class<?>) left : left.getClass(); String methodName = right.getText(); method = findMethod(cls, methodName, argsType); if (method == null) { String getMethod = "get"; method = findMethod(cls, getMethod, new Class<?>[] { String.class }); args = new Object[] { exp.getText() }; } if (method != null) return invoke(left, method, args); return null; } private Method findMethod(Class<?> cls, String methodName, Class<?>[] argsType) { Method method = ReflectUtil.findMethod(cls, methodName, argsType); return getCallableMethod(method); } private Method getMethod(Class<?> cls, String methodName, Class<?>[] argsType) { Method method = ReflectUtil.getMethod(cls, methodName, argsType); return getCallableMethod(method); } private Method getCallableMethod(Method m) { if (m == null || securityMgr.isCallable(m)) return m; throw new SecurityException("安全管理器[" + securityMgr.getClass().getSimpleName() + "]禁止调用方法[" + m.toString() + "]"); } /** * 调用方法 * * @param obj * @param method * @param args * @return */ public static Object invoke(Object obj, Method method, Object[] args) { try { return method.invoke(obj, args); } catch (IllegalArgumentException | IllegalAccessException e) { logger.error("", e); } catch (InvocationTargetException e) { logger.error("", e.getTargetException()); } return null; } @Override public FelMethod toMethod(FelNode node, FelContext context) { StringBuilder sb = new StringBuilder(); List<FelNode> children = node.getChildren(); FelNode l = children.get(0); SourceBuilder leftMethod = l.toMethod(context); Class<?> cls = leftMethod.returnType(context, l); String leftSrc = leftMethod.source(context, l); if (cls.isPrimitive()) { Class<?> wrapperClass = ReflectUtil.toWrapperClass(cls); // 如果左边返回的值的基本类型,要转成包装类型[eg:((Integer)1).doubleValue()] sb.append("((").append(wrapperClass.getSimpleName()).append(")").append(leftSrc).append(")"); } else { sb.append(leftSrc); } sb.append("."); Method method = null; FelNode rightNode = children.get(1); List<FelNode> params = rightNode.getChildren(); List<SourceBuilder> paramMethods = new ArrayList<SourceBuilder>(); Class<?>[] paramValueTypes = null; boolean hasParam = params != null && !params.isEmpty(); String rightMethod = rightNode.getText(); String rightMethodParam = ""; if (hasParam) { // 有参数 paramValueTypes = new Class<?>[params.size()]; for (int i = 0; i < params.size(); i++) { FelNode p = params.get(i); SourceBuilder paramMethod = p.toMethod(context); paramMethods.add(paramMethod); paramValueTypes[i] = paramMethod.returnType(context, p); } // 根据参数查找方法 method = findMethod(cls, rightNode.getText(), paramValueTypes); if (method != null) { Class<?>[] paramTypes = method.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; FelNode p = params.get(i); String paramCode = getParamCode(paramType, p, context); rightMethodParam += paramCode + ","; } rightMethod = method.getName(); } } else { method = findMethod(cls, rightNode.getText(), new Class<?>[0]); if (method == null) { // 当没有找到方法 ,直接使用get方法来获取属性 method = getMethod(cls, "get", new Class<?>[] { String.class }); if (method != null) { rightMethod = "get"; rightMethodParam = "\"" + rightNode.getText() + "\""; } } else { rightMethod = method.getName(); } } if (method != null) {} if (rightMethodParam.endsWith(",")) { rightMethodParam = rightMethodParam.substring(0, rightMethodParam.length() - 1); } rightMethod += "(" + rightMethodParam + ")"; sb.append(rightMethod); FelMethod returnMe = new FelMethod(method == null ? null : method.getReturnType(), sb.toString()); return returnMe; } /** * 获取参数代码 * * @param paramType * 方法声明的参数类型 * @param paramValueType * 参数值的类型 * @param paramMethod * @return */ public static String getParamCode(Class<?> paramType, FelNode node, FelContext ctx) { // 如果类型相等(包装类型与基本类型(int和Integer)也认为是相等 ),直接添加参数。 String paramCode = ""; SourceBuilder paramMethod = node.toMethod(ctx); Class<?> paramValueType = paramMethod.returnType(ctx, node); if (ReflectUtil.isTypeMatch(paramType, paramValueType)) { paramCode = paramMethod.source(ctx, node); } else { // 如果类型不匹配,使用强制转型 String className = null; Class<?> wrapperClass = ReflectUtil.toWrapperClass(paramType); if (wrapperClass != null) { className = wrapperClass.getName(); } else { className = paramType.getName(); } paramCode = "(" + className + ")" + paramMethod.source(ctx, node); } return paramCode; } }
Java
--リトマスの死儀式 function c8955148.initial_effect(c) aux.AddRitualProcGreaterCode(c,72566043) --to deck local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TODECK+CATEGORY_DRAW) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_GRAVE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCountLimit(1,8955148) e1:SetTarget(c8955148.tdtg) e1:SetOperation(c8955148.tdop) c:RegisterEffect(e1) end function c8955148.tdfilter(c) return c:IsCode(72566043) and c:IsAbleToDeck() end function c8955148.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c8955148.tdfilter(chkc) and chkc~=e:GetHandler() end if chk==0 then return e:GetHandler():IsAbleToDeck() and Duel.IsExistingTarget(c8955148.tdfilter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectTarget(tp,c8955148.tdfilter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,1,e:GetHandler()) g:AddCard(e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_TODECK,g,2,0,0) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c8955148.tdop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) then local g=Group.FromCards(c,tc) if Duel.SendtoDeck(g,nil,2,REASON_EFFECT)==0 then return end Duel.ShuffleDeck(tp) Duel.BreakEffect() Duel.Draw(tp,1,REASON_EFFECT) end end
Java
/* ***************************************************************************** * The method lives() is based on Xitari's code, from Google Inc. * * 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************** * A.L.E (Arcade Learning Environment) * Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and * the Reinforcement Learning and Artificial Intelligence Laboratory * Released under the GNU General Public License; see License.txt for details. * * Based on: Stella -- "An Atari 2600 VCS Emulator" * Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team * * ***************************************************************************** */ #include "games/supported/ChopperCommand.hpp" #include "games/RomUtils.hpp" namespace ale { using namespace stella; ChopperCommandSettings::ChopperCommandSettings() { reset(); } /* create a new instance of the rom */ RomSettings* ChopperCommandSettings::clone() const { return new ChopperCommandSettings(*this); } /* process the latest information from ALE */ void ChopperCommandSettings::step(const System& system) { // update the reward reward_t score = getDecimalScore(0xEE, 0xEC, &system); score *= 100; m_reward = score - m_score; m_score = score; // update terminal status m_lives = readRam(&system, 0xE4) & 0xF; m_terminal = (m_lives == 0); /* * Memory address 0xC2 indicates whether the Chopper is pointed * left or right on the screen. * - If the value is 0x00 we're looking left. * - If the value ix 0x01 we are looking right. * At the beginning of the game when we're selecting the game mode * we are always facing left, therefore, 0xC2 == 0x00. * When the game starts the chopper is initialized facing * right, i.e., 0xC2 == 0x01. We know if the game has started * if at any point 0xC2 == 0x01 so we can just OR the LSB of 0xC2 * to keep track of whether the game has started or not. * * */ m_is_started |= readRam(&system, 0xC2) & 0x1; } /* is end of game */ bool ChopperCommandSettings::isTerminal() const { return (m_is_started && m_terminal); }; /* get the most recently observed reward */ reward_t ChopperCommandSettings::getReward() const { return m_reward; } /* is an action part of the minimal set? */ bool ChopperCommandSettings::isMinimal(const Action& a) const { switch (a) { case PLAYER_A_NOOP: case PLAYER_A_FIRE: case PLAYER_A_UP: case PLAYER_A_RIGHT: case PLAYER_A_LEFT: case PLAYER_A_DOWN: case PLAYER_A_UPRIGHT: case PLAYER_A_UPLEFT: case PLAYER_A_DOWNRIGHT: case PLAYER_A_DOWNLEFT: case PLAYER_A_UPFIRE: case PLAYER_A_RIGHTFIRE: case PLAYER_A_LEFTFIRE: case PLAYER_A_DOWNFIRE: case PLAYER_A_UPRIGHTFIRE: case PLAYER_A_UPLEFTFIRE: case PLAYER_A_DOWNRIGHTFIRE: case PLAYER_A_DOWNLEFTFIRE: return true; default: return false; } } /* reset the state of the game */ void ChopperCommandSettings::reset() { m_reward = 0; m_score = 0; m_terminal = false; m_lives = 3; m_is_started = false; } /* saves the state of the rom settings */ void ChopperCommandSettings::saveState(Serializer& ser) { ser.putInt(m_reward); ser.putInt(m_score); ser.putBool(m_terminal); ser.putInt(m_lives); } // loads the state of the rom settings void ChopperCommandSettings::loadState(Deserializer& ser) { m_reward = ser.getInt(); m_score = ser.getInt(); m_terminal = ser.getBool(); m_lives = ser.getInt(); } // returns a list of mode that the game can be played in ModeVect ChopperCommandSettings::getAvailableModes() { return {0, 2}; } // set the mode of the game // the given mode must be one returned by the previous function void ChopperCommandSettings::setMode( game_mode_t m, System& system, std::unique_ptr<StellaEnvironmentWrapper> environment) { if (m == 0 || m == 2) { // read the mode we are currently in unsigned char mode = readRam(&system, 0xE0); // press select until the correct mode is reached while (mode != m) { environment->pressSelect(2); mode = readRam(&system, 0xE0); } //reset the environment to apply changes. environment->softReset(); } else { throw std::runtime_error("This mode doesn't currently exist for this game"); } } DifficultyVect ChopperCommandSettings::getAvailableDifficulties() { return {0, 1}; } } // namespace ale
Java