code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
/**
* \file
*
* \brief Metafunction \c zencxx::mpl::v_at
*
* \date Sat Jun 30 22:23:42 MSK 2012 -- Initial design
*/
/*
* Copyright (C) 2012-2014 Alex Turbov and contributors, all rights reserved.
* This is free software. It is licensed for use, modification and
* redistribution under the terms of the GNU Lesser General Public License,
* version 3 or later <http://gnu.org/licenses/lgpl.html>
*
* ZenCxx 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 3 of the License, or
* (at your option) any later version.
*
* ZenCxx is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.";
*/
#pragma once
// Project specific includes
#include <zencxx/mpl/details/v_at_impl.hh>
// Standard includes
#include <boost/mpl/long.hpp>
namespace zencxx { namespace mpl {
/**
* \brief Variadic version of \c at
*
* Metafunction to get an item at given index \c N from variadic sequence.
*
* \tparam N item index to get
* \tparam Seq variadic sequence of elements
*
*/
template <typename N, typename... Seq>
struct v_at : details::v_at_impl<N, boost::mpl::long_<0>, Seq...>
{};
/**
* \brief Variadic version of \c at_c
*
* Metafunction to get an item at given index \c N from variadic sequence.
*
* \tparam N item index to get
* \tparam Seq variadic sequence of elements
*
*/
template <long N, typename... Seq>
struct v_at_c : details::v_at_impl<boost::mpl::long_<N>, boost::mpl::long_<0>, Seq...>
{};
}} // namespace mpl, zencxx
| zaufi/zencxx | zencxx/mpl/v_at.hh | C++ | lgpl-3.0 | 1,976 |
#!/usr/bin/env python
'''
mavlink python utility functions
Copyright Andrew Tridgell 2011
Released under GNU GPL version 3 or later
'''
import socket, math, struct, time, os, fnmatch, array, sys, errno
import select
# adding these extra imports allows pymavlink to be used directly with pyinstaller
# without having complex spec files. To allow for installs that don't have ardupilotmega
# at all we avoid throwing an exception if it isn't installed
try:
import json
from pymavlink.dialects.v10 import ardupilotmega
except Exception:
pass
# maximum packet length for a single receive call - use the UDP limit
UDP_MAX_PACKET_LEN = 65535
'''
Support having a $HOME/.pymavlink/mavextra.py for extra graphing functions
'''
home = os.getenv('HOME')
if home is not None:
extra = os.path.join(home, '.pymavlink', 'mavextra.py')
if os.path.exists(extra):
import imp
mavuser = imp.load_source('pymavlink.mavuser', extra)
from pymavlink.mavuser import *
# Store the MAVLink library for the currently-selected dialect
# (set by set_dialect())
mavlink = None
# Store the mavlink file currently being operated on
# (set by mavlink_connection())
mavfile_global = None
# If the caller hasn't specified a particular native/legacy version, use this
default_native = False
# Use a globally-set MAVLink dialect if one has been specified as an environment variable.
if not 'MAVLINK_DIALECT' in os.environ:
os.environ['MAVLINK_DIALECT'] = 'ardupilotmega'
def mavlink10():
'''return True if using MAVLink 1.0'''
return not 'MAVLINK09' in os.environ
def evaluate_expression(expression, vars):
'''evaluation an expression'''
try:
v = eval(expression, globals(), vars)
except NameError:
return None
except ZeroDivisionError:
return None
return v
def evaluate_condition(condition, vars):
'''evaluation a conditional (boolean) statement'''
if condition is None:
return True
v = evaluate_expression(condition, vars)
if v is None:
return False
return v
class location(object):
'''represent a GPS coordinate'''
def __init__(self, lat, lng, alt=0, heading=0):
self.lat = lat
self.lng = lng
self.alt = alt
self.heading = heading
def __str__(self):
return "lat=%.6f,lon=%.6f,alt=%.1f" % (self.lat, self.lng, self.alt)
def set_dialect(dialect):
'''set the MAVLink dialect to work with.
For example, set_dialect("ardupilotmega")
'''
global mavlink, current_dialect
from .generator import mavparse
if mavlink is None or mavlink.WIRE_PROTOCOL_VERSION == "1.0" or not 'MAVLINK09' in os.environ:
wire_protocol = mavparse.PROTOCOL_1_0
modname = "pymavlink.dialects.v10." + dialect
else:
wire_protocol = mavparse.PROTOCOL_0_9
modname = "pymavlink.dialects.v09." + dialect
try:
mod = __import__(modname)
except Exception:
# auto-generate the dialect module
from .generator.mavgen import mavgen_python_dialect
mavgen_python_dialect(dialect, wire_protocol)
mod = __import__(modname)
components = modname.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
current_dialect = dialect
mavlink = mod
# Set the default dialect. This is done here as it needs to be after the function declaration
set_dialect(os.environ['MAVLINK_DIALECT'])
class mavfile(object):
'''a generic mavlink port'''
def __init__(self, fd, address, source_system=255, notimestamps=False, input=True, use_native=default_native):
global mavfile_global
if input:
mavfile_global = self
self.fd = fd
self.address = address
self.messages = { 'MAV' : self }
if mavlink.WIRE_PROTOCOL_VERSION == "1.0":
self.messages['HOME'] = mavlink.MAVLink_gps_raw_int_message(0,0,0,0,0,0,0,0,0,0)
mavlink.MAVLink_waypoint_message = mavlink.MAVLink_mission_item_message
else:
self.messages['HOME'] = mavlink.MAVLink_gps_raw_message(0,0,0,0,0,0,0,0,0)
self.params = {}
self.target_system = 0
self.target_component = 0
self.source_system = source_system
self.first_byte = True
self.robust_parsing = True
self.mav = mavlink.MAVLink(self, srcSystem=self.source_system, use_native=use_native)
self.mav.robust_parsing = self.robust_parsing
self.logfile = None
self.logfile_raw = None
self.param_fetch_in_progress = False
self.param_fetch_complete = False
self.start_time = time.time()
self.flightmode = "UNKNOWN"
self.vehicle_type = "UNKNOWN"
self.mav_type = mavlink.MAV_TYPE_FIXED_WING
self.base_mode = 0
self.timestamp = 0
self.message_hooks = []
self.idle_hooks = []
self.uptime = 0.0
self.notimestamps = notimestamps
self._timestamp = None
self.ground_pressure = None
self.ground_temperature = None
self.altitude = 0
self.WIRE_PROTOCOL_VERSION = mavlink.WIRE_PROTOCOL_VERSION
self.last_seq = {}
self.mav_loss = 0
self.mav_count = 0
self.stop_on_EOF = False
self.portdead = False
def auto_mavlink_version(self, buf):
'''auto-switch mavlink protocol version'''
global mavlink
if len(buf) == 0:
return
try:
magic = ord(buf[0])
except:
magic = buf[0]
if not magic in [ 85, 254 ]:
return
self.first_byte = False
if self.WIRE_PROTOCOL_VERSION == "0.9" and magic == 254:
self.WIRE_PROTOCOL_VERSION = "1.0"
set_dialect(current_dialect)
elif self.WIRE_PROTOCOL_VERSION == "1.0" and magic == 85:
self.WIRE_PROTOCOL_VERSION = "0.9"
set_dialect(current_dialect)
os.environ['MAVLINK09'] = '1'
else:
return
# switch protocol
(callback, callback_args, callback_kwargs) = (self.mav.callback,
self.mav.callback_args,
self.mav.callback_kwargs)
self.mav = mavlink.MAVLink(self, srcSystem=self.source_system)
self.mav.robust_parsing = self.robust_parsing
self.WIRE_PROTOCOL_VERSION = mavlink.WIRE_PROTOCOL_VERSION
(self.mav.callback, self.mav.callback_args, self.mav.callback_kwargs) = (callback,
callback_args,
callback_kwargs)
def recv(self, n=None):
'''default recv method'''
raise RuntimeError('no recv() method supplied')
def close(self, n=None):
'''default close method'''
raise RuntimeError('no close() method supplied')
def write(self, buf):
'''default write method'''
raise RuntimeError('no write() method supplied')
def select(self, timeout):
'''wait for up to timeout seconds for more data'''
if self.fd is None:
time.sleep(min(timeout,0.5))
return True
try:
(rin, win, xin) = select.select([self.fd], [], [], timeout)
except select.error:
return False
return len(rin) == 1
def pre_message(self):
'''default pre message call'''
return
def set_rtscts(self, enable):
'''enable/disable RTS/CTS if applicable'''
return
def post_message(self, msg):
'''default post message call'''
if '_posted' in msg.__dict__:
return
msg._posted = True
msg._timestamp = time.time()
type = msg.get_type()
if type != 'HEARTBEAT' or (msg.type != mavlink.MAV_TYPE_GCS and msg.type != mavlink.MAV_TYPE_GIMBAL):
self.messages[type] = msg
if 'usec' in msg.__dict__:
self.uptime = msg.usec * 1.0e-6
if 'time_boot_ms' in msg.__dict__:
self.uptime = msg.time_boot_ms * 1.0e-3
if self._timestamp is not None:
if self.notimestamps:
msg._timestamp = self.uptime
else:
msg._timestamp = self._timestamp
src_system = msg.get_srcSystem()
src_component = msg.get_srcComponent()
src_tuple = (src_system, src_component)
radio_tuple = (ord('3'), ord('D'))
if not (src_tuple == radio_tuple or msg.get_type() == 'BAD_DATA'):
if not src_tuple in self.last_seq:
last_seq = -1
else:
last_seq = self.last_seq[src_tuple]
seq = (last_seq+1) % 256
seq2 = msg.get_seq()
if seq != seq2 and last_seq != -1:
diff = (seq2 - seq) % 256
self.mav_loss += diff
#print("lost %u seq=%u seq2=%u last_seq=%u src_system=%u %s" % (diff, seq, seq2, last_seq, src_system, msg.get_type()))
self.last_seq[src_tuple] = seq2
self.mav_count += 1
self.timestamp = msg._timestamp
if type == 'HEARTBEAT' and msg.get_srcComponent() != mavlink.MAV_COMP_ID_GIMBAL:
self.target_system = msg.get_srcSystem()
self.target_component = msg.get_srcComponent()
if mavlink.WIRE_PROTOCOL_VERSION == '1.0' and msg.type != mavlink.MAV_TYPE_GCS:
self.flightmode = mode_string_v10(msg)
self.mav_type = msg.type
self.base_mode = msg.base_mode
elif type == 'PARAM_VALUE':
s = str(msg.param_id)
self.params[str(msg.param_id)] = msg.param_value
if msg.param_index+1 == msg.param_count:
self.param_fetch_in_progress = False
self.param_fetch_complete = True
elif type == 'SYS_STATUS' and mavlink.WIRE_PROTOCOL_VERSION == '0.9':
self.flightmode = mode_string_v09(msg)
elif type == 'GPS_RAW':
if self.messages['HOME'].fix_type < 2:
self.messages['HOME'] = msg
elif type == 'GPS_RAW_INT':
if self.messages['HOME'].fix_type < 3:
self.messages['HOME'] = msg
for hook in self.message_hooks:
hook(self, msg)
def packet_loss(self):
'''packet loss as a percentage'''
if self.mav_count == 0:
return 0
return (100.0*self.mav_loss)/(self.mav_count+self.mav_loss)
def recv_msg(self):
'''message receive routine'''
self.pre_message()
while True:
n = self.mav.bytes_needed()
s = self.recv(n)
numnew = len(s)
if numnew != 0:
if self.logfile_raw:
self.logfile_raw.write(str(s))
if self.first_byte:
self.auto_mavlink_version(s)
# We always call parse_char even if the new string is empty, because the existing message buf might already have some valid packet
# we can extract
msg = self.mav.parse_char(s)
if msg:
if self.logfile and msg.get_type() != 'BAD_DATA' :
usec = int(time.time() * 1.0e6) & ~3
self.logfile.write(str(struct.pack('>Q', usec) + msg.get_msgbuf()))
self.post_message(msg)
return msg
else:
# if we failed to parse any messages _and_ no new bytes arrived, return immediately so the client has the option to
# timeout
if numnew == 0:
return None
def recv_match(self, condition=None, type=None, blocking=False, timeout=None):
'''recv the next MAVLink message that matches the given condition
type can be a string or a list of strings'''
if type is not None and not isinstance(type, list):
type = [type]
start_time = time.time()
while True:
if timeout is not None:
now = time.time()
if now < start_time:
start_time = now # If an external process rolls back system time, we should not spin forever.
if start_time + timeout < time.time():
return None
m = self.recv_msg()
if m is None:
if blocking:
for hook in self.idle_hooks:
hook(self)
if timeout is None:
self.select(0.05)
else:
self.select(timeout/2)
continue
return None
if type is not None and not m.get_type() in type:
continue
if not evaluate_condition(condition, self.messages):
continue
return m
def check_condition(self, condition):
'''check if a condition is true'''
return evaluate_condition(condition, self.messages)
def mavlink10(self):
'''return True if using MAVLink 1.0'''
return self.WIRE_PROTOCOL_VERSION == "1.0"
def setup_logfile(self, logfile, mode='w'):
'''start logging to the given logfile, with timestamps'''
self.logfile = open(logfile, mode=mode)
def setup_logfile_raw(self, logfile, mode='w'):
'''start logging raw bytes to the given logfile, without timestamps'''
self.logfile_raw = open(logfile, mode=mode)
def wait_heartbeat(self, blocking=True):
'''wait for a heartbeat so we know the target system IDs'''
return self.recv_match(type='HEARTBEAT', blocking=blocking)
def param_fetch_all(self):
'''initiate fetch of all parameters'''
if time.time() - getattr(self, 'param_fetch_start', 0) < 2.0:
# don't fetch too often
return
self.param_fetch_start = time.time()
self.param_fetch_in_progress = True
self.mav.param_request_list_send(self.target_system, self.target_component)
def param_fetch_one(self, name):
'''initiate fetch of one parameter'''
try:
idx = int(name)
self.mav.param_request_read_send(self.target_system, self.target_component, "", idx)
except Exception:
self.mav.param_request_read_send(self.target_system, self.target_component, name, -1)
def time_since(self, mtype):
'''return the time since the last message of type mtype was received'''
if not mtype in self.messages:
return time.time() - self.start_time
return time.time() - self.messages[mtype]._timestamp
def param_set_send(self, parm_name, parm_value, parm_type=None):
'''wrapper for parameter set'''
if self.mavlink10():
if parm_type == None:
parm_type = mavlink.MAVLINK_TYPE_FLOAT
self.mav.param_set_send(self.target_system, self.target_component,
parm_name, parm_value, parm_type)
else:
self.mav.param_set_send(self.target_system, self.target_component,
parm_name, parm_value)
def waypoint_request_list_send(self):
'''wrapper for waypoint_request_list_send'''
if self.mavlink10():
self.mav.mission_request_list_send(self.target_system, self.target_component)
else:
self.mav.waypoint_request_list_send(self.target_system, self.target_component)
def waypoint_clear_all_send(self):
'''wrapper for waypoint_clear_all_send'''
if self.mavlink10():
self.mav.mission_clear_all_send(self.target_system, self.target_component)
else:
self.mav.waypoint_clear_all_send(self.target_system, self.target_component)
def waypoint_request_send(self, seq):
'''wrapper for waypoint_request_send'''
if self.mavlink10():
self.mav.mission_request_send(self.target_system, self.target_component, seq)
else:
self.mav.waypoint_request_send(self.target_system, self.target_component, seq)
def waypoint_set_current_send(self, seq):
'''wrapper for waypoint_set_current_send'''
if self.mavlink10():
self.mav.mission_set_current_send(self.target_system, self.target_component, seq)
else:
self.mav.waypoint_set_current_send(self.target_system, self.target_component, seq)
def waypoint_current(self):
'''return current waypoint'''
if self.mavlink10():
m = self.recv_match(type='MISSION_CURRENT', blocking=True)
else:
m = self.recv_match(type='WAYPOINT_CURRENT', blocking=True)
return m.seq
def waypoint_count_send(self, seq):
'''wrapper for waypoint_count_send'''
if self.mavlink10():
self.mav.mission_count_send(self.target_system, self.target_component, seq)
else:
self.mav.waypoint_count_send(self.target_system, self.target_component, seq)
def set_mode_flag(self, flag, enable):
'''
Enables/ disables MAV_MODE_FLAG
@param flag The mode flag,
see MAV_MODE_FLAG enum
@param enable Enable the flag, (True/False)
'''
if self.mavlink10():
mode = self.base_mode
if (enable == True):
mode = mode | flag
elif (enable == False):
mode = mode & ~flag
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_DO_SET_MODE, 0,
mode,
0, 0, 0, 0, 0, 0)
else:
print("Set mode flag not supported")
def set_mode_auto(self):
'''enter auto mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_MISSION_START, 0, 0, 0, 0, 0, 0, 0, 0)
else:
MAV_ACTION_SET_AUTO = 13
self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_SET_AUTO)
def mode_mapping(self):
'''return dictionary mapping mode names to numbers, or None if unknown'''
mav_type = self.field('HEARTBEAT', 'type', self.mav_type)
if mav_type is None:
return None
map = None
if mav_type in [mavlink.MAV_TYPE_QUADROTOR,
mavlink.MAV_TYPE_HELICOPTER,
mavlink.MAV_TYPE_HEXAROTOR,
mavlink.MAV_TYPE_OCTOROTOR,
mavlink.MAV_TYPE_TRICOPTER]:
map = mode_mapping_acm
if mav_type == mavlink.MAV_TYPE_FIXED_WING:
map = mode_mapping_apm
if mav_type == mavlink.MAV_TYPE_GROUND_ROVER:
map = mode_mapping_rover
if mav_type == mavlink.MAV_TYPE_ANTENNA_TRACKER:
map = mode_mapping_tracker
if map is None:
return None
inv_map = dict((a, b) for (b, a) in list(map.items()))
return inv_map
def set_mode(self, mode):
'''enter arbitrary mode'''
if isinstance(mode, str):
map = self.mode_mapping()
if map is None or mode not in map:
print("Unknown mode '%s'" % mode)
return
mode = map[mode]
self.mav.set_mode_send(self.target_system,
mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED,
mode)
def set_mode_rtl(self):
'''enter RTL mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH, 0, 0, 0, 0, 0, 0, 0, 0)
else:
MAV_ACTION_RETURN = 3
self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_RETURN)
def set_mode_manual(self):
'''enter MANUAL mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_DO_SET_MODE, 0,
mavlink.MAV_MODE_MANUAL_ARMED,
0, 0, 0, 0, 0, 0)
else:
MAV_ACTION_SET_MANUAL = 12
self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_SET_MANUAL)
def set_mode_fbwa(self):
'''enter FBWA mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_DO_SET_MODE, 0,
mavlink.MAV_MODE_STABILIZE_ARMED,
0, 0, 0, 0, 0, 0)
else:
print("Forcing FBWA not supported")
def set_mode_loiter(self):
'''enter LOITER mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_NAV_LOITER_UNLIM, 0, 0, 0, 0, 0, 0, 0, 0)
else:
MAV_ACTION_LOITER = 27
self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_LOITER)
def set_servo(self, channel, pwm):
'''set a servo value'''
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_DO_SET_SERVO, 0,
channel, pwm,
0, 0, 0, 0, 0)
def set_relay(self, relay_pin=0, state=True):
'''Set relay_pin to value of state'''
if self.mavlink10():
self.mav.command_long_send(
self.target_system, # target_system
self.target_component, # target_component
mavlink.MAV_CMD_DO_SET_RELAY, # command
0, # Confirmation
relay_pin, # Relay Number
int(state), # state (1 to indicate arm)
0, # param3 (all other params meaningless)
0, # param4
0, # param5
0, # param6
0) # param7
else:
print("Setting relays not supported.")
def calibrate_level(self):
'''calibrate accels (1D version)'''
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
1, 1, 0, 0, 0, 0, 0)
def calibrate_pressure(self):
'''calibrate pressure'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
0, 0, 1, 0, 0, 0, 0)
else:
MAV_ACTION_CALIBRATE_PRESSURE = 20
self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_CALIBRATE_PRESSURE)
def reboot_autopilot(self, hold_in_bootloader=False):
'''reboot the autopilot'''
if self.mavlink10():
if hold_in_bootloader:
param1 = 3
else:
param1 = 1
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0,
param1, 0, 0, 0, 0, 0, 0)
# send an old style reboot immediately afterwards in case it is an older firmware
# that doesn't understand the new convention
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0,
1, 0, 0, 0, 0, 0, 0)
def wait_gps_fix(self):
self.recv_match(type='VFR_HUD', blocking=True)
if self.mavlink10():
self.recv_match(type='GPS_RAW_INT', blocking=True,
condition='GPS_RAW_INT.fix_type==3 and GPS_RAW_INT.lat != 0 and GPS_RAW_INT.alt != 0')
else:
self.recv_match(type='GPS_RAW', blocking=True,
condition='GPS_RAW.fix_type==2 and GPS_RAW.lat != 0 and GPS_RAW.alt != 0')
def location(self, relative_alt=False):
'''return current location'''
self.wait_gps_fix()
# wait for another VFR_HUD, to ensure we have correct altitude
self.recv_match(type='VFR_HUD', blocking=True)
self.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
if relative_alt:
alt = self.messages['GLOBAL_POSITION_INT'].relative_alt*0.001
else:
alt = self.messages['VFR_HUD'].alt
return location(self.messages['GPS_RAW_INT'].lat*1.0e-7,
self.messages['GPS_RAW_INT'].lon*1.0e-7,
alt,
self.messages['VFR_HUD'].heading)
def arducopter_arm(self):
'''arm motors (arducopter only)'''
if self.mavlink10():
self.mav.command_long_send(
self.target_system, # target_system
self.target_component,
mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command
0, # confirmation
1, # param1 (1 to indicate arm)
0, # param2 (all other params meaningless)
0, # param3
0, # param4
0, # param5
0, # param6
0) # param7
def arducopter_disarm(self):
'''calibrate pressure'''
if self.mavlink10():
self.mav.command_long_send(
self.target_system, # target_system
self.target_component,
mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command
0, # confirmation
0, # param1 (0 to indicate disarm)
0, # param2 (all other params meaningless)
0, # param3
0, # param4
0, # param5
0, # param6
0) # param7
def motors_armed(self):
'''return true if motors armed'''
if not 'HEARTBEAT' in self.messages:
return False
m = self.messages['HEARTBEAT']
return (m.base_mode & mavlink.MAV_MODE_FLAG_SAFETY_ARMED) != 0
def motors_armed_wait(self):
'''wait for motors to be armed'''
while True:
m = self.wait_heartbeat()
if self.motors_armed():
return
def motors_disarmed_wait(self):
'''wait for motors to be disarmed'''
while True:
m = self.wait_heartbeat()
if not self.motors_armed():
return
def field(self, type, field, default=None):
'''convenient function for returning an arbitrary MAVLink
field with a default'''
if not type in self.messages:
return default
return getattr(self.messages[type], field, default)
def param(self, name, default=None):
'''convenient function for returning an arbitrary MAVLink
parameter with a default'''
if not name in self.params:
return default
return self.params[name]
def set_close_on_exec(fd):
'''set the clone on exec flag on a file descriptor. Ignore exceptions'''
try:
import fcntl
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(fd, fcntl.F_SETFD, flags)
except Exception:
pass
class mavserial(mavfile):
'''a serial mavlink port'''
def __init__(self, device, baud=115200, autoreconnect=False, source_system=255, use_native=default_native):
import serial
if ',' in device and not os.path.exists(device):
device, baud = device.split(',')
self.baud = baud
self.device = device
self.autoreconnect = autoreconnect
# we rather strangely set the baudrate initially to 1200, then change to the desired
# baudrate. This works around a kernel bug on some Linux kernels where the baudrate
# is not set correctly
self.port = serial.Serial(self.device, 1200, timeout=0,
dsrdtr=False, rtscts=False, xonxoff=False)
try:
fd = self.port.fileno()
set_close_on_exec(fd)
except Exception:
fd = None
self.set_baudrate(self.baud)
mavfile.__init__(self, fd, device, source_system=source_system, use_native=use_native)
self.rtscts = False
def set_rtscts(self, enable):
'''enable/disable RTS/CTS if applicable'''
self.port.setRtsCts(enable)
self.rtscts = enable
def set_baudrate(self, baudrate):
'''set baudrate'''
self.port.setBaudrate(baudrate)
def close(self):
self.port.close()
def recv(self,n=None):
if n is None:
n = self.mav.bytes_needed()
if self.fd is None:
waiting = self.port.inWaiting()
if waiting < n:
n = waiting
ret = self.port.read(n)
return ret
def write(self, buf):
try:
if not isinstance(buf, str):
buf = str(buf)
return self.port.write(buf)
except Exception:
if not self.portdead:
print("Device %s is dead" % self.device)
self.portdead = True
if self.autoreconnect:
self.reset()
return -1
def reset(self):
import serial
try:
newport = serial.Serial(self.device, self.baud, timeout=0,
dsrdtr=False, rtscts=False, xonxoff=False)
self.port.close()
self.port = newport
print("Device %s reopened OK" % self.device)
self.portdead = False
try:
self.fd = self.port.fileno()
except Exception:
self.fd = None
if self.rtscts:
self.set_rtscts(self.rtscts)
return True
except Exception:
return False
class mavudp(mavfile):
'''a UDP mavlink socket'''
def __init__(self, device, input=True, broadcast=False, source_system=255, use_native=default_native):
a = device.split(':')
if len(a) != 2:
print("UDP ports must be specified as host:port")
sys.exit(1)
self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udp_server = input
if input:
self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.port.bind((a[0], int(a[1])))
else:
self.destination_addr = (a[0], int(a[1]))
if broadcast:
self.port.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
set_close_on_exec(self.port.fileno())
self.port.setblocking(0)
self.last_address = None
mavfile.__init__(self, self.port.fileno(), device, source_system=source_system, input=input, use_native=use_native)
def close(self):
self.port.close()
def recv(self,n=None):
try:
data, self.last_address = self.port.recvfrom(UDP_MAX_PACKET_LEN)
except socket.error as e:
if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK, errno.ECONNREFUSED ]:
return ""
raise
return data
def write(self, buf):
try:
if self.udp_server:
if self.last_address:
self.port.sendto(buf, self.last_address)
else:
self.port.sendto(buf, self.destination_addr)
except socket.error:
pass
def recv_msg(self):
'''message receive routine for UDP link'''
self.pre_message()
s = self.recv()
if len(s) == 0:
return None
if self.first_byte:
self.auto_mavlink_version(s)
msg = self.mav.parse_buffer(s)
if msg is not None:
for m in msg:
self.post_message(m)
return msg[0]
return None
class mavtcp(mavfile):
'''a TCP mavlink socket'''
def __init__(self, device, source_system=255, retries=3, use_native=default_native):
a = device.split(':')
if len(a) != 2:
print("TCP ports must be specified as host:port")
sys.exit(1)
self.port = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.destination_addr = (a[0], int(a[1]))
while retries >= 0:
retries -= 1
if retries <= 0:
self.port.connect(self.destination_addr)
else:
try:
self.port.connect(self.destination_addr)
break
except Exception as e:
if retries > 0:
print(e, "sleeping")
time.sleep(1)
continue
self.port.setblocking(0)
set_close_on_exec(self.port.fileno())
self.port.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
mavfile.__init__(self, self.port.fileno(), "tcp:" + device, source_system=source_system, use_native=use_native)
def close(self):
self.port.close()
def recv(self,n=None):
if n is None:
n = self.mav.bytes_needed()
try:
data = self.port.recv(n)
except socket.error as e:
if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
return ""
raise
return data
def write(self, buf):
try:
self.port.send(buf)
except socket.error:
pass
class mavlogfile(mavfile):
'''a MAVLink logfile reader/writer'''
def __init__(self, filename, planner_format=None,
write=False, append=False,
robust_parsing=True, notimestamps=False, source_system=255, use_native=default_native):
self.filename = filename
self.writeable = write
self.robust_parsing = robust_parsing
self.planner_format = planner_format
self._two64 = math.pow(2.0, 63)
mode = 'rb'
if self.writeable:
if append:
mode = 'ab'
else:
mode = 'wb'
self.f = open(filename, mode)
self.filesize = os.path.getsize(filename)
self.percent = 0
mavfile.__init__(self, None, filename, source_system=source_system, notimestamps=notimestamps, use_native=use_native)
if self.notimestamps:
self._timestamp = 0
else:
self._timestamp = time.time()
self.stop_on_EOF = True
self._last_message = None
self._last_timestamp = None
def close(self):
self.f.close()
def recv(self,n=None):
if n is None:
n = self.mav.bytes_needed()
return self.f.read(n)
def write(self, buf):
self.f.write(buf)
def scan_timestamp(self, tbuf):
'''scan forward looking in a tlog for a timestamp in a reasonable range'''
while True:
(tusec,) = struct.unpack('>Q', tbuf)
t = tusec * 1.0e-6
if abs(t - self._last_timestamp) <= 3*24*60*60:
break
c = self.f.read(1)
if len(c) != 1:
break
tbuf = tbuf[1:] + c
return t
def pre_message(self):
'''read timestamp if needed'''
# read the timestamp
if self.filesize != 0:
self.percent = (100.0 * self.f.tell()) / self.filesize
if self.notimestamps:
return
if self.planner_format:
tbuf = self.f.read(21)
if len(tbuf) != 21 or tbuf[0] != '-' or tbuf[20] != ':':
raise RuntimeError('bad planner timestamp %s' % tbuf)
hnsec = self._two64 + float(tbuf[0:20])
t = hnsec * 1.0e-7 # convert to seconds
t -= 719163 * 24 * 60 * 60 # convert to 1970 base
self._link = 0
else:
tbuf = self.f.read(8)
if len(tbuf) != 8:
return
(tusec,) = struct.unpack('>Q', tbuf)
t = tusec * 1.0e-6
if (self._last_timestamp is not None and
self._last_message.get_type() == "BAD_DATA" and
abs(t - self._last_timestamp) > 3*24*60*60):
t = self.scan_timestamp(tbuf)
self._link = tusec & 0x3
self._timestamp = t
def post_message(self, msg):
'''add timestamp to message'''
# read the timestamp
super(mavlogfile, self).post_message(msg)
if self.planner_format:
self.f.read(1) # trailing newline
self.timestamp = msg._timestamp
self._last_message = msg
if msg.get_type() != "BAD_DATA":
self._last_timestamp = msg._timestamp
class mavmemlog(mavfile):
'''a MAVLink log in memory. This allows loading a log into
memory to make it easier to do multiple sweeps over a log'''
def __init__(self, mav):
mavfile.__init__(self, None, 'memlog')
self._msgs = []
self._index = 0
self._count = 0
self.messages = {}
while True:
m = mav.recv_msg()
if m is None:
break
self._msgs.append(m)
self._count = len(self._msgs)
def recv_msg(self):
'''message receive routine'''
if self._index >= self._count:
return None
m = self._msgs[self._index]
self._index += 1
self.percent = (100.0 * self._index) / self._count
self.messages[m.get_type()] = m
return m
def rewind(self):
'''rewind to start'''
self._index = 0
self.percent = 0
self.messages = {}
class mavchildexec(mavfile):
'''a MAVLink child processes reader/writer'''
def __init__(self, filename, source_system=255, use_native=default_native):
from subprocess import Popen, PIPE
import fcntl
self.filename = filename
self.child = Popen(filename, shell=False, stdout=PIPE, stdin=PIPE, bufsize=0)
self.fd = self.child.stdout.fileno()
fl = fcntl.fcntl(self.fd, fcntl.F_GETFL)
fcntl.fcntl(self.fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
fl = fcntl.fcntl(self.child.stdout.fileno(), fcntl.F_GETFL)
fcntl.fcntl(self.child.stdout.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
mavfile.__init__(self, self.fd, filename, source_system=source_system, use_native=use_native)
def close(self):
self.child.close()
def recv(self,n=None):
try:
x = self.child.stdout.read(1)
except Exception:
return ''
return x
def write(self, buf):
self.child.stdin.write(buf)
def mavlink_connection(device, baud=115200, source_system=255,
planner_format=None, write=False, append=False,
robust_parsing=True, notimestamps=False, input=True,
dialect=None, autoreconnect=False, zero_time_base=False,
retries=3, use_native=default_native):
'''open a serial, UDP, TCP or file mavlink connection'''
global mavfile_global
if dialect is not None:
set_dialect(dialect)
if device.startswith('tcp:'):
return mavtcp(device[4:], source_system=source_system, retries=retries, use_native=use_native)
if device.startswith('udpin:'):
return mavudp(device[6:], input=True, source_system=source_system, use_native=use_native)
if device.startswith('udpout:'):
return mavudp(device[7:], input=False, source_system=source_system, use_native=use_native)
# For legacy purposes we accept the following syntax and let the caller to specify direction
if device.startswith('udp:'):
return mavudp(device[4:], input=input, source_system=source_system, use_native=use_native)
if device.lower().endswith('.bin') or device.lower().endswith('.px4log'):
# support dataflash logs
from pymavlink import DFReader
m = DFReader.DFReader_binary(device, zero_time_base=zero_time_base)
mavfile_global = m
return m
if device.endswith('.log'):
# support dataflash text logs
from pymavlink import DFReader
if DFReader.DFReader_is_text_log(device):
m = DFReader.DFReader_text(device, zero_time_base=zero_time_base)
mavfile_global = m
return m
# list of suffixes to prevent setting DOS paths as UDP sockets
logsuffixes = ['mavlink', 'log', 'raw', 'tlog' ]
suffix = device.split('.')[-1].lower()
if device.find(':') != -1 and not suffix in logsuffixes:
return mavudp(device, source_system=source_system, input=input, use_native=use_native)
if os.path.isfile(device):
if device.endswith(".elf") or device.find("/bin/") != -1:
print("executing '%s'" % device)
return mavchildexec(device, source_system=source_system, use_native=use_native)
else:
return mavlogfile(device, planner_format=planner_format, write=write,
append=append, robust_parsing=robust_parsing, notimestamps=notimestamps,
source_system=source_system, use_native=use_native)
return mavserial(device, baud=baud, source_system=source_system, autoreconnect=autoreconnect, use_native=use_native)
class periodic_event(object):
'''a class for fixed frequency events'''
def __init__(self, frequency):
self.frequency = float(frequency)
self.last_time = time.time()
def force(self):
'''force immediate triggering'''
self.last_time = 0
def trigger(self):
'''return True if we should trigger now'''
tnow = time.time()
if tnow < self.last_time:
print("Warning, time moved backwards. Restarting timer.")
self.last_time = tnow
if self.last_time + (1.0/self.frequency) <= tnow:
self.last_time = tnow
return True
return False
try:
from curses import ascii
have_ascii = True
except:
have_ascii = False
def is_printable(c):
'''see if a character is printable'''
global have_ascii
if have_ascii:
return ascii.isprint(c)
if isinstance(c, int):
ic = c
else:
ic = ord(c)
return ic >= 32 and ic <= 126
def all_printable(buf):
'''see if a string is all printable'''
for c in buf:
if not is_printable(c) and not c in ['\r', '\n', '\t']:
return False
return True
class SerialPort(object):
'''auto-detected serial port'''
def __init__(self, device, description=None, hwid=None):
self.device = device
self.description = description
self.hwid = hwid
def __str__(self):
ret = self.device
if self.description is not None:
ret += " : " + self.description
if self.hwid is not None:
ret += " : " + self.hwid
return ret
def auto_detect_serial_win32(preferred_list=['*']):
'''try to auto-detect serial ports on win32'''
try:
from serial.tools.list_ports_windows import comports
list = sorted(comports())
except:
return []
ret = []
others = []
for port, description, hwid in list:
matches = False
p = SerialPort(port, description=description, hwid=hwid)
for preferred in preferred_list:
if fnmatch.fnmatch(description, preferred) or fnmatch.fnmatch(hwid, preferred):
matches = True
if matches:
ret.append(p)
else:
others.append(p)
if len(ret) > 0:
return ret
# now the rest
ret.extend(others)
return ret
def auto_detect_serial_unix(preferred_list=['*']):
'''try to auto-detect serial ports on unix'''
import glob
glist = glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') + glob.glob('/dev/serial/by-id/*')
ret = []
others = []
# try preferred ones first
for d in glist:
matches = False
for preferred in preferred_list:
if fnmatch.fnmatch(d, preferred):
matches = True
if matches:
ret.append(SerialPort(d))
else:
others.append(SerialPort(d))
if len(ret) > 0:
return ret
ret.extend(others)
return ret
def auto_detect_serial(preferred_list=['*']):
'''try to auto-detect serial port'''
# see if
if os.name == 'nt':
return auto_detect_serial_win32(preferred_list=preferred_list)
return auto_detect_serial_unix(preferred_list=preferred_list)
def mode_string_v09(msg):
'''mode string for 0.9 protocol'''
mode = msg.mode
nav_mode = msg.nav_mode
MAV_MODE_UNINIT = 0
MAV_MODE_MANUAL = 2
MAV_MODE_GUIDED = 3
MAV_MODE_AUTO = 4
MAV_MODE_TEST1 = 5
MAV_MODE_TEST2 = 6
MAV_MODE_TEST3 = 7
MAV_NAV_GROUNDED = 0
MAV_NAV_LIFTOFF = 1
MAV_NAV_HOLD = 2
MAV_NAV_WAYPOINT = 3
MAV_NAV_VECTOR = 4
MAV_NAV_RETURNING = 5
MAV_NAV_LANDING = 6
MAV_NAV_LOST = 7
MAV_NAV_LOITER = 8
cmode = (mode, nav_mode)
mapping = {
(MAV_MODE_UNINIT, MAV_NAV_GROUNDED) : "INITIALISING",
(MAV_MODE_MANUAL, MAV_NAV_VECTOR) : "MANUAL",
(MAV_MODE_TEST3, MAV_NAV_VECTOR) : "CIRCLE",
(MAV_MODE_GUIDED, MAV_NAV_VECTOR) : "GUIDED",
(MAV_MODE_TEST1, MAV_NAV_VECTOR) : "STABILIZE",
(MAV_MODE_TEST2, MAV_NAV_LIFTOFF) : "FBWA",
(MAV_MODE_AUTO, MAV_NAV_WAYPOINT) : "AUTO",
(MAV_MODE_AUTO, MAV_NAV_RETURNING) : "RTL",
(MAV_MODE_AUTO, MAV_NAV_LOITER) : "LOITER",
(MAV_MODE_AUTO, MAV_NAV_LIFTOFF) : "TAKEOFF",
(MAV_MODE_AUTO, MAV_NAV_LANDING) : "LANDING",
(MAV_MODE_AUTO, MAV_NAV_HOLD) : "LOITER",
(MAV_MODE_GUIDED, MAV_NAV_VECTOR) : "GUIDED",
(MAV_MODE_GUIDED, MAV_NAV_WAYPOINT) : "GUIDED",
(100, MAV_NAV_VECTOR) : "STABILIZE",
(101, MAV_NAV_VECTOR) : "ACRO",
(102, MAV_NAV_VECTOR) : "ALT_HOLD",
(107, MAV_NAV_VECTOR) : "CIRCLE",
(109, MAV_NAV_VECTOR) : "LAND",
}
if cmode in mapping:
return mapping[cmode]
return "Mode(%s,%s)" % cmode
mode_mapping_apm = {
0 : 'MANUAL',
1 : 'CIRCLE',
2 : 'STABILIZE',
3 : 'TRAINING',
4 : 'ACRO',
5 : 'FBWA',
6 : 'FBWB',
7 : 'CRUISE',
8 : 'AUTOTUNE',
10 : 'AUTO',
11 : 'RTL',
12 : 'LOITER',
14 : 'LAND',
15 : 'GUIDED',
16 : 'INITIALISING'
}
mode_mapping_acm = {
0 : 'STABILIZE',
1 : 'ACRO',
2 : 'ALT_HOLD',
3 : 'AUTO',
4 : 'GUIDED',
5 : 'LOITER',
6 : 'RTL',
7 : 'CIRCLE',
8 : 'POSITION',
9 : 'LAND',
10 : 'OF_LOITER',
11 : 'DRIFT',
13 : 'SPORT',
14 : 'FLIP',
15 : 'AUTOTUNE',
16 : 'POSHOLD'
}
mode_mapping_rover = {
0 : 'MANUAL',
2 : 'LEARNING',
3 : 'STEERING',
4 : 'HOLD',
10 : 'AUTO',
11 : 'RTL',
15 : 'GUIDED',
16 : 'INITIALISING'
}
mode_mapping_tracker = {
0 : 'MANUAL',
1 : 'STOP',
2 : 'SCAN',
10 : 'AUTO',
16 : 'INITIALISING'
}
mode_mapping_px4 = {
0 : 'MANUAL',
1 : 'ATTITUDE',
2 : 'EASY',
3 : 'AUTO'
}
def mode_mapping_byname(mav_type):
'''return dictionary mapping mode names to numbers, or None if unknown'''
map = None
if mav_type in [mavlink.MAV_TYPE_QUADROTOR,
mavlink.MAV_TYPE_HELICOPTER,
mavlink.MAV_TYPE_HEXAROTOR,
mavlink.MAV_TYPE_OCTOROTOR,
mavlink.MAV_TYPE_TRICOPTER]:
map = mode_mapping_acm
if mav_type == mavlink.MAV_TYPE_FIXED_WING:
map = mode_mapping_apm
if mav_type == mavlink.MAV_TYPE_GROUND_ROVER:
map = mode_mapping_rover
if mav_type == mavlink.MAV_TYPE_ANTENNA_TRACKER:
map = mode_mapping_tracker
if map is None:
return None
inv_map = dict((a, b) for (b, a) in map.items())
return inv_map
def mode_mapping_bynumber(mav_type):
'''return dictionary mapping mode numbers to name, or None if unknown'''
map = None
if mav_type in [mavlink.MAV_TYPE_QUADROTOR,
mavlink.MAV_TYPE_HELICOPTER,
mavlink.MAV_TYPE_HEXAROTOR,
mavlink.MAV_TYPE_OCTOROTOR,
mavlink.MAV_TYPE_TRICOPTER]:
map = mode_mapping_acm
if mav_type == mavlink.MAV_TYPE_FIXED_WING:
map = mode_mapping_apm
if mav_type == mavlink.MAV_TYPE_GROUND_ROVER:
map = mode_mapping_rover
if mav_type == mavlink.MAV_TYPE_ANTENNA_TRACKER:
map = mode_mapping_tracker
if map is None:
return None
return map
def mode_string_v10(msg):
'''mode string for 1.0 protocol, from heartbeat'''
if not msg.base_mode & mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED:
return "Mode(0x%08x)" % msg.base_mode
if msg.type in [ mavlink.MAV_TYPE_QUADROTOR, mavlink.MAV_TYPE_HEXAROTOR,
mavlink.MAV_TYPE_OCTOROTOR, mavlink.MAV_TYPE_TRICOPTER,
mavlink.MAV_TYPE_COAXIAL,
mavlink.MAV_TYPE_HELICOPTER ]:
if msg.custom_mode in mode_mapping_acm:
return mode_mapping_acm[msg.custom_mode]
if msg.type == mavlink.MAV_TYPE_FIXED_WING:
if msg.custom_mode in mode_mapping_apm:
return mode_mapping_apm[msg.custom_mode]
if msg.type == mavlink.MAV_TYPE_GROUND_ROVER:
if msg.custom_mode in mode_mapping_rover:
return mode_mapping_rover[msg.custom_mode]
if msg.type == mavlink.MAV_TYPE_ANTENNA_TRACKER:
if msg.custom_mode in mode_mapping_tracker:
return mode_mapping_tracker[msg.custom_mode]
return "Mode(%u)" % msg.custom_mode
def mode_string_apm(mode_number):
'''return mode string for APM:Plane'''
if mode_number in mode_mapping_apm:
return mode_mapping_apm[mode_number]
return "Mode(%u)" % mode_number
def mode_string_acm(mode_number):
'''return mode string for APM:Copter'''
if mode_number in mode_mapping_acm:
return mode_mapping_acm[mode_number]
return "Mode(%u)" % mode_number
def mode_string_px4(mode_number):
'''return mode string for PX4 flight stack'''
if mode_number in mode_mapping_px4:
return mode_mapping_px4[mode_number]
return "Mode(%u)" % mode_number
class x25crc(object):
'''x25 CRC - based on checksum.h from mavlink library'''
def __init__(self, buf=''):
self.crc = 0xffff
self.accumulate(buf)
def accumulate(self, buf):
'''add in some more bytes'''
bytes = array.array('B')
if isinstance(buf, array.array):
bytes.extend(buf)
else:
bytes.fromstring(buf)
accum = self.crc
for b in bytes:
tmp = b ^ (accum & 0xff)
tmp = (tmp ^ (tmp<<4)) & 0xFF
accum = (accum>>8) ^ (tmp<<8) ^ (tmp<<3) ^ (tmp>>4)
accum = accum & 0xFFFF
self.crc = accum
class MavlinkSerialPort():
'''an object that looks like a serial port, but
transmits using mavlink SERIAL_CONTROL packets'''
def __init__(self, portname, baudrate, devnum=0, devbaud=0, timeout=3, debug=0):
from . import mavutil
self.baudrate = 0
self.timeout = timeout
self._debug = debug
self.buf = ''
self.port = devnum
self.debug("Connecting with MAVLink to %s ..." % portname)
self.mav = mavutil.mavlink_connection(portname, autoreconnect=True, baud=baudrate)
self.mav.wait_heartbeat()
self.debug("HEARTBEAT OK\n")
if devbaud != 0:
self.setBaudrate(devbaud)
self.debug("Locked serial device\n")
def debug(self, s, level=1):
'''write some debug text'''
if self._debug >= level:
print(s)
def write(self, b):
'''write some bytes'''
from . import mavutil
self.debug("sending '%s' (0x%02x) of len %u\n" % (b, ord(b[0]), len(b)), 2)
while len(b) > 0:
n = len(b)
if n > 70:
n = 70
buf = [ord(x) for x in b[:n]]
buf.extend([0]*(70-len(buf)))
self.mav.mav.serial_control_send(self.port,
mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE |
mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND,
0,
0,
n,
buf)
b = b[n:]
def _recv(self):
'''read some bytes into self.buf'''
from . import mavutil
start_time = time.time()
while time.time() < start_time + self.timeout:
m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0',
type='SERIAL_CONTROL', blocking=False, timeout=0)
if m is not None and m.count != 0:
break
self.mav.mav.serial_control_send(self.port,
mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE |
mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND,
0,
0,
0, [0]*70)
m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0',
type='SERIAL_CONTROL', blocking=True, timeout=0.01)
if m is not None and m.count != 0:
break
if m is not None:
if self._debug > 2:
print(m)
data = m.data[:m.count]
self.buf += ''.join(str(chr(x)) for x in data)
def read(self, n):
'''read some bytes'''
if len(self.buf) == 0:
self._recv()
if len(self.buf) > 0:
if n > len(self.buf):
n = len(self.buf)
ret = self.buf[:n]
self.buf = self.buf[n:]
if self._debug >= 2:
for b in ret:
self.debug("read 0x%x" % ord(b), 2)
return ret
return ''
def flushInput(self):
'''flush any pending input'''
self.buf = ''
saved_timeout = self.timeout
self.timeout = 0.5
self._recv()
self.timeout = saved_timeout
self.buf = ''
self.debug("flushInput")
def setBaudrate(self, baudrate):
'''set baudrate'''
from . import mavutil
if self.baudrate == baudrate:
return
self.baudrate = baudrate
self.mav.mav.serial_control_send(self.port,
mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE,
0,
self.baudrate,
0, [0]*70)
self.flushInput()
self.debug("Changed baudrate %u" % self.baudrate)
if __name__ == '__main__':
serial_list = auto_detect_serial(preferred_list=['*FTDI*',"*Arduino_Mega_2560*", "*3D_Robotics*", "*USB_to_UART*", '*PX4*', '*FMU*'])
for port in serial_list:
print("%s" % port)
| magicrub/mavlink | pymavlink/mavutil.py | Python | lgpl-3.0 | 57,225 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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 3 of the License, or
(at your option) any later version.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "createvpcassociationauthorizationrequest.h"
#include "createvpcassociationauthorizationrequest_p.h"
#include "createvpcassociationauthorizationresponse.h"
#include "route53request_p.h"
namespace QtAws {
namespace Route53 {
/*!
* \class QtAws::Route53::CreateVPCAssociationAuthorizationRequest
* \brief The CreateVPCAssociationAuthorizationRequest class provides an interface for Route53 CreateVPCAssociationAuthorization requests.
*
* \inmodule QtAwsRoute53
*
* Amazon Route 53 is a highly available and scalable Domain Name System (DNS) web
*
* \sa Route53Client::createVPCAssociationAuthorization
*/
/*!
* Constructs a copy of \a other.
*/
CreateVPCAssociationAuthorizationRequest::CreateVPCAssociationAuthorizationRequest(const CreateVPCAssociationAuthorizationRequest &other)
: Route53Request(new CreateVPCAssociationAuthorizationRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a CreateVPCAssociationAuthorizationRequest object.
*/
CreateVPCAssociationAuthorizationRequest::CreateVPCAssociationAuthorizationRequest()
: Route53Request(new CreateVPCAssociationAuthorizationRequestPrivate(Route53Request::CreateVPCAssociationAuthorizationAction, this))
{
}
/*!
* \reimp
*/
bool CreateVPCAssociationAuthorizationRequest::isValid() const
{
return false;
}
/*!
* Returns a CreateVPCAssociationAuthorizationResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * CreateVPCAssociationAuthorizationRequest::response(QNetworkReply * const reply) const
{
return new CreateVPCAssociationAuthorizationResponse(*this, reply);
}
/*!
* \class QtAws::Route53::CreateVPCAssociationAuthorizationRequestPrivate
* \brief The CreateVPCAssociationAuthorizationRequestPrivate class provides private implementation for CreateVPCAssociationAuthorizationRequest.
* \internal
*
* \inmodule QtAwsRoute53
*/
/*!
* Constructs a CreateVPCAssociationAuthorizationRequestPrivate object for Route53 \a action,
* with public implementation \a q.
*/
CreateVPCAssociationAuthorizationRequestPrivate::CreateVPCAssociationAuthorizationRequestPrivate(
const Route53Request::Action action, CreateVPCAssociationAuthorizationRequest * const q)
: Route53RequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the CreateVPCAssociationAuthorizationRequest
* class' copy constructor.
*/
CreateVPCAssociationAuthorizationRequestPrivate::CreateVPCAssociationAuthorizationRequestPrivate(
const CreateVPCAssociationAuthorizationRequestPrivate &other, CreateVPCAssociationAuthorizationRequest * const q)
: Route53RequestPrivate(other, q)
{
}
} // namespace Route53
} // namespace QtAws
| pcolby/libqtaws | src/route53/createvpcassociationauthorizationrequest.cpp | C++ | lgpl-3.0 | 3,538 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.usergroups.ws;
import org.sonar.server.ws.WsAction;
public interface UserGroupsWsAction extends WsAction {
// Marker interface
}
| SonarSource/sonarqube | server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/UserGroupsWsAction.java | Java | lgpl-3.0 | 1,002 |
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import db
import logging
class UserPrefs(db.Model):
tz_offset = db.IntegerProperty(default=0)
user = db.UserProperty(auto_current_user_add=True)
def cache_set(self):
tid = self.key().name()
memcache.set('UserPrefs:' + tid, self)
# Put needs to be overriden to use memcache
def put(self):
super(UserPrefs, self).put()
logging.info('cache set')
self.cache_set()
# This function gets the user but uses some hidden tricks.
def get_userprefs(user_id=None):
if not user_id:
user = users.get_current_user()
if not user:
return None
user_id = user.user_id()
userprefs = memcache.get('UserPrefs:' + user_id)
if not userprefs:
# Perform DB Query if cached version is not found
key = db.Key.from_path('UserPrefs', user_id)
userprefs = db.get(key)
if not userprefs:
userprefs = UserPrefs(key_name=user_id)
return userprefs | jscontreras/learning-gae | models.py | Python | lgpl-3.0 | 1,072 |
<?php
require_once TL_ROOT . '/system/modules/bootstrap/config/bootstrap/assets.php';
require_once TL_ROOT . '/system/modules/bootstrap/config/bootstrap/classes.php';
require_once TL_ROOT . '/system/modules/bootstrap/config/bootstrap/layout.php';
require_once TL_ROOT . '/system/modules/bootstrap/config/bootstrap/form.php';
require_once TL_ROOT . '/system/modules/bootstrap/config/bootstrap/templates.php';
require_once TL_ROOT . '/system/modules/bootstrap/config/bootstrap/wrappers.php';
require_once TL_ROOT . '/system/modules/bootstrap/config/bootstrap/miscellaneous.php';
require_once TL_ROOT . '/system/modules/bootstrap/config/bootstrap/stylepicker.php';
/**
* frontend modules
*/
$GLOBALS['FE_MOD']['navigationMenu']['bootstrap_navbar'] = 'Netzmacht\Bootstrap\Module\Navbar';
$GLOBALS['FE_MOD']['miscellaneous']['bootstrap_modal'] = 'Netzmacht\Bootstrap\Module\Modal';
$GLOBALS['BE_MOD']['design']['themes']['tables'][] = 'tl_bootstrap';
/**
* content elements
*/
$GLOBALS['TL_CTE']['bootstrap_carousel']['bootstrap_carouselStart'] = 'Netzmacht\Bootstrap\ContentElement\Carousel';
$GLOBALS['TL_CTE']['bootstrap_carousel']['bootstrap_carouselPart'] = 'Netzmacht\Bootstrap\ContentElement\Carousel';
$GLOBALS['TL_CTE']['bootstrap_carousel']['bootstrap_carouselEnd'] = 'Netzmacht\Bootstrap\ContentElement\Carousel';
$GLOBALS['TL_CTE']['bootstrap_tabs']['bootstrap_tabStart'] = 'Netzmacht\Bootstrap\ContentElement\Tab';
$GLOBALS['TL_CTE']['bootstrap_tabs']['bootstrap_tabPart'] = 'Netzmacht\Bootstrap\ContentElement\Tab';
$GLOBALS['TL_CTE']['bootstrap_tabs']['bootstrap_tabEnd'] = 'Netzmacht\Bootstrap\ContentElement\Tab';
$GLOBALS['TL_CTE']['accordion']['bootstrap_accordionGroupStart'] = 'Netzmacht\Bootstrap\ContentElement\AccordionGroup';
$GLOBALS['TL_CTE']['accordion']['bootstrap_accordionGroupEnd'] = 'Netzmacht\Bootstrap\ContentElement\AccordionGroup';
$GLOBALS['TL_CTE']['links']['bootstrap_button'] = 'Netzmacht\Bootstrap\ContentElement\Button';
$GLOBALS['TL_CTE']['links']['bootstrap_buttons'] = 'Netzmacht\Bootstrap\ContentElement\Buttons';
$GLOBALS['TL_CTE']['subcolumns']['bootstrap_columnset'] = 'Netzmacht\Bootstrap\ContentElement\ColumnSet';
/**
* form wigets
*/
$GLOBALS['TL_FFL']['button'] = 'Netzmacht\Bootstrap\Form\Button';
/**
* backend widgets
*/
$GLOBALS['BE_FFL']['singleSelect'] = 'Netzmacht\Bootstrap\Widget\SingleSelectSelectMenu';
/**
* hooks
*/
$GLOBALS['TL_HOOKS']['initializeSystem'][] = array('Netzmacht\Bootstrap\Bootstrap', 'initializeConfig');
$GLOBALS['TL_HOOKS']['getPageLayout'][] = array('Netzmacht\Bootstrap\Bootstrap', 'initializeLayout');
$GLOBALS['TL_HOOKS']['parseTemplate'][] = array('Netzmacht\Bootstrap\Template\Modifier', 'execute');
$GLOBALS['TL_HOOKS']['parseFrontendTemplate'][] = array('Netzmacht\Bootstrap\Template\Modifier', 'parse');
$GLOBALS['TL_HOOKS']['replaceInsertTags'][] = array('Netzmacht\Bootstrap\InsertTags', 'replaceTags');
$GLOBALS['TL_HOOKS']['simpleAjax'][] = array('Netzmacht\Bootstrap\Ajax', 'loadModalContent');
/**
* Events
*/
$GLOBALS['TL_EVENT_SUBSCRIBERS'][] = 'Netzmacht\Bootstrap\Form\Subscriber';
$GLOBALS['TL_EVENT_SUBSCRIBERS'][] = 'Netzmacht\Bootstrap\Module\Modal\Subscriber';
/**
* wrapper
*/
$GLOBALS['TL_WRAPPERS']['start'][] = 'bootstrap_accordionGroupStart';
$GLOBALS['TL_WRAPPERS']['stop'][] = 'bootstrap_accordionGroupEnd';
$GLOBALS['TL_WRAPPERS']['start'][] = 'bootstrap_tabStart';
$GLOBALS['TL_WRAPPERS']['stop'][] = 'bootstrap_tabEnd';
$GLOBALS['TL_WRAPPERS']['separator'][] = 'bootstrap_tabPart';
$GLOBALS['TL_WRAPPERS']['start'][] = 'bootstrap_carouselStart';
$GLOBALS['TL_WRAPPERS']['stop'][] = 'bootstrap_carouselEnd';
$GLOBALS['TL_WRAPPERS']['separator'][] = 'bootstrap_carouselPart';
$GLOBALS['TL_WRAPPERS']['start'][] = 'bootstrap_buttonToolbarStart';
$GLOBALS['TL_WRAPPERS']['stop'][] = 'bootstrap_buttonToolbarEnd';
$GLOBALS['TL_WRAPPERS']['start'][] = 'bootstrap_buttonGroupStart';
$GLOBALS['TL_WRAPPERS']['stop'][] = 'bootstrap_buttonGroupEnd';
/**
* stylesheets
*/
if(TL_MODE == 'BE') {
$GLOBALS['TL_CSS']['bootstrap'] = 'system/modules/bootstrap/assets/css/backend.css|all|static';
}
/**
* settings
*/
$GLOBALS['TL_CONFIG']['gravatarSize'] = '60';
/**
*
*/
$GLOBALS['TL_PURGE']['custom']['bootstrap_symlink'] = array(
'callback' => array('Netzmacht\Bootstrap\Installer', 'recreateSymlink')
);
| netzmacht-archive/contao-bootstrap | module/config/config.php | PHP | lgpl-3.0 | 4,583 |
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco 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 3 of the License, or
* (at your option) any later version.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.bulkimport.impl;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.action.evaluator.NoConditionEvaluator;
import org.alfresco.repo.action.executer.CopyActionExecuter;
import org.alfresco.repo.action.executer.MoveActionExecuter;
import org.alfresco.repo.bulkimport.BulkImportParameters;
import org.alfresco.repo.bulkimport.NodeImporter;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionCondition;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.rule.Rule;
import org.alfresco.service.cmr.rule.RuleType;
import org.alfresco.service.cmr.version.Version;
import org.alfresco.service.cmr.version.VersionHistory;
import org.alfresco.test_category.OwnJVMTestsCategory;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.springframework.util.ResourceUtils;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @since 4.0
*/
@Category(OwnJVMTestsCategory.class)
public class BulkImportTest extends AbstractBulkImportTests
{
private StreamingNodeImporterFactory streamingNodeImporterFactory;
@BeforeClass
public static void beforeTests()
{
startContext();
}
@Before
public void setup() throws SystemException, NotSupportedException
{
super.setup();
streamingNodeImporterFactory = (StreamingNodeImporterFactory)ctx.getBean("streamingNodeImporterFactory");
}
/**
* For replaceExisting = true, the title must be taken from the metadata and not overridden by the actual filename.
*
* @throws Throwable
*/
@Test
public void testMNT8470() throws Throwable
{
txn = transactionService.getUserTransaction();
txn.begin();
NodeRef folderNode = topLevelFolder.getNodeRef();
try
{
NodeImporter nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport1"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
}
catch(Throwable e)
{
fail(e.getMessage());
}
System.out.println(bulkImporter.getStatus());
assertEquals(false, bulkImporter.getStatus().inProgress());
List<FileInfo> folders = getFolders(folderNode, null);
assertEquals(1, folders.size());
FileInfo folder1 = folders.get(0);
assertEquals("folder1", folder1.getName());
// title should be taken from the metadata file
assertEquals("", folder1.getProperties().get(ContentModel.PROP_TITLE));
}
@Test
public void testCopyImportStriping() throws Throwable
{
txn = transactionService.getUserTransaction();
txn.begin();
NodeRef folderNode = topLevelFolder.getNodeRef();
try
{
NodeImporter nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
}
catch(Throwable e)
{
fail(e.getMessage());
}
System.out.println(bulkImporter.getStatus());
checkFiles(folderNode, null, 2, 9,
new ExpectedFile[]
{
new ExpectedFile("quickImg1.xls", MimetypeMap.MIMETYPE_EXCEL),
new ExpectedFile("quickImg1.doc", MimetypeMap.MIMETYPE_WORD),
new ExpectedFile("quick.txt", MimetypeMap.MIMETYPE_TEXT_PLAIN, "The quick brown fox jumps over the lazy dog"),
},
new ExpectedFolder[]
{
new ExpectedFolder("folder1"),
new ExpectedFolder("folder2")
});
List<FileInfo> folders = getFolders(folderNode, "folder1");
assertEquals("", 1, folders.size());
NodeRef folder1 = folders.get(0).getNodeRef();
checkFiles(folder1, null, 1, 0, null,
new ExpectedFolder[]
{
new ExpectedFolder("folder1.1")
});
folders = getFolders(folderNode, "folder2");
assertEquals("", 1, folders.size());
NodeRef folder2 = folders.get(0).getNodeRef();
checkFiles(folder2, null, 1, 0,
new ExpectedFile[]
{
},
new ExpectedFolder[]
{
new ExpectedFolder("folder2.1")
});
folders = getFolders(folder1, "folder1.1");
assertEquals("", 1, folders.size());
NodeRef folder1_1 = folders.get(0).getNodeRef();
checkFiles(folder1_1, null, 2, 12,
new ExpectedFile[]
{
new ExpectedFile("quick.txt", MimetypeMap.MIMETYPE_TEXT_PLAIN, "The quick brown fox jumps over the lazy dog"),
new ExpectedFile("quick.sxw", MimetypeMap.MIMETYPE_OPENOFFICE1_WRITER),
new ExpectedFile("quick.tar", "application/x-gtar"),
},
new ExpectedFolder[]
{
new ExpectedFolder("folder1.1.1"),
new ExpectedFolder("folder1.1.2")
});
folders = getFolders(folder2, "folder2.1");
assertEquals("", 1, folders.size());
NodeRef folder2_1 = folders.get(0).getNodeRef();
checkFiles(folder2_1, null, 0, 17,
new ExpectedFile[]
{
new ExpectedFile("quick.png", MimetypeMap.MIMETYPE_IMAGE_PNG),
new ExpectedFile("quick.pdf", MimetypeMap.MIMETYPE_PDF),
new ExpectedFile("quick.odt", MimetypeMap.MIMETYPE_OPENDOCUMENT_TEXT),
},
new ExpectedFolder[]
{
});
}
protected Rule createCopyRule(NodeRef targetNode, boolean isAppliedToChildren)
{
Rule rule = new Rule();
rule.setRuleType(RuleType.INBOUND);
String title = "rule title " + System.currentTimeMillis();
rule.setTitle(title);
rule.setDescription(title);
rule.applyToChildren(isAppliedToChildren);
Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(MoveActionExecuter.PARAM_DESTINATION_FOLDER, targetNode);
Action action = actionService.createAction(CopyActionExecuter.NAME, params);
ActionCondition condition = actionService.createActionCondition(NoConditionEvaluator.NAME);
action.addActionCondition(condition);
rule.setAction(action);
return rule;
}
@Test
public void testImportWithRules() throws Throwable
{
NodeRef folderNode = topLevelFolder.getNodeRef();
NodeImporter nodeImporter = null;
txn = transactionService.getUserTransaction();
txn.begin();
NodeRef targetNode = fileFolderService.create(top, "target", ContentModel.TYPE_FOLDER).getNodeRef();
// Create a rule on the node into which we're importing
Rule newRule = createCopyRule(targetNode, false);
this.ruleService.saveRule(folderNode, newRule);
txn.commit();
txn = transactionService.getUserTransaction();
txn.begin();
nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(false);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
System.out.println(bulkImporter.getStatus());
assertEquals(74, bulkImporter.getStatus().getNumberOfContentNodesCreated());
checkFiles(folderNode, null, 2, 9, new ExpectedFile[] {
new ExpectedFile("quickImg1.xls", MimetypeMap.MIMETYPE_EXCEL),
new ExpectedFile("quickImg1.doc", MimetypeMap.MIMETYPE_WORD),
new ExpectedFile("quick.txt", MimetypeMap.MIMETYPE_TEXT_PLAIN, "The quick brown fox jumps over the lazy dog"),
},
new ExpectedFolder[] {
new ExpectedFolder("folder1"),
new ExpectedFolder("folder2")
});
List<FileInfo> folders = getFolders(folderNode, "folder1");
assertEquals("", 1, folders.size());
NodeRef folder1 = folders.get(0).getNodeRef();
checkFiles(folder1, null, 1, 0, null, new ExpectedFolder[] {
new ExpectedFolder("folder1.1")
});
folders = getFolders(folderNode, "folder2");
assertEquals("", 1, folders.size());
NodeRef folder2 = folders.get(0).getNodeRef();
checkFiles(folder2, null, 1, 0, new ExpectedFile[] {
},
new ExpectedFolder[] {
new ExpectedFolder("folder2.1")
});
folders = getFolders(folder1, "folder1.1");
assertEquals("", 1, folders.size());
NodeRef folder1_1 = folders.get(0).getNodeRef();
checkFiles(folder1_1, null, 2, 12, new ExpectedFile[] {
new ExpectedFile("quick.txt", MimetypeMap.MIMETYPE_TEXT_PLAIN, "The quick brown fox jumps over the lazy dog"),
new ExpectedFile("quick.sxw", MimetypeMap.MIMETYPE_OPENOFFICE1_WRITER),
new ExpectedFile("quick.tar", "application/x-gtar"),
},
new ExpectedFolder[] {
new ExpectedFolder("folder1.1.1"),
new ExpectedFolder("folder1.1.2")
});
folders = getFolders(folder2, "folder2.1");
assertEquals("", 1, folders.size());
NodeRef folder2_1 = folders.get(0).getNodeRef();
checkFiles(folder2_1, null, 0, 17, new ExpectedFile[] {
new ExpectedFile("quick.png", MimetypeMap.MIMETYPE_IMAGE_PNG),
new ExpectedFile("quick.pdf", MimetypeMap.MIMETYPE_PDF),
new ExpectedFile("quick.odt", MimetypeMap.MIMETYPE_OPENDOCUMENT_TEXT),
},
new ExpectedFolder[] {
});
}
@Test
// Tests the mimetype is set correctly for .ai and eps files, plus gif (which was working anyway).
public void testMNT18275_ai_eps() throws Throwable
{
NodeRef folderNode = topLevelFolder.getNodeRef();
NodeImporter nodeImporter = null;
txn = transactionService.getUserTransaction();
txn.begin();
nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport5"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
System.out.println(bulkImporter.getStatus());
checkFiles(folderNode, null, 0, 3, new ExpectedFile[] {
new ExpectedFile("quick.gif", MimetypeMap.MIMETYPE_IMAGE_GIF),
new ExpectedFile("Amazing.ai", MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR),
new ExpectedFile("quick.eps", MimetypeMap.MIMETYPE_APPLICATION_EPS)
},
new ExpectedFolder[] {
});
}
/**
* MNT-9076: Penultimate version cannot be accessed from Share when uploading using bulkimport
*
* @throws Throwable
*/
@Test
public void testMNT9076() throws Throwable
{
txn = transactionService.getUserTransaction();
txn.begin();
NodeRef folderNode = topLevelFolder.getNodeRef();
try
{
NodeImporter nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport2"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
}
catch(Throwable e)
{
fail(e.getMessage());
}
System.out.println(bulkImporter.getStatus());
assertEquals(false, bulkImporter.getStatus().inProgress());
List<FileInfo> files = getFiles(folderNode, null);
assertEquals("One file is expected to be imported:", 1, files.size());
FileInfo file = files.get(0);
assertEquals("File name is not equal:", "fileWithVersions.txt", file.getName());
NodeRef file0NodeRef = file.getNodeRef();
assertTrue("Imported file should be versioned:", versionService.isVersioned(file0NodeRef));
VersionHistory history = versionService.getVersionHistory(file0NodeRef);
assertEquals("Imported file should have 4 versions:", 4, history.getAllVersions().size());
Version[] versions = history.getAllVersions().toArray(new Version[4]);
//compare the content of each version
ContentReader contentReader;
contentReader = this.contentService.getReader(versions[0].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is the final version of fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[1].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 3 of fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[2].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 2 of fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[3].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 1 of fileWithVersions.txt.", contentReader.getContentString());
}
/**
* MNT-9067: bulkimport "Replace existing files" option does not work when versioning is enabled
*
* @throws Throwable
*/
@Test
public void testMNT9067() throws Throwable
{
txn = transactionService.getUserTransaction();
txn.begin();
NodeRef folderNode = topLevelFolder.getNodeRef();
//initial import
try
{
NodeImporter nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport3/initial"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
}
catch(Throwable e)
{
fail(e.getMessage());
}
txn.commit();
txn = transactionService.getUserTransaction();
txn.begin();
System.out.println(bulkImporter.getStatus());
assertEquals(false, bulkImporter.getStatus().inProgress());
List<FileInfo> files = getFiles(folderNode, null);
assertEquals("One file is expected to be imported:", 1, files.size());
FileInfo file = files.get(0);
assertEquals("File name is not equal:", "fileWithVersions.txt", file.getName());
NodeRef fileNodeRef = file.getNodeRef();
assertTrue("Imported file should be versioned:", versionService.isVersioned(fileNodeRef));
VersionHistory history = versionService.getVersionHistory(fileNodeRef);
assertEquals("Imported file should have 4 versions:", 4, history.getAllVersions().size());
//replace versioned file with new versioned file
try
{
NodeImporter nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport3/replace_with_versioned"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
}
catch(Throwable e)
{
fail(e.getMessage());
}
System.out.println(bulkImporter.getStatus());
assertEquals(false, bulkImporter.getStatus().inProgress());
txn.commit();
txn = transactionService.getUserTransaction();
txn.begin();
files = getFiles(folderNode, null);
assertEquals("One file is expected to be imported:", 1, files.size());
file = files.get(0);
assertEquals("File name is not equal:", "fileWithVersions.txt", file.getName());
fileNodeRef = file.getNodeRef();
assertTrue("Imported file should be versioned:", versionService.isVersioned(fileNodeRef));
history = versionService.getVersionHistory(fileNodeRef);
assertNotNull(history);
assertEquals("Imported file should have 9 versions:", 9, history.getAllVersions().size());
Version[] versions = history.getAllVersions().toArray(new Version[9]);
//compare the content of each version
ContentReader contentReader;
contentReader = this.contentService.getReader(versions[0].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is the final version of replaced on import fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[1].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 4 of replaced on import fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[2].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 3 of replaced on import fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[3].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 2 of replaced on import fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[4].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 1 of replaced on import fileWithVersions.txt.", contentReader.getContentString());
// versions from bulkimport3/initial
contentReader = this.contentService.getReader(versions[5].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is the final version of fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[6].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 3 of fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[7].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 2 of fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[8].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 1 of fileWithVersions.txt.", contentReader.getContentString());
txn.commit();
txn = transactionService.getUserTransaction();
txn.begin();
//import non versioned file
try
{
NodeImporter nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport3/replace_with_non_versioned"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
}
catch(Throwable e)
{
fail(e.getMessage());
}
txn.commit();
txn = transactionService.getUserTransaction();
txn.begin();
System.out.println(bulkImporter.getStatus());
assertEquals(false, bulkImporter.getStatus().inProgress());
files = getFiles(folderNode, null);
assertEquals("One file is expected to be imported:", 1, files.size());
file = files.get(0);
assertEquals("File name is not equal:", "fileWithVersions.txt", file.getName());
fileNodeRef = file.getNodeRef();
assertTrue("Imported file should be non versioned:", !versionService.isVersioned(fileNodeRef));
contentReader = this.contentService.getReader(fileNodeRef, ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is non versioned fileWithVersions.txt.", contentReader.getContentString());
txn.commit();
txn = transactionService.getUserTransaction();
txn.begin();
//use initial file again to replace non versioned file
try
{
NodeImporter nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport3/initial"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
}
catch(Throwable e)
{
fail(e.getMessage());
}
txn.commit();
txn = transactionService.getUserTransaction();
txn.begin();
System.out.println(bulkImporter.getStatus());
assertEquals(false, bulkImporter.getStatus().inProgress());
files = getFiles(folderNode, null);
assertEquals("One file is expected to be imported:", 1, files.size());
file = files.get(0);
assertEquals("File name is not equal:", "fileWithVersions.txt", file.getName());
fileNodeRef = file.getNodeRef();
assertTrue("Imported file should be versioned:", versionService.isVersioned(fileNodeRef));
history = versionService.getVersionHistory(fileNodeRef);
assertNotNull(history);
assertEquals("Imported file should have 4 versions:", 4, history.getAllVersions().size());
versions = history.getAllVersions().toArray(new Version[4]);
//compare the content of each version
contentReader = this.contentService.getReader(versions[0].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is the final version of fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[1].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 3 of fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[2].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 2 of fileWithVersions.txt.", contentReader.getContentString());
contentReader = this.contentService.getReader(versions[3].getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
assertNotNull(contentReader);
assertEquals("This is version 1 of fileWithVersions.txt.", contentReader.getContentString());
}
/**
* MNT-15367: Unable to bulk import filenames with Portuguese characters in a Linux environment
*
* @throws Throwable
*/
@Test
public void testImportFilesWithSpecialCharacters() throws Throwable
{
NodeRef folderNode = topLevelFolder.getNodeRef();
NodeImporter nodeImporter = null;
File source = ResourceUtils.getFile("classpath:bulkimport4");
//Simulate the name of the file with an invalid encoding.
String fileName = new String("135 Carbonรรรด13 NMR spectroscopy_DS_NS_final_cau.txt".getBytes(Charset.forName("ISO-8859-1")),
Charset.forName("UTF-8"));
Path dest = source.toPath().resolve("encoding");
try
{
dest = Files.createDirectory(dest);
}
catch (FileAlreadyExistsException ex)
{
//It is fine if the folder already exists, though it should not.
}
Path destFile = dest.resolve(fileName);
unpack(source.toPath(), destFile);
txn = transactionService.getUserTransaction();
txn.begin();
nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport4/encoding"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
assertEquals(1, bulkImporter.getStatus().getNumberOfContentNodesCreated());
checkFiles(folderNode, null, 0, 1,
new ExpectedFile[] { new ExpectedFile(fileName, MimetypeMap.MIMETYPE_TEXT_PLAIN)},
null);
Files.deleteIfExists(destFile);
Files.deleteIfExists(dest);
}
/**
* MNT-18001: Presence of versionLabel in metadata file throws error in bulk importer
*/
@Test
public void testImportFilesWithVersionLabel() throws Throwable
{
txn = transactionService.getUserTransaction();
txn.begin();
// Get metadata file with versionLabel property
NodeRef folderNode = topLevelFolder.getNodeRef();
NodeImporter nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport6"));
// Set parameters for bulk import: Target space, Disable rule processing, Replace existing files, Batch size:1, Number of threads:1
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setExistingFileMode(BulkImportParameters.ExistingFileMode.REPLACE);
bulkImportParameters.setBatchSize(1);
bulkImportParameters.setNumThreads(1);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
List<FileInfo> files = getFiles(folderNode, null);
assertNotNull(files);
FileInfo file = files.get(0);
assertNotNull(file);
VersionHistory history = versionService.getVersionHistory(file.getNodeRef());
assertEquals(1, bulkImporter.getStatus().getNumberOfContentNodesCreated());
assertEquals("Imported file should have 3 versions:", 3, history.getAllVersions().size());
}
/**
* Simplifies calling {@ResourceUtils.getFile} so that a {@link RuntimeException}
* is thrown rather than a checked {@link FileNotFoundException} exception.
*
* @param resourceName e.g. "classpath:folder/file"
* @return File object
*/
private File resourceAsFile(String resourceName)
{
try
{
return ResourceUtils.getFile(resourceName);
}
catch (FileNotFoundException e)
{
throw new RuntimeException("Resource "+resourceName+" not found", e);
}
}
@Test
public void canVersionDocsWithoutSpecialInputFileNameExtension()
throws HeuristicMixedException, IOException, SystemException,
HeuristicRollbackException, NotSupportedException, RollbackException
{
testCanVersionDocsWithoutSpecialInputFileNameExtension(file ->
streamingNodeImporterFactory.getNodeImporter(resourceAsFile("classpath:bulkimport-autoversion/"+file)));
}
private void unpack(Path source, Path destFile)
{
Path archive = source.resolve("testbulk.gz");
try (GZIPInputStream gzis = new GZIPInputStream(Files.newInputStream(archive));
OutputStream out = Files.newOutputStream(destFile, StandardOpenOption.CREATE))
{
byte[] buffer = new byte[1024];
int len;
while ((len = gzis.read(buffer)) > 0)
{
out.write(buffer, 0, len);
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
| Alfresco/alfresco-repository | src/test/java/org/alfresco/repo/bulkimport/impl/BulkImportTest.java | Java | lgpl-3.0 | 33,463 |
/*
* jesadido-poc
* Copyright (C) 2016 Stefan K. Baur
*
* Licensed under the GNU Lesser General Public License, Version 3.0 (LGPL-3.0)
* https://www.gnu.org/licenses/lgpl-3.0.txt
*/
package org.jesadido.poc.usecases.gaming.graphics.rags;
public interface Rag extends RagVisitable {}
| stefan-baur/jesadido-poc | src/main/java/org/jesadido/poc/usecases/gaming/graphics/rags/Rag.java | Java | lgpl-3.0 | 290 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.monitoring.ce;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.ce.CeActivityDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.monitoring.ServerMonitoringMetrics;
import static java.util.Objects.requireNonNull;
public class RecentTasksDurationTask extends ComputeEngineMetricsTask {
private static final Logger LOGGER = Loggers.get(RecentTasksDurationTask.class);
private final System2 system;
private long lastUpdatedTimestamp;
public RecentTasksDurationTask(DbClient dbClient, ServerMonitoringMetrics metrics, Configuration config,
System2 system) {
super(dbClient, metrics, config);
this.system = system;
this.lastUpdatedTimestamp = system.now();
}
@Override
public void run() {
try (DbSession dbSession = dbClient.openSession(false)) {
List<CeActivityDto> recentSuccessfulTasks = getRecentSuccessfulTasks(dbSession);
Collection<String> componentUuids = recentSuccessfulTasks.stream()
.map(CeActivityDto::getMainComponentUuid)
.collect(Collectors.toList());
List<ComponentDto> componentDtos = dbClient.componentDao().selectByUuids(dbSession, componentUuids);
Map<String, String> componentUuidAndKeys = componentDtos.stream()
.collect(Collectors.toMap(ComponentDto::uuid, ComponentDto::getKey));
reportObservedDurationForTasks(recentSuccessfulTasks, componentUuidAndKeys);
}
lastUpdatedTimestamp = system.now();
}
private List<CeActivityDto> getRecentSuccessfulTasks(DbSession dbSession) {
List<CeActivityDto> recentTasks = dbClient.ceActivityDao().selectNewerThan(dbSession, lastUpdatedTimestamp);
return recentTasks.stream()
.filter(c -> c.getStatus() == CeActivityDto.Status.SUCCESS)
.collect(Collectors.toList());
}
private void reportObservedDurationForTasks(List<CeActivityDto> tasks, Map<String, String> componentUuidAndKeys) {
for (CeActivityDto task : tasks) {
String mainComponentUuid = task.getMainComponentUuid();
Long executionTimeMs = task.getExecutionTimeMs();
try {
requireNonNull(mainComponentUuid);
requireNonNull(executionTimeMs);
String mainComponentKey = componentUuidAndKeys.get(mainComponentUuid);
requireNonNull(mainComponentKey);
metrics.observeComputeEngineTaskDuration(executionTimeMs, task.getTaskType(), mainComponentKey);
} catch (RuntimeException e) {
LOGGER.warn("Can't report metric data for a CE task with component uuid " + mainComponentUuid, e);
}
}
}
}
| SonarSource/sonarqube | server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/ce/RecentTasksDurationTask.java | Java | lgpl-3.0 | 3,709 |
/*******************************************************************************
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package com.jaspersoft.studio.editor.jrexpressions.services;
import org.eclipse.xtext.common.services.DefaultTerminalConverters;
import org.eclipse.xtext.conversion.IValueConverter;
import org.eclipse.xtext.conversion.ValueConverter;
import org.eclipse.xtext.conversion.ValueConverterException;
import org.eclipse.xtext.nodemodel.INode;
/**
* Custom value converter service that allows to handle correctly
* octet, hex, and long number strings.
*
* @author Massimo Rabbi (mrabbi@users.sourceforge.net)
*
*/
public class CustomTerminalConverters extends DefaultTerminalConverters {
private static final int RADIX_8 = 8;
private static final int RADIX_16 = 16;
@Override
@ValueConverter(rule = "INT")
public IValueConverter<Integer> INT() {
return new IValueConverter<Integer>(){
@Override
public Integer toValue(String string, INode node)
throws ValueConverterException {
if(string.startsWith("0x") || string.startsWith("0X")){
String stripped = string.substring(2, string.length());
return Integer.parseInt(stripped,RADIX_16);
}
else if(string.startsWith("0")){
return Integer.parseInt(string,RADIX_8);
}
else {
return Integer.parseInt(string);
}
}
@Override
public String toString(Integer value)
throws ValueConverterException {
return value.toString();
}
};
}
@ValueConverter(rule = "LONG")
public IValueConverter<Long> LONG() {
return new IValueConverter<Long>(){
@Override
public Long toValue(String string, INode node)
throws ValueConverterException {
if(string.startsWith("0x") || string.startsWith("0X")){
String stripped = string.substring(2, string.length()-1);
return Long.parseLong(stripped,RADIX_16);
}
else if(string.startsWith("0")){
String stripped = string.substring(0, string.length()-1);
return Long.parseLong(stripped,RADIX_8);
}
else {
String stripped = string.substring(0, string.length()-1);
return Long.parseLong(stripped);
}
}
@Override
public String toString(Long value) throws ValueConverterException {
return value.toString();
}
};
}
}
| OpenSoftwareSolutions/PDFReporter-Studio | com.jaspersoft.studio.editor.jrexpressions/src/com/jaspersoft/studio/editor/jrexpressions/services/CustomTerminalConverters.java | Java | lgpl-3.0 | 2,775 |
// ------------------------------------------------------
// DVTk - The Healthcare Validation Toolkit (www.dvtk.org)
// Copyright ยฉ 2009 DVTk
// ------------------------------------------------------
// This file is part of DVTk.
//
// DVTk 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 3.0
// of the License, or (at your option) any later version.
//
// DVTk is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with this
// library; if not, see <http://www.gnu.org/licenses/>
using System;
namespace DvtkApplicationLayer.UserInterfaces
{
/// <summary>
/// Used to be able to have a combination of an Object and a String representation for use in a ComboBox.
/// </summary>
internal class InputFormObjectAndString
{
//
// - Fields -
//
/// <summary>
/// See property TheObject
/// </summary>
private Object theObject = null;
/// <summary>
/// See property TheString
/// </summary>
private String theString = null;
//
// - Constructors -
//
/// <summary>
/// Hide default constructor.
/// </summary>
private InputFormObjectAndString()
{
// Do nothing.
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="theObject">The Object.</param>
/// <param name="theString">The String.</param>
public InputFormObjectAndString(Object theObject, String theString)
{
this.theObject = theObject;
this.theString = theString;
}
//
// - Properties -
//
/// <summary>
/// Get the Object.
/// </summary>
internal Object TheObject
{
get
{
return(this.theObject);
}
}
/// <summary>
/// Get the String.
/// </summary>
internal String TheString
{
get
{
return(this.theString);
}
}
//
// - Methods -
//
/// <summary>
/// This ToString method has been overriden to be able to display a different String then
/// the ToString Object of the this.theObject instance.
/// </summary>
/// <returns></returns>
public override String ToString()
{
return(this.theString);
}
}
}
| marcokemper/DVTk | DVTk_Library/Source/Assemblies/DVTk Application Layer/UserInterfaces/InputFormObjectAndString.cs | C# | lgpl-3.0 | 2,547 |
<?php
require_once 'PHP/MapFilter/TreePattern.php';
require_once 'tests/Functional.php';
/**
* @covers MapFilter_TreePattern_Tree_Iterator
* @covers MapFilter_TreePattern_Tree_Iterator_Builder
*/
class MapFilter_Test_Unit_TreePattern_Iterator extends
MapFilter_TreePattern_Test_Functional
{
/**
* @expectedException MapFilter_TreePattern_Tree_InvalidContentException
* @expectedExceptionMessage Node 'iterator' has no content.
*
* @covers MapFilter_TreePattern_Tree_InvalidContentException
* @covers MapFilter_TreePattern_Tree_Iterator_Builder<extended>
*/
public function testTextContent () {
MapFilter_TreePattern_Xml::load ( '
<pattern>
<iterator>value</iterator>
</pattern>
' );
}
/**
* @expectedException MapFilter_TreePattern_NotExactlyOneFollowerException
* @expectedExceptionMessage The 'iterator' node must have exactly one follower but 2 given.
*
* @covers MapFilter_TreePattern_NotExactlyOneFollowerException
* @covers MapFilter_TreePattern_Tree_Iterator_Builder
*/
public function testNotExactlyOneFollower () {
MapFilter_TreePattern_Xml::load ( '
<pattern>
<iterator>
<all />
<opt />
</iterator>
</pattern>
' );
}
public function provideNonIntegralLengthConstraint () {
return Array (
Array ( '<iterator min="-1" />' ),
Array ( '<iterator min="ten" />' ),
Array ( '<iterator max="-1" />' ),
Array ( '<iterator max="ten" />' ),
Array ( '<iterator max="1" min="-1" />' ),
Array ( '<iterator min="1" max="-1" />' ),
Array ( '<iterator max="-1" min="-1" />' ),
);
}
/**
* @dataProvider provideNonIntegralLengthConstraint
*
* @expectedException MapFilter_TreePattern_Tree_Iterator_InvalidLengthConstraintException
*
* @covers MapFilter_TreePattern_Tree_Iterator
* @covers MapFilter_TreePattern_Tree_Iterator_InvalidLengthConstraintException
*/
public function testInvalidLengthConstraint ( $pattern ) {
MapFilter_TreePattern_Xml::load ( $pattern );
}
/**
* @expectedException MapFilter_TreePattern_Tree_Iterator_EmptyIntervalSpecifiedException
*
* @covers MapFilter_TreePattern_Tree_Iterator
* @covers MapFilter_TreePattern_Tree_Iterator_EmptyIntervalSpecifiedException
*/
public function testEmptyIntervalSpecified () {
MapFilter_TreePattern_Xml::load ( '
<iterator min="2" max="1" />
' );
}
public function provideEmptyIterator () {
return Array (
Array (
null,
null,
Array ( 'no_iterator' ),
Array ()
),
Array (
Array (),
Array (),
Array (),
Array ( 'iterator' )
),
Array (
Array ( 'some', 'content' ),
Array ( 'some', 'content' ),
Array (),
Array ( 'iterator' )
),
Array (
4,
null,
Array ( 'no_iterator' ),
Array ()
),
Array (
'string',
null,
Array ( 'no_iterator' ),
Array ()
),
Array (
Array ( 'key' => 'value' ),
Array ( 'key' => 'value' ),
Array (),
Array ( 'iterator' )
),
);
}
/**
* @dataProvider provideEmptyIterator
*
* @covers MapFilter_TreePattern_Tree_Iterator
*/
public function testEmptyIterator ( $query, $result, $asserts, $flags ) {
$pattern = MapFilter_TreePattern_Xml::load ( '
<pattern>
<iterator flag="iterator" assert="no_iterator" />
</pattern>
' );
$this->assertResultsEquals ( $pattern, $query, $result, $asserts, $flags );
}
public function provideStructIterator () {
return Array (
Array (
Array (),
Array (),
Array (),
Array ( 'iterator' )
),
Array (
Array ( Array ( 'int' => 42 ) ),
Array ( Array ( 'int' => 42 ) ),
Array (),
Array ( 'int', 'iterator' )
),
Array (
Array ( 42 ),
Array ( 42 ),
Array (),
Array ( 'int', 'iterator' )
),
Array (
Array ( Array ( 'int' => 42 ), Array ( 'int' => 43 ), Array ( 'int' => 44 ) ),
Array ( Array ( 'int' => 42 ), Array ( 'int' => 43 ), Array ( 'int' => 44 ) ),
Array (),
Array ( 'int', 'iterator' )
),
Array (
Array ( 42, 43, 44 ),
Array ( 42, 43, 44 ),
Array (),
Array ( 'int', 'iterator' )
),
Array (
Array ( Array ( 'int' => 42 ), 43 ),
Array ( Array ( 'int' => 42 ), 43 ),
Array (),
Array ( 'int', 'iterator' )
),
Array (
Array ( Array ( 'int' => 'a number' ) ),
Array ( Array ( 'int' => 'zero' ) ),
Array (),
Array ( 'int', 'iterator' )
),
Array (
Array (
Array ( 'int' => 42 ), Array ( 'int' => 'a number' ),
Array ( 'int' => 43 ), Array ( 'int' => 'string' )
),
Array (
Array ( 'int' => 42 ), Array ( 'int' => 'zero' ),
Array ( 'int' => 43 ), Array ( 'int' => 'zero' )
),
Array (),
Array ( 'int', 'iterator' )
),
Array (
Array ( 'val' ),
Array (),
Array ( 'no_int' ),
Array ( 'iterator' )
),
Array (
Array ( 'string' => 'val' ),
Array (),
Array ( 'no_int' ),
Array ( 'iterator' )
),
Array (
'val',
null,
Array ( 'no_iterator' ),
Array ()
),
);
}
/**
* @dataProvider provideStructIterator
*
* @covers MapFilter_TreePattern_Tree_Iterator
*/
public function testStructIterator ( $query, $result, $asserts, $flags ) {
$pattern = MapFilter_TreePattern_Xml::load ( '
<pattern>
<iterator flag="iterator" assert="no_iterator">
<one flag="int" assert="no_int">
<value pattern="/^\d+$/" />
<key name="int">
<value pattern="/^\d+$/" default="zero" />
</key>
</one>
</iterator>
</pattern>
' );
$this->assertResultsEquals ( $pattern, $query, $result, $asserts, $flags );
}
public function provideKeyIterator () {
return Array (
Array (
null,
null,
Array ( 'no_iterator' ),
Array (),
),
Array (
Array (),
Array (),
Array (),
Array ( 'iterator' ),
),
Array (
Array ( 'key' => 7 ),
Array (),
Array ( 'no_key1', 'no_key2' ),
Array ( 'iterator' ),
),
Array (
Array ( 7 ),
Array (),
Array ( 'no_key1', 'no_key2' ),
Array ( 'iterator' ),
),
Array (
Array ( Array ( 'key1' => 7 ) ),
Array ( Array ( 'key1' => 7 ) ),
Array (),
Array ( 'iterator', 'key1' ),
),
Array (
Array ( Array ( 'key2' => 7 ) ),
Array ( Array ( 'key2' => 7 ) ),
Array ( 'no_key1' ),
Array ( 'iterator', 'key2' ),
),
Array (
Array ( Array ( 'key1' => 7 ), Array ( 'key1' => 8 ) ),
Array ( Array ( 'key1' => 7 ), Array ( 'key1' => 8 ) ),
Array (),
Array ( 'iterator', 'key1' ),
),
Array (
Array ( Array ( 'key2' => 7 ), Array ( 'key2' => 8 ) ),
Array ( Array ( 'key2' => 7 ), Array ( 'key2' => 8 ) ),
Array ( 'no_key1' ),
Array ( 'iterator', 'key2' ),
),
Array (
Array ( Array ( 'key1' => 7 ), Array ( 'key2' => 8 ) ),
Array ( Array ( 'key1' => 7 ), Array ( 'key2' => 8 ) ),
Array ( 'no_key1' ),
Array ( 'iterator', 'key1', 'key2' ),
),
Array (
Array ( Array ( 'key1' => 7 ), Array ( 'key2' => 8 ) ),
Array ( Array ( 'key1' => 7 ), Array ( 'key2' => 8 ) ),
Array ( 'no_key1' ),
Array ( 'iterator', 'key1', 'key2' ),
),
Array (
Array ( Array ( 'key1' => 'invalid' ), Array ( 'key2' => 8 ) ),
Array ( 1 => Array ( 'key2' => 8 ) ),
Array ( 'no_key1' => 'invalid', 'no_key2' ),
Array ( 'iterator', 'key2' ),
),
Array (
Array ( Array ( 'key1' => 8 ), Array ( 'key2' => 'invalid' ) ),
Array ( Array ( 'key1' => 8 ) ),
Array ( 'no_key1', 'no_key2' => 'invalid' ),
Array ( 'iterator', 'key1' ),
),
Array (
Array ( Array ( 'key1' => 'invalid' ), Array ( 'key1' => 8 ) ),
Array ( 1 => Array ( 'key1' => 8 ) ),
Array ( 'no_key1' => 'invalid', 'no_key2' ),
Array ( 'iterator', 'key1' ),
),
Array (
Array ( Array ( 'key1' => 8 ), Array ( 'key1' => 'invalid' ) ),
Array ( Array ( 'key1' => 8 ) ),
Array ( 'no_key1' => 'invalid', 'no_key2' ),
Array ( 'iterator', 'key1' ),
),
Array (
Array ( Array ( 'key2' => 'invalid' ), Array ( 'key2' => 8 ) ),
Array ( 1 => Array ( 'key2' => 8 ) ),
Array ( 'no_key1', 'no_key2' => 'invalid' ),
Array ( 'iterator', 'key2' ),
),
Array (
Array ( Array ( 'key2' => 8 ), Array ( 'key2' => 'invalid' ) ),
Array ( Array ( 'key2' => 8 ) ),
Array ( 'no_key1', 'no_key2' => 'invalid' ),
Array ( 'iterator', 'key2' ),
),
Array (
Array (
Array ( 'wrong' => 1 ), Array ( 'key1' => 7 ),
Array ( 'wrong' => 2 ), Array ( 'key2' => 8 ),
Array ( 'wrong' => 3 )
),
Array ( 1 => Array ( 'key1' => 7 ), 3 => Array ( 'key2' => 8 ) ),
Array ( 'no_key1', 'no_key2' ),
Array ( 'iterator', 'key1', 'key2' ),
),
Array (
Array ( Array ( 'key1' => 6, 'key2' => 7 ) ),
Array ( Array ( 'key1' => 6 ) ),
Array (),
Array ( 'iterator', 'key1' ),
),
Array (
Array ( Array ( 'key1' => 'invalid' ) ),
Array (),
Array ( 'no_key1' => 'invalid', 'no_key2' ),
Array ( 'iterator' ),
),
Array (
Array ( Array ( 'key2' => 'invalid' ) ),
Array (),
Array ( 'no_key1', 'no_key2' => 'invalid' ),
Array ( 'iterator' ),
),
Array (
Array ( Array ( 'key1' => 'invalid', 'key2' => 'invalid' ) ),
Array (),
Array ( 'no_key1' => 'invalid', 'no_key2' => 'invalid' ),
Array ( 'iterator' ),
),
Array (
Array ( Array ( 'key1' => 'invalid', 'key2' => 7 ) ),
Array ( Array ( 'key2' => 7 ) ),
Array ( 'no_key1' => 'invalid' ),
Array ( 'iterator', 'key2' ),
),
Array (
Array ( Array ( 'key1' => 7, 'key2' => 'invalid' ) ),
Array ( Array ( 'key1' => 7 ) ),
Array (),
Array ( 'iterator', 'key1' ),
),
);
}
/**
* @dataProvider provideKeyIterator
*/
public function testKeyIterator ( $query, $result, $asserts, $flags ) {
$pattern = MapFilter_TreePattern_Xml::load ( '
<pattern>
<iterator flag="iterator" assert="no_iterator">
<one>
<key name="key1" flag="key1" assert="no_key1">
<value pattern="/^\d+$/" />
</key>
<key name="key2" flag="key2" assert="no_key2">
<value pattern="/^\d+$/" />
</key>
</one>
</iterator>
</pattern>
' );
$this->assertResultsEquals ( $pattern, $query, $result, $asserts, $flags );
}
public function provideConstrainedIterator () {
return Array (
Array (
null,
null,
Array ( 'it' ),
Array ()
),
Array (
Array ( 1 ),
Array ( 1 ),
Array (),
Array ( 'it' )
),
Array (
Array ( 1, 2 ),
Array ( 1, 2 ),
Array (),
Array ( 'it' )
),
Array (
Array ( 1, 2, 3 ),
Array ( 1, 2 ),
Array (),
Array ( 'it' )
),
Array (
Array (),
null,
Array ( 'it' ),
Array ()
),
);
}
/**
* @dataProvider provideConstrainedIterator
*
* @covers MapFilter_TreePattern_Tree_Iterator
*/
public function testConstrainedIterator (
$query, $result, $asserts, $flags
) {
$pattern = MapFilter_TreePattern_Xml::load ( '
<pattern>
<iterator flag="it" assert="it" min="1" max="2" />
</pattern>
' );
$this->assertResultsEquals ( $pattern, $query, $result, $asserts, $flags );
}
public function provideTopConstrainedIterator () {
return Array (
Array (
null,
null,
Array ( 'it' ),
Array ()
),
Array (
Array (),
Array (),
Array (),
Array ( 'it' )
),
Array (
Array ( 1 ),
Array ( 1 ),
Array (),
Array ( 'it' )
),
Array (
Array ( 1, 2 ),
Array ( 1, 2 ),
Array (),
Array ( 'it' )
),
Array (
Array ( 1, 2, 3 ),
Array ( 1, 2 ),
Array (),
Array ( 'it' )
),
);
}
/**
* @dataProvider provideTopConstrainedIterator
*
* @covers MapFilter_TreePattern_Tree_Iterator
*/
public function testTopConstrainedIterator (
$query, $result, $asserts, $flags
) {
$pattern = MapFilter_TreePattern_Xml::load ( '
<pattern>
<iterator flag="it" assert="it" max="2" />
</pattern>
' );
$this->assertResultsEquals ( $pattern, $query, $result, $asserts, $flags );
}
public function provideBottomConstrainedIterator () {
return Array (
Array (
null,
null,
Array ( 'it' ),
Array ()
),
Array (
Array (),
null,
Array ( 'it' ),
Array ()
),
Array (
Array ( 1 ),
null,
Array ( 'it' ),
Array ()
),
Array (
Array ( 1, 2 ),
Array ( 1, 2 ),
Array (),
Array ( 'it' )
),
Array (
Array ( 1, 2, 3 ),
Array ( 1, 2, 3 ),
Array (),
Array ( 'it' )
),
);
}
/**
* @dataProvider provideBottomConstrainedIterator
*
* @covers MapFilter_TreePattern_Tree_Iterator
*/
public function testBottomConstrainedIterator (
$query, $result, $asserts, $flags
) {
$pattern = MapFilter_TreePattern_Xml::load ( '
<pattern>
<iterator flag="it" assert="it" min="2" />
</pattern>
' );
$this->assertResultsEquals ( $pattern, $query, $result, $asserts, $flags );
}
public function provideValidatingConstrainedIterator () {
return Array (
Array (
null,
null,
Array ( 'it' ),
Array ()
),
Array (
Array (),
null,
Array ( 'it' ),
Array ()
),
Array (
Array ( 1 ),
Array ( 1 ),
Array (),
Array ( 'it', 'val' )
),
Array (
Array ( 1, 2 ),
Array ( 1, 2 ),
Array (),
Array ( 'it', 'val' )
),
Array (
Array ( 1, 2, 3 ),
Array ( 1, 2 ),
Array (),
Array ( 'it', 'val' )
),
Array (
Array ( 'hello', 'world' ),
null,
Array ( 'flag' => 'world', 'it' ),
Array ()
),
Array (
Array ( 'hello', 1, 'world' ),
Array ( 1 => 1 ),
Array ( 'flag' => 'world' ),
Array ( 'it', 'val' )
),
Array (
Array ( 'hello', 1, 'world', 2 ),
Array ( 1 => 1, 3 => 2 ),
Array ( 'flag' => 'world' ),
Array ( 'it', 'val' )
),
Array (
Array ( 1, 'hello', 2, 'world', 3 ),
Array ( 0 => 1, 2 => 2 ),
Array ( 'flag' => 'hello' ),
Array ( 'it', 'val' )
),
);
}
/**
* @dataProvider provideValidatingConstrainedIterator
*
* @covers MapFilter_TreePattern_Tree_Iterator
*/
public function testValidatingConstrainedIterator (
$query, $result, $asserts, $flags
) {
$pattern = MapFilter_TreePattern_Xml::load ( '
<pattern>
<!-- [TreePattern_Iterator] -->
<iterator flag="it" assert="it" min="1" max="2">
<value flag="val" assert="flag" pattern="/^\d+$/"/>
</iterator>
<!-- [TreePattern_Iterator] -->
</pattern>
' );
$this->assertResultsEquals ( $pattern, $query, $result, $asserts, $flags );
}
public function provideExactlyConstrainedIterator () {
return Array (
Array (
null,
null,
Array ( 'it' ),
Array ()
),
Array (
Array (),
null,
Array ( 'it' ),
Array ()
),
Array (
Array ( 1 ),
null,
Array ( 'it' ),
Array ()
),
Array (
Array ( 1, 2 ),
Array ( 1, 2 ),
Array (),
Array ( 'it', 'val' )
),
Array (
Array ( 1, 2, 3 ),
Array ( 1, 2 ),
Array (),
Array ( 'it', 'val' )
),
Array (
Array ( 'hello world' ),
null,
Array ( 'flag' => 'hello world', 'it' ),
Array ()
),
Array (
Array ( 'hello', 'world' ),
null,
Array ( 'flag' => 'world', 'it' ),
Array ()
),
// TODO
// Sets the last failing assert value
// it should probably be the first one or all of them
Array (
Array ( 'hello', 1, 'world' ),
null,
Array ( 'flag' => 'world', 'it' ),
Array ()
),
Array (
Array ( 'hello', 1, 'world', 2 ),
Array ( 1 => 1, 3 => 2 ),
Array ( 'flag' => 'world' ),
Array ( 'it', 'val' )
),
Array (
Array ( 1, 'hello', 2, 'world', 3 ),
Array ( 0 => 1, 2 => 2 ),
Array ( 'flag' => 'hello' ),
Array ( 'it', 'val' )
),
);
}
/**
* @dataProvider provideExactlyConstrainedIterator
*
* @covers MapFilter_TreePattern_Tree_Iterator
*/
public function testExactlyConstrainedIterator (
$query, $result, $asserts, $flags
) {
$pattern = MapFilter_TreePattern_Xml::load ( '
<pattern>
<iterator flag="it" assert="it" min="2" max="2">
<value flag="val" assert="flag" pattern="/\d/"/>
</iterator>
</pattern>
' );
$this->assertResultsEquals ( $pattern, $query, $result, $asserts, $flags );
}
public function provideBinaryTree () {
return Array (
Array ( 42, 42 ),
Array (
Array ( 42, 43 ),
Array ( 42, 43 ),
Array (),
Array ( 'has_node' )
),
Array (
Array ( Array ( 42, 43 ), 44 ),
Array ( Array ( 42, 43 ), 44 ),
Array (),
Array ( 'has_node' )
),
Array (
Array ( 42, Array ( 43, 44 ) ),
Array ( 42, Array ( 43, 44 ) ),
Array (),
Array ( 'has_node' )
),
Array (
Array ( Array ( 42, 43 ), Array ( 44, 45 ) ),
Array ( Array ( 42, 43 ), Array ( 44, 45 ) ),
Array (),
Array ( 'has_node' )
),
Array (
Array ( Array ( Array ( 42, 43 ), 44 ), 45 ),
Array ( Array ( Array ( 42, 43 ), 44 ), 45 ),
Array (),
Array ( 'has_node' )
),
Array (
Array ( 42, Array ( 43, Array ( 44, 45 ) ) ),
Array ( 42, Array ( 43, Array ( 44, 45 ) ) ),
Array (),
Array ( 'has_node' )
),
// Errors
Array (
'asdf',
null,
Array ( 'invalid_leaf' => 'asdf' )
),
Array (
Array ( 'asdf', 42 ),
null,
Array ( 'invalid_leaf' => 'asdf' )
),
Array (
Array ( 42, 'asdf' ),
null,
Array ( 'invalid_leaf' => 'asdf' )
),
Array (
Array ( 'first', 'second' ),
null,
Array ( 'invalid_leaf' => 'second' )
),
Array (
Array ( 42, 43, 44 ),
Array ( 42, 43 ),
Array (),
Array ( 'has_node' )
),
Array (
Array ( 42 ),
null,
),
Array (
Array ( Array ( 42, 43 ), Array ( 44, 45 ), Array ( 46, 47 ) ),
Array ( Array ( 42, 43 ), Array ( 44, 45 ) ),
Array (),
Array ( 'has_node' )
),
Array (
Array ( Array ( 42 ) ),
null,
),
);
}
/**
* @dataProvider provideBinaryTree
*
* @covers MapFilter_TreePattern_Tree_Iterator
*/
public function testBinaryTree (
$query, $result, $asserts = Array (), $flags = Array ()
) {
$pattern = MapFilter_TreePattern_Xml::load ( '
<!-- [TreePattern_RecursiveIterator] -->
<pattern name="main">
<one>
<iterator flag="has_node" min="2" max="2" attachPattern="main" />
<value pattern="/.*/">
<value assert="invalid_leaf" pattern="/\d/" />
</value>
</one>
</pattern>
<!-- [TreePattern_RecursiveIterator] -->
' );
$this->assertResultsEquals ( $pattern, $query, $result, $asserts, $flags );
}
}
| olivergondza/MapFilter_TreePattern | tests/Unit/Tree/Iterator.test.php | PHP | lgpl-3.0 | 23,226 |
<?php
// This file is shared between server and recorder and should be kept identical in both projects.
// Specialized loggers for each are implemented with this one as base.
// example :
// $logger->log(EventType::RECORDER_UPLOAD_TO_EZCAST, LogLevel::ERROR, "Couldn't get info from slide module. Slides will be ignored", array("cli_process_upload"), $asset);
require_once("logger_event_type.php");
/**
*
* Describes log levels. Frm PSR-3 Logger Interface. (http://www.php-fig.org/psr/psr-3/)
*/
class LogLevel
{
/**
* System is unusable.
*/
const EMERGENCY = 'emergency';
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*/
const ALERT = 'alert';
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*/
const CRITICAL = 'critical';
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*/
const ERROR = 'error';
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*/
const WARNING = 'warning';
/**
* Normal but significant events.
*/
const NOTICE = 'notice';
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*/
const INFO = 'info';
/**
* Detailed debug information.
* Those are not sent to server from recorders if $send_debug_logs_to_server is disabled (recorder global config)
*/
const DEBUG = 'debug';
/**
* Return log level given in the form of LogLevel::* into an integer
*/
static function get_log_level_integer($log_level) {
return LogLevel::$log_levels[$log_level];
}
// index by LogLevel
static $log_levels = array(
LogLevel::EMERGENCY => 0,
LogLevel::ALERT => 1,
LogLevel::CRITICAL => 2,
LogLevel::ERROR => 3,
LogLevel::WARNING => 4,
LogLevel::NOTICE => 5,
LogLevel::INFO => 6,
LogLevel::DEBUG => 7
);
}
/* This structure is used to pass temporary results from the `log` parent function to its child.
* Feel free to change it if you find another more elegant solution.
*/
class LogData {
public $log_level_integer = null;
public $type_id = null;
public $context = null;
}
//Log serverside structure for db insertion using the ezmanager services
class ServersideLogEntry {
public $id = 0;
public $asset = "";
public $origin = "";
public $asset_classroom_id = null;
public $asset_course = null;
public $asset_author = null;
public $asset_cam_slide = null;
public $event_time;
public $type_id = 0;
public $context = "";
public $loglevel = 7;
public $message = "";
}
abstract class Logger {
/* Reverted EventType array -> key: id, value: EventType
* Filled at Logger construct.
*/
public static $event_type_by_id = false;
//set this to true to echo all logs
public static $print_logs = false;
/*
* Reverted LogLevel array -> key: id, value: LogLevel name (string)
* Filled at Logger construct
*/
public static $log_level_name_by_id = false;
protected function __construct() {
$this->fill_event_type_by_id();
$this->fill_level_name_by_id();
}
public function get_type_name($index)
{
if(isset(Logger::$event_type_by_id[$index]))
return Logger::$event_type_by_id[$index];
else
return false;
}
public function get_log_level_name($index)
{
if(isset(Logger::$log_level_name_by_id[$index]))
return Logger::$log_level_name_by_id[$index];
else
return false;
}
/**
* Logs with an arbitrary level.
*
* @param mixed $type type in the form of EventType::*
* @param mixed $level in the form of LogLevel::*
* @param string $message
* @param string $asset asset identifier
* @param array $context Additional context info. Context can have several levels, such as array('module', 'capture_ffmpeg').
* @param string $asset asset name
* @param AssetLogInfo $asset_info Additional information about asset if any, in the form of a AssetLogInfo structure
* @return LogData temporary data, used by children functions
*/
protected function _log(&$type, &$level, &$message, array &$context = array(), &$asset = "dummy",
&$author = null, &$cam_slide = null, &$course = null, &$classroom = null)
{
global $debug_mode;
global $service;
if(!isset($message) || !$message)
$message = "";
if(!isset($asset) || !$asset)
$asset = "dummy";
$tempLogData = new LogData();
//limit string size
$message = substr($message, 0, 1000);
// convert given loglevel to integer for db storage
try {
$tempLogData->log_level_integer = LogLevel::get_log_level_integer($level);
} catch (Exception $e) {
//invalid level given, default to "error" and prepend this problem to the message
$message = "(Invalid log level) " . $message;
$tempLogData->log_level_integer = LogLevel::$log_levels[LogLevel::ERROR];
}
//convert given type_id to integer for db storage
$tempLogData->type_id = isset(EventType::$event_type_id[$type]) ? EventType::$event_type_id[$type] : 0;
if(!isset($author))
$author = "";
if(!isset($cam_slide))
$cam_slide = "";
if(!isset($course))
$course = "";
if(!isset($classroom))
$classroom = "";
// pipes will be used as seperator between contexts
// concat contexts for db insert
$tempLogData->context = implode('|', $context);
// okay, all data ready
$print_str = "log| [$level] / context: $tempLogData->context / type: $type / " . $message;
if(Logger::$print_logs)
echo $print_str . PHP_EOL;
if($debug_mode
&& $type != EventType::PHP //PHP events are already printed in custom_error_handling.php
&& (!isset($service) || $service == false) //some services will try to parse the response, and our <script> may interfere in this case
&& php_sapi_name() != "cli") //don't print in CLI
{
$sanitized_str = addslashes(htmlspecialchars($print_str));
echo("<script>console.log(\"$sanitized_str\");</script>");
}
//idea: if level is critical or below, add strack trace to message
return $tempLogData;
}
// -- PROTECTED
// ----------
//fill $event_type_by_id from $event_type_id
protected function fill_event_type_by_id()
{
if(Logger::$event_type_by_id == false) {
Logger::$event_type_by_id = array();
foreach(EventType::$event_type_id as $key => $value) {
Logger::$event_type_by_id[$value] = $key;
}
}
return Logger::$event_type_by_id;
}
//fill $log_level_name_by_id from $log_levels
protected function fill_level_name_by_id()
{
if(Logger::$log_level_name_by_id == false) {
Logger::$log_level_name_by_id = array();
foreach(LogLevel::$log_levels as $key => $value) {
Logger::$log_level_name_by_id[$value] = $key;
}
}
return Logger::$log_level_name_by_id;
}
} | ulbpodcast/ezrecorder | logger.php | PHP | lgpl-3.0 | 7,928 |
/**
* Copyright (c) 2010-2012, Vincent Vollers and Christopher J. Kucera
* 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 Minecraft X-Ray team 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 VINCENT VOLLERS OR CJ KUCERA 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.
*/
package de.keyle.dungeoncraft.editor.editors.world.render.dialog;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.metal.MetalBorders.TextFieldBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class WarningDialog extends JFrame {
private static final long serialVersionUID = 1185056716578355842L;
private static final int FRAMEWIDTH = 400;
private static final int FRAMEHEIGHT = 250;
private JCheckBox showCheckbox;
private JButton okButton;
private GridBagLayout gridBagLayoutManager;
private JScrollPane mainLabel;
public static boolean selectedShow;
public static Image iconImage;
/**
* Centers this dialog on the screen
*/
private void centerDialogOnScreen() {
Toolkit t = Toolkit.getDefaultToolkit();
Dimension screenSize = t.getScreenSize();
int x = (screenSize.width / 2) - (this.getWidth() / 2);
int y = (screenSize.height / 2) - (this.getHeight() / 2);
gridBagLayoutManager = new GridBagLayout();
this.setLocation(x, y);
this.setAlwaysOnTop(true);
}
/**
* Layouts all the controls and labels on the dialog using a gridbaglayout
*/
private void layoutControlsOnDialog(boolean showCheckboxBool) {
JPanel basicPanel = new JPanel();
this.getContentPane().setLayout(gridBagLayoutManager);
basicPanel.setLayout(gridBagLayoutManager);
GridBagConstraints c = new GridBagConstraints();
JLabel headerLabel = new JLabel("Warning");
headerLabel.setFont(new Font("Arial", Font.BOLD, 18));
int current_grid_y = 0;
c.insets = new Insets(5, 5, 5, 5);
c.weighty = .1f;
// Checkbox to see if we'll show this warning in the future
showCheckbox = new JCheckBox("Show this warning next time");
showCheckbox.setSelected(true);
// Now actually add the buttons
c.insets = new Insets(5, 5, 5, 5);
c.gridx = 0;
c.gridwidth = 1;
c.weightx = 1f;
c.weighty = 0f;
c.anchor = GridBagConstraints.CENTER;
current_grid_y++;
c.gridy = current_grid_y;
addComponent(basicPanel, headerLabel, c);
current_grid_y++;
c.gridy = current_grid_y;
c.anchor = GridBagConstraints.NORTHWEST;
c.weighty = 1f;
c.fill = GridBagConstraints.BOTH;
addComponent(basicPanel, mainLabel, c);
if (showCheckboxBool) {
current_grid_y++;
c.gridy = current_grid_y;
c.weighty = 0f;
c.weightx = 1f;
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.NONE;
addComponent(basicPanel, showCheckbox, c);
}
// Add our JPanel to the window
c.weightx = 1.0f;
c.weighty = .1f;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
addComponent(this.getContentPane(), basicPanel, c);
// Now add the button
c.insets = new Insets(5, 15, 5, 15);
c.gridwidth = 1;
c.weightx = 1f;
c.weighty = 0f;
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.SOUTHEAST;
c.fill = GridBagConstraints.HORIZONTAL;
addComponent(this.getContentPane(), okButton, c);
}
/**
* Adds a component to the container and updates the constraints for that component
*
* @param root The contiainer to add the component to
* @param comp The component to add to the container
* @param constraints The constraints which affect the component
*/
private void addComponent(Container root, Component comp, GridBagConstraints constraints) {
gridBagLayoutManager.setConstraints(comp, constraints);
root.add(comp);
}
/**
* Builds the OK Button and attaches the actions to it
*/
private void buildButtons(String warningText) {
JRootPane rootPane = this.getRootPane();
// The "Jump" button
okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogOK();
}
});
// Key mapping for the OK button
KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(enterStroke, "ENTER");
KeyStroke escapeStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeStroke, "ENTER");
rootPane.getActionMap().put("ENTER", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
dialogOK();
}
});
// Main label
JTextArea labelArea = new JTextArea(warningText);
labelArea.setLineWrap(true);
labelArea.setWrapStyleWord(true);
labelArea.setEditable(false);
labelArea.setMargin(new Insets(8, 8, 8, 8));
labelArea.setBorder(new CompoundBorder(new TextFieldBorder(), new EmptyBorder(6, 6, 6, 6)));
mainLabel = new JScrollPane(labelArea);
mainLabel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
mainLabel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
}
/**
* Actions to perform if the "OK" button is hit, or otherwise triggered.
*/
private void dialogOK() {
setSelectedValues();
setVisible(false);
dispose();
synchronized (WarningDialog.this) {
WarningDialog.this.notify();
}
}
/**
* Sets the selected values to the static properties of this resolution dialog
*/
private void setSelectedValues() {
WarningDialog.selectedShow = this.showCheckbox.isSelected();
}
/**
* Creates a new WarningDialog
*
* @param windowName the title of the dialog
*/
protected WarningDialog(String windowName, String warningText, boolean showCheckbox, int width, int height) {
super(windowName);
if (WarningDialog.iconImage != null) {
this.setIconImage(WarningDialog.iconImage);
}
this.setSize(width, height);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setMinimumSize(new Dimension(width, height));
centerDialogOnScreen();
buildButtons(warningText);
layoutControlsOnDialog(showCheckbox);
validate();
this.setVisible(true);
}
/**
* Pops up the dialog window
*
* @param windowName the title of the dialog
*/
public static void presentDialog(String windowName, String warningText) {
presentDialog(windowName, warningText, true, FRAMEWIDTH, FRAMEHEIGHT);
}
/**
* Pops up the dialog window
*
* @param windowName the title of the dialog
*/
public static void presentDialog(String windowName, String warningText, boolean showCheckbox, int width, int height) {
final WarningDialog dialog = new WarningDialog(windowName, warningText, showCheckbox, width, height);
try {
dialog.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} | xXKeyleXx/DungeonCraft-Editor | src/main/java/de/keyle/dungeoncraft/editor/editors/world/render/dialog/WarningDialog.java | Java | lgpl-3.0 | 9,176 |
// Written by Jรผrgen Moรgraber - mossgrabers.de
// (c) 2017-2022
// Licensed under LGPLv3 - http://www.gnu.org/licenses/lgpl-3.0.txt
package de.mossgrabers.framework.daw;
import de.mossgrabers.framework.daw.data.IParameter;
import de.mossgrabers.framework.observer.IObserverManagement;
/**
* Interface to a DAW project.
*
* @author Jürgen Moßgraber
*/
public interface IProject extends IObserverManagement
{
/**
* Get the name of the active project.
*
* @return The name
*/
String getName ();
/**
* Switch to the previous open project.
*/
void previous ();
/**
* Switch to the next open project.
*/
void next ();
/**
* Creates a new empty scene as the last scene in the project.
*
* @since API version 13
*/
void createScene ();
/**
* Creates a new scene (using an existing empty scene if possible) from the clips that are
* currently playing in the clip launcher.
*/
void createSceneFromPlayingLauncherClips ();
/**
* Save the current project.
*/
void save ();
/**
* Show the load project dialog.
*/
void load ();
/**
* Get the cue mix parameter.
*
* @return The cue mix parameter
*/
IParameter getCueMixParameter ();
/**
* Get the cue volume as a formatted text.
*
* @return The cue volume text
*/
String getCueVolumeStr ();
/**
* Get the cue volume as a formatted text.
*
* @param limit Limit the text to this length
* @return The cue volume text
*/
String getCueVolumeStr (int limit);
/**
* Get the cue volume.
*
* @return The cue volume
*/
int getCueVolume ();
/**
* Change the cue volume.
*
* @param control The control value
*/
void changeCueVolume (int control);
/**
* Set the cue volume.
*
* @param value The new value
*/
void setCueVolume (int value);
/**
* Reset the cue volume to its default value.
*/
void resetCueVolume ();
/**
* Signal that the cue volume fader/knob is touched for automation recording.
*
* @param isBeingTouched True if touched
*/
void touchCueVolume (boolean isBeingTouched);
/**
* Get the cue volume parameter.
*
* @return The cue volume parameter
*/
IParameter getCueVolumeParameter ();
/**
* Get the cue mix as a formatted text
*
* @return The cue mix text
*/
String getCueMixStr ();
/**
* Get the cue mix as a formatted text
*
* @param limit Limit the text to this l@Override ength
* @return The cue mix text
*/
String getCueMixStr (int limit);
/**
* Get the cue mix.
*
* @return The cue mix
*/
int getCueMix ();
/**
* Change the cue mix.
*
* @param control The control value
*/
void changeCueMix (int control);
/**
* Set the cue mix.
*
* @param value The new value
*/
void setCueMix (int value);
/**
* Reset the cue mix to its default value.
*/
void resetCueMix ();
/**
* Signal that the cue mix fader/knob is touched for automation recording.
*
* @param isBeingTouched True if touched
*/
void touchCueMix (boolean isBeingTouched);
/**
* Check if any of the tracks is soloed.
*
* @return True if there is at least one soloed track
*/
boolean hasSolo ();
/**
* Check if any of the tracks is muted.
*
* @return True if there is at least one muted track
*/
boolean hasMute ();
/**
* Deactivate all solo states of all tracks.
*/
void clearSolo ();
/**
* Deactivate all mute states of all tracks.
*/
void clearMute ();
}
| git-moss/DrivenByMoss | src/main/java/de/mossgrabers/framework/daw/IProject.java | Java | lgpl-3.0 | 4,126 |
<?php
/* @var $this TacheController */
/* @var $model Tache */
/* @var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'tache-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Les champs avec <span class="required">*</span> sont obligatoires. </p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'nom'); ?>
<?php echo $form->textField($model,'nom',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'nom'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textField($model,'description',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'date_limite'); ?>
<?php echo CHtml::activeTextField($model,'date_limite',array('size'=>10,"id"=>"date_limite")); ?>
<?php $this->widget('application.extensions.calendar.SCalendar',
array(
'inputField'=>'date_limite',
'ifFormat'=>'%H:%M %Y-%m-%d',
'showsTime'=>true,
'range'=>"[1880,2025]"
));
?>
<?php echo $form->error($model,'date_limite'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Crรฉer' : 'Enregistrer'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form --> | nmalservet/ebiose | ebiose/protected/views/tache/_form.php | PHP | lgpl-3.0 | 1,434 |
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2011, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
/**
* ่ๆๆบMIPSๅ้
ๅๅฒ
* The Class VmMipsAllocationHistoryEntry.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.1.2
*/
public class VmStateHistoryEntry {
/** The time. */
private double time;
/** ๅ้
็MIPS The allocated mips. */
private double allocatedMips;
/** ่ฏทๆฑ็MIPS The requested mips. */
private double requestedMips;
/** ๆฏๅฆๅจ่ฟ็งป็่ๆๆบไธญ The is in migration. */
private boolean isInMigration;
/**
* Instantiates a new vm mips allocation history entry.
*
* @param time the time
* @param allocatedMips the allocated mips
* @param requestedMips the requested mips
* @param isInMigration the is in migration
*/
public VmStateHistoryEntry(double time, double allocatedMips, double requestedMips, boolean isInMigration) {
setTime(time);
setAllocatedMips(allocatedMips);
setRequestedMips(requestedMips);
setInMigration(isInMigration);
}
/**
* Sets the time.
*
* @param time the new time
*/
protected void setTime(double time) {
this.time = time;
}
/**
* Gets the time.
*
* @return the time
*/
public double getTime() {
return time;
}
/**
* Sets the allocated mips.
*
* @param allocatedMips the new allocated mips
*/
protected void setAllocatedMips(double allocatedMips) {
this.allocatedMips = allocatedMips;
}
/**
* Gets the allocated mips.
*
* @return the allocated mips
*/
public double getAllocatedMips() {
return allocatedMips;
}
/**
* Sets the requested mips.
*
* @param requestedMips the new requested mips
*/
protected void setRequestedMips(double requestedMips) {
this.requestedMips = requestedMips;
}
/**
* Gets the requested mips.
*
* @return the requested mips
*/
public double getRequestedMips() {
return requestedMips;
}
/**
* Sets the in migration.
*
* @param isInMigration the new in migration
*/
protected void setInMigration(boolean isInMigration) {
this.isInMigration = isInMigration;
}
/**
* Checks if is in migration.
*
* @return true, if is in migration
*/
public boolean isInMigration() {
return isInMigration;
}
}
| demiaowu/annotation-of-cloudsim3.0.3 | sources/org/cloudbus/cloudsim/VmStateHistoryEntry.java | Java | lgpl-3.0 | 2,561 |
package com.inspirationlogical.receipt.waiter.controller.reatail.sale.buttons;
import de.felixroske.jfxsupport.AbstractFxmlView;
import de.felixroske.jfxsupport.FXMLView;
import org.springframework.context.annotation.Scope;
@FXMLView(value = "/view/fxml/BackButtonElement.fxml", bundle = "properties/waiter_hu.properties")
@Scope("prototype")
public class BackButtonFxmlView extends AbstractFxmlView {
}
| iplogical/res | app/waiter/src/main/java/com/inspirationlogical/receipt/waiter/controller/reatail/sale/buttons/BackButtonFxmlView.java | Java | lgpl-3.0 | 406 |
<?php
/***************************************************************\
| |
| apexx CMS & Portalsystem |
| ============================ |
| (c) Copyright 2005-2009, Christian Scheb |
| http://www.stylemotion.de |
| |
|---------------------------------------------------------------|
| THIS SOFTWARE IS NOT FREE! MAKE SURE YOU OWN A VALID LICENSE! |
| DO NOT REMOVE ANY COPYRIGHTS WITHOUT PERMISSION! |
| SOFTWARE BELONGS TO ITS AUTHORS! |
\***************************************************************/
# MAIN CLASS
# ==========
//Security-Check
if ( !defined('APXRUN') ) die('You are not allowed to execute this file directly!');
class action {
//STARTUP
function __construct() {
//Code um die Explorer-Leiste zu aktualisieren
$this->refresh=<<<CODE
<script language="JavaScript" type="text/javascript">
<!--
top.frames[0].window.location.reload();
//-->
</script>
CODE;
}
//***************************** Index-Seite *****************************
function index() {
global $set,$apx,$db;
//Ist der Nutzer angemeldet?
if ( !$apx->user->info['userid'] ) {
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=user.login');
return;
}
//Online-Liste
list($online)=$db->first("SELECT count(userid) FROM ".PRE."_user LEFT JOIN ".PRE."_user_groups USING(groupid) WHERE ( gtype IN ('admin','indiv') AND lastactive>='".(time()-$apx->user->timeout*60)."' )");
$data=$db->fetch("SELECT username FROM ".PRE."_user LEFT JOIN ".PRE."_user_groups USING(groupid) WHERE ( gtype IN ('admin','indiv') AND lastactive>='".(time()-$apx->user->timeout*60)."' ) ORDER BY username ASC");
foreach ( $data AS $res ) {
$usernames[]=$res['username'];
}
$apx->tmpl->assign('ONLINE_COUNT',$online);
$apx->tmpl->assign('ONLINE',implode(', ',$usernames));
//Benutzer-Informationen
list($groupname)=$db->first("SELECT name FROM ".PRE."_user_groups WHERE groupid='".$apx->user->info['groupid']."' LIMIT 1");
$apx->tmpl->assign('USERID',$apx->user->info['userid']);
$apx->tmpl->assign('USERNAME_LOGIN',replace($apx->user->info['username_login']));
$apx->tmpl->assign('USERNAME',replace($apx->user->info['username']));
$apx->tmpl->assign('EMAIL',replace($apx->user->info['email']));
$apx->tmpl->assign('GROUP',replace($groupname));
$apx->tmpl->assign('SESSION',mkdate($apx->user->info['lastonline']));
$apx->tmpl->assign('VERSION',VERSION);
$apx->tmpl->assign('MODULES',count($apx->modules));
$apx->tmpl->parse('index');
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Module *****************************
function mshow() {
global $set,$apx,$db,$html;
//Navi aktualisieren
if ( $_REQUEST['resetnav'] ) {
echo $this->refresh;
}
//Liste aktualisieren
if ( $_REQUEST['do']=='refresh' ) {
$this->mshow_refresh();
return;
}
//Alle Modul-Informationen einlesen
$regmods=$this->get_modinfo();
//Module, die nicht aktiv sind -> Sprachpaket laden
foreach ( $regmods AS $modulename => $module ) {
if ( in_array($modulename,$apx->coremodules) ) continue;
$apx->lang->module_load($modulename);
}
$apx->lang->dropall('modulename');
echo'<p class="slink">» <a href="action.php?action=main.mshow&do=refresh">'.$apx->lang->get('REFRESH').'</a></p>';
$col[]=array('',1,'align="center"');
$col[]=array('COL_TITLE',70,'class="title"');
$col[]=array('COL_ID',30,'align="center"');
//STATISCHE MODULE
foreach ( $apx->coremodules AS $modulename ) {
++$i;
$module=$regmods[$modulename];
$tabledata[$i]['ID']=$modulename;
$tabledata[$i]['COL1']='<img src="design/greendot.gif" alt="'.$apx->lang->get('CORE_ACTIVE').'" title="'.$apx->lang->get('CORE_ACTIVE').'" />';
$tabledata[$i]['COL2']=$apx->lang->get('MODULENAME_'.strtoupper($modulename));
$tabledata[$i]['COL3']=$modulename;
$alert=$apx->lang->get('TITLE').': '.$apx->lang->get('MODULENAME_'.strtoupper($modulename)).'\n';
$alert.=$apx->lang->get('AUTHOR').': '.$module['author'].'\n';
$alert.=$apx->lang->get('CONTACT').': '.$module['contact'].'\n';
$alert.=$apx->lang->get('DEPENDENCE').': ';
if ( is_array($module['dependence']) && count($module['dependence']) ) $alert.=@implode(', ',$module['dependence']);
else $alert.=$apx->lang->get('NO');
if ( is_array($module['requirement']) && count($module['requirement']) ) {
$alert.='\n\n';
$alert.=$apx->lang->get('REQUIREMENTS').': ';
$ri = 0;
foreach ( $module['requirement'] AS $reqModule => $reqVersion ) {
++$ri;
if ( $ri>1 ) {
$alert.= ', ';
}
$alert.= $apx->lang->get('MODULENAME_'.strtoupper($reqModule)).' ('.$reqVersion.')';
}
}
$alert.='\n\n';
$alert.=$apx->lang->get('INSTALLEDVERSION').': '.$module['installed_version_dotted'].'\n';
$alert.=$apx->lang->get('CURRENTVERSION').': '.$module['current_version_dotted'];
if ( $module['installed_version']<$module['current_version'] ) $alert.='\n'.$apx->lang->get('UPDATEREQUIRED');
//Optionen
$tabledata[$i]['OPTIONS'].='<a href="javascript:void(0)" onclick="alert(\''.$alert.'\')"><img src="design/info.gif" alt="" style="vertical-align:middle;" /></a>';
$tabledata[$i]['OPTIONS'].='<img src="design/ispace.gif" alt="" />';
//Aktualisieren
if ( file_exists(BASEDIR.getmodulepath($modulename).'setup.php') ) {
if ( $module['installed'] && $module['installed_version']<$module['current_version'] && $this->checkRequirement($module, $regmods) && $apx->user->has_right('main.mupdate') ) $tabledata[$i]['OPTIONS'].=optionHTMLOverlay('update.gif', 'main.mupdate', 'module='.$modulename, $apx->lang->get('UPDATE'));
else $tabledata[$i]['OPTIONS'].='<img src="design/ispace.gif" alt="" />';
}
if ( $apx->user->has_right('main.mconfig') ) $tabledata[$i]['OPTIONS'].=optionHTML('config.gif', 'main.mconfig', 'module='.$modulename, $apx->lang->get('CONFIG'));
else $tabledata[$i]['OPTIONS'].='<img src="design/ispace.gif" alt="" />';
unset($module,$action);
}
//ZUSATZ-MODULE
if ( count($regmods) ) {
//Spacer
$tabledata[$i+1]['SPACER']=true;
foreach ( $regmods AS $modulename => $module ) {
if ( in_array($modulename,$apx->coremodules) ) continue;
++$i;
if ( $module['active'] ) $tabledata[$i]['COL1']='<img src="design/greendot.gif" alt="'.$apx->lang->get('CORE_ACTIVE').'" title="'.$apx->lang->get('CORE_ACTIVE').'" />';
else $tabledata[$i]['COL1']='<img src="design/reddot.gif" alt="'.$apx->lang->get('CORE_INACTIVE').'" title="'.$apx->lang->get('CORE_INACTIVE').'" />';
$tabledata[$i]['ID']=$modulename;
$tabledata[$i]['COL2']=$apx->lang->get('MODULENAME_'.strtoupper($modulename));
$tabledata[$i]['COL3']=$modulename;
$alert=$apx->lang->get('TITLE').': '.$apx->lang->get('MODULENAME_'.strtoupper($modulename)).'\n';
$alert.=$apx->lang->get('AUTHOR').': '.$module['author'].'\n';
$alert.=$apx->lang->get('CONTACT').': '.$module['contact'].'\n';
$alert.=$apx->lang->get('DEPENDENCE').': ';
if ( is_array($module['dependence']) && count($module['dependence']) ) $alert.=@implode(', ',$module['dependence']);
else $alert.=$apx->lang->get('NO');
if ( is_array($module['requirement']) && count($module['requirement']) ) {
$alert.='\n\n';
$alert.=$apx->lang->get('REQUIREMENTS').': ';
$ri = 0;
foreach ( $module['requirement'] AS $reqModule => $reqVersion ) {
++$ri;
if ( $ri>1 ) {
$alert.= ', ';
}
$alert.= $apx->lang->get('MODULENAME_'.strtoupper($reqModule)).' ('.$reqVersion.')';
}
}
$alert.='\n\n';
$alert.=$apx->lang->get('INSTALLEDVERSION').': '.$module['installed_version_dotted'].'\n';
$alert.=$apx->lang->get('CURRENTVERSION').': '.$module['current_version_dotted'];
if ( $module['installed_version']<$module['current_version'] ) $alert.='\n'.$apx->lang->get('UPDATEREQUIRED');
//Optionen
$tabledata[$i]['OPTIONS'].='<a href="javascript:void(0)" onclick="alert(\''.$alert.'\')"><img src="design/info.gif" alt="" style="vertical-align:middle;" /></a>';
//Aktivieren/Deaktivieren
if ( $module['active'] ) $tabledata[$i]['OPTIONS'].=optionHTMLOverlay('disable.gif', 'main.mdisable', 'module='.$modulename, $apx->lang->get('CORE_DISABLE'));
elseif ( !$module['active'] && $module['installed'] ) $tabledata[$i]['OPTIONS'].=optionHTMLOverlay('enable.gif', 'main.menable', 'module='.$modulename, $apx->lang->get('CORE_ENABLE'));
else $tabledata[$i]['OPTIONS'].='<img src="design/ispace.gif" alt="" />';
//Installieren/Aktualisieren/Deinstallieren
if ( file_exists(BASEDIR.getmodulepath($modulename).'setup.php') ) {
if ( !$module['installed'] && $this->checkRequirement($module, $regmods) && $apx->user->has_right('main.minstall') ) $tabledata[$i]['OPTIONS'].=optionHTMLOverlay('install.gif', 'main.minstall', 'module='.$modulename, $apx->lang->get('INSTALL'));
elseif ( $module['installed'] && $module['installed_version']<$module['current_version'] && $this->checkRequirement($module, $regmods) && $apx->user->has_right('main.mupdate') ) $tabledata[$i]['OPTIONS'].=optionHTMLOverlay('update.gif', 'main.mupdate', 'module='.$modulename, $apx->lang->get('UPDATE'));
elseif ( $module['installed'] && !$module['active'] && $apx->user->has_right('main.muninstall') ) $tabledata[$i]['OPTIONS'].=optionHTMLOverlay('uninstall.gif', 'main.muninstall', 'module='.$modulename, $apx->lang->get('UNINSTALL'));
else $tabledata[$i]['OPTIONS'].='<img src="design/ispace.gif" alt="" />';
}
else $tabledata[$i]['OPTIONS'].='<img src="design/ispace.gif" alt="" />';
if ( $apx->user->has_right('main.mconfig') && $module['installed'] && $module['active'] ) $tabledata[$i]['OPTIONS'].=optionHTML('config.gif', 'main.mconfig', 'module='.$modulename, $apx->lang->get('CONFIG'));
else $tabledata[$i]['OPTIONS'].='<img src="design/ispace.gif" alt="" />';
}
}
$multiactions = array();
if ( $apx->user->has_right('main.menable') ) $multiactions[] = array($apx->lang->get('CORE_ENABLE'), 'action.php?action=main.menable', false);
if ( $apx->user->has_right('main.mdisable') ) $multiactions[] = array($apx->lang->get('CORE_DISABLE'), 'action.php?action=main.mdisable', false);
if ( $apx->user->has_right('main.minstall') ) $multiactions[] = array($apx->lang->get('INSTALL'), 'action.php?action=main.minstall', false);
if ( $apx->user->has_right('main.muninstall') ) $multiactions[] = array($apx->lang->get('UNINSTALL'), 'action.php?action=main.muninstall', false);
if ( $apx->user->has_right('main.mupdate') ) $multiactions[] = array($apx->lang->get('UPDATE'), 'action.php?action=main.mupdate', false);
$apx->tmpl->assign('TABLE', $tabledata);
$html->table($col, $multiactions);
}
//REGISTRIERTE MODULE -> INFO AUSLESEN
function get_modinfo($module=false) {
global $set,$apx,$db;
//Ein Modul
if ( $module ) {
$res=$db->first("SELECT * FROM ".PRE."_modules WHERE module='".addslashes($module)."' LIMIT 1");
return $this->regmod_readout($res);
}
//Alle
else {
$data=$db->fetch("SELECT * FROM ".PRE."_modules ORDER BY module");
if ( !count($data) ) return array();
foreach ( $data AS $res ) {
$feedback=$this->regmod_readout($res);
if ( $feedback===false ) continue;
$mods[$res['module']]=$feedback;
}
return $mods;
}
}
//INFO VERARBEITEN
function regmod_readout($res) {
$modulename=$res['module'];
if ( !file_exists(BASEDIR.getmodulepath($modulename).'init.php') ) return false;
include(BASEDIR.getmodulepath($modulename).'init.php');
$info=$module;
$info['active']=$res['active'];
$info['installed']=$res['installed'];
$info['installed_version']=$res['version'];
$info['current_version']=intval(str_replace('.','',$info['version']));
$info['installed_version_dotted']=$res['version'][0].'.'.$res['version'][1].'.'.$res['version'][2];
$info['current_version_dotted']=$info['version'];
//unset($info['version']);
//Aktualisierbare Versionen
if ( !isset($info['updateable']) ) {
$info['updateable']=array();
}
elseif ( is_array($info['updateable']) ) {
foreach ( $info['updateable'] AS $key => $version ) {
$info['updateable'][$key]=intval(str_replace('.','',$version));
}
}
else {
$temp=array(intval(str_replace('.','',$info['updateable'])));
$info['updateable']=$temp;
}
return $info;
}
//Anforderungen prรผfen
function checkRequirement($module, $allmodules) {
if ( !is_array($module['requirement']) ) return true;
foreach ( $module['requirement'] AS $reqModule => $reqVersion ) {
$reqVersion = intval(str_replace('.','',$reqVersion));
if ( !isset($allmodules[$reqModule]) ) {
return false;
}
elseif ( $allmodules[$reqModule]['installed_version']<$reqVersion ) {
return false;
}
}
return true;
}
//รBERSICHT AKTUALISIEREN
function mshow_refresh() {
global $set,$apx,$db;
$regmods=$this->get_modinfo();
$db->query("DELETE FROM ".PRE."_modules");
$listdir=opendir(BASEDIR.getpath('moduledir'));
while ( $file=readdir($listdir) ) {
if ( $file=="." || $file==".." || !is_dir(BASEDIR.getpath('moduledir').$file) ) continue;
$db->query("INSERT INTO ".PRE."_modules VALUES ('".$file."','".iif(isset($regmods[$file]),$regmods[$file]['active'],'0')."','".iif(isset($regmods[$file]),$regmods[$file]['installed'],'0')."','".iif(isset($regmods[$file]),$regmods[$file]['installed_version'],'0')."')");
}
@closedir($listdir);
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow');
}
//***************************** Module aktivieren *****************************
function menable() {
global $set,$apx,$db;
//Mehrere
if ( is_array($_REQUEST['multiid']) ) {
if ( !checkToken() ) printInvalidToken();
else {
foreach ( $_REQUEST['multiid'] AS $module ) {
if ( in_array($module, $apx->coremodules) ) continue; //Core herausfiltern
$modules[] = $module;
}
//Nix zu tun
if ( !count($modules) ) {
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow');
return;
}
//Aktion ausfรผhren
$db->query("UPDATE ".PRE."_modules SET active='1' WHERE ( installed='1' AND module IN ('".implode("','", array_map('addslashes', $modules))."') )");
foreach ( $plain AS $id ) logit('MAIN_MENABLE',$id);
//Cache leeren!
$apx->tmpl->clear_cache();
//Navigation aktualisieren
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow&resetnav=1');
}
}
//Einzeln
else {
$module=$this->get_modinfo($_REQUEST['module']);
if ( !$_REQUEST['module'] ) die('missing module!');
if ( !is_array($module) ) die('unknown module!');
if ( !$module['installed'] ) die('can not enable, module is not installed!');
if ( $_POST['send'] ) {
if ( !checkToken() ) printInvalidToken();
else {
$db->query("UPDATE ".PRE."_modules SET active='1' WHERE module='".addslashes($_REQUEST['module'])."' LIMIT 1");
logit('MAIN_MENABLE',$_REQUEST['module']);
printJSRedirect('action.php?action=main.mshow&resetnav=1');
//Cache leeren!
$apx->tmpl->clear_cache();
}
}
else {
//Sprachpaket erst laden, weil ist ja deaktiviert
$apx->lang->module_load($_REQUEST['module']);
$apx->lang->dropall('modulename');
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($apx->lang->get('MODULENAME_'.strtoupper($_REQUEST['module']))))));
$insert['MODULE']=$_REQUEST['module'];
tmessageOverlay('menable',$insert);
}
}
}
//***************************** Module deaktivieren *****************************
function mdisable() {
global $set,$apx,$db;
//Mehrere
if ( is_array($_REQUEST['multiid']) ) {
if ( !checkToken() ) printInvalidToken();
else {
foreach ( $_REQUEST['multiid'] AS $module ) {
if ( in_array($module, $apx->coremodules) ) continue; //Core herausfiltern
$modules[] = $module;
}
//Nix zu tun
if ( !count($modules) ) {
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow');
return;
}
//Aktion ausfรผhren
$db->query("UPDATE ".PRE."_modules SET active='0' WHERE ( installed='1' AND module IN ('".implode("','", array_map('addslashes', $modules))."') )");
foreach ( $plain AS $id ) logit('MAIN_MDISABLE',$id);
//Cache leeren!
$apx->tmpl->clear_cache();
//Navigation aktualisieren
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow&resetnav=1');
}
}
//Einzeln
else {
$module=$this->get_modinfo($_REQUEST['module']);
$regmods=$this->get_modinfo();
if ( !$_REQUEST['module'] ) die('missing module!');
if ( !is_array($module) ) die('unknown module!');
if ( in_array($_REQUEST['module'],$apx->coremodules) ) die('can not disable core-modules!');
//Dependence-Check
if ( $_POST['send'] ) {
if ( !checkToken() ) printInvalidToken();
else {
$db->query("UPDATE ".PRE."_modules SET active='0' WHERE module='".addslashes($_REQUEST['module'])."' LIMIT 1");
logit('MAIN_MDISABLE',$_REQUEST['module']);
printJSRedirect('action.php?action=main.mshow&resetnav=1');
//Cache leeren!
$apx->tmpl->clear_cache();
}
}
else {
$isdep=array();
foreach ( $regmods AS $modulename => $info ) {
if ( !is_array($info['dependence']) || !in_array($_REQUEST['module'],$info['dependence']) ) continue;
$isdep[]=$modulename;
}
if ( count($isdep) ) {
$input['DEPENDENCE']=implode(', ',$isdep);
}
$apx->lang->dropall('modulename');
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($apx->lang->get('MODULENAME_'.strtoupper($_REQUEST['module']))))));
$input['MODULE']=$_REQUEST['module'];
tmessageOverlay('mdisable',$input);
}
}
}
//***************************** Module installieren *****************************
function minstall() {
global $set,$apx,$db;
require_once(BASEDIR.'lib/functions.setup.php');
//Mehrere
if ( is_array($_REQUEST['multiid']) ) {
if ( !checkToken() ) printInvalidToken();
else {
$regmods=$this->get_modinfo();
define('SETUPMODE','install');
foreach ( $_REQUEST['multiid'] AS $module ) {
if ( !isset($regmods[$module]) ) continue; //Modul existiert nicht
if ( $regmods[$module]['installed'] ) continue; //Modul ist schon installiert
if ( !$this->checkRequirement($regmods[$module], $regmods) ) continue; //Anforderungen nicht erfรผllt
if ( !file_exists(BASEDIR.getmodulepath($module).'setup.php') ) die('missing setup.php of module "'.$module.'"!');
$modules[] = $module;
}
//Nix zu tun
if ( !count($modules) ) {
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow');
return;
}
//Installation ausfรผhren
set_time_limit(600);
foreach ( $modules AS $module ) {
require(BASEDIR.getmodulepath($module).'setup.php');
$db->query("UPDATE ".PRE."_modules SET installed='1',version='".$regmods[$module]['current_version']."' WHERE module='".addslashes($module)."' LIMIT 1");
logit('MAIN_MINSTALL',$module);
}
//Cache leeren!
$apx->tmpl->clear_cache();
//Navigation aktualisieren
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow&resetnav=1');
}
}
//Einzeln
else {
if ( !$_REQUEST['module'] ) die('missing module!');
$regmods=$this->get_modinfo();
$module=$regmods[$_REQUEST['module']];
if ( !is_array($module) ) die('unknown module!');
if ( !$this->checkRequirement($module, $regmods) ) die('requirements not complied!');
if ( $module['installed'] ) die('can not install, module is already installed!');
define('SETUPMODE','install');
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
if ( !file_exists(BASEDIR.getmodulepath($_REQUEST['module']).'setup.php') ) die('missing setup.php');
//Installation ausfรผhren
set_time_limit(600);
require(BASEDIR.getmodulepath($_REQUEST['module']).'setup.php');
//MYSQL-Update
$db->query("UPDATE ".PRE."_modules SET installed='1',version='".$module['current_version']."' WHERE module='".addslashes($_REQUEST['module'])."'");
logit('MAIN_MINSTALL',$_REQUEST['module']);
printJSRedirect('action.php?action=main.mshow');
}
}
else {
//Sprachpaket erst laden, weil ist ja deaktiviert
$apx->lang->module_load($_REQUEST['module']);
$apx->lang->dropall('modulename');
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($apx->lang->get('MODULENAME_'.strtoupper($_REQUEST['module']))))));
$input['MODULE']=$_REQUEST['module'];
tmessageOverlay('minstall',$input);
}
}
}
//***************************** Module deinstallieren *****************************
function muninstall() {
global $set,$apx,$db;
require_once(BASEDIR.'lib/functions.setup.php');
//Mehrere
if ( is_array($_REQUEST['multiid']) ) {
if ( !checkToken() ) printInvalidToken();
else {
$regmods=$this->get_modinfo();
define('SETUPMODE','uninstall');
foreach ( $_REQUEST['multiid'] AS $module ) {
if ( in_array($moduleid, $apx->coremodules) ) continue; //Core herausfiltern
if ( !isset($regmods[$module]) ) continue; //Modul existiert nicht
if ( !$regmods[$module]['installed'] || $regmods[$module]['active'] ) continue; //Nicht installiert oder noch aktiv
if ( !file_exists(BASEDIR.getmodulepath($module).'setup.php') ) die('missing setup.php of module "'.$module.'"!');
$modules[] = $module;
}
//Nix zu tun
if ( !count($modules) ) {
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow');
return;
}
//Deinstallation ausfรผhren
set_time_limit(600);
foreach ( $modules AS $module ) {
require(BASEDIR.getmodulepath($module).'setup.php');
$db->query("DELETE FROM ".PRE."_config WHERE module='".addslashes($module)."'"); //Config entfernen
$db->query("UPDATE ".PRE."_modules SET installed='0',version='0' WHERE module='".addslashes($module)."' LIMIT 1");
logit('MAIN_MUNINSTALL',$module);
}
//Cache leeren!
$apx->tmpl->clear_cache();
//Navigation aktualisieren
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow&resetnav=1');
}
}
//Einzeln
else {
$module=$this->get_modinfo($_REQUEST['module']);
if ( !$_REQUEST['module'] ) die('missing module!');
if ( !is_array($module) ) die('unknown module!');
if ( $module['active'] ) die('can not uninstall, module still active!');
if ( !$module['installed'] ) die('can not uninstall, module is not installed!');
if ( in_array($_REQUEST['module'],$apx->coremodules) ) die('can not uninstall core-modules!');
define('SETUPMODE','uninstall');
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
if ( !file_exists(BASEDIR.getmodulepath($_REQUEST['module']).'setup.php') ) die('missing setup.php');
//Deinstallation ausfรผhren
set_time_limit(600);
require(BASEDIR.getmodulepath($_REQUEST['module']).'setup.php');
//MySQL-Update
$db->query("UPDATE ".PRE."_modules SET installed='0',version='0' WHERE module='".addslashes($_REQUEST['module'])."'");
$db->query("DELETE FROM ".PRE."_config WHERE module='".addslashes($_REQUEST['module'])."'");
logit('MAIN_MUNINSTALL',$_REQUEST['module']);
printJSRedirect('action.php?action=main.mshow');
}
}
else {
//Sprachpaket erst laden, weil ist ja deaktiviert
$apx->lang->module_load($_REQUEST['module']);
$apx->lang->dropall('modulename');
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($apx->lang->get('MODULENAME_'.strtoupper($_REQUEST['module']))))));
$input['MODULE']=$_REQUEST['module'];
tmessageOverlay('muninstall',$input);
}
}
}
//***************************** Module aktualisieren *****************************
function mupdate() {
global $set,$apx,$db;
require_once(BASEDIR.'lib/functions.setup.php');
//Mehrere
if ( is_array($_REQUEST['multiid']) ) {
if ( !checkToken() ) printInvalidToken();
else {
$regmods=$this->get_modinfo();
define('SETUPMODE','update');
foreach ( $_REQUEST['multiid'] AS $module ) {
if ( !isset($regmods[$module]) ) continue; //Modul existiert nicht
if ( !$regmods[$module]['installed'] ) continue; //Nicht installiert
if ( !$this->checkRequirement($regmods[$module], $regmods) ) continue; //Anforderungen nicht erfรผllt
if ( !file_exists(BASEDIR.getmodulepath($module).'setup.php') ) die('missing setup.php of module "'.$module.'"!');
if ( $regmods[$module]['installed_version']==$regmods[$module]['current_version'] ) continue;
$modules[] = $module;
}
//Nix zu tun
if ( !count($modules) ) {
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow');
return;
}
//Aktualisierung ausfรผhren
set_time_limit(600);
foreach ( $modules AS $module ) {
$installed_version=$regmods[$module]['installed_version'];
require(BASEDIR.getmodulepath($module).'setup.php');
$db->query("UPDATE ".PRE."_modules SET version='".$regmods[$module]['current_version']."' WHERE module='".addslashes($module)."'");
logit('MAIN_MUPDATE',$module);
}
//Cache leeren!
$apx->tmpl->clear_cache();
//Navigation aktualisieren
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.mshow');
}
}
//Einzeln
else {
if ( !$_REQUEST['module'] ) die('missing module!');
$regmods=$this->get_modinfo();
$module=$regmods[$_REQUEST['module']];
if ( !is_array($module) ) die('unknown module!');
if ( !$module['installed'] ) die('can not update, module is not installed!');
if ( !$this->checkRequirement($module, $regmods) ) die('requirements not complied!');
if ( $module['installed_version']==$module['current_version'] ) die('module is already up to date!');
define('SETUPMODE','update');
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
if ( !file_exists(BASEDIR.getmodulepath($_REQUEST['module']).'setup.php') ) die('missing setup.php');
//Aktualisierung ausfรผhren
set_time_limit(600);
$installed_version=$module['installed_version'];
require(BASEDIR.getmodulepath($_REQUEST['module']).'setup.php');
//MYSQL aktualisieren
$db->query("UPDATE ".PRE."_modules SET version='".$module['current_version']."' WHERE module='".addslashes($_REQUEST['module'])."'");
logit('MAIN_MUPDATE',$_REQUEST['module']);
printJSRedirect('action.php?action=main.mshow');
}
}
else {
$apx->lang->dropall('modulename');
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($apx->lang->get('MODULENAME_'.strtoupper($_REQUEST['module']))))));
$input['MODULE']=$_REQUEST['module'];
tmessageOverlay('mupdate',$input);
}
}
}
//***************************** Module konfigurieren *****************************
function mconfig() {
global $set,$apx,$db;
if ( !$_REQUEST['module'] ) die('missing module!');
if ( $_POST['send'] ) {
if ( !checkToken() ) infoInvalidToken();
else {
$info=array();
$data=$db->fetch("SELECT varname,type,addnl FROM ".PRE."_config WHERE ( module='".addslashes($_REQUEST['module'])."' AND addnl!='BLOCK' ) ORDER BY ord ASC");
foreach ( $data AS $res ) {
$postvalue=$_POST[$res['varname']];
//Switch
if ( $res['type']=='switch' ) {
$thevalue=iif($postvalue,1,0);
}
//String
elseif ( $res['type']=='string' ) {
$thevalue=addslashes($postvalue);
}
//Multiline
elseif ( $res['type']=='multiline' ) {
$thevalue=addslashes($postvalue);
}
//Array
elseif ( $res['type']=='array' ) {
$thearray=array();
if ( is_array($postvalue) ) {
foreach ( $postvalue AS $element ) {
if ( !$element ) continue;
$thearray[]=$element;
}
}
$thevalue=serialize($thearray);
}
//Array mit Keys
elseif ( $res['type']=='array_keys' ) {
$thearray=array();
if ( is_array($postvalue) ) {
foreach ( $postvalue AS $element ) {
if ( !$element['key'] && !$element['value'] ) continue;
$thearray[$element['key']]=$element['value'];
}
}
$thevalue=serialize($thearray);
}
//Integer
elseif ( $res['type']=='int' ) {
$thevalue=(int)$postvalue;
}
//Float
elseif ( $res['type']=='float' ) {
$thevalue=(float)$postvalue;
}
//Select
elseif ( $res['type']=='select' ) {
$possible=unserialize($res['addnl']);
foreach ( $possible AS $value => $descr ) {
if ( $value==$postvalue ) {
$thevalue=$value;
break;
}
}
}
if ( !isset($thevalue) ) continue;
$db->query("UPDATE ".PRE."_config SET value='".$thevalue."',lastchange=".time()." WHERE ( module='".addslashes($_REQUEST['module'])."' AND varname='".$res['varname']."' )");
unset($thevalue);
}
logit('MAIN_MCONFIG',$_REQUEST['module']);
printJSRedirect('action.php?action=main.mshow');
}
}
else {
$apx->lang->drop('config',$_REQUEST['module']);
$buckets = array();
$data=$db->fetch("SELECT * FROM ".PRE."_config WHERE ( module='".addslashes($_REQUEST['module'])."' AND addnl!='BLOCK' ) ORDER BY ord ASC");
if ( count($data) ) {
foreach ( $data AS $res ) {
if ( !$res['type'] ) continue;
$temp['NAME']=$res['varname'];
$temp['DESCRIPTION']=$apx->lang->get(strtoupper($res['varname']));
$temp['TYPE']=$res['type'];
if ( $res['addnl']=='MULTILINE' ) $temp['MULTILINE']=1;
if ( $res['addnl']=='password' ) $temp['PASSWORD']=1;
//Switch
if ( $res['type']=='switch' ) {
$temp['VALUE']=iif($res['value'],1,0);
}
//String
elseif ( $res['type']=='string' ) {
++$i;
$temp['VALUE']=compatible_hsc($res['value']);
}
//Multiline
elseif ( $res['type']=='multiline' ) {
++$i;
$temp['VALUE']=compatible_hsc($res['value']);
}
//Array
elseif ( $res['type']=='array' ) {
$array=unserialize($res['value']);
if ( !is_array($array) ) $array=array();
$temp['ELEMENT']=array();
foreach ( $array AS $arrayvalue ) {
++$i;
$temp['ELEMENT'][$i]['VALUE']=compatible_hsc($arrayvalue);
$temp['ELEMENT'][$i]['DISPLAY']=1;
}
for ( $ai=0; $ai<=20; $ai++ ) {
++$i;
$temp['ELEMENT'][$i]['DISPLAY']=0;
}
}
//Array mit Keys
elseif ( $res['type']=='array_keys' ) {
$array=unserialize($res['value']);
if ( !is_array($array) ) $array=array();
$temp['ELEMENT']=array();
foreach ( $array AS $arraykey => $arrayvalue ) {
++$i;
$temp['ELEMENT'][$i]['KEY']=compatible_hsc($arraykey);
$temp['ELEMENT'][$i]['VALUE']=compatible_hsc($arrayvalue);
$temp['ELEMENT'][$i]['DISPLAY']=1;
}
for ( $ai=0; $ai<=20; $ai++ ) {
++$i;
$temp['ELEMENT'][$i]['DISPLAY']=0;
}
}
//Integer
elseif ( $res['type']=='int' ) {
$temp['VALUE']=(int)$res['value'];
}
//Float
elseif ( $res['type']=='float' ) {
$temp['VALUE']=(float)$res['value'];
}
//Select
elseif ( $res['type']=='select' ) {
$possible=unserialize($res['addnl']);
foreach ( $possible AS $value => $descr ) {
$temp['OPTIONS'][]=array(
'NAME'=>$apx->lang->insertpack($descr),
'VALUE'=>$value,
'SELECTED'=>iif($value==$res['value'],true,false)
);
}
}
$buckets[$res['tab']][]=$temp;
$temp=array();
}
}
$vardata = array();
foreach ( $buckets AS $tabname => $vars ) {
$vardata[] = array(
'ID' => strtolower($tabname),
'NAME' => compatible_hsc($apx->lang->get($tabname)),
'VAR' => $vars
);
}
$apx->tmpl->assign('TAB',$vardata);
$apx->tmpl->assign('TAB_COUNT',count($vardata));
$apx->tmpl->assign('MODULE',$_REQUEST['module']);
$apx->tmpl->assign('MODULENAME',$apx->lang->get('MODULENAME_'.strtoupper($_REQUEST['module'])));
$apx->tmpl->parse('config');
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Sektionen *****************************
function secshow() {
global $set,$apx,$db,$html;
//Aktionen
if ( $_REQUEST['do']=='add' ) return $this->secshow_add();
if ( $_REQUEST['do']=='edit' ) return $this->secshow_edit();
if ( $_REQUEST['do']=='del' ) return $this->secshow_del();
if ( $_REQUEST['do']=='default' ) return $this->secshow_default();
echo'<p class="slink">» <a href="action.php?action=main.secshow&do=add">'.$apx->lang->get('ADDSECTION').'</a></p>';
$col[]=array('',1,'align="center"');
$col[]=array('',1,'align="center"');
$col[]=array('COL_ID',3,'align="center"');
$col[]=array('COL_TITLE',42,'class="title"');
$col[]=array('COL_VIRTUAL',28,'align="center"');
$col[]=array('COL_THEME',28,'align="center"');
$data=$db->fetch("SELECT * FROM ".PRE."_sections ORDER BY title ASC");
if ( count($data) ) {
foreach ( $data AS $res ) {
++$i;
if ( $res['default'] ) $tabledata[$i]['COL1']='<img src="design/default.gif" alt="'.$apx->lang->get('DEFAULT').'" title="'.$apx->lang->get('DEFAULT').'" />';
else $tabledata[$i]['COL1']=' ';
if ( $res['active'] ) $tabledata[$i]['COL2']='<img src="design/greendot.gif" alt="'.$apx->lang->get('CORE_ACTIVE').'" title="'.$apx->lang->get('CORE_ACTIVE').'" />';
else $tabledata[$i]['COL2']='<img src="design/reddot.gif" alt="'.$apx->lang->get('CORE_INACTIVE').'" title="'.$apx->lang->get('CORE_INACTIVE').'" />';
$tabledata[$i]['COL3']=$res['id'];
$tabledata[$i]['COL4']='<a href="'.mklink('../index.php','index.html',$res['id']).'" target="_blank">'.replace($res['title']).'</a>';
$tabledata[$i]['COL5']=$res['virtual'];
$tabledata[$i]['COL6']=$res['theme'];
//Optionen
$tabledata[$i]['OPTIONS'].=optionHTML('edit.gif', 'main.secshow', 'do=edit&id='.$res['id'], $apx->lang->get('CORE_EDIT'));
if ( !$res['default'] ) $tabledata[$i]['OPTIONS'].=optionHTMLOverlay('del.gif', 'main.secshow', 'do=del&id='.$res['id'], $apx->lang->get('CORE_DEL'));
else $tabledata[$i]['OPTIONS'].='<img src="design/ispace.gif" alt="" />';
if ( !$res['default'] && $res['active'] ) $tabledata[$i]['OPTIONS'].=optionHTML('mkdefault.gif', 'main.secshow', 'do=default&id='.$res['id'], $apx->lang->get('MKDEFAULT'));
else $tabledata[$i]['OPTIONS'].='<img src="design/ispace.gif" alt="" />';
}
}
$apx->tmpl->assign('TABLE',$tabledata);
$html->table($col);
//SEO-URLs => Rewrite-Code ausgeben
if ( $set['main']['staticsites'] ) {
$rwcode = '';
foreach ( $apx->sections AS $section ) {
$rwcode .= 'RewriteRule ^'.$section['virtual'].'/(.*)$ $1?sec='.$section['id'].' [QSA]<br />';
}
$apx->tmpl->assign('RWCODE',$rwcode);
$apx->tmpl->parse('rewritecode');
}
}
//***************************** Sektion anlegen *****************************
function secshow_add() {
global $set,$apx,$db;
$apx->lang->dropaction('main','secadd');
if ( $_POST['send']==1 ) {
list($check)=$db->first("SELECT id FROM ".PRE."_sections WHERE LOWER(title)='".strtolower($_POST['title'])."' LIMIT 1");
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['title'] || !$_POST['virtual'] || !$_POST['theme'] || !$_POST['msg_noaccess'] ) infoNotComplete();
elseif ( !preg_match('#^[A-Za-z0-9_-]+$#',$_POST['virtual']) ) info($apx->lang->get('INFO_VIRTUALFORMAT'));
elseif ( $check ) info($apx->lang->get('INFO_EXISTS'));
else {
//Wenn es die erste Sektion ist
if ( !$apx->section_default ) {
$_POST['default']=1;
$_POST['active']=1;
}
$db->dinsert(PRE.'_sections','title,virtual,theme,lang,active,msg_noaccess,default');
logit('MAIN_SECADD','ID #'.$db->insert_id());
printJSRedirect('action.php?action=main.secshow');
}
}
else {
$_POST['active']=1;
//Themes auslesen
$handle=opendir(BASEDIR.getpath('tmpldir'));
while ( $file=readdir($handle) ) {
if ( $file=='.' || $file=='..' ) continue;
if ( !is_dir(BASEDIR.getpath('tmpldir').$file) ) continue;
$designid=$file;
$designlist.='<option value="'.$designid.'"'.iif($designid==$_POST['theme'],' selected="selected"').'>'.$file.'</option>';
}
closedir($handle);
//Sprache
$lang='<option value="">'.$apx->lang->get('DEFAULT').'</option>';
foreach ( $apx->languages AS $id => $name ) {
$lang.='<option value="'.$id.'"'.iif($_POST['lang']==$id,' selected="selected"').'>'.$name.'</option>';
}
$apx->tmpl->assign('TITLE',compatible_hsc($_POST['title']));
$apx->tmpl->assign('VIRTUAL',compatible_hsc($_POST['virtual']));
$apx->tmpl->assign('THEME',$designlist);
$apx->tmpl->assign('LANG',$lang);
$apx->tmpl->assign('ACTIVE',(int)$_POST['active']);
$apx->tmpl->assign('MSG_NOACCESS',compatible_hsc($_POST['msg_noaccess']));
$apx->tmpl->assign('ACTION','add');
$apx->tmpl->parse('secadd_secedit');
}
}
//***************************** Sektion bearbeiten *****************************
function secshow_edit() {
global $set,$apx,$db;
$apx->lang->dropaction('main','secedit');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die('missing ID!');
if ( $_POST['send']==1 ) {
list($check)=$db->first("SELECT id FROM ".PRE."_sections WHERE ( LOWER(title)='".strtolower($_POST['title'])."' AND id!='".$_REQUEST['id']."' ) LIMIT 1");
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['title'] || !$_POST['virtual'] || !$_POST['theme'] || !$_POST['msg_noaccess'] ) infoNotComplete();
elseif ( !preg_match('#^[A-Za-z0-9_-]+$#',$_POST['virtual']) ) info($apx->lang->get('INFO_VIRTUALFORMAT'));
elseif ( $_REQUEST['id']==$apx->section_default && !$_POST['active'] ) info($apx->lang->get('INFO_ISDEFAULT'));
elseif ( $check ) info($apx->lang->get('INFO_EXISTS'));
else {
$db->dupdate(PRE.'_sections','title,virtual,theme,lang,active,msg_noaccess',"WHERE id='".$_REQUEST['id']."' LIMIT 1");
logit('MAIN_SECEDIT','ID #'.$_REQUEST['id']);
printJSRedirect('action.php?action=main.secshow');
}
}
else {
$res=$db->first("SELECT title,virtual,theme,lang,active,msg_noaccess FROM ".PRE."_sections WHERE id='".$_REQUEST['id']."' LIMIT 1",1);
foreach ( $res AS $key => $value ) $_POST[$key]=$value;
//Themes auslesen
$handle=opendir(BASEDIR.getpath('tmpldir'));
while ( $file=readdir($handle) ) {
if ( $file=='.' || $file=='..' ) continue;
if ( !is_dir(BASEDIR.getpath('tmpldir').$file) ) continue;
$designid=$file;
$designlist.='<option value="'.$designid.'"'.iif($designid==$_POST['theme'],' selected="selected"').'>'.$file.'</option>';
}
closedir($handle);
//Sprache
$lang='<option value="">'.$apx->lang->get('DEFAULT').'</option>';
foreach ( $apx->languages AS $id => $name ) {
$lang.='<option value="'.$id.'"'.iif($_POST['lang']==$id,' selected="selected"').'>'.$name.'</option>';
}
$apx->tmpl->assign('TITLE',compatible_hsc($_POST['title']));
$apx->tmpl->assign('VIRTUAL',compatible_hsc($_POST['virtual']));
$apx->tmpl->assign('THEME',$designlist);
$apx->tmpl->assign('LANG',$lang);
$apx->tmpl->assign('ACTIVE',(int)$_POST['active']);
$apx->tmpl->assign('MSG_NOACCESS',compatible_hsc($_POST['msg_noaccess']));
$apx->tmpl->assign('ACTION','edit');
$apx->tmpl->assign('ID',$_REQUEST['id']);
$apx->tmpl->parse('secadd_secedit');
}
}
//***************************** Sektion lรถschen *****************************
function secshow_del() {
global $set,$apx,$db;
$apx->lang->dropaction('main','secdel');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die('missing ID!');
if ( $_REQUEST['id']==$apx->section_default ) die('can not delete default section!');
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
$db->query("DELETE FROM ".PRE."_sections WHERE id='".$_REQUEST['id']."' LIMIT 1");
logit('MAIN_SECDEL','ID #'.$_REQUEST['id']);
printJSReload();
}
}
else {
list($title) = $db->first("SELECT title FROM ".PRE."_sections WHERE id='".$_REQUEST['id']."' LIMIT 1");
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($title))));
tmessageOverlay('secdel',array('ID' => $_REQUEST['id']));
}
}
//***************************** Standard-Sektion setzen *****************************
function secshow_default() {
global $set,$apx,$db;
$apx->lang->dropaction('main','secdefault');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die('missing ID!');
if ( !$apx->section_is_active($_REQUEST['id']) ) die('section is not enabled!');
$db->query("UPDATE ".PRE."_sections SET ".PRE."_sections.default=0");
$db->query("UPDATE ".PRE."_sections SET ".PRE."_sections.default=1 WHERE id='".$_REQUEST['id']."' LIMIT 1");
logit('MAIN_SECDEFAULT','ID #'.$_REQUEST['id']);
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.secshow');
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Sprachpakete *****************************
function lshow() {
global $set,$apx,$db,$html;
$langinfo=$set['main']['languages'];
//Aktionen
if ( $_REQUEST['do']=='add' ) return $this->lshow_add();
if ( $_REQUEST['do']=='del' ) return $this->lshow_del();
if ( $_REQUEST['do']=='default' ) return $this->lshow_default();
echo'<p class="slink">» <a href="action.php?action=main.lshow&do=add">'.$apx->lang->get('ADDLANGPACK').'</a></p>';
$col[]=array('',1,'align="center"');
$col[]=array('COL_DIR',10,'align="center"');
$col[]=array('COL_TITLE',90,'class="title"');
foreach ( $langinfo AS $dir => $res ) {
++$i;
if ( $res['default'] ) $tabledata[$i]['COL1']='<img src="design/default.gif" alt="'.$apx->lang->get('DEFAULT').'" title="'.$apx->lang->get('DEFAULT').'" />';
else $tabledata[$i]['COL1']=' ';
$tabledata[$i]['COL2']=$dir;
$tabledata[$i]['COL3']=replace($res['title']);
//Optionen
if ( !$res['default'] ) $tabledata[$i]['OPTIONS'].=optionHTMLOverlay('del.gif', 'main.lshow', 'do=del&id='.$dir, $apx->lang->get('CORE_DEL'));
if ( !$res['default'] ) $tabledata[$i]['OPTIONS'].=optionHTML('mkdefault.gif', 'main.lshow', 'do=default&id='.$dir, $apx->lang->get('MKDEFAULT'));
}
$apx->tmpl->assign('TABLE',$tabledata);
$html->table($col);
}
//***************************** Sprachpaket hinzufรผgen *****************************
function lshow_add() {
global $set,$apx,$db;
$apx->lang->dropaction('main','ladd');
$langinfo=$set['main']['languages'];
if ( $_POST['send']==1 ) {
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['dir'] || !$_POST['title'] ) infoNotComplete();
elseif ( $langinfo[$_POST['dir']] ) info($apx->lang->get('INFO_EXISTS'));
elseif ( !is_dir(BASEDIR.'language/'.$_POST['dir']) ) info($apx->lang->get('INFO_MISSINGDIR'));
else {
$langinfo[$_POST['dir']]=array(
'title' => $_POST['title'],
'default' => false
);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($langinfo))."' WHERE ( module='main' AND varname='languages' ) LIMIT 1");
logit('MAIN_LADD',$_POST['dir']);
printJSRedirect('action.php?action=main.lshow');
}
}
else {
$apx->tmpl->assign('DIR',compatible_hsc($_POST['dir']));
$apx->tmpl->assign('TITLE',compatible_hsc($_POST['title']));
$apx->tmpl->parse('ladd');
}
}
//***************************** Sprachpaket lรถschen *****************************
function lshow_del() {
global $set,$apx,$db;
$apx->lang->dropaction('main','ldel');
if ( !$_REQUEST['id'] ) die('missing ID!');
$langinfo=$set['main']['languages'];
if ( $langinfo[$_REQUEST['id']]['default'] ) die('can not delete default langpack!');
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
unset($langinfo[$_REQUEST['id']]);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($langinfo))."' WHERE ( module='main' AND varname='languages' ) LIMIT 1");
logit('MAIN_LDEL',$_REQUEST['id']);
printJSReload();
}
}
else {
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($langinfo[$_REQUEST['id']]['title']))));
tmessageOverlay('ldel',array('ID' => $_REQUEST['id']));
}
}
//***************************** Sprachpaket als Standard setzen *****************************
function lshow_default() {
global $set,$apx,$db;
$apx->lang->dropaction('main','ldefault');
if ( !$_REQUEST['id'] ) die('missing ID!');
foreach ( $set['main']['languages'] AS $key => $info ) $set['main']['languages'][$key]['default'] = false;
$set['main']['languages'][$_REQUEST['id']]['default'] = true;
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($set['main']['languages']))."' WHERE ( module='main' AND varname='languages' ) LIMIT 1");
logit('MAIN_LDEFAULT',$_REQUEST['id']);
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.lshow');
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Vorlagen *****************************
function tshow() {
global $set,$apx,$db,$html;
//Aktionen
if ( $_REQUEST['do']=='add' ) return $this->tshow_add();
if ( $_REQUEST['do']=='edit' ) return $this->tshow_edit();
if ( $_REQUEST['do']=='del' ) return $this->tshow_del();
echo '<p class="slink">» <a href="action.php?action=main.tshow&do=add">'.$apx->lang->get('ADDTEMPLATE').'</a></p>';
echo '<p class="hint">'.$apx->lang->get('INFOTEXT').'</p>';
$col[]=array('COL_TITLE',100,'class="title"');
$data=$db->fetch("SELECT id,title FROM ".PRE."_templates ORDER BY title ASC");
if ( count($data) ) {
foreach ( $data AS $res ) {
++$i;
$tabledata[$i]['COL1']=replace($res['title']);
//Optionen
$tabledata[$i]['OPTIONS'].=optionHTML('edit.gif', 'main.tshow', 'do=edit&id='.$res['id'], $apx->lang->get('CORE_EDIT'));
$tabledata[$i]['OPTIONS'].=optionHTMLOverlay('del.gif', 'main.tshow', 'do=del&id='.$res['id'], $apx->lang->get('CORE_DEL'));
}
}
$apx->tmpl->assign('TABLE',$tabledata);
$html->table($col);
}
//***************************** Vorlagen hinzufรผgen *****************************
function tshow_add() {
global $set,$apx,$db;
$apx->lang->dropaction('main','tadd');
if ( $_POST['send']==1 ) {
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['title'] || !$_POST['code'] ) infoNotComplete();
else {
$db->dinsert(PRE.'_templates','title,code');
logit('MAIN_TADD','ID #'.$db->insert_id());
message($apx->lang->get('MSG_OK_ADD'),'action.php?action=main.tshow');
return;
}
}
mediamanager('main');
$apx->tmpl->assign('TITLE',compatible_hsc($_POST['title']));
$apx->tmpl->assign('CODE',compatible_hsc($_POST['code']));
$apx->tmpl->assign('ACTION','add');
$apx->tmpl->parse('tadd_tedit');
}
//***************************** Vorlagen bearbeiten *****************************
function tshow_edit() {
global $set,$apx,$db;
$apx->lang->dropaction('main','tedit');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die("missing ID!");
if ( $_POST['send']==1 ) {
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['title'] || !$_POST['code'] ) infoNotComplete();
else {
$db->dupdate(PRE.'_templates','title,code',"WHERE id='".$_REQUEST['id']."' LIMIT 1");
logit('MAIN_TEDIT','ID #'.$_REQUEST['id']);
message($apx->lang->get('MSG_OK_EDIT'),'action.php?action=main.tshow');
return;
}
}
else {
list($_POST['title'],$_POST['code'])=$db->first("SELECT title,code FROM ".PRE."_templates WHERE id='".$_REQUEST['id']."' LIMIT 1");
}
mediamanager('main');
$apx->tmpl->assign('TITLE',compatible_hsc($_POST['title']));
$apx->tmpl->assign('CODE',compatible_hsc($_POST['code']));
$apx->tmpl->assign('ACTION','edit');
$apx->tmpl->assign('ID',$_REQUEST['id']);
$apx->tmpl->parse('tadd_tedit');
}
//***************************** Vorlagen lรถschen *****************************
function tshow_del() {
global $set,$apx,$db;
$apx->lang->dropaction('main','tdel');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die("missing ID!");
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
$db->query("DELETE FROM ".PRE."_templates WHERE id='".$_REQUEST['id']."'");
logit('MAIN_TDEL','ID #'.$_REQUEST['id']);
printJSReload();
}
}
else {
list($title) = $db->first("SELECT title FROM ".PRE."_templates WHERE id='".$_REQUEST['id']."' LIMIT 1");
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($title))));
tmessageOverlay('tdel',array('ID' => $_REQUEST['id']));
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** HTML-Codeschnipsel *****************************
function snippets() {
global $set,$apx,$db,$html;
//Aktionen
if ( $_REQUEST['do']=='add' ) return $this->snippets_add();
if ( $_REQUEST['do']=='edit' ) return $this->snippets_edit();
if ( $_REQUEST['do']=='del' ) return $this->snippets_del();
echo '<p class="slink">» <a href="action.php?action=main.snippets&do=add">'.$apx->lang->get('ADDSNIPPET').'</a></p>';
echo '<p class="hint">'.$apx->lang->get('INFOTEXT').'</p>';
$col[]=array('ID',1,'');
$col[]=array('COL_TITLE',100,'class="title"');
$data=$db->fetch("SELECT id,title FROM ".PRE."_snippets ORDER BY title ASC");
if ( count($data) ) {
foreach ( $data AS $res ) {
++$i;
$tabledata[$i]['COL1']=$res['id'];;
$tabledata[$i]['COL2']=replace($res['title']);
//Optionen
$tabledata[$i]['OPTIONS'].=optionHTML('edit.gif', 'main.snippets', 'do=edit&id='.$res['id'], $apx->lang->get('CORE_EDIT'));
$tabledata[$i]['OPTIONS'].=optionHTMLOverlay('del.gif', 'main.snippets', 'do=del&id='.$res['id'], $apx->lang->get('CORE_DEL'));
}
}
$apx->tmpl->assign('TABLE',$tabledata);
$html->table($col);
}
//***************************** HTML-Codeschnipsel hinzufรผgen *****************************
function snippets_add() {
global $set,$apx,$db;
$apx->lang->dropaction('main','snippetadd');
if ( $_POST['send']==1 ) {
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['title'] || !$_POST['code'] ) infoNotComplete();
else {
$db->dinsert(PRE.'_snippets','title,code');
logit('MAIN_TADD','ID #'.$db->insert_id());
printJSRedirect('action.php?action=main.snippets');
}
}
else {
mediamanager('main');
$apx->tmpl->assign('TITLE',compatible_hsc($_POST['title']));
$apx->tmpl->assign('CODE',compatible_hsc($_POST['code']));
$apx->tmpl->assign('ACTION','add');
$apx->tmpl->parse('snipadd_snipedit');
}
}
//***************************** HTML-Codeschnipsel bearbeiten *****************************
function snippets_edit() {
global $set,$apx,$db;
$apx->lang->dropaction('main','snippetedit');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die("missing ID!");
if ( $_POST['send']==1 ) {
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['title'] || !$_POST['code'] ) infoNotComplete();
else {
$db->dupdate(PRE.'_snippets','title,code',"WHERE id='".$_REQUEST['id']."' LIMIT 1");
logit('MAIN_TEDIT','ID #'.$_REQUEST['id']);
printJSRedirect('action.php?action=main.snippets');
}
}
else {
list($_POST['title'],$_POST['code'])=$db->first("SELECT title,code FROM ".PRE."_snippets WHERE id='".$_REQUEST['id']."' LIMIT 1");
mediamanager('main');
$apx->tmpl->assign('TITLE',compatible_hsc($_POST['title']));
$apx->tmpl->assign('CODE',compatible_hsc($_POST['code']));
$apx->tmpl->assign('ACTION','edit');
$apx->tmpl->assign('ID',$_REQUEST['id']);
$apx->tmpl->parse('snipadd_snipedit');
}
}
//***************************** HTML-Codeschnipsel lรถschen *****************************
function snippets_del() {
global $set,$apx,$db;
$apx->lang->dropaction('main','snippetdel');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die("missing ID!");
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
$db->query("DELETE FROM ".PRE."_snippets WHERE id='".$_REQUEST['id']."'");
logit('MAIN_SNIPPETDEL','ID #'.$_REQUEST['id']);
printJSReload();
}
}
else {
list($title) = $db->first("SELECT title FROM ".PRE."_snippets WHERE id='".$_REQUEST['id']."' LIMIT 1");
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($title))));
tmessageOverlay('snipdel',array('ID' => $_REQUEST['id']));
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Tags *****************************
function tags() {
global $set,$apx,$db,$html;
//Aktionen
if ( $_REQUEST['do']=='edit' ) return $this->tags_edit();
if ( $_REQUEST['do']=='del' ) return $this->tags_del();
//Suche durchfรผhren
if ( $_REQUEST['item'] ) {
$data=$db->fetch("SELECT tagid FROM ".PRE."_tags WHERE tag LIKE '%".addslashes_like($_REQUEST['item'])."%'");
$ids = get_ids($data, 'tagid');
$ids[] = -1;
$searchid = saveSearchResult('admin_tags', $ids, $_REQUEST['item']);
header("HTTP/1.1 301 Moved Permanently");
header('Location: action.php?action=main.tags&searchid='.$searchid);
return;
}
//Suchergebnis?
$resultFilter = '';
if ( $_REQUEST['searchid'] ) {
$searchRes = getSearchResult('admin_tags', $_REQUEST['searchid']);
if ( $searchRes ) {
list($resultIds, $resultMeta) = $searchRes;
$_REQUEST['item'] = $resultMeta;
$resultFilter = " AND tagid IN (".implode(', ', $resultIds).")";
}
else {
$_REQUEST['searchid'] = '';
}
}
//Suchformular
$apx->tmpl->assign('ITEM',compatible_hsc($_REQUEST['item']));
$apx->tmpl->parse('tagssearch');
$orderdef[0]='name';
$orderdef['name']=array('tag','ASC','COL_NAME');
$col[]=array('COL_NAME',100,'class="title"');
list($count)=$db->first("SELECT count(tagid) FROM ".PRE."_tags WHERE 1 ".$resultFilter);
pages('action.php?action=main.tags'.iif($_REQUEST['searchid'], '&searchid='.$_REQUEST['searchid']).'&sortby='.$_REQUEST['sortby'],$count);
$data=$db->fetch("SELECT tagid, tag FROM ".PRE."_tags WHERE 1 ".$resultFilter.getorder($orderdef).getlimit());
if ( count($data) ) {
foreach ( $data AS $res ) {
++$i;
$tabledata[$i]['COL1']=replace($res['tag']);
//Optionen
$tabledata[$i]['OPTIONS'].=optionHTMLOverlay('edit.gif', 'main.tags', 'do=edit&id='.$res['tagid'], $apx->lang->get('CORE_EDIT'));
$tabledata[$i]['OPTIONS'].=optionHTMLOverlay('del.gif', 'main.tags', 'do=del&id='.$res['tagid'], $apx->lang->get('CORE_DEL'));
}
}
$apx->tmpl->assign('TABLE',$tabledata);
$html->table($col);
}
//***************************** Tag bearbeiten *****************************
function tags_edit() {
global $set,$apx,$db;
$apx->lang->dropaction('main','tagedit');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die("missing ID!");
if ( $_POST['send'] ) {
if ( $_POST['tag'] ) {
if ( !checkToken() ) printInvalidToken();
else {
$db->dupdate(PRE.'_tags','tag',"WHERE tagid='".$_REQUEST['id']."' LIMIT 1");
logit('MAIN_TAGSEDIT','ID #'.$_REQUEST['id']);
printJSReload();
}
return;
}
}
else {
list($_POST['tag'])=$db->first("SELECT tag FROM ".PRE."_tags WHERE tagid='".$_REQUEST['id']."' LIMIT 1");
}
tmessageOverlay('tagsedit', array(
'ID' => $_REQUEST['id'],
'TAG' => compatible_hsc($_POST['tag'])
));
}
//***************************** Tag lรถschen *****************************
function tags_del() {
global $set,$apx,$db;
$apx->lang->dropaction('main','tagdel');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die("missing ID!");
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
$db->query("DELETE FROM ".PRE."_tags WHERE tagid='".$_REQUEST['id']."'");
logit('MAIN_TAGSDEL','ID #'.$_REQUEST['id']);
//Verknรผpfungen lรถschen
if ( $apx->is_module('articles') ) {
$db->query("DELETE FROM ".PRE."_articles_tags WHERE tagid='".$_REQUEST['id']."'");
}
if ( $apx->is_module('calendar') ) {
$db->query("DELETE FROM ".PRE."_calendar_tags WHERE tagid='".$_REQUEST['id']."'");
}
if ( $apx->is_module('downloads') ) {
$db->query("DELETE FROM ".PRE."_downloads_tags WHERE tagid='".$_REQUEST['id']."'");
}
if ( $apx->is_module('gallery') ) {
$db->query("DELETE FROM ".PRE."_gallery_tags WHERE tagid='".$_REQUEST['id']."'");
}
if ( $apx->is_module('glossar') ) {
$db->query("DELETE FROM ".PRE."_glossar_tags WHERE tagid='".$_REQUEST['id']."'");
}
if ( $apx->is_module('links') ) {
$db->query("DELETE FROM ".PRE."_links_tags WHERE tagid='".$_REQUEST['id']."'");
}
if ( $apx->is_module('news') ) {
$db->query("DELETE FROM ".PRE."_news_tags WHERE tagid='".$_REQUEST['id']."'");
}
if ( $apx->is_module('poll') ) {
$db->query("DELETE FROM ".PRE."_poll_tags WHERE tagid='".$_REQUEST['id']."'");
}
if ( $apx->is_module('products') ) {
$db->query("DELETE FROM ".PRE."_products_tags WHERE tagid='".$_REQUEST['id']."'");
}
if ( $apx->is_module('videos') ) {
$db->query("DELETE FROM ".PRE."_videos_tags WHERE tagid='".$_REQUEST['id']."'");
}
printJSReload();
}
}
else {
list($title) = $db->first("SELECT tag FROM ".PRE."_tags WHERE tagid='".$_REQUEST['id']."' LIMIT 1");
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($title))));
tmessageOverlay('tagdel',array('ID' => $_REQUEST['id']));
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Smilies *****************************
function sshow() {
global $set,$apx,$db,$html;
$smilies=$set['main']['smilies'];
if ( !is_array($smilies) ) $smilies=array();
//Aktionen
if ( $_REQUEST['do']=='add' ) return $this->sshow_add();
if ( $_REQUEST['do']=='edit' ) return $this->sshow_edit();
if ( $_REQUEST['do']=='del' ) return $this->sshow_del();
echo'<p class="slink">» <a href="action.php?action=main.sshow&do=add">'.$apx->lang->get('ADDSMILIE').'</a></p>';
echo'<p class="hint">'.$apx->lang->get('MAININFO').'</p>';
$orderdef[0]='code';
$orderdef['code']=array('code','ASC','COL_CODE');
$orderdef['description']=array('description','ASC','COL_DESCR');
$smilies=array_sort_def($smilies,$orderdef);
$col[]=array('COL_SMILIE',10,'align="center"');
$col[]=array('COL_CODE',25,'align="center"');
$col[]=array('COL_DESCR',65,'');
$count=count($smilies);
pages('action.php?action=main.sshow&sortby='.$_REQUEST['sortby'],$count);
foreach ( $smilies AS $key => $info ) {
++$i;
if ( $i<=($_REQUEST['p']-1)*$set['main']['admin_epp'] ) continue;
if ( $i>$_REQUEST['p']*$set['main']['admin_epp'] ) break;
$tabledata[$i]['COL1']='<img src="'.iif(substr($info['file'],0,1)=="/",$info['file'],""."../".$info['file']).'" alt="" />';
$tabledata[$i]['COL2']=replace($info['code']);
$tabledata[$i]['COL3']=iif($info['description'],replace($info['description']),' ');
//Optionen
$tabledata[$i]['OPTIONS'].=optionHTML('edit.gif', 'main.sshow', 'do=edit&id='.$key, $apx->lang->get('CORE_EDIT'));
$tabledata[$i]['OPTIONS'].=optionHTMLOverlay('del.gif', 'main.sshow', 'do=del&id='.$key, $apx->lang->get('CORE_DEL'));
}
$apx->tmpl->assign('TABLE',$tabledata);
$html->table($col);
orderstr($orderdef,'action.php?action=main.sshow');
save_index($_SERVER['REQUEST_URI']);
}
//***************************** Smilies hinzufรผgen *****************************
function sshow_add() {
global $set,$apx,$db;
$apx->lang->dropaction('main','sadd');
$smilies=$set['main']['smilies'];
if ( $_POST['send']==1 ) {
foreach ( $smilies AS $info ) {
if ( $info['code']==$_POST['code'] ) $check=true;
}
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['code'] || !$_POST['file'] ) infoNotComplete();
elseif ( $check ) info($apx->lang->get('INFO_EXISTS'));
else {
$nextkey=array_key_max($smilies)+1;
$smilies[$nextkey]=array(
'code' => $_POST['code'],
'file' => $_POST['file'],
'description' => $_POST['description']
);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($smilies))."' WHERE ( module='main' AND varname='smilies' ) LIMIT 1");
logit('MAIN_SADD','ID #'.$nextkey);
printJSRedirect('action.php?action=main.sshow');
}
}
else {
$apx->tmpl->assign('CODE',compatible_hsc($_POST['code']));
$apx->tmpl->assign('FILE',compatible_hsc($_POST['file']));
$apx->tmpl->assign('DESCRIPTION',compatible_hsc($_POST['description']));
$apx->tmpl->assign('PREVIEW',iif($_POST['file'],iif(substr($_POST['file'],0,1)=="/",$_POST['file'],"../".$_POST['file']),'design/nopic.gif'));
$apx->tmpl->assign('ACTION','add');
$apx->tmpl->parse('sadd_sedit');
}
}
//***************************** Smilies bearbeiten *****************************
function sshow_edit() {
global $set,$apx,$db;
$apx->lang->dropaction('main','sedit');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die('missing ID!');
$smilies=$set['main']['smilies'];
if ( $_POST['send']==1 ) {
foreach ( $smilies AS $key => $info ) {
if ( $key!=$_REQUEST['id'] && $info['code']==$_POST['code'] ) $check=true;
}
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['code'] || !$_POST['file'] ) infoNotComplete();
elseif ( $check ) info($apx->lang->get('INFO_EXISTS'));
else {
$smilies[$_REQUEST['id']]=array(
'code' => $_POST['code'],
'file' => $_POST['file'],
'description' => $_POST['description']
);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($smilies))."' WHERE ( module='main' AND varname='smilies' ) LIMIT 1");
logit('MAIN_SEDIT','ID #'.$_REQUEST['id']);
printJSRedirect(get_index('main.sshow'));
}
}
else {
foreach ( $smilies[$_REQUEST['id']] AS $key => $val ) $_POST[$key]=$val;
$apx->tmpl->assign('CODE',compatible_hsc($_POST['code']));
$apx->tmpl->assign('FILE',compatible_hsc($_POST['file']));
$apx->tmpl->assign('DESCRIPTION',compatible_hsc($_POST['description']));
$apx->tmpl->assign('PREVIEW',iif($_POST['file'],iif(substr($_POST['file'],0,1)=="/",$_POST['file'],"../".$_POST['file']),'design/nopic.gif'));
$apx->tmpl->assign('ACTION','edit');
$apx->tmpl->assign('ID',$_REQUEST['id']);
$apx->tmpl->parse('sadd_sedit');
}
}
//***************************** Smilies lรถschen *****************************
function sshow_del() {
global $set,$apx,$db;
$apx->lang->dropaction('main','sdel');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die('missing ID!');
$smilies=$set['main']['smilies'];
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
unset($smilies[$_REQUEST['id']]);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($smilies))."' WHERE ( module='main' AND varname='smilies' ) LIMIT 1");
logit('MAIN_SDEL','ID #'.$_REQUEST['id']);
printJSReload();
}
}
else {
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($smilies[$_REQUEST['id']]['code']))));
tmessageOverlay("sdel",array('ID' => $_REQUEST['id']));
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Codes *****************************
function cshow() {
global $set,$apx,$db,$html;
$codes=$set['main']['codes'];
if ( !is_array($codes) ) $codes=array();
//Aktionen
if ( $_REQUEST['do']=='add' ) return $this->cshow_add();
if ( $_REQUEST['do']=='edit' ) return $this->cshow_edit();
if ( $_REQUEST['do']=='del' ) return $this->cshow_del();
echo'<p class="slink">» <a href="action.php?action=main.cshow&do=add">'.$apx->lang->get('ADDCODE').'</a></p>';
echo'<p class="hint">'.$apx->lang->get('MAININFO').'</p>';
$orderdef[0]='code';
$orderdef['code']=array('code','ASC','COL_CODE');
$codes=array_sort_def($codes,$orderdef);
$col[]=array('COL_CODE',10,'align="center"');
$col[]=array('COL_REPLACE',45,'align="center"');
$col[]=array('COL_EXAMPLE',45,'align="center"');
$count=count($codes);
pages('action.php?action=main.cshow&sortby='.$_REQUEST['sortby'],$count);
foreach ( $codes AS $key => $res ) {
++$i;
if ( $i<=($_REQUEST['p']-1)*$set['main']['admin_epp'] ) continue;
if ( $i>$_REQUEST['p']*$set['main']['admin_epp'] ) break;
$tabledata[$i]['COL1']=strtoupper($res['code']);
$tabledata[$i]['COL2']=iif(strlen($res['replace'])>45,replace(substr($res['replace'],0,42).' ...'),replace($res['replace']));
$tabledata[$i]['COL3']=iif($res['example'],replace($res['example']),' ');
//Optionen
$tabledata[$i]['OPTIONS'].=optionHTML('edit.gif', 'main.cshow', 'do=edit&id='.$key, $apx->lang->get('CORE_EDIT'));
$tabledata[$i]['OPTIONS'].=optionHTMLOverlay('del.gif', 'main.cshow', 'do=del&id='.$key, $apx->lang->get('CORE_DEL'));
}
$apx->tmpl->assign('TABLE',$tabledata);
$html->table($col);
orderstr($orderdef,'action.php?action=main.cshow');
save_index($_SERVER['REQUEST_URI']);
}
//***************************** Codes hinzufรผgen *****************************
function cshow_add() {
global $set,$apx,$db;
$apx->lang->dropaction('main','cadd');
$codes=$set['main']['codes'];
if ( $_POST['send']==1 ) {
$_POST['code']=strtoupper($_POST['code']);
foreach ( $codes AS $res ) {
if ( $res['code']==$_POST['code'] && $res['count']==$_POST['count'] ) $check=true;
}
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['code'] || !$_POST['count'] || !$_POST['replace'] ) infoNotComplete();
elseif ( $check ) info($apx->lang->get('INFO_EXISTS'));
elseif ( $_POST['code']=='PHP' ) info($apx->lang->get('INFO_BLOCK'));
else {
$nextkey=array_key_max($codes)+1;
$codes[$nextkey]=array(
'code' => $_POST['code'],
'count' => $_POST['count'],
'replace' => $_POST['replace'],
'example' => $_POST['example'],
'allowsig' => (int)$_POST['allowsig']
);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($codes))."' WHERE ( module='main' AND varname='codes' ) LIMIT 1");
logit('MAIN_CADD','ID #'.$nextkey);
printJSRedirect('action.php?action=main.cshow');
}
}
else {
$_POST['allowsig']=$_POST['count']=1;
$apx->tmpl->assign('CODE',compatible_hsc($_POST['code']));
$apx->tmpl->assign('REPLACE',compatible_hsc($_POST['replace']));
$apx->tmpl->assign('EXAMPLE',compatible_hsc($_POST['example']));
$apx->tmpl->assign('COUNT',(int)$_POST['count']);
$apx->tmpl->assign('ALLOWSIG',(int)$_POST['allowsig']);
$apx->tmpl->assign('ACTION','add');
$apx->tmpl->parse('cadd_cedit');
}
}
//***************************** Codes bearbeiten *****************************
function cshow_edit() {
global $set,$apx,$db;
$apx->lang->dropaction('main','cedit');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die('missing ID!');
$codes=$set['main']['codes'];
if ( $_POST['send']==1 ) {
$_POST['code']=strtoupper($_POST['code']);
foreach ( $codes AS $key => $res ) {
if ( $key!=$_REQUEST['id'] && $res['code']==$_POST['code'] && $res['count']==$_POST['count'] ) $check=true;
}
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['code'] || !$_POST['count'] || !$_POST['replace'] ) infoNotComplete();
elseif ( $check ) info($apx->lang->get('INFO_EXISTS'));
elseif ( $_POST['code']=='PHP' ) info($apx->lang->get('INFO_BLOCK'));
else {
$codes[$_REQUEST['id']]=array(
'code' => $_POST['code'],
'count' => $_POST['count'],
'replace' => $_POST['replace'],
'example' => $_POST['example'],
'allowsig' => (int)$_POST['allowsig']
);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($codes))."' WHERE ( module='main' AND varname='codes' ) LIMIT 1");
logit('MAIN_CEDIT','ID #'.$_REQUEST['id']);
printJSRedirect(get_index('main.cshow'));
}
}
else {
foreach ( $codes[$_REQUEST['id']] AS $key => $val ) $_POST[$key]=$val;
$apx->tmpl->assign('CODE',compatible_hsc($_POST['code']));
$apx->tmpl->assign('REPLACE',compatible_hsc($_POST['replace']));
$apx->tmpl->assign('EXAMPLE',compatible_hsc($_POST['example']));
$apx->tmpl->assign('COUNT',(int)$_POST['count']);
$apx->tmpl->assign('ALLOWSIG',(int)$_POST['allowsig']);
$apx->tmpl->assign('ACTION','edit');
$apx->tmpl->assign('ID',$_REQUEST['id']);
$apx->tmpl->parse('cadd_cedit');
}
}
//***************************** Codes lรถschen *****************************
function cshow_del() {
global $set,$apx,$db;
$apx->lang->dropaction('main','cdel');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die('missing ID!');
$codes=$set['main']['codes'];
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
unset($codes[$_REQUEST['id']]);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($codes))."' WHERE ( module='main' AND varname='codes' ) LIMIT 1");
logit('MAIN_CDEL','ID #'.$_REQUEST['id']);
printJSReload();
}
}
else {
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($codes[$_REQUEST['id']]['code']))));
tmessageOverlay('cdel',array('ID' => $_REQUEST['id']));
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Badwords *****************************
function bshow() {
global $set,$apx,$db,$html;
$badwords=$set['main']['badwords'];
if ( !is_array($badwords) ) $badwords=array();
//Aktionen
if ( $_REQUEST['do']=='add' ) return $this->bshow_add();
if ( $_REQUEST['do']=='edit' ) return $this->bshow_edit();
if ( $_REQUEST['do']=='del' ) return $this->bshow_del();
echo'<p class="slink">» <a href="action.php?action=main.bshow&do=add">'.$apx->lang->get('ADDBADWORD').'</a></p>';
echo'<p class="hint">'.$apx->lang->get('MAININFO').'</p>';
$orderdef[0]='find';
$orderdef['find']=array('find','ASC','SORT_FIND');
$orderdef['replace']=array('replace','ASC','SORT_REPLACE');
$badwords=array_sort_def($badwords,$orderdef);
$col[]=array('COL_FIND',50,'');
$col[]=array('COL_REPLACE',50,'');
$count=count($badwords);
pages('action.php?action=main.bshow&sortby='.$_REQUEST['sortby'],$count);
foreach ( $badwords AS $key => $res ) {
++$i;
if ( $i<=($_REQUEST['p']-1)*$set['main']['admin_epp'] ) continue;
if ( $i>$_REQUEST['p']*$set['main']['admin_epp'] ) break;
$tabledata[$i]['COL1']=replace($res['find']);
$tabledata[$i]['COL2']=replace($res['replace']);
//Optionen
$tabledata[$i]['OPTIONS'] .= optionHTML('edit.gif', 'main.bshow', 'do=edit&id='.$key, $apx->lang->get('CORE_EDIT'));
$tabledata[$i]['OPTIONS'] .= optionHTMLOverlay('del.gif', 'main.bshow', 'do=del&id='.$key, $apx->lang->get('CORE_DEL'));
}
$apx->tmpl->assign('TABLE',$tabledata);
$html->table($col);
orderstr($orderdef,'action.php?action=main.bshow');
save_index($_SERVER['REQUEST_URI']);
}
//***************************** Badwords hinzufรผgen *****************************
function bshow_add() {
global $set,$apx,$db;
$apx->lang->dropaction('main','badd');
$badwords=$set['main']['badwords'];
if ( $_POST['send']==1 ) {
$_POST['find']=strtolower($_POST['find']);
foreach ( $badwords AS $res ) {
if ( $res['find']==$_POST['find'] ) $check=true;
}
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['find'] || !$_POST['replace'] ) infoNotComplete();
elseif ( $check ) info($apx->lang->get('INFO_EXISTS'));
else {
$nextkey=array_key_max($badwords)+1;
$badwords[$nextkey]=array(
'find' => $_POST['find'],
'replace' => $_POST['replace']
);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($badwords))."' WHERE ( module='main' AND varname='badwords' ) LIMIT 1");
logit('MAIN_BADD','ID #'.$nextkey);
printJSRedirect('action.php?action=main.bshow');
}
}
else {
$apx->tmpl->assign('FIND',compatible_hsc($_POST['find']));
$apx->tmpl->assign('REPLACE',compatible_hsc($_POST['replace']));
$apx->tmpl->assign('ACTION','add');
$apx->tmpl->parse('badd_bedit');
}
}
//***************************** Badwords bearbeiten *****************************
function bshow_edit() {
global $set,$apx,$db;
$apx->lang->dropaction('main','bedit');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die('missing ID!');
$badwords=$set['main']['badwords'];
if ( $_POST['send']==1 ) {
$_POST['find']=strtolower($_POST['find']);
foreach ( $badwords AS $key => $res ) {
if ( $key!=$_REQUEST['id'] && $res['find']==$_POST['find'] ) $check=true;
}
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['find'] || !$_POST['replace'] ) infoNotComplete();
elseif ( $check ) info($apx->lang->get('INFO_EXISTS'));
else {
$badwords[$_REQUEST['id']]=array(
'find' => $_POST['find'],
'replace' => $_POST['replace']
);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($badwords))."' WHERE ( module='main' AND varname='badwords' ) LIMIT 1");
logit('MAIN_BEDIT',"ID #".$_REQUEST['id']);
printJSRedirect(get_index('main.bshow'));
}
}
//Daten auslesen
else {
foreach ( $badwords[$_REQUEST['id']] AS $key => $val ) $_POST[$key]=$val;
$apx->tmpl->assign('FIND',compatible_hsc($_POST['find']));
$apx->tmpl->assign('REPLACE',compatible_hsc($_POST['replace']));
$apx->tmpl->assign('ACTION','edit');
$apx->tmpl->assign('ID',$_REQUEST['id']);
$apx->tmpl->parse('badd_bedit');
}
}
//***************************** Badwords lรถschen *****************************
function bshow_del() {
global $set,$apx,$db;
$apx->lang->dropaction('main','bdel');
$_REQUEST['id']=(int)$_REQUEST['id'];
if ( !$_REQUEST['id'] ) die('missing ID!');
$badwords=$set['main']['badwords'];
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
unset($badwords[$_REQUEST['id']]);
$db->query("UPDATE ".PRE."_config SET value='".addslashes(serialize($badwords))."' WHERE ( module='main' AND varname='badwords' ) LIMIT 1");
logit('MAIN_BDEL','ID #'.$_REQUEST['id']);
printJSReload();
}
}
else {
$apx->tmpl->assign('MESSAGE', $apx->lang->get('MSG_TEXT', array('TITLE' => compatible_hsc($badwords[$_REQUEST['id']]['find']))));
tmessageOverlay('bdel',array('ID' => $_REQUEST['id']));
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Protokoll *****************************
function log() {
global $set,$apx,$db;
logit('MAIN_LOG');
$apx->lang->dropall('log');
if ( $apx->user->has_spright('main.log') ) {
if ( $_REQUEST['clean'] ) {
$this->log_clean();
return;
}
elseif ( $_REQUEST['download'] ) {
$this->log_download();
return;
}
echo'<p class="slink">';
echo'» <a href="javascript:MessageOverlayManager.createLayer(\'action.php?action=main.log&clean=1\');">'.$apx->lang->get('CLEANLOG').'</a><br />';
echo'» <a href="action.php?action=main.log&download=1&sectoken='.$apx->session->get('sectoken').'">'.$apx->lang->get('DOWNLOADLOG').'</a>';
echo'</p>';
}
$log=compatible_hsc($this->log_get(100));
$log.=date('Y/m/d H:i:s',time()-TIMEDIFF).' >>> LOG END';
$apx->tmpl->assign('LOG',$log);
$apx->tmpl->parse('log');
}
//PROTOKOLL GENERIEREN
function log_get($limit=null) {
global $set,$apx,$db;
if ( $limit ) {
list($count) = $db->first("SELECT count(*) FROM ".PRE."_log");
$query = $db->query("SELECT a.*,b.username FROM ".PRE."_log AS a LEFT JOIN ".PRE."_user AS b USING(userid) ORDER BY time ASC LIMIT ".max(array($count-$limit, 0)).",".$limit);
}
else {
$query = $db->query("SELECT a.*,b.username FROM ".PRE."_log AS a LEFT JOIN ".PRE."_user AS b USING(userid) ORDER BY time ASC");
}
$strlen_ip = 3+1+3+1+3+1+3;
$strlen_username = 30;
//Log zusammensetzen
while ( $res = $query->fetch_array() ) {
$out.=$res['time'].' ';
$out.=str_pad($res['username'],$strlen_username).' ';
$out.=str_pad($res['ip'],$strlen_ip).' ';
$out.=$res['text'];
if ( $res['affects']!='' ) $out.=' -> '.$res['affects'];
$out.="\n";
}
$db->free_result($query);
//Sprachplatzhalter
$out = $apx->lang->insertpack($out);
return $out;
}
//PROTOKOLL LEEREN
function log_clean() {
global $set,$apx,$db;
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
$db->query("DELETE FROM ".PRE."_log");
logit('MAIN_LOG_CLEAN');
printJSReload();
}
}
else {
tmessageOverlay('logclean');
}
}
//LOG HERUNTERLADEN
function log_download() {
if ( !checkToken() ) printInvalidToken();
else {
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename=apexx_'.date('Y-m-d_H-i-s',time()-TIMEDIFF).'.log');
header('Accept-Ranges: bytes');
echo strtr($this->log_get(),array('>'=>'>','<'=>'<'));
exit;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Umgebungsvariablen *****************************
function env() {
global $set,$apx,$db;
list($count_user)=$db->first("SELECT count(userid) FROM ".PRE."_user");
list($count_group)=$db->first("SELECT count(groupid) FROM ".PRE."_user_groups");
$apx->tmpl->assign('SERVER',$_SERVER['SERVER_SOFTWARE']);
$apx->tmpl->assign('PHP',phpversion());
$apx->tmpl->assign('MYSQL',$db->server_info());
$apx->tmpl->assign('VERSION',VERSION);
$apx->tmpl->assign('C_USER',$count_user);
$apx->tmpl->assign('C_GROUP',$count_group);
$apx->tmpl->assign('PATH_BASEDIR',BASEDIR);
$apx->tmpl->assign('PATH_MODULES',BASEDIR.getpath('moduledir'));
$apx->tmpl->assign('PATH_UPLOADS',BASEDIR.getpath('uploads'));
//Funktionen
$tfuncs=$apx->functions;
ksort($tfuncs);
foreach ( $tfuncs AS $module => $funcs ) {
ksort($funcs);
foreach ( $funcs AS $name => $info ) {
++$i;
$funcdata[$i]['FUNC']='{'.$name.'()}';
$funcdata[$i]['FUNCNAME']=$info[0].'()';
$funcdata[$i]['PARAMS']=iif($info[1]==true,$apx->lang->get('YES'),$apx->lang->get('NO'));
$funcdata[$i]['MODULE']=$module;
}
}
$apx->tmpl->assign('TFUNC',$funcdata);
$apx->tmpl->parse('env');
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Gesuchte Begriffe *****************************
function searches() {
global $set,$apx,$db;
$data=$db->fetch("
SELECT item,count(item) AS count
FROM ".PRE."_search_item
WHERE time>='".(time()-30*24*3600)."'
GROUP BY item
ORDER by count DESC
");
if ( count($data) ) {
foreach ( $data AS $res ) {
++$i;
$tabledata[$i]['HITS']=number_format($res['count'],0,'','.');
$tabledata[$i]['STRING']=htmlentities($res['item'],ENT_QUOTES,"UTF-8");
}
}
$apx->tmpl->assign('SEARCH',$tabledata);
$apx->tmpl->parse('searches');
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Seite schlieรen *****************************
function close() {
global $set,$apx,$db;
if ( $_POST['send']==1 ) {
if ( !checkToken() ) infoInvalidToken();
elseif ( !$_POST['message'] ) infoNotComplete();
else {
$db->query("UPDATE ".PRE."_config SET value=1 WHERE ( varname='closed' AND module='main' ) LIMIT 1");
$db->query("UPDATE ".PRE."_config SET value='".addslashes($_POST['message'])."' WHERE ( varname='close_message' AND module='main' ) LIMIT 1");
logit('MAIN_CLOSE');
printJSRedirect('action.php?action=main.close');
return;
}
}
elseif ( $_POST['send']==2 ) {
$db->query("UPDATE ".PRE."_config SET value=0 WHERE ( varname='closed' AND module='main' ) LIMIT 1");
logit('MAIN_CLOSE_OPEN');
printJSRedirect('action.php?action=main.close');
}
else {
$apx->tmpl->assign('CLOSED', $set['main']['closed']);
$apx->tmpl->assign('MESSAGE', compatible_hsc($set['main']['close_message']));
$apx->tmpl->parse('close');
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//***************************** Cache leeren *****************************
function delcache() {
global $set,$apx,$db;
if ( $_POST['send']==1 ) {
if ( !checkToken() ) printInvalidToken();
else {
$apx->tmpl->clear_cache();
logit('MAIN_DELCACHE');
message($apx->lang->get('MSG_OK'),'action.php?action=main.index');
}
}
else tmessage('delcache',$insert);
}
} //END CLASS
?>
| scheb/open-apexx | src/modules/main/admin.php | PHP | lgpl-3.0 | 81,701 |
/*
Program for testing dccrg using Conway's game of life.
Copyright 2010, 2011, 2012, 2013, 2014,
2015, 2016, 2018 Finnish Meteorological Institute
Copyright 2018 Ilja Honkonen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 3
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "algorithm"
#include "array"
#include "cstdlib"
#include "fstream"
#include "iostream"
#include "unordered_set"
#include "boost/lexical_cast.hpp"
#include "boost/program_options.hpp"
#include "mpi.h"
#include "zoltan.h"
#include "dccrg_stretched_cartesian_geometry.hpp"
#include "dccrg.hpp"
#include "cell.hpp"
#include "initialize.hpp"
#include "save.hpp"
#ifdef OPTIMIZED
#include "solve_optimized.hpp"
#else
#include "solve.hpp"
#endif
using namespace std;
using namespace boost;
using namespace dccrg;
/*!
Returns EXIT_SUCCESS if the state of the given game at given timestep is correct on this process, returns EXIT_FAILURE otherwise.
timestep == 0 means before any turns have been taken.
*/
int check_game_of_life_state(int timestep, const Dccrg<Cell, Stretched_Cartesian_Geometry>& grid)
{
for (const auto& cell: grid.local_cells()) {
// check cells that are always supposed to be alive
switch (cell.id) {
case 22:
case 23:
case 32:
case 33:
case 36:
case 39:
case 47:
case 48:
case 52:
case 53:
case 94:
case 95:
case 110:
case 122:
case 137:
case 138:
case 188:
case 199:
case 206:
if (!cell.data->data[0]) {
cerr << "Cell " << cell.id
<< " isn't alive on timestep " << timestep
<< endl;
return EXIT_FAILURE;
}
break;
default:
break;
}
// these are supposed to be alive every other turn
if (timestep % 2 == 0) {
switch (cell.id) {
case 109:
case 123:
case 189:
case 190:
case 198:
case 200:
case 204:
case 205:
if (!cell.data->data[0]) {
cerr << "Cell " << cell.id
<< " isn't alive on timestep " << timestep
<< endl;
return EXIT_FAILURE;
}
break;
default:
break;
}
} else {
switch (cell.id) {
case 174:
case 184:
case 214:
case 220:
if (!cell.data->data[0]) {
cerr << "Cell " << cell.id
<< " isn't alive on timestep " << timestep
<< endl;
return EXIT_FAILURE;
}
break;
default:
break;
}
}
// check that the glider is moving correctly
switch (timestep) {
/* can't be bothered manually for cases 1-19, use an automatic method later */
case 20:
switch (cell.id) {
case 43:
case 44:
case 45:
case 60:
case 74:
if (!cell.data->data[0]) {
cerr << "Cell " << cell.id
<< " isn't alive on timestep " << timestep
<< endl;
return EXIT_FAILURE;
}
break;
default:
break;
}
break;
case 21:
switch (cell.id) {
case 29:
case 44:
case 45:
case 58:
case 60:
if (!cell.data->data[0]) {
cerr << "Cell " << cell.id
<< " isn't alive on timestep " << timestep
<< endl;
return EXIT_FAILURE;
}
break;
default:
break;
}
break;
case 22:
switch (cell.id) {
case 29:
case 30:
case 43:
case 45:
case 60:
if (!cell.data->data[0]) {
cerr << "Cell " << cell.id
<< " isn't alive on timestep " << timestep
<< endl;
return EXIT_FAILURE;
}
break;
default:
break;
}
break;
case 23:
switch (cell.id) {
case 29:
case 30:
case 45:
case 59:
if (!cell.data->data[0]) {
cerr << "Cell " << cell.id
<< " isn't alive on timestep " << timestep
<< endl;
return EXIT_FAILURE;
}
break;
default:
break;
}
break;
case 24:
switch (cell.id) {
case 29:
case 30:
case 45:
if (!cell.data->data[0]) {
cerr << "Cell " << cell.id
<< " isn't alive on timestep " << timestep
<< endl;
return EXIT_FAILURE;
}
break;
default:
break;
}
break;
default:
break;
}
}
return EXIT_SUCCESS;
}
int main(int argc, char* argv[])
{
if (MPI_Init(&argc, &argv) != MPI_SUCCESS) {
cerr << "Coudln't initialize MPI." << endl;
abort();
}
MPI_Comm comm = MPI_COMM_WORLD;
int rank = 0, comm_size = 0;
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &comm_size);
/*
Options
*/
char direction;
bool save_results = false, verbose = false;
boost::program_options::options_description options("Usage: program_name [options], where options are:");
options.add_options()
("help", "print this help message")
("direction",
boost::program_options::value<char>(&direction)->default_value('z'),
"Create a 2d grid with normal into direction arg (x, y or z)")
("save", "Save the game to vtk files")
("verbose", "Print information about the game");
// read options from command line
boost::program_options::variables_map option_variables;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, options), option_variables);
boost::program_options::notify(option_variables);
// print a help message if asked
if (option_variables.count("help") > 0) {
if (rank == 0) {
cout << options << endl;
}
MPI_Barrier(comm);
MPI_Finalize();
return EXIT_SUCCESS;
}
if (option_variables.count("verbose") > 0) {
verbose = true;
}
if (option_variables.count("save") > 0) {
save_results = true;
}
// intialize Zoltan
float zoltan_version;
if (Zoltan_Initialize(argc, argv, &zoltan_version) != ZOLTAN_OK) {
cerr << "Zoltan_Initialize failed" << endl;
abort();
}
if (verbose && rank == 0) {
cout << "Using Zoltan version " << zoltan_version << endl;
}
// initialize grid
Dccrg<Cell, Stretched_Cartesian_Geometry> grid;
const uint64_t base_length = 15;
const double cell_length = 1.0 / base_length;
// set grid length in each dimension based on direction given by user
std::array<uint64_t, 3> grid_length = {{0, 0, 0}};
switch (direction) {
case 'x':
grid_length[0] = 1;
grid_length[1] = base_length;
grid_length[2] = base_length;
break;
case 'y':
grid_length[0] = base_length;
grid_length[1] = 1;
grid_length[2] = base_length;
break;
case 'z':
grid_length[0] = base_length;
grid_length[1] = base_length;
grid_length[2] = 1;
break;
default:
cerr << "Unsupported direction given: " << direction << endl;
break;
}
const unsigned int neighborhood_size = 1;
grid
.set_initial_length(grid_length)
.set_neighborhood_length(neighborhood_size)
.set_maximum_refinement_level(0)
.set_load_balancing_method("RANDOM")
.initialize(comm);
Stretched_Cartesian_Geometry::Parameters geom_params;
for (size_t dimension = 0; dimension < grid_length.size(); dimension++) {
for (uint64_t i = 0; i <= grid_length[dimension]; i++) {
geom_params.coordinates[dimension].push_back(double(i) * cell_length);
}
}
grid.set_geometry(geom_params);
#ifdef SEND_SINGLE_CELLS
grid.set_send_single_cells(true);
#endif
if (verbose && rank == 0) {
cout << "Maximum refinement level of the grid: " << grid.get_maximum_refinement_level()
<< "\nNumber of cells: "
<< (geom_params.coordinates[0].size() - 1)
* (geom_params.coordinates[1].size() - 1)
* (geom_params.coordinates[2].size() - 1)
<< "\nSending single cells: " << boolalpha << grid.get_send_single_cells()
<< endl << endl;
}
initialize(grid, base_length);
// every process outputs the game state into its own file
string basename("tests/game_of_life/game_of_life_test_");
basename.append(1, direction).append("_").append(lexical_cast<string>(rank)).append("_");
// visualize the game with visit -o game_of_life_test.visit
ofstream visit_file;
if (save_results && rank == 0) {
string visit_file_name("tests/game_of_life/game_of_life_test_");
visit_file_name += direction;
visit_file_name += ".visit";
visit_file.open(visit_file_name.c_str());
visit_file << "!NBLOCKS " << comm_size << endl;
}
const int time_steps = 25;
if (verbose && rank == 0) {
cout << "step: ";
}
for (int step = 0; step < time_steps; step++) {
grid.balance_load();
grid.start_remote_neighbor_copy_updates();
grid.wait_remote_neighbor_copy_updates();
int result = check_game_of_life_state(step, grid);
if ((grid_length[0] != 15 and grid_length[1] != 15) or result != EXIT_SUCCESS) {
cout << "Process " << rank << ": Game of Life test failed on timestep: " << step << endl;
abort();
}
if (verbose && rank == 0) {
cout << step << " ";
cout.flush();
}
if (save_results) {
// write the game state into a file named according to the current time step
string output_name(basename);
output_name.append(lexical_cast<string>(step)).append(".vtk");
save(output_name, rank, grid);
// visualize the game with visit -o game_of_life_test.visit
if (rank == 0) {
for (int process = 0; process < comm_size; process++) {
visit_file << "game_of_life_test_"
<< direction << "_"
<< process << "_"
<< lexical_cast<string>(step)
<< ".vtk"
<< endl;
}
}
}
get_live_neighbors(grid);
}
if (rank == 0 and save_results) {
visit_file.close();
}
MPI_Finalize();
return EXIT_SUCCESS;
}
| fmihpc/dccrg | tests/game_of_life/game_of_life_test.cpp | C++ | lgpl-3.0 | 9,602 |
/*
Copyright 2009 Adam Ribaldo
Developed by Adam Ribaldo, Chris Lloyd
This file is part of SevenUpLive.
http://www.makingthenoise.com/sevenup/
SevenUpLive 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 3 of the License, or
(at your option) any later version.
SevenUpLive 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 SevenUpLive. If not, see <http://www.gnu.org/licenses/>.
*/
package mtn.sevenuplive.modes.events;
public class KeyTransposeGroupEvent implements Event {
public static final String KEY_TRANSPOSE_GROUP_EVENT = "KEY_TRANSPOSE_GROUP_EVENT";
private int group;
private int key_x;
private int key_y;
public int getGroup() {
return group;
}
public int getKeyX() {
return key_x;
}
public int getKeyY() {
return key_y;
}
public KeyTransposeGroupEvent() {}
public KeyTransposeGroupEvent(int group, int key_x, int key_y) {
this.group = group;
this.key_x = key_x;
this.key_y = key_y;
}
public String getType() {
return KEY_TRANSPOSE_GROUP_EVENT;
}
}
| adamribaudo/sevenuplive | src/mtn/sevenuplive/modes/events/KeyTransposeGroupEvent.java | Java | lgpl-3.0 | 1,461 |
#ifndef OFFL8DEC2013
#define OFFL8DEC2013
/*
* Initializes v[0..len-1] to mic device number/ -1 if on host.
*/
__declspec(target(mic)) void dummy(double *v, long len);
/*
* Does nothing.
*/
__declspec(target(mic)) void dummyx(double *v, long len);
/*
* With fst[i] being i*n/nmic,
* array section v[fst[i]..fst[i+1]-1] is allocated on mic device #i.
*/
void alloc_micmem(double *v, long n, int nmic);
/*
* With fst[i] being i*n/nmic,
* array section v[fst[i]..fst[i+1]-1] is freed on mic device #i.
*/
void free_micmem(double *v, long n, int nmic);
/*
* xfers v[0..n-1].
* nmic: num of mic devices.
* xfer direction is in.
* Memory on mics is neither allocated not freed.
*/
void xfer_in(double *v, long n, int nmic);
/*
* xfer direction is out. Same as above, otherwise.
*/
void xfer_out(double *v, long n, int nmic);
/*
* xfer direction is in and out. Same as above, otherwise.
*/
void xfer_inout(double *v, long n, int nmic);
#endif
| divakarvi/bk-spca | xphi/offload/offl.hh | C++ | lgpl-3.0 | 964 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-09 17:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('patrons', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='patron',
name='canonisation',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='patron',
name='reminiscence',
field=models.DateField(blank=True, null=True),
),
]
| PrayAndGrow/server | patrons/migrations/0002_auto_20160409_1714.py | Python | lgpl-3.0 | 620 |
<?php
/**
* Date Property Value
*
* RFC 5545 Definition
*
* Value Name: DATE
*
* Purpose: This value type is used to identify values that contain a
* calendar date.
*
* Formal Definition: The value type is defined by the following
* notation:
*
* date = date-value
* date-value = date-fullyear date-month date-mday
* date-fullyear = 4DIGIT
* date-month = 2DIGIT ;01-12
* date-mday = 2DIGIT ;01-28, 01-29, 01-30, 01-31
* ;based on month/year
*
* Description: If the property permits, multiple "date" values are
* specified as a COMMA character (US-ASCII decimal 44) separated list
* of values. The format for the value type is expressed as the [ISO
* 8601] complete representation, basic format for a calendar date. The
* textual format specifies a four-digit year, two-digit month, and
* two-digit day of the month. There are no separator characters between
* the year, month and day component text.
*
* No additional content value encoding (i.e., BACKSLASH character
* encoding) is defined for this value type.
*
* Example: The following represents July 14, 1997:
*
* 19970714
*
* @package qCal
* @subpackage qCal\Value
* @author Luke Visinoni <luke.visinoni@gmail.com>
* @copyright (c) 2014 Luke Visinoni <luke.visinoni@gmail.com>
* @license GNU Lesser General Public License v3 (see LICENSE file)
*/
namespace qCal\Value;
use \qCal\DateTime;
class Date extends \qCal\Value {
public function toString() {
return $this->value->toDate();
}
protected function cast($value) {
// @todo return qCal\DateTime\Date object
return new DateTime($value);
}
}
| nozavroni/qcal | lib/qCal/Value/Date.php | PHP | lgpl-3.0 | 1,720 |
<?php
// ---------- CREDITS ----------
// Mirrored from pocketmine\network\mcpe\protocol\RequestChunkRadiusPacket.php
// Mirroring was done by @CortexPE of @LeverylTeam :D
//
// NOTE: We know that this was hacky... But It's here to still provide support for old plugins
// ---------- CREDITS ----------
namespace pocketmine\network\protocol;
use pocketmine\network\mcpe\protocol\RequestChunkRadiusPacket as Original;
class RequestChunkRadiusPacket extends Original {
}
| LeverylTeam/Leveryl | src/pocketmine/network/protocol/RequestChunkRadiusPacket.php | PHP | lgpl-3.0 | 479 |
//
// Shape.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 10/28/12.
//
//
#ifndef __G3MiOSSDK__Shape__
#define __G3MiOSSDK__Shape__
#include "Geodetic3D.hpp"
#include "Context.hpp"
#include "Vector3D.hpp"
class MutableMatrix44D;
#include "Effects.hpp"
#include <vector>
#include "GLState.hpp"
#include "SurfaceElevationProvider.hpp"
#include "Geodetic3D.hpp"
class ShapePendingEffect;
class GPUProgramState;
class Shape : public SurfaceElevationListener, EffectTarget{
private:
Geodetic3D* _position;
AltitudeMode _altitudeMode;
Angle* _heading;
Angle* _pitch;
Angle* _roll;
double _scaleX;
double _scaleY;
double _scaleZ;
double _translationX;
double _translationY;
double _translationZ;
// const Planet* _planet;
mutable MutableMatrix44D* _transformMatrix;
MutableMatrix44D* getTransformMatrix(const Planet* planet) const;
std::vector<ShapePendingEffect*> _pendingEffects;
bool _enable;
mutable GLState* _glState;
SurfaceElevationProvider* _surfaceElevationProvider;
double _surfaceElevation;
protected:
virtual void cleanTransformMatrix();
public:
MutableMatrix44D* createTransformMatrix(const Planet* planet) const;
Shape(Geodetic3D* position,
AltitudeMode altitudeMode) :
_position( position ),
_altitudeMode(altitudeMode),
_heading( new Angle(Angle::zero()) ),
_pitch( new Angle(Angle::zero()) ),
_roll( new Angle(Angle::zero()) ),
_scaleX(1),
_scaleY(1),
_scaleZ(1),
_translationX(0),
_translationY(0),
_translationZ(0),
_transformMatrix(NULL),
_enable(true),
_surfaceElevation(0),
_glState(new GLState())
{
}
virtual ~Shape();
const Geodetic3D getPosition() const {
return *_position;
}
const Angle getHeading() const {
return *_heading;
}
const Angle getPitch() const {
return *_pitch;
}
const Angle getRoll() const {
return *_roll;
}
void setPosition(Geodetic3D* position,
AltitudeMode altitudeMode) {
delete _position;
_position = position;
_altitudeMode = altitudeMode;
cleanTransformMatrix();
}
void setPosition(Geodetic3D* position) {
delete _position;
_position = position;
cleanTransformMatrix();
}
void addShapeEffect(Effect* effect);
void setAnimatedPosition(const TimeInterval& duration,
const Geodetic3D& position,
bool linearInterpolation=false);
void setAnimatedPosition(const TimeInterval& duration,
const Geodetic3D& position,
const Angle& pitch,
const Angle& heading,
const Angle& roll,
bool linearInterpolation=false);
void setAnimatedPosition(const Geodetic3D& position,
bool linearInterpolation=false) {
setAnimatedPosition(TimeInterval::fromSeconds(3),
position,
linearInterpolation);
}
void setHeading(const Angle& heading) {
#ifdef C_CODE
delete _heading;
_heading = new Angle(heading);
#endif
#ifdef JAVA_CODE
_heading = heading;
#endif
cleanTransformMatrix();
}
void setPitch(const Angle& pitch) {
#ifdef C_CODE
delete _pitch;
_pitch = new Angle(pitch);
#endif
#ifdef JAVA_CODE
_pitch = pitch;
#endif
cleanTransformMatrix();
}
void setRoll(const Angle& roll) {
#ifdef C_CODE
delete _roll;
_roll = new Angle(roll);
#endif
#ifdef JAVA_CODE
_roll = roll;
#endif
cleanTransformMatrix();
}
void setScale(double scale) {
setScale(scale, scale, scale);
}
void setTranslation(const Vector3D& translation) {
setTranslation(translation._x,
translation._y,
translation._z);
}
void setTranslation(double translationX,
double translationY,
double translationZ) {
_translationX = translationX;
_translationY = translationY;
_translationZ = translationZ;
cleanTransformMatrix();
}
void setScale(double scaleX,
double scaleY,
double scaleZ) {
_scaleX = scaleX;
_scaleY = scaleY;
_scaleZ = scaleZ;
cleanTransformMatrix();
}
void setScale(const Vector3D& scale) {
setScale(scale._x,
scale._y,
scale._z);
}
Vector3D getScale() const {
return Vector3D(_scaleX,
_scaleY,
_scaleZ);
}
void setAnimatedScale(const TimeInterval& duration,
double scaleX,
double scaleY,
double scaleZ);
void setAnimatedScale(double scaleX,
double scaleY,
double scaleZ) {
setAnimatedScale(TimeInterval::fromSeconds(1),
scaleX,
scaleY,
scaleZ);
}
void setAnimatedScale(const Vector3D& scale) {
setAnimatedScale(scale._x,
scale._y,
scale._z);
}
void setAnimatedScale(const TimeInterval& duration,
const Vector3D& scale) {
setAnimatedScale(duration,
scale._x,
scale._y,
scale._z);
}
void orbitCamera(const TimeInterval& duration,
double fromDistance, double toDistance,
const Angle& fromAzimuth, const Angle& toAzimuth,
const Angle& fromAltitude, const Angle& toAltitude);
bool isEnable() const {
return _enable;
}
void setEnable(bool enable) {
_enable = enable;
}
void render(const G3MRenderContext* rc,
GLState* parentState,
bool renderNotReadyShapes);
virtual void initialize(const G3MContext* context) {
_surfaceElevationProvider = context->getSurfaceElevationProvider();
if (_surfaceElevationProvider != NULL) {
_surfaceElevationProvider->addListener(_position->_latitude,
_position->_longitude,
this);
}
}
virtual bool isReadyToRender(const G3MRenderContext* rc) = 0;
virtual void rawRender(const G3MRenderContext* rc,
GLState* parentGLState,
bool renderNotReadyShapes) = 0;
virtual bool isTransparent(const G3MRenderContext* rc) = 0;
void elevationChanged(const Geodetic2D& position,
double rawElevation, // Without considering vertical exaggeration
double verticalExaggeration);
void elevationChanged(const Sector& position,
const ElevationData* rawElevationData, // Without considering vertical exaggeration
double verticalExaggeration) {}
virtual std::vector<double> intersectionsDistances(const Vector3D& origin,
const Vector3D& direction) const = 0;
};
#endif
| ccarducci/Ushahidi_local | G3MiOSSDK/Commons/Rendererers/Shape.hpp | C++ | lgpl-3.0 | 7,170 |
/* $Id: clparser.cpp 485043 2015-11-18 14:43:31Z sadyrovr $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Dmitry Kazimirov
*
*/
#include <ncbi_pch.hpp>
#include <corelib/ncbiapp.hpp>
#include <connect/services/clparser.hpp>
#include <algorithm>
BEGIN_NCBI_SCOPE
#define VERSION_OPT_ID -1
#define HELP_OPT_ID -2
#define COMMAND_OPT_ID -3
#define HELP_CMD_ID -1
#define UNSPECIFIED_CATEGORY_ID -1
#define DEFAULT_HELP_TEXT_WIDTH 72
#define DEFAULT_CMD_DESCR_INDENT 24
#define DEFAULT_OPT_DESCR_INDENT 32
typedef list<string> TNameVariantList;
struct SOptionOrCommandInfo : public CObject
{
SOptionOrCommandInfo(int id, const string& name_variants) : m_Id(id)
{
NStr::Split(name_variants, "|", m_NameVariants,
NStr::fSplit_MergeDelimiters | NStr::fSplit_Truncate);
}
const string& GetPrimaryName() const {return m_NameVariants.front();}
int m_Id;
TNameVariantList m_NameVariants;
};
struct SOptionInfo : public SOptionOrCommandInfo
{
SOptionInfo(int opt_id, const string& name_variants,
CCommandLineParser::EOptionType type,
const string& description) :
SOptionOrCommandInfo(opt_id, name_variants),
m_Type(type),
m_Description(description)
{
}
static string AddDashes(const string& opt_name)
{
return opt_name.length() == 1 ? '-' + opt_name : "--" + opt_name;
}
string GetNameVariants() const
{
string result(AddDashes(m_NameVariants.front()));
if (m_NameVariants.size() > 1) {
result.append(" [");
TNameVariantList::const_iterator name(m_NameVariants.begin());
result.append(AddDashes(*++name));
while (++name != m_NameVariants.end()) {
result.append(", ");
result.append(AddDashes(*name));
}
result.push_back(']');
}
if (m_Type == CCommandLineParser::eOptionWithParameter)
result.append(" ARG");
return result;
}
int m_Type;
string m_Description;
};
typedef list<const SOptionInfo*> TOptionInfoList;
struct SCommonParts
{
SCommonParts(const string& synopsis, const string& usage) :
m_Synopsis(synopsis),
m_Usage(usage)
{
}
string m_Synopsis;
string m_Usage;
TOptionInfoList m_PositionalArguments;
TOptionInfoList m_AcceptedOptions;
};
struct SCommandInfo : public SOptionOrCommandInfo, public SCommonParts
{
SCommandInfo(int cmd_id, const string& name_variants,
const string& synopsis, const string& usage) :
SOptionOrCommandInfo(cmd_id, name_variants),
SCommonParts(synopsis, usage)
{
}
string GetNameVariants() const
{
if (m_NameVariants.size() == 1)
return m_NameVariants.front();
TNameVariantList::const_iterator name(m_NameVariants.begin());
string result(*name);
result.append(" (");
result.append(*++name);
while (++name != m_NameVariants.end()) {
result.append(", ");
result.append(*name);
}
result.push_back(')');
return result;
}
};
typedef list<const SCommandInfo*> TCommandInfoList;
struct SCategoryInfo : public CObject
{
SCategoryInfo(const string& title) : m_Title(title) {}
string m_Title;
TCommandInfoList m_Commands;
};
typedef list<const char*> TPositionalArgumentList;
struct SCommandLineParserImpl : public CObject, public SCommonParts
{
SCommandLineParserImpl(
const string& program_name,
const string& program_summary,
const string& program_description,
const string& version_info);
void PrintWordWrapped(int topic_len, int indent,
const string& text, int cont_indent = -1) const;
void Help(const TPositionalArgumentList& commands,
bool using_help_command) const;
void HelpOnCommand(const SCommonParts* common_parts,
const string& name_for_synopsis, const string& name_for_usage) const;
void Throw(const string& error, const string& cmd = kEmptyStr) const;
int ParseAndValidate(int argc, const char* const *argv);
// Command and argument definitions.
string m_ProgramName;
string m_VersionInfo;
typedef map<string, const SOptionInfo*> TOptionNameToOptionInfoMap;
typedef map<string, const SCommandInfo*> TCommandNameToCommandInfoMap;
const SOptionInfo* m_SingleLetterOptions[256];
TOptionNameToOptionInfoMap m_OptionToOptInfoMap;
map<int, CRef<SOptionInfo> > m_OptIdToOptionInfoMap;
TCommandNameToCommandInfoMap m_CommandNameToCommandInfoMap;
map<int, CRef<SCommandInfo> > m_CmdIdToCommandInfoMap;
typedef map<int, CRef<SCategoryInfo> > TCatIdToCategoryInfoMap;
TCatIdToCategoryInfoMap m_CatIdToCatInfoMap;
SOptionInfo m_VersionOption;
SOptionInfo m_HelpOption;
bool CommandsAreDefined() const
{
return !m_CommandNameToCommandInfoMap.empty();
}
// Parsing results.
typedef pair<const SOptionInfo*, const char*> TOptionValue;
typedef list<TOptionValue> TOptionValues;
TOptionValues m_OptionValues;
TOptionValues::const_iterator m_NextOptionValue;
// Help text formatting.
int m_MaxHelpTextWidth;
int m_CmdDescrIndent;
int m_OptDescrIndent;
};
static const char s_Help[] = "help";
static const char s_Version[] = "version";
SCommandLineParserImpl::SCommandLineParserImpl(
const string& program_name,
const string& program_summary,
const string& program_description,
const string& version_info) :
SCommonParts(program_summary, program_description),
m_ProgramName(program_name),
m_VersionInfo(version_info),
m_VersionOption(VERSION_OPT_ID, s_Version,
CCommandLineParser::eSwitch, kEmptyStr),
m_HelpOption(HELP_OPT_ID, s_Help,
CCommandLineParser::eSwitch, kEmptyStr),
m_MaxHelpTextWidth(DEFAULT_HELP_TEXT_WIDTH),
m_CmdDescrIndent(DEFAULT_CMD_DESCR_INDENT),
m_OptDescrIndent(DEFAULT_OPT_DESCR_INDENT)
{
memset(m_SingleLetterOptions, 0, sizeof(m_SingleLetterOptions));
m_OptionToOptInfoMap[s_Version] = &m_VersionOption;
m_OptionToOptInfoMap[s_Help] = &m_HelpOption;
m_CatIdToCatInfoMap[UNSPECIFIED_CATEGORY_ID] =
new SCategoryInfo("Available commands");
}
void SCommandLineParserImpl::PrintWordWrapped(int topic_len,
int indent, const string& text, int cont_indent) const
{
if (text.empty()) {
printf("\n");
return;
}
const char* line = text.data();
const char* text_end = line + text.length();
int offset = indent;
if (topic_len > 0 && (offset -= topic_len) < 1) {
offset = indent;
printf("\n");
}
if (cont_indent < 0)
cont_indent = indent;
#ifdef __GNUC__
const char* next_line = NULL; // A no-op assignment to make GCC happy.
#else
const char* next_line;
#endif
do {
const char* line_end;
// Check for verbatim formatting.
if (*line != ' ') {
const char* pos = line;
const char* max_pos = line + m_MaxHelpTextWidth - indent;
line_end = NULL;
for (;;) {
if (*pos == ' ') {
line_end = pos;
while (pos < text_end && pos[1] == ' ')
++pos;
next_line = pos + 1;
} else if (*pos == '\n') {
next_line = (line_end = pos) + 1;
break;
}
if (++pos > max_pos && line_end != NULL)
break;
if (pos == text_end) {
next_line = line_end = pos;
break;
}
}
} else {
// Preformatted text -- do not wrap.
line_end = strchr(line, '\n');
next_line = (line_end == NULL ? line_end = text_end : line_end + 1);
}
int line_len = int(line_end - line);
if (line_len > 0)
printf("%*.*s\n", offset + line_len, line_len, line);
else
printf("\n");
offset = indent = cont_indent;
} while ((line = next_line) < text_end);
}
void SCommandLineParserImpl::Help(const TPositionalArgumentList& commands,
bool using_help_command) const
{
ITERATE(TOptionValues, option_value, m_OptionValues)
if (option_value->first->m_Id != HELP_OPT_ID) {
string opt_name(option_value->first->GetNameVariants());
if (using_help_command)
Throw("command 'help' doesn't accept option '" +
opt_name + "'", s_Help);
else
Throw("'--help' cannot be combined with option '" +
opt_name + "'", "--help");
}
if (!CommandsAreDefined())
HelpOnCommand(this, m_ProgramName, m_ProgramName);
else if (commands.empty()) {
printf("Usage: %s <command> [options] [args]\n", m_ProgramName.c_str());
PrintWordWrapped(0, 0, m_Synopsis);
printf("Type '%s help <command>' for help on a specific command.\n"
"Type '%s --version' to see the program version.\n",
m_ProgramName.c_str(), m_ProgramName.c_str());
if (!m_Usage.empty()) {
printf("\n");
PrintWordWrapped(0, 0, m_Usage);
}
ITERATE(TCatIdToCategoryInfoMap, category, m_CatIdToCatInfoMap) {
if (!category->second->m_Commands.empty()) {
printf("\n%s:\n\n", category->second->m_Title.c_str());
ITERATE(TCommandInfoList, cmd, category->second->m_Commands)
PrintWordWrapped(printf(" %s",
(*cmd)->GetNameVariants().c_str()),
m_CmdDescrIndent - 2, "- " + (*cmd)->m_Synopsis,
m_CmdDescrIndent);
}
}
printf("\n");
} else {
SCommandInfo help_command(HELP_CMD_ID, s_Help,
"Describe the usage of this program or its commands.", kEmptyStr);
SOptionInfo command_arg(COMMAND_OPT_ID, "COMMAND",
CCommandLineParser::eZeroOrMorePositional, kEmptyStr);
help_command.m_PositionalArguments.push_back(&command_arg);
ITERATE(TPositionalArgumentList, cmd_name, commands) {
const SCommandInfo* command_info;
TCommandNameToCommandInfoMap::const_iterator cmd =
m_CommandNameToCommandInfoMap.find(*cmd_name);
if (cmd != m_CommandNameToCommandInfoMap.end())
command_info = cmd->second;
else if (*cmd_name == s_Help)
command_info = &help_command;
else {
printf("'%s': unknown command.\n\n", *cmd_name);
continue;
}
HelpOnCommand(command_info, command_info->GetNameVariants(),
m_ProgramName + ' ' + command_info->GetPrimaryName());
}
}
}
void SCommandLineParserImpl::HelpOnCommand(const SCommonParts* common_parts,
const string& name_for_synopsis, const string& name_for_usage) const
{
int text_len = printf("%s:", name_for_synopsis.c_str());
PrintWordWrapped(text_len, text_len + 1, common_parts->m_Synopsis);
printf("\n");
string args;
ITERATE(TOptionInfoList, arg, common_parts->m_PositionalArguments) {
if (!args.empty())
args.push_back(' ');
switch ((*arg)->m_Type) {
case CCommandLineParser::ePositionalArgument:
args.append((*arg)->GetPrimaryName());
break;
case CCommandLineParser::eOptionalPositional:
args.push_back('[');
args.append((*arg)->GetPrimaryName());
args.push_back(']');
break;
case CCommandLineParser::eZeroOrMorePositional:
args.push_back('[');
args.append((*arg)->GetPrimaryName());
args.append("...]");
break;
default: // always CCommandLineParser::eOneOrMorePositional
args.append((*arg)->GetPrimaryName());
args.append("...");
}
}
text_len = printf("Usage: %s", name_for_usage.c_str());
PrintWordWrapped(text_len, text_len + 1, args);
if (!common_parts->m_Usage.empty()) {
printf("\n");
PrintWordWrapped(0, 0, common_parts->m_Usage);
}
if (!common_parts->m_AcceptedOptions.empty()) {
printf("\nValid options:\n");
ITERATE(TOptionInfoList, opt, common_parts->m_AcceptedOptions)
PrintWordWrapped(printf(" %-*s :", m_OptDescrIndent - 5,
(*opt)->GetNameVariants().c_str()),
m_OptDescrIndent, (*opt)->m_Description);
}
printf("\n");
}
void SCommandLineParserImpl::Throw(const string& error, const string& cmd) const
{
string message;
if (error.empty())
message.append(m_Synopsis);
else {
message.append(m_ProgramName);
message.append(": ");
message.append(error);
}
message.append("\nType '");
message.append(m_ProgramName);
if (!CommandsAreDefined())
message.append(" --help' for usage.\n");
else if (cmd.empty())
message.append(" help' for usage.\n");
else {
message.append(" help ");
message.append(cmd);
message.append("' for usage.\n");
}
throw runtime_error(message);
}
int SCommandLineParserImpl::ParseAndValidate(int argc, const char* const *argv)
{
if (m_ProgramName.empty()) {
m_ProgramName = *argv;
string::size_type basename_pos = m_ProgramName.find_last_of("/\\:");
if (basename_pos != string::npos)
m_ProgramName = m_ProgramName.substr(basename_pos + 1);
}
TPositionalArgumentList positional_arguments;
// Part one: parsing.
while (--argc > 0) {
const char* arg = *++argv;
// Check if the current argument is a positional argument.
if (*arg != '-' || arg[1] == '\0')
positional_arguments.push_back(arg);
else {
// No, it's an option. Check whether it's a
// single-letter option or a long option.
const SOptionInfo* option_info;
const char* opt_param;
if (*++arg == '-') {
// It's a long option.
// If it's a free standing double dash marker,
// treat the rest of arguments as positional.
if (*++arg == '\0') {
while (--argc > 0)
positional_arguments.push_back(*++argv);
break;
}
// Check if a parameter is specified for this option.
opt_param = strchr(arg, '=');
string opt_name;
if (opt_param != NULL)
opt_name.assign(arg, opt_param++);
else
opt_name.assign(arg);
TOptionNameToOptionInfoMap::const_iterator opt_info(
m_OptionToOptInfoMap.find(opt_name));
if (opt_info == m_OptionToOptInfoMap.end())
Throw("unknown option '--" + opt_name + "'");
option_info = opt_info->second;
// Check if this option must have a parameter.
if (option_info->m_Type == CCommandLineParser::eSwitch) {
// No, it's a switch; it's not supposed to have a parameter.
if (opt_param != NULL)
Throw("option '--" + opt_name +
"' does not expect a parameter");
opt_param = "yes";
} else
// The option expects a parameter.
if (opt_param == NULL) {
// Parameter is not specified; use the next
// command line argument as a parameter for
// this option.
if (--argc == 0)
Throw("option '--" + opt_name +
"' requires a parameter");
opt_param = *++argv;
}
} else {
// The current argument is a (series of) one-letter option(s).
for (;;) {
char opt_letter = *arg++;
option_info = m_SingleLetterOptions[
(unsigned char) opt_letter];
if (option_info == NULL)
Throw(string("unknown option '-") + opt_letter + "'");
// Check if this option must have a parameter.
if (option_info->m_Type == CCommandLineParser::eSwitch) {
// It's a switch; it's not supposed to have a parameter.
opt_param = "yes";
if (*arg == '\0')
break;
} else {
// It's an option that expects a parameter.
if (*arg == '\0') {
// Use the next command line argument
// as a parameter for this option.
if (--argc == 0)
Throw(string("option '-") + opt_letter +
"' requires a parameter");
opt_param = *++argv;
} else
opt_param = arg;
break;
}
m_OptionValues.push_back(TOptionValue(
option_info, opt_param));
}
}
m_OptionValues.push_back(TOptionValue(option_info, opt_param));
}
}
// Part two: validation.
TOptionValues::iterator option_value(m_OptionValues.begin());
while (option_value != m_OptionValues.end())
switch (option_value->first->m_Id) {
case VERSION_OPT_ID:
puts(m_VersionInfo.c_str());
return HELP_CMD_ID;
case HELP_OPT_ID:
m_OptionValues.erase(option_value++);
Help(positional_arguments, false);
return HELP_CMD_ID;
default:
++option_value;
}
string command_name;
const TOptionInfoList* expected_positional_arguments;
int ret_val;
if (!CommandsAreDefined()) {
expected_positional_arguments = &m_PositionalArguments;
ret_val = 0;
} else {
if (positional_arguments.empty())
Throw(m_OptionValues.empty() ? "" : "a command is required");
command_name = positional_arguments.front();
positional_arguments.pop_front();
TCommandNameToCommandInfoMap::const_iterator command =
m_CommandNameToCommandInfoMap.find(command_name);
if (command == m_CommandNameToCommandInfoMap.end()) {
if (command_name == s_Help) {
Help(positional_arguments, true);
return HELP_CMD_ID;
}
Throw("unknown command '" + command_name + "'");
}
const SCommandInfo* command_info = command->second;
ITERATE(TOptionValues, option_value, m_OptionValues)
if (find(command_info->m_AcceptedOptions.begin(),
command_info->m_AcceptedOptions.end(), option_value->first) ==
command_info->m_AcceptedOptions.end())
Throw("command '" + command_name + "' doesn't accept option '" +
option_value->first->GetNameVariants() + "'",
command_name);
expected_positional_arguments = &command_info->m_PositionalArguments;
ret_val = command_info->m_Id;
}
TPositionalArgumentList::const_iterator arg_value =
positional_arguments.begin();
TOptionInfoList::const_iterator expected_arg =
expected_positional_arguments->begin();
for (;;) {
if (expected_arg != expected_positional_arguments->end())
if (arg_value == positional_arguments.end())
switch ((*expected_arg)->m_Type) {
case CCommandLineParser::ePositionalArgument:
case CCommandLineParser::eOneOrMorePositional:
Throw("missing argument '" +
(*expected_arg)->GetPrimaryName() + "'", command_name);
}
else
switch ((*expected_arg)->m_Type) {
case CCommandLineParser::ePositionalArgument:
case CCommandLineParser::eOptionalPositional:
m_OptionValues.push_back(TOptionValue(
*expected_arg, *arg_value));
++arg_value;
++expected_arg;
continue;
default:
do
m_OptionValues.push_back(TOptionValue(
*expected_arg, *arg_value));
while (++arg_value != positional_arguments.end());
}
else
if (arg_value != positional_arguments.end())
Throw("too many positional arguments", command_name);
break;
}
m_NextOptionValue = m_OptionValues.begin();
return ret_val;
}
CCommandLineParser::CCommandLineParser(
const string& program_name,
const string& version_info,
const string& program_summary,
const string& program_description) :
m_Impl(new SCommandLineParserImpl(
program_name, program_summary, program_description, version_info))
{
}
void CCommandLineParser::SetHelpTextMargins(int help_text_width,
int cmd_descr_indent, int opt_descr_indent)
{
m_Impl->m_MaxHelpTextWidth = help_text_width;
m_Impl->m_CmdDescrIndent = cmd_descr_indent;
m_Impl->m_OptDescrIndent = opt_descr_indent;
}
void CCommandLineParser::AddOption(CCommandLineParser::EOptionType type,
int opt_id, const string& name_variants, const string& description)
{
_ASSERT(opt_id >= 0 && m_Impl->m_OptIdToOptionInfoMap.find(opt_id) ==
m_Impl->m_OptIdToOptionInfoMap.end() && "Option IDs must be unique");
SOptionInfo* option_info = m_Impl->m_OptIdToOptionInfoMap[opt_id] =
new SOptionInfo(opt_id, name_variants, type, description);
switch (type) {
default:
_ASSERT(option_info->m_NameVariants.size() == 1 &&
"Positional arguments do not allow name variants");
m_Impl->m_PositionalArguments.push_back(option_info);
break;
case eSwitch:
case eOptionWithParameter:
ITERATE(TNameVariantList, name, option_info->m_NameVariants)
if (name->length() == 1)
m_Impl->m_SingleLetterOptions[
(unsigned char) name->at(0)] = option_info;
else
m_Impl->m_OptionToOptInfoMap[*name] = option_info;
m_Impl->m_AcceptedOptions.push_back(option_info);
}
}
void CCommandLineParser::AddCommandCategory(int cat_id, const string& title)
{
_ASSERT(cat_id >= 0 && m_Impl->m_CatIdToCatInfoMap.find(cat_id) ==
m_Impl->m_CatIdToCatInfoMap.end() && "Category IDs must be unique");
m_Impl->m_CatIdToCatInfoMap[cat_id] = new SCategoryInfo(title);
}
void CCommandLineParser::AddCommand(int cmd_id, const string& name_variants,
const string& synopsis, const string& usage, int cat_id)
{
_ASSERT(cmd_id >= 0 && m_Impl->m_CmdIdToCommandInfoMap.find(cmd_id) ==
m_Impl->m_CmdIdToCommandInfoMap.end() && "Command IDs must be unique");
_ASSERT(m_Impl->m_CatIdToCatInfoMap.find(cat_id) !=
m_Impl->m_CatIdToCatInfoMap.end() && "No such category ID");
SCommandInfo* command_info = m_Impl->m_CmdIdToCommandInfoMap[cmd_id] =
new SCommandInfo(cmd_id, name_variants, synopsis, usage);
m_Impl->m_CatIdToCatInfoMap[cat_id]->m_Commands.push_back(command_info);
ITERATE(TNameVariantList, name, command_info->m_NameVariants)
m_Impl->m_CommandNameToCommandInfoMap[*name] = command_info;
}
void CCommandLineParser::AddAssociation(int cmd_id, int opt_id)
{
_ASSERT(m_Impl->m_CmdIdToCommandInfoMap.find(cmd_id) !=
m_Impl->m_CmdIdToCommandInfoMap.end() && "No such command ID");
_ASSERT(m_Impl->m_OptIdToOptionInfoMap.find(opt_id) !=
m_Impl->m_OptIdToOptionInfoMap.end() && "No such option ID");
SCommandInfo* cmd_info = m_Impl->m_CmdIdToCommandInfoMap[cmd_id];
SOptionInfo* opt_info = m_Impl->m_OptIdToOptionInfoMap[opt_id];
switch (opt_info->m_Type) {
case eSwitch:
case eOptionWithParameter:
cmd_info->m_AcceptedOptions.push_back(opt_info);
break;
default:
_ASSERT("Invalid sequence of optional positional arguments" &&
(cmd_info->m_PositionalArguments.empty() ||
cmd_info->m_PositionalArguments.back()->m_Type ==
ePositionalArgument ||
(cmd_info->m_PositionalArguments.back()->m_Type ==
eOptionalPositional &&
opt_info->m_Type != ePositionalArgument)));
cmd_info->m_PositionalArguments.push_back(opt_info);
}
}
int CCommandLineParser::Parse(int argc, const char* const *argv)
{
return m_Impl->ParseAndValidate(argc, argv);
}
const string& CCommandLineParser::GetProgramName() const
{
return m_Impl->m_ProgramName;
}
bool CCommandLineParser::NextOption(int* opt_id, const char** opt_value)
{
if (m_Impl->m_NextOptionValue == m_Impl->m_OptionValues.end())
return false;
*opt_id = m_Impl->m_NextOptionValue->first->m_Id;
*opt_value = m_Impl->m_NextOptionValue->second;
++m_Impl->m_NextOptionValue;
return true;
}
END_NCBI_SCOPE
| kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/src/connect/services/clparser.cpp | C++ | lgpl-3.0 | 26,989 |
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2016 Pelican Mapping
* http://osgearth.org
*
* osgEarth 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarth/Map>
#include <osgEarth/MapFrame>
#include <osgEarth/MapModelChange>
#include <osgEarth/Registry>
#include <osgEarth/TileSource>
#include <osgEarth/HeightFieldUtils>
#include <osgEarth/URI>
#include <osgEarth/ElevationPool>
#include <osgEarth/Utils>
#include <iterator>
using namespace osgEarth;
#define LC "[Map] "
//------------------------------------------------------------------------
Map::ElevationLayerCB::ElevationLayerCB(Map* map) :
_map(map)
{
//nop
}
void
Map::ElevationLayerCB::onVisibleChanged(TerrainLayer* layer)
{
osg::ref_ptr<Map> map;
if ( _map.lock(map) )
{
_map->notifyElevationLayerVisibleChanged(layer);
}
}
//------------------------------------------------------------------------
Map::Map() :
osg::Object(),
_dataModelRevision(0)
{
ctor();
}
Map::Map( const MapOptions& options ) :
osg::Object(),
_mapOptions ( options ),
_initMapOptions ( options ),
_dataModelRevision ( 0 )
{
ctor();
}
void
Map::ctor()
{
// Set the object name.
osg::Object::setName("osgEarth.Map");
// Generate a UID.
_uid = Registry::instance()->createUID();
// If the registry doesn't have a default cache policy, but the
// map options has one, make the map policy the default.
if (_mapOptions.cachePolicy().isSet() &&
!Registry::instance()->defaultCachePolicy().isSet())
{
Registry::instance()->setDefaultCachePolicy( _mapOptions.cachePolicy().get() );
OE_INFO << LC
<< "Setting default cache policy from map ("
<< _mapOptions.cachePolicy()->usageString() << ")" << std::endl;
}
// the map-side dbOptions object holds I/O information for all components.
_readOptions = osg::clone( Registry::instance()->getDefaultOptions() );
// put the CacheSettings object in there. We will propogate this throughout
// the data model and the renderer. These will be stored in the readOptions
// (and ONLY there)
CacheSettings* cacheSettings = new CacheSettings();
// Set up a cache if there's one in the options:
if (_mapOptions.cache().isSet())
cacheSettings->setCache(CacheFactory::create(_mapOptions.cache().get()));
// Otherwise use the registry default cache if there is one:
if (cacheSettings->getCache() == 0L)
cacheSettings->setCache(Registry::instance()->getDefaultCache());
// Integrate local cache policy (which can be overridden by the environment)
cacheSettings->integrateCachePolicy(_mapOptions.cachePolicy());
// store in the options so we can propagate it to layers, etc.
cacheSettings->store(_readOptions.get());
OE_INFO << LC << cacheSettings->toString() << "\n";
// remember the referrer for relative-path resolution:
URIContext( _mapOptions.referrer() ).store( _readOptions.get() );
// we do our own caching
_readOptions->setObjectCacheHint( osgDB::Options::CACHE_NONE );
// encode this map in the read options.
OptionsData<const Map>::set(_readOptions, "osgEarth.Map", this);
// set up a callback that the Map will use to detect Elevation Layer
// visibility changes
_elevationLayerCB = new ElevationLayerCB(this);
// elevation sampling
_elevationPool = new ElevationPool();
_elevationPool->setMap( this );
}
Map::~Map()
{
OE_DEBUG << LC << "~Map" << std::endl;
}
ElevationPool*
Map::getElevationPool() const
{
return _elevationPool.get();
}
void
Map::notifyElevationLayerVisibleChanged(TerrainLayer* layer)
{
// bump the revision safely:
Revision newRevision;
{
Threading::ScopedWriteLock lock( const_cast<Map*>(this)->_mapDataMutex );
newRevision = ++_dataModelRevision;
}
// a separate block b/c we don't need the mutex
for( MapCallbackList::iterator i = _mapCallbacks.begin(); i != _mapCallbacks.end(); i++ )
{
i->get()->onMapModelChanged( MapModelChange(
MapModelChange::TOGGLE_ELEVATION_LAYER, newRevision, layer) );
}
}
bool
Map::isGeocentric() const
{
return
_mapOptions.coordSysType() == MapOptions::CSTYPE_GEOCENTRIC ||
_mapOptions.coordSysType() == MapOptions::CSTYPE_GEOCENTRIC_CUBE;
}
const osgDB::Options*
Map::getGlobalOptions() const
{
return _globalOptions.get();
}
void
Map::setGlobalOptions( const osgDB::Options* options )
{
_globalOptions = options;
}
void
Map::setMapName( const std::string& name ) {
_name = name;
}
Revision
Map::getDataModelRevision() const
{
return _dataModelRevision;
}
const Profile*
Map::getProfile() const
{
if ( !_profile.valid() )
const_cast<Map*>(this)->calculateProfile();
return _profile.get();
}
Cache*
Map::getCache() const
{
CacheSettings* cacheSettings = CacheSettings::get(_readOptions.get());
return cacheSettings ? cacheSettings->getCache() : 0L;
}
void
Map::setCache(Cache* cache)
{
// note- probably unsafe to do this after initializing the terrain. so don't.
CacheSettings* cacheSettings = CacheSettings::get(_readOptions.get());
if (cacheSettings && cacheSettings->getCache() != cache)
cacheSettings->setCache(cache);
}
void
Map::addMapCallback( MapCallback* cb ) const
{
if ( cb )
const_cast<Map*>(this)->_mapCallbacks.push_back( cb );
}
void
Map::removeMapCallback( MapCallback* cb )
{
MapCallbackList::iterator i = std::find( _mapCallbacks.begin(), _mapCallbacks.end(), cb);
if (i != _mapCallbacks.end())
{
_mapCallbacks.erase( i );
}
}
void
Map::beginUpdate()
{
MapModelChange msg( MapModelChange::BEGIN_BATCH_UPDATE, _dataModelRevision );
for( MapCallbackList::iterator i = _mapCallbacks.begin(); i != _mapCallbacks.end(); i++ )
{
i->get()->onMapModelChanged( msg );
}
}
void
Map::endUpdate()
{
MapModelChange msg( MapModelChange::END_BATCH_UPDATE, _dataModelRevision );
for( MapCallbackList::iterator i = _mapCallbacks.begin(); i != _mapCallbacks.end(); i++ )
{
i->get()->onMapModelChanged( msg );
}
}
void
Map::addLayer(Layer* layer)
{
osgEarth::Registry::instance()->clearBlacklist();
if ( layer )
{
TerrainLayer* terrainLayer = dynamic_cast<TerrainLayer*>(layer);
if (terrainLayer)
{
// Set the DB options for the map from the layer, including the cache policy.
terrainLayer->setReadOptions( _readOptions.get() );
// Tell the layer the map profile, if supported:
if ( _profile.valid() )
{
terrainLayer->setTargetProfileHint( _profile.get() );
}
// open the layer:
terrainLayer->open();
}
ElevationLayer* elevationLayer = dynamic_cast<ElevationLayer*>(layer);
if (elevationLayer)
{
elevationLayer->addCallback(_elevationLayerCB.get());
// invalidate the elevation pool
getElevationPool()->clear();
}
ModelLayer* modelLayer = dynamic_cast<ModelLayer*>(layer);
if (modelLayer)
{
// initialize the model layer
modelLayer->setReadOptions(_readOptions.get());
// open it and check the status
modelLayer->open();
}
MaskLayer* maskLayer = dynamic_cast<MaskLayer*>(layer);
if (maskLayer)
{
// initialize the model layer
maskLayer->setReadOptions(_readOptions.get());
// open it and check the status
maskLayer->open();
}
int newRevision;
unsigned index = -1;
// Add the layer to our stack.
{
Threading::ScopedWriteLock lock( _mapDataMutex );
_layers.push_back( layer );
index = _layers.size() - 1;
newRevision = ++_dataModelRevision;
}
// a separate block b/c we don't need the mutex
for( MapCallbackList::iterator i = _mapCallbacks.begin(); i != _mapCallbacks.end(); i++ )
{
i->get()->onMapModelChanged(MapModelChange(
MapModelChange::ADD_LAYER, newRevision, layer, index));
}
}
}
void
Map::insertLayer(Layer* layer, unsigned index)
{
osgEarth::Registry::instance()->clearBlacklist();
if ( layer )
{
TerrainLayer* terrainLayer = dynamic_cast<TerrainLayer*>(layer);
if (terrainLayer)
{
// Set the DB options for the map from the layer, including the cache policy.
terrainLayer->setReadOptions( _readOptions.get() );
// Tell the layer the map profile, if supported:
if ( _profile.valid() )
{
terrainLayer->setTargetProfileHint( _profile.get() );
}
// open the layer:
terrainLayer->open();
}
ModelLayer* modelLayer = dynamic_cast<ModelLayer*>(layer);
if (modelLayer)
{
// initialize the model layer
modelLayer->setReadOptions(_readOptions.get());
// open it and check the status
modelLayer->open();
}
ElevationLayer* elevationLayer = dynamic_cast<ElevationLayer*>(layer);
if (elevationLayer)
{
elevationLayer->addCallback(_elevationLayerCB.get());
}
MaskLayer* maskLayer = dynamic_cast<MaskLayer*>(layer);
if (maskLayer)
{
// initialize the model layer
maskLayer->setReadOptions(_readOptions.get());
// open it and check the status
maskLayer->open();
}
int newRevision;
// Add the layer to our stack.
{
Threading::ScopedWriteLock lock( _mapDataMutex );
if (index >= _layers.size())
_layers.push_back(layer);
else
_layers.insert( _layers.begin() + index, layer );
newRevision = ++_dataModelRevision;
}
// a separate block b/c we don't need the mutex
for( MapCallbackList::iterator i = _mapCallbacks.begin(); i != _mapCallbacks.end(); i++ )
{
//i->get()->onMapModelChanged( MapModelChange(
// MapModelChange::ADD_IMAGE_LAYER, newRevision, layer, index) );
i->get()->onMapModelChanged(MapModelChange(
MapModelChange::ADD_LAYER, newRevision, layer, index));
}
}
}
void
Map::removeLayer(Layer* layer)
{
osgEarth::Registry::instance()->clearBlacklist();
unsigned int index = -1;
osg::ref_ptr<Layer> layerToRemove = layer;
Revision newRevision;
if ( layerToRemove.get() )
{
Threading::ScopedWriteLock lock( _mapDataMutex );
index = 0;
for( LayerVector::iterator i = _layers.begin(); i != _layers.end(); i++, index++ )
{
if ( i->get() == layerToRemove.get() )
{
_layers.erase( i );
newRevision = ++_dataModelRevision;
break;
}
}
}
ElevationLayer* elevationLayer = dynamic_cast<ElevationLayer*>(layerToRemove.get());
if (elevationLayer)
{
elevationLayer->removeCallback(_elevationLayerCB.get());
// invalidate the pool
getElevationPool()->clear();
}
// a separate block b/c we don't need the mutex
if ( newRevision >= 0 ) // layerToRemove.get() )
{
for( MapCallbackList::iterator i = _mapCallbacks.begin(); i != _mapCallbacks.end(); i++ )
{
i->get()->onMapModelChanged( MapModelChange(
MapModelChange::REMOVE_LAYER, newRevision, layerToRemove.get(), index) );
}
}
}
void
Map::moveLayer(Layer* layer, unsigned newIndex)
{
unsigned int oldIndex = 0;
unsigned int actualIndex = 0;
Revision newRevision;
if ( layer )
{
Threading::ScopedWriteLock lock( _mapDataMutex );
// preserve the layer with a ref:
osg::ref_ptr<Layer> layerToMove = layer;
// find it:
LayerVector::iterator i_oldIndex = _layers.end();
for( LayerVector::iterator i = _layers.begin(); i != _layers.end(); i++, actualIndex++ )
{
if ( i->get() == layer )
{
i_oldIndex = i;
oldIndex = actualIndex;
break;
}
}
if ( i_oldIndex == _layers.end() )
return; // layer not found in list
// erase the old one and insert the new one.
_layers.erase( i_oldIndex );
_layers.insert( _layers.begin() + newIndex, layerToMove.get() );
newRevision = ++_dataModelRevision;
}
// if this is an elevation layer, invalidate the elevation pool
if (dynamic_cast<ElevationLayer*>(layer))
{
getElevationPool()->clear();
}
// a separate block b/c we don't need the mutex
if ( layer )
{
for( MapCallbackList::iterator i = _mapCallbacks.begin(); i != _mapCallbacks.end(); i++ )
{
i->get()->onMapModelChanged( MapModelChange(
MapModelChange::MOVE_LAYER, newRevision, layer, oldIndex, newIndex) );
}
}
}
Revision
Map::getLayers(LayerVector& out_list) const
{
out_list.reserve( _layers.size() );
Threading::ScopedReadLock lock( const_cast<Map*>(this)->_mapDataMutex );
for( LayerVector::const_iterator i = _layers.begin(); i != _layers.end(); ++i )
out_list.push_back( i->get() );
return _dataModelRevision;
}
unsigned
Map::getNumLayers() const
{
Threading::ScopedReadLock lock( const_cast<Map*>(this)->_mapDataMutex );
return _layers.size();
}
Layer*
Map::getLayerByName(const std::string& name) const
{
Threading::ScopedReadLock( const_cast<Map*>(this)->_mapDataMutex );
for(LayerVector::const_iterator i = _layers.begin(); i != _layers.end(); ++i)
if ( i->get()->getName() == name )
return i->get();
return 0L;
}
Layer*
Map::getLayerByUID(UID layerUID) const
{
Threading::ScopedReadLock( const_cast<Map*>(this)->_mapDataMutex );
for( LayerVector::const_iterator i = _layers.begin(); i != _layers.end(); ++i )
if ( i->get()->getUID() == layerUID )
return i->get();
return 0L;
}
Layer*
Map::getLayerAt(unsigned index) const
{
Threading::ScopedReadLock( const_cast<Map*>(this)->_mapDataMutex );
if ( index >= 0 && index < (int)_layers.size() )
return _layers[index].get();
else
return 0L;
}
unsigned
Map::getIndexOfLayer(Layer* layer) const
{
Threading::ScopedReadLock( const_cast<Map*>(this)->_mapDataMutex );
unsigned index = 0;
for (; index < _layers.size(); ++index)
{
if (_layers[index] == layer)
break;
}
return index;
}
void
Map::clear()
{
LayerVector layersRemoved;
Revision newRevision;
{
Threading::ScopedWriteLock lock( _mapDataMutex );
layersRemoved.swap( _layers );
// calculate a new revision.
newRevision = ++_dataModelRevision;
}
// a separate block b/c we don't need the mutex
for( MapCallbackList::iterator i = _mapCallbacks.begin(); i != _mapCallbacks.end(); i++ )
{
for(LayerVector::iterator layer = layersRemoved.begin();
layer != layersRemoved.end();
++layer)
{
i->get()->onMapModelChanged(MapModelChange(MapModelChange::REMOVE_LAYER, newRevision, layer->get()));
}
}
// Invalidate the elevation pool.
getElevationPool()->clear();
}
void
Map::setLayersFromMap(const Map* map)
{
this->clear();
if ( map )
{
LayerVector layers;
map->getLayers(layers);
for (LayerVector::iterator i = layers.begin(); i != layers.end(); ++i)
addLayer(i->get());
}
}
void
Map::calculateProfile()
{
if ( !_profile.valid() )
{
osg::ref_ptr<const Profile> userProfile;
if ( _mapOptions.profile().isSet() )
{
userProfile = Profile::create( _mapOptions.profile().value() );
}
if ( _mapOptions.coordSysType() == MapOptions::CSTYPE_GEOCENTRIC )
{
if ( userProfile.valid() )
{
if ( userProfile->isOK() && userProfile->getSRS()->isGeographic() )
{
_profile = userProfile.get();
}
else
{
OE_WARN << LC
<< "Map is geocentric, but the configured profile SRS ("
<< userProfile->getSRS()->getName() << ") is not geographic; "
<< "it will be ignored."
<< std::endl;
}
}
}
else if ( _mapOptions.coordSysType() == MapOptions::CSTYPE_GEOCENTRIC_CUBE )
{
if ( userProfile.valid() )
{
if ( userProfile->isOK() && userProfile->getSRS()->isCube() )
{
_profile = userProfile.get();
}
else
{
OE_WARN << LC
<< "Map is geocentric cube, but the configured profile SRS ("
<< userProfile->getSRS()->getName() << ") is not geocentric cube; "
<< "it will be ignored."
<< std::endl;
}
}
}
else // CSTYPE_PROJECTED
{
if ( userProfile.valid() )
{
if ( userProfile->isOK() && userProfile->getSRS()->isProjected() )
{
_profile = userProfile.get();
}
else
{
OE_WARN << LC
<< "Map is projected, but the configured profile SRS ("
<< userProfile->getSRS()->getName() << ") is not projected; "
<< "it will be ignored."
<< std::endl;
}
}
}
// At this point, if we don't have a profile we need to search tile sources until we find one.
if ( !_profile.valid() )
{
Threading::ScopedReadLock lock( _mapDataMutex );
for (LayerVector::iterator i = _layers.begin(); i != _layers.end(); ++i)
{
TerrainLayer* terrainLayer = dynamic_cast<TerrainLayer*>(i->get());
if (terrainLayer && terrainLayer->getTileSource())
{
_profile = terrainLayer->getTileSource()->getProfile();
}
}
}
// ensure that the profile we found is the correct kind
// convert a geographic profile to Plate Carre if necessary
if ( _mapOptions.coordSysType() == MapOptions::CSTYPE_GEOCENTRIC && !( _profile.valid() && _profile->getSRS()->isGeographic() ) )
{
// by default, set a geocentric map to use global-geodetic WGS84.
_profile = osgEarth::Registry::instance()->getGlobalGeodeticProfile();
}
else if ( _mapOptions.coordSysType() == MapOptions::CSTYPE_GEOCENTRIC_CUBE && !( _profile.valid() && _profile->getSRS()->isCube() ) )
{
//If the map type is a Geocentric Cube, set the profile to the cube profile.
_profile = osgEarth::Registry::instance()->getCubeProfile();
}
else if ( _mapOptions.coordSysType() == MapOptions::CSTYPE_PROJECTED && _profile.valid() && _profile->getSRS()->isGeographic() )
{
OE_INFO << LC << "Projected map with geographic SRS; activating EQC profile" << std::endl;
unsigned u, v;
_profile->getNumTiles(0, u, v);
const osgEarth::SpatialReference* eqc = _profile->getSRS()->createEquirectangularSRS();
osgEarth::GeoExtent e = _profile->getExtent().transform( eqc );
_profile = osgEarth::Profile::create( eqc, e.xMin(), e.yMin(), e.xMax(), e.yMax(), u, v);
}
else if ( _mapOptions.coordSysType() == MapOptions::CSTYPE_PROJECTED && !( _profile.valid() && _profile->getSRS()->isProjected() ) )
{
// TODO: should there be a default projected profile?
_profile = 0;
}
// finally, fire an event if the profile has been set.
if ( _profile.valid() )
{
OE_INFO << LC << "Map profile is: " << _profile->toString() << std::endl;
for( MapCallbackList::iterator i = _mapCallbacks.begin(); i != _mapCallbacks.end(); i++ )
{
i->get()->onMapInfoEstablished( MapInfo(this) );
}
}
else
{
OE_WARN << LC << "Warning, not yet able to establish a map profile!" << std::endl;
}
}
if ( _profile.valid() )
{
// tell all the loaded layers what the profile is, as a hint
{
Threading::ScopedWriteLock lock( _mapDataMutex );
for (LayerVector::iterator i = _layers.begin(); i != _layers.end(); ++i)
{
TerrainLayer* terrainLayer = dynamic_cast<TerrainLayer*>(i->get());
if (terrainLayer && terrainLayer->getEnabled())
{
terrainLayer->setTargetProfileHint(_profile.get());
}
}
}
// create a "proxy" profile to use when querying elevation layers with a vertical datum
if ( _profile->getSRS()->getVerticalDatum() != 0L )
{
ProfileOptions po = _profile->toProfileOptions();
po.vsrsString().unset();
_profileNoVDatum = Profile::create(po);
}
else
{
_profileNoVDatum = _profile;
}
}
}
const SpatialReference*
Map::getWorldSRS() const
{
return isGeocentric() ? getSRS()->getECEF() : getSRS();
}
bool
Map::sync(MapFrame& frame) const
{
bool result = false;
if ( frame._mapDataModelRevision != _dataModelRevision || !frame._initialized )
{
// hold the read lock while copying the layer lists.
Threading::ScopedReadLock lock( const_cast<Map*>(this)->_mapDataMutex );
if (!frame._initialized)
frame._layers.reserve(_layers.size());
frame._layers.clear();
std::copy(_layers.begin(), _layers.end(), std::back_inserter(frame._layers));
// sync the revision numbers.
frame._initialized = true;
frame._mapDataModelRevision = _dataModelRevision;
result = true;
}
return result;
}
| ldelgass/osgearth | src/osgEarth/Map.cpp | C++ | lgpl-3.0 | 23,400 |
package fr.theflogat.technicalWizardry.items.runes;
import java.util.List;
import org.lwjgl.input.Keyboard;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fr.theflogat.technicalWizardry.TechnicalWizardry;
import fr.theflogat.technicalWizardry.lib.References;
import fr.theflogat.technicalWizardry.lib.config.Names;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Icon;
public class RuneLight extends Item{
public RuneLight(int id) {
super(id);
this.setCreativeTab(TechnicalWizardry.CreativeTabTWU);
this.setUnlocalizedName(Names.RuneLight_UnlocalizedName);
}
public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4) {
if(Keyboard.isKeyDown(42)){
par3List.add("Right-click on Glowstone");
} else {
par3List.add("--Press Shift For More Info--");
}
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister icon) {
itemIcon = icon.registerIcon(References.MOD_ID.toLowerCase() + ":" + Names.RuneLight_UnlocalizedName);
}
@Override
@SideOnly(Side.CLIENT)
public Icon getIconFromDamage(int damage) {
return itemIcon;
}
}
| theflogat/Theflogats-Mods | fr/theflogat/technicalWizardry/items/runes/RuneLight.java | Java | lgpl-3.0 | 1,391 |
# (C) British Crown Copyright 2011 - 2012, Met Office
#
# This file is part of cartopy.
#
# cartopy 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 3 of the License, or
# (at your option) any later version.
#
# cartopy 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 cartopy. If not, see <http://www.gnu.org/licenses/>.
import unittest
import cartopy
import cartopy.io.shapereader as shp
COASTLINE_PATH = shp.natural_earth()
class TestCoastline(unittest.TestCase):
def test_robust(self):
# Make sure all the coastlines can be projected without raising any
# exceptions.
projection = cartopy.crs.TransverseMercator(central_longitude=-90)
reader = shp.Reader(COASTLINE_PATH)
all_geometries = list(reader.geometries())
geometries = []
geometries += all_geometries
#geometries += all_geometries[48:52] # Aus & Taz
#geometries += all_geometries[72:73] # GB
#for geometry in geometries:
for i, geometry in enumerate(geometries[93:]):
for line_string in geometry:
multi_line_string = projection.project_geometry(line_string)
if __name__ == '__main__':
unittest.main()
| lbdreyer/cartopy | lib/cartopy/tests/test_coastline.py | Python | lgpl-3.0 | 1,600 |
/**
* AnalyzerBeans
* Copyright (C) 2014 Neopost - Customer Information Management
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.eobjects.analyzer.beans;
import java.util.Date;
import java.util.List;
import junit.framework.TestCase;
import org.eobjects.analyzer.configuration.AnalyzerBeansConfiguration;
import org.eobjects.analyzer.configuration.AnalyzerBeansConfigurationImpl;
import org.eobjects.analyzer.connection.DatastoreCatalogImpl;
import org.eobjects.analyzer.data.InputColumn;
import org.eobjects.analyzer.data.MockInputColumn;
import org.eobjects.analyzer.job.AnalysisJob;
import org.eobjects.analyzer.job.builder.AnalysisJobBuilder;
import org.eobjects.analyzer.job.builder.AnalyzerJobBuilder;
import org.eobjects.analyzer.job.runner.AnalysisResultFuture;
import org.eobjects.analyzer.job.runner.AnalysisRunnerImpl;
import org.eobjects.analyzer.result.AnalyzerResult;
import org.eobjects.analyzer.result.AnnotatedRowsResult;
import org.eobjects.analyzer.result.CrosstabNavigator;
import org.eobjects.analyzer.result.ResultProducer;
import org.eobjects.analyzer.result.renderer.CrosstabTextRenderer;
import org.eobjects.analyzer.test.TestHelper;
public class DateAndTimeAnalyzerTest extends TestCase {
public void testOrderFactTable() throws Throwable {
AnalyzerBeansConfiguration conf = new AnalyzerBeansConfigurationImpl().replace(new DatastoreCatalogImpl(
TestHelper.createSampleDatabaseDatastore("orderdb")));
AnalysisJobBuilder ajb = new AnalysisJobBuilder(conf);
try {
ajb.setDatastore("orderdb");
ajb.addSourceColumns("ORDERFACT.ORDERDATE", "ORDERFACT.REQUIREDDATE", "ORDERFACT.SHIPPEDDATE");
AnalyzerJobBuilder<DateAndTimeAnalyzer> analyzer = ajb.addAnalyzer(DateAndTimeAnalyzer.class);
analyzer.addInputColumns(ajb.getSourceColumns());
AnalysisJob job = ajb.toAnalysisJob();
AnalysisResultFuture resultFuture = new AnalysisRunnerImpl(conf).run(job);
resultFuture.await();
if (!resultFuture.isSuccessful()) {
throw resultFuture.getErrors().get(0);
}
assertTrue(resultFuture.isSuccessful());
List<AnalyzerResult> results = resultFuture.getResults();
assertEquals(1, results.size());
DateAndTimeAnalyzerResult result = (DateAndTimeAnalyzerResult) results.get(0);
String[] resultLines = new CrosstabTextRenderer().render(result).split("\n");
assertEquals(8, resultLines.length);
assertEquals(" ORDERDATE REQUIREDDATE SHIPPEDDATE ", resultLines[0]);
assertEquals("Row count 2996 2996 2996 ", resultLines[1]);
assertEquals("Null count 0 0 141 ", resultLines[2]);
assertEquals("Highest date 2005-05-31 2005-06-11 2005-05-20 ", resultLines[3]);
assertEquals("Lowest date 2003-01-06 2003-01-13 2003-01-10 ", resultLines[4]);
assertEquals("Highest time 00:00:00.000 00:00:00.000 00:00:00.000 ", resultLines[5]);
assertEquals("Lowest time 00:00:00.000 00:00:00.000 00:00:00.000 ", resultLines[6]);
String meanResultLine = resultLines[7];
// due to timezone diffs, this line will have slight variants on
// different machines
assertTrue(meanResultLine.startsWith("Mean 2004-05-14"));
CrosstabNavigator<?> nav = result.getCrosstab().where("Column", "ORDERDATE");
InputColumn<?> column = ajb.getSourceColumnByName("ORDERDATE");
ResultProducer resultProducer = nav.where("Measure", "Highest date").explore();
testAnnotatedRowResult(resultProducer.getResult(), column, 19, 19);
resultProducer = nav.where("Measure", "Lowest date").explore();
testAnnotatedRowResult(resultProducer.getResult(), column, 4, 4);
resultProducer = nav.where("Measure", "Highest time").explore();
testAnnotatedRowResult(resultProducer.getResult(), column, 2996, 1000);
resultProducer = nav.where("Measure", "Lowest time").explore();
testAnnotatedRowResult(resultProducer.getResult(), column, 2996, 1000);
assertEquals(2996, result.getRowCount(new MockInputColumn<Date>("ORDERDATE")));
assertEquals(0, result.getNullCount(new MockInputColumn<Date>("ORDERDATE")));
assertEquals(12934, result.getHighestDate(new MockInputColumn<Date>("ORDERDATE")));
assertEquals(12058, result.getLowestDate(new MockInputColumn<Date>("ORDERDATE")));
} finally {
ajb.close();
}
}
public void testResultConvertToDaysFromEpoch() throws Exception {
assertEquals(0, DateAndTimeAnalyzerResult.convertToDaysSinceEpoch("1970-01-01"));
assertEquals(1, DateAndTimeAnalyzerResult.convertToDaysSinceEpoch("1970-01-02"));
assertEquals(31, DateAndTimeAnalyzerResult.convertToDaysSinceEpoch("1970-02-01"));
assertEquals(12934, DateAndTimeAnalyzerResult.convertToDaysSinceEpoch("2005-05-31"));
}
private void testAnnotatedRowResult(AnalyzerResult result, InputColumn<?> col, int rowCount, int distinctRowCount) {
assertTrue("Unexpected result type: " + result.getClass(), result instanceof AnnotatedRowsResult);
AnnotatedRowsResult res = (AnnotatedRowsResult) result;
InputColumn<?>[] highlightedColumns = res.getHighlightedColumns();
assertEquals(1, highlightedColumns.length);
assertEquals(col, highlightedColumns[0]);
assertEquals(rowCount, res.getAnnotatedRowCount());
assertEquals(distinctRowCount, res.getRows().length);
}
}
| datacleaner/AnalyzerBeans | components/basic-analyzers/src/test/java/org/eobjects/analyzer/beans/DateAndTimeAnalyzerTest.java | Java | lgpl-3.0 | 6,479 |
jsh.App[modelid] = new (function(){
var _this = this;
this.menu_id_auto = 0;
this.oninit = function(){
XModels[modelid].menu_id_auto = function () {
if(!_this.menu_id_auto) _this.menu_id_auto = xmodel.controller.form.Data.menu_id_auto;
return _this.menu_id_auto;
};
jsh.$root('.menu_id_auto.tree').data('oncontextmenu','return '+XExt.getJSApp(modelid)+'.oncontextmenu(this, n);');
};
this.oncontextmenu = function(ctrl, n){
var menuid = '._item_context_menu_menu_id_auto';
var menu_add = jsh.$root(menuid).children('.insert');
var menu_delete = jsh.$root(menuid).children('.delete');
var jctrl = $(ctrl);
var level = 0;
var jpctrl = jctrl;
while(!jpctrl.hasClass('tree') && (level < 100)){ level++; jpctrl = jpctrl.parent(); }
if(level == 1){
menu_add.show();
menu_delete.hide();
}
else if(level == 2){
menu_add.show();
menu_delete.show();
}
else if(level == 3){
menu_add.hide();
menu_delete.show();
}
else { /* Do nothing */ }
XExt.ShowContextMenu(menuid, $(ctrl).data('value'), { id:n });
return false;
};
this.menu_id_onchange = function(obj, newval, undoChange) {
if(jsh.XPage.GetChanges().length){
undoChange();
return XExt.Alert('Please save changes before navigating to a different record.');
}
jsh.App[modelid].select_menu_id_auto(newval);
};
this.select_menu_id_auto = function(newval, cb){
xmodel.set('cur_menu_id_auto', newval);
xmodel.controller.form.Data.menu_id_auto = newval;
this.menu_id_auto = newval;
jsh.XPage.Select({ modelid: XBase[xmodel.module_namespace+'Dev/Menu'][0], force: true }, cb);
};
this.item_insert = function(context_item){
if(jsh.XPage.GetChanges().length) return XExt.Alert('Please save changes before adding menu items.');
var fields = {
'menu_name': { 'caption': 'Menu ID', 'actions': 'BI', 'type': 'varchar', 'length': 30, 'validators': [XValidate._v_Required(), XValidate._v_MaxLength(30)] },
'menu_desc': { 'caption': 'Display Name', 'actions': 'BI', 'type': 'varchar', 'length': 255, 'validators': [XValidate._v_Required(), XValidate._v_MaxLength(255)] },
};
var data = { 'menu_id_parent': jsh.xContextMenuItemData.id };
var validate = new XValidate();
_.each(fields, function (val, key) { validate.AddControlValidator('.Menu_InsertPopup .' + key, '_obj.' + key, val.caption, 'BI', val.validators); });
XExt.CustomPrompt('.Menu_InsertPopup','\
<div class="Menu_InsertPopup xdialogbox xpromptbox" style="width:360px;"> \
<h3>Add Child Item</h3> \
<div align="left" style="padding-top:15px;"> \
<div style="width:100px;display:inline-block;margin-bottom:8px;text-align:right;">Menu ID:</div> <input autocomplete="off" type="text" class="menu_name" style="width:150px;" maxlength="255" /> (ex. ORDERS)<br/> \
<div style="width:100px;display:inline-block;text-align:right;">Display Name:</div> <input autocomplete="off" type="text" class="menu_desc" style="width:150px;"maxlength="255" /><br/> \
<div style="text-align:center;"><input type="button" value="Add" class="button_ok" style="margin-right:15px;" /> <input type="button" value="Cancel" class="button_cancel" /></div> \
</div> \
</div> \
',function(){ //onInit
window.setTimeout(function(){jsh.$root('.Menu_InsertPopup .menu_name').focus();},1);
}, function (success) { //onAccept
_.each(fields, function (val, key) { data[key] = jsh.$root('.Menu_InsertPopup .' + key).val(); });
if (!validate.ValidateControls('I', data, '')) return;
var insertTarget = xmodel.module_namespace+'Dev/Menu_Exec_Insert';
XForm.prototype.XExecutePost(insertTarget, data, function (rslt) { //On success
if ('_success' in rslt) {
jsh.App[modelid].select_menu_id_auto(parseInt(rslt[insertTarget][0].menu_id_auto), function(){
success();
jsh.XPage.Refresh();
});
}
});
}, function () { //onCancel
}, function () { //onClosed
});
};
this.getSMbyValue = function(menu_id_auto){
if(!menu_id_auto) return null;
var lov = xmodel.controller.form.LOVs.menu_id_auto;
for(var i=0;i<lov.length;i++){
if(lov[i][jsh.uimap.code_val]==menu_id_auto.toString()) return lov[i];
}
return null;
};
this.getSMbyID = function(menu_id){
if(!menu_id) return null;
var lov = xmodel.controller.form.LOVs.menu_id_auto;
for(var i=0;i<lov.length;i++){
if(lov[i][jsh.uimap.code_id]==menu_id.toString()) return lov[i];
}
return null;
};
this.item_delete = function(context_item){
if(jsh.XPage.GetChanges().length) return XExt.Alert('Please save changes before deleting menu items.');
var item_desc = XExt.getLOVTxt(xmodel.controller.form.LOVs.menu_id_auto,context_item);
var menu = jsh.App[modelid].getSMbyValue(context_item);
var menu_parent = null;
var has_children = false;
if(menu){
if(!menu[jsh.uimap.code_parent_id]) return XExt.Alert('Cannot delete root node');
menu_parent = jsh.App[modelid].getSMbyID(menu[jsh.uimap.code_parent_id]);
var lov = xmodel.controller.form.LOVs.menu_id_auto;
for(var i=0;i<lov.length;i++){
if(lov[i][jsh.uimap.code_parent_id] && (lov[i][jsh.uimap.code_parent_id].toString()==menu[jsh.uimap.code_id].toString())) has_children = true;
}
}
if(has_children){ XExt.Alert('Cannot delete menu item with children. Please delete child items first.'); return; }
//Move to parent ID if the deleted node is selected
var new_menu_id_auto = null;
if(_this.menu_id_auto==context_item){
if(menu_parent) new_menu_id_auto = menu_parent[jsh.uimap.code_val];
}
XExt.Confirm('Are you sure you want to delete \''+item_desc+'\'?',function(){
XForm.prototype.XExecutePost(xmodel.module_namespace+'Dev/Menu_Exec_Delete', { menu_id_auto: context_item }, function (rslt) { //On success
if ('_success' in rslt) {
//Select parent
if(new_menu_id_auto) XExt.TreeSelectNode(jsh.$root('.menu_id_auto.tree'),new_menu_id_auto);
jsh.XPage.Refresh();
}
});
});
};
})(); | apHarmony/jsharmony-factory | models/Dev_Menu_Tree_Editor.js | JavaScript | lgpl-3.0 | 6,260 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, csv, time, codecs, shutil, urllib2, logging
from optparse import make_option
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from django.utils.text import slugify
from zipfile import ZipFile
from zup.utils import gooseapi, unicode_dict_reader, unique_mkdir
from zup.models import Job, Url
logger = logging.getLogger('zup')
class Command(BaseCommand):
'''
usage type:
python manage.py start_job --job=1 --cmd=test
'''
args = ''
help = 'execute some job on corpus.'
option_list = BaseCommand.option_list + (
make_option('--job',
action='store',
dest='job_pk',
default=False,
help='job primary key'),
make_option('--cmd',
action='store',
dest='cmd',
default=False,
help='manage.py command to be executed'),
)
def _test(self, job):
job.status = Job.RUNNING
job.save()
time.sleep(15)
job.status = Job.COMPLETED
job.save()
def _scrape(self, job, fields=['title', 'tags', 'meta_keywords']):
logger.debug('starting command "scrape"')
job.status = Job.RUNNING
job.save()
job_path = job.get_path()
path = unique_mkdir(os.path.join(job_path, 'files'))
urls = job.urls.all()
# create zip filename and remove previous one
zip_path = os.path.join(job_path, 'urls_to_zip.zip')
if os.path.exists(zip_path):
os.remove(zip_path)
# create csv report
rep_path = os.path.join(path, 'report.csv')
reports = []
logger.debug('zip path: %s' % zip_path)
# filename length
max_length = 64
with ZipFile(zip_path, 'w') as zip_file:
for i,url in enumerate(urls): # sync or not async
index = '%0*d' % (5, int(i) + 1)
url.status= Url.READY
url.save()
try:
g = gooseapi(url=url.url)
except urllib2.HTTPError, e:
url.status= Url.ERROR
url.log = '%s' % e
url.save()
continue
except urllib2.URLError, e:
url.status= Url.ERROR
url.log = '%s' % e
url.save()
continue
except ValueError, e: # that is, url is not a valid url
url.status= Url.ERROR
url.log = '%s' % e
url.save()
continue
except IOError, e: # probably the stopword file was not found, skip this url
url.status= Url.ERROR
url.log = '%s' % e
url.save()
continue
except Exception, e:
logger.exception(e)
continue
logger.debug('title: %s', g.title)
logger.debug('url: %s', url.url)
# handling not found title stuff
slug = '%s-%s' % (index,slugify(g.title if g.title else url.url)[:max_length])
slug_base = slug
textified = os.path.join(path, slug)
c = 1
while os.path.exists(textified):
candidate = '%s-%s-%s' % (index, slug_base, c)
if len(candidate) > max_length:
slug = slug[:max_length-len('-%s' % c)]
slug = re.sub('\-+','-',candidate)
textified = os.path.join(path, slug)
c += 1
textified = "%s.txt" % textified
with codecs.open(textified, encoding='utf-8', mode='w') as f:
f.write('\n\n%s\n\n\n\n' % g.title)
f.write(g.cleaned_text)
# completed url scraping
url.status= Url.COMPLETED
url.save()
zip_file.write(textified, os.path.basename(textified))
# WRITE SOME REPORT
result = {
'id': index,
'path': os.path.basename(textified),
'url': url.url
}
for i in fields:
if i == 'tags':
result[i] = ', '.join(getattr(g, i))
else:
result[i] = getattr(g, i)
result[i]=result[i].encode('utf8')
reports.append(result)
# JOB FINISHED, WRITING REPORT
with open(rep_path, 'w') as report:
writer = csv.DictWriter(report, ['id', 'path', 'url'] + fields)
writer.writeheader()
for report in reports:
writer.writerow(report)
zip_file.write(rep_path, os.path.basename(rep_path))
shutil.rmtree(path)
# close job
job.status = Job.COMPLETED
job.save()
def handle(self, *args, **options):
if not options['cmd']:
raise CommandError("\n ouch. You should specify a valid function as cmd param")
if not options['job_pk']:
raise CommandError("\n ouch. please provide a job id to record logs and other stuff")
# maximum 5 jobs at the same time
try:
job = Job.objects.get(pk=options['job_pk'])
except Job.DoesNotExist, e:
raise CommandError("\n ouch. Try again, job pk=%s does not exist!" % options['job_pk'])
cmd = '_%s' % options['cmd']
getattr(self, cmd)(job=job) # no job will be charged!
| medialab/zup | zup/management/commands/start_job.py | Python | lgpl-3.0 | 5,000 |
/*
* server/zone/objects/tangible/tools/repairtool/RepairTool.cpp generated by engine3 IDL compiler 0.55
*/
#include "RepairTool.h"
#include "RepairToolImplementation.h"
#include "../Tool.h"
#include "../../../scene/SceneObject.h"
#include "../../../creature/CreatureObject.h"
#include "../../../player/Player.h"
/*
* RepairToolStub
*/
RepairTool::RepairTool(unsigned long long oid, unsigned int tempCRC, const UnicodeString& n, const String& tempn) : Tool(DummyConstructorParameter::instance()) {
_impl = new RepairToolImplementation(oid, tempCRC, n, tempn);
_impl->_setStub(this);
}
RepairTool::RepairTool(CreatureObject* creature, unsigned long long oid, unsigned int tempCRC, const UnicodeString& n, const String& tempn) : Tool(DummyConstructorParameter::instance()) {
_impl = new RepairToolImplementation(creature, oid, tempCRC, n, tempn);
_impl->_setStub(this);
}
RepairTool::RepairTool(DummyConstructorParameter* param) : Tool(param) {
}
RepairTool::~RepairTool() {
}
void RepairTool::generateAttributes(SceneObject* obj) {
if (_impl == NULL) {
if (!deployed)
throw ObjectNotDeployedException(this);
DistributedMethod method(this, 6);
method.addObjectParameter(obj);
method.executeWithVoidReturn();
} else
((RepairToolImplementation*) _impl)->generateAttributes(obj);
}
int RepairTool::useObject(Player* player) {
if (_impl == NULL) {
if (!deployed)
throw ObjectNotDeployedException(this);
DistributedMethod method(this, 7);
method.addObjectParameter(player);
return method.executeWithSignedIntReturn();
} else
return ((RepairToolImplementation*) _impl)->useObject(player);
}
void RepairTool::setQuality(int q) {
if (_impl == NULL) {
if (!deployed)
throw ObjectNotDeployedException(this);
DistributedMethod method(this, 8);
method.addSignedIntParameter(q);
method.executeWithVoidReturn();
} else
((RepairToolImplementation*) _impl)->setQuality(q);
}
int RepairTool::getQuality() {
if (_impl == NULL) {
if (!deployed)
throw ObjectNotDeployedException(this);
DistributedMethod method(this, 9);
return method.executeWithSignedIntReturn();
} else
return ((RepairToolImplementation*) _impl)->getQuality();
}
/*
* RepairToolAdapter
*/
RepairToolAdapter::RepairToolAdapter(RepairToolImplementation* obj) : ToolAdapter(obj) {
}
Packet* RepairToolAdapter::invokeMethod(uint32 methid, DistributedMethod* inv) {
Packet* resp = new MethodReturnMessage(0);
switch (methid) {
case 6:
generateAttributes((SceneObject*) inv->getObjectParameter());
break;
case 7:
resp->insertSignedInt(useObject((Player*) inv->getObjectParameter()));
break;
case 8:
setQuality(inv->getSignedIntParameter());
break;
case 9:
resp->insertSignedInt(getQuality());
break;
default:
return NULL;
}
return resp;
}
void RepairToolAdapter::generateAttributes(SceneObject* obj) {
return ((RepairToolImplementation*) impl)->generateAttributes(obj);
}
int RepairToolAdapter::useObject(Player* player) {
return ((RepairToolImplementation*) impl)->useObject(player);
}
void RepairToolAdapter::setQuality(int q) {
return ((RepairToolImplementation*) impl)->setQuality(q);
}
int RepairToolAdapter::getQuality() {
return ((RepairToolImplementation*) impl)->getQuality();
}
/*
* RepairToolHelper
*/
RepairToolHelper* RepairToolHelper::staticInitializer = RepairToolHelper::instance();
RepairToolHelper::RepairToolHelper() {
className = "RepairTool";
DistributedObjectBroker::instance()->registerClass(className, this);
}
void RepairToolHelper::finalizeHelper() {
RepairToolHelper::finalize();
}
DistributedObject* RepairToolHelper::instantiateObject() {
return new RepairTool(DummyConstructorParameter::instance());
}
DistributedObjectAdapter* RepairToolHelper::createAdapter(DistributedObjectStub* obj) {
DistributedObjectAdapter* adapter = new RepairToolAdapter((RepairToolImplementation*) obj->_getImplementation());
obj->_setClassName(className);
obj->_setClassHelper(this);
adapter->setStub(obj);
return adapter;
}
/*
* RepairToolServant
*/
RepairToolServant::RepairToolServant(unsigned long long oid, unsigned int type) : ToolImplementation(oid, type) {
_classHelper = RepairToolHelper::instance();
}
RepairToolServant::~RepairToolServant() {
}
void RepairToolServant::_setStub(DistributedObjectStub* stub) {
_this = (RepairTool*) stub;
ToolServant::_setStub(stub);
}
DistributedObjectStub* RepairToolServant::_getStub() {
return _this;
}
| TheAnswer/FirstTest | src/server/zone/objects/tangible/tools/repairtool/RepairTool.cpp | C++ | lgpl-3.0 | 4,464 |
package net.paissad.tools.reqcoco.core.report;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.paissad.tools.reqcoco.api.exception.ReqReportBuilderException;
import net.paissad.tools.reqcoco.api.model.Requirement;
import net.paissad.tools.reqcoco.api.report.ReqReportConfig;
public class ReqReportBuilderConsole extends AbstractReqReportBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(ReqReportBuilderConsole.class);
private static final String LOGGER_PREFIX_TAG = String.format("%-15s -", "[ConsoleReport]");
private static final Charset UTF8 = Charset.forName("UTF-8");
@Override
public void configure(final Collection<Requirement> requirements, final ReqReportConfig config) throws ReqReportBuilderException {
super.configure(requirements, config);
this.setOutput(System.out);
}
@Override
public void run() throws ReqReportBuilderException {
if (getRequirements().isEmpty()) {
LOGGER.warn("{} No requirements = no console report", LOGGER_PREFIX_TAG);
} else {
LOGGER.info("{} Starting to generate console report", LOGGER_PREFIX_TAG);
try {
final OutputStream out = getOutput(); // Important note : never close the standard output stream :D
out.write((getReportConfig().getTitle() + "\n").getBytes(UTF8));
out.write("========================================== SUMMARY ===============================================\n".getBytes(UTF8));
final String summaryFormat = "%-25s : %s\n";
out.write(String.format(summaryFormat, "Number of requirements", getRequirements().size()).getBytes(UTF8));
out.write(String.format(summaryFormat, "Code done ratio", getCodeDoneRatio() * 100 + " %").getBytes(UTF8));
out.write(String.format(summaryFormat, "Tests done ratio", getTestDoneRatio() * 100 + " %").getBytes(UTF8));
out.write("==================================================================================================\n".getBytes(UTF8));
final String reqListFormat = "%s\n";
getRequirements().forEach(req -> printRequirement(out, reqListFormat, req));
out.write("==================================================================================================\n".getBytes(UTF8));
} catch (Exception e) {
String errMsg = "Error while building console report : " + e.getMessage();
LOGGER.error(LOGGER_PREFIX_TAG + errMsg, e);
throw new ReqReportBuilderException(errMsg, e);
}
LOGGER.info("{} Finished generating console report", LOGGER_PREFIX_TAG);
}
}
private void printRequirement(final OutputStream out, final String reqListFormat, Requirement req) {
try {
out.write(String.format(reqListFormat, req.toString()).getBytes(UTF8));
} catch (IOException e) {
LOGGER.error(LOGGER_PREFIX_TAG + "Unable to print requirement having name {} : {}", req.getName(), e);
}
}
@Override
protected String getDefaultFileReportExtension() {
return "";
}
}
| paissad/reqcoco | reqcoco-core/src/main/java/net/paissad/tools/reqcoco/core/report/ReqReportBuilderConsole.java | Java | lgpl-3.0 | 3,045 |
package fr.theflogat.technicalWizardry.lib;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumMovingObjectType;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import org.lwjgl.input.Keyboard;
public class Formulas extends Item {
public Formulas(int par1) {
super(par1);
// TODO Auto-generated constructor stub
}
public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4) {
if(Keyboard.isKeyDown(42)){
par3List.add("");
} else {
par3List.add("--Press Shift For More Info--");
}
}
public ItemStack add(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer){
MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(par2World, par3EntityPlayer, true);
if (movingobjectposition.typeOfHit == EnumMovingObjectType.TILE)
{
int i = movingobjectposition.blockX;
int j = movingobjectposition.blockY;
int k = movingobjectposition.blockZ;
par2World.setBlockToAir(i, j, k);
if (--par1ItemStack.stackSize <= 0)
{
return new ItemStack(Item.bucketWater);
}
if (!par3EntityPlayer.inventory.addItemStackToInventory(new ItemStack(Item.bucketWater)))
{
par3EntityPlayer.dropPlayerItem(new ItemStack(Item.bucketWater.itemID, 1, 0));
}
}
return par1ItemStack;
}
}
| theflogat/Theflogats-Mods | fr/theflogat/technicalWizardry/lib/Formulas.java | Java | lgpl-3.0 | 1,662 |
package bradleyross.j2ee.servlets;
import java.util.Enumeration;
/**
* This is a simple example of a Java servlet.
*<p>It identifies information about the node transmitting the
* the HTTP request. This could be used in aiding security
* efforts by specifying that certain actions can only be
* carried out if the node transmitting the request is a
* link local address, site local address, or loopback
* address. Since these types of addresses can't be sent
* over the public internet, this would help insure that hackers
* couldn't carry out the operations remotely.</p>
* <p>This is a very simple example based on the idea that
* simple examples should be under two pages in length.</p>
* <p>You will notice to references to the javax.servlet and
* javax.servlet.http packages appear as hyperlinks. This is
* because I included the following options in the javadoc command.</p>
*<p><code>-link "http://java.sun.com/j2se/1.4.2/docs/api"</code> <br>
*<code>-link "http://tomcat.apache.org/tomcat-5.5-doc/servletapi"</code></p>
*<p>The relationship between the Java servlet to be executed and the
* HTTP call to the application server is defined by the server.xml file
* for the application server and the WEB-INF/web.xml file that exists for
* each web application. The following is the WEB-INF/web.xml file
* that was used with this servlet.</p>
* <p><code><pre>
* <web-app>
* <servlet>
* <servlet-name>first</servlet-name>
* <servlet-class>bradleyross.servlets.firstServlet</servlet-class>
* </servlet>
* <servlet-mapping>
* <servlet-name>first</servlet-name>
* <url-pattern>/firstServlet</url-pattern>
* </servlet-mapping>
* </web-app>
</pre></code></p>
*<p>The meaning of this XML document is as follows.</p>
*<p><ul>
*<li><p>The servlet is named <code>first</code>
* (<code>servlet-name</code>). This name doesn't appear
* in the Java code but is means of describing the configuration to
* the application server.</p></li>
*<li><p>The Java class for the servlet is
* <code>bradleyross.servlets.firstServlet</code>
* (<code>servlet-class</code>). (Although it isn't
* indicated from this document, this class
* file was included in the CLASSPATH for the application server and
* is therefore accessible to the system.)</p></li>
*<li><p>The URL entered in the browser will contain <code>/test</code>
* to indicate that this servlet is to be executed
* (<code>servlet-mapping</code>). This is known as the
* servlet path, meaning that it refers to the path
* within the web application.</p></li>
*</ul></p>
*<p>The web application is contained in the directory
* <code>webapps/test</code> on the application server, meaning that the
* XML file is at <code>webapps/test/WEB-INF/web.xml</code>. Unless
* there are entries in server.xml, the context path for the
* web application is <code>/test</code>, meaning that the
* servlet is accessed as <code>/test/firstServlet</code>. (The
* context path followed by the servlet path.)</p>
* @author Bradley Ross
*/
public class firstServlet extends javax.servlet.http.HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String firstCell(String contents)
{
StringBuffer value = new StringBuffer();
value.append("<tr><td>" + contents + "</td>");
return new String(value);
}
private String lastCell(String contents)
{
StringBuffer value = new StringBuffer();
value.append("<td>" + contents + "</td></tr>");
return new String(value);
}
private String doubleCell(String first, String last)
{
StringBuffer value = new StringBuffer();
value.append("<tr><td>" + first + "</td><td>" +
last + "</td></tr>");
return new String(value);
}
public void init (javax.servlet.ServletConfig config)
throws javax.servlet.ServletException
{ super.init(config); }
public void destroy()
{ super.destroy(); }
// @SuppressWarnings("unchecked")
/**
* @param req Information concerning the HTTP request received
* by the server.
* @param res Information concerning the HTTP response generated
* by the server.
*/
public void service (javax.servlet.http.HttpServletRequest req,
javax.servlet.http.HttpServletResponse res)
throws java.io.IOException
{
res.setContentType("text/html");
java.io.PrintWriter out = res.getWriter();
out.println("<html><head>");
out.println("<title>Sample Servlet</title>");
out.println("</head></body>");
out.println("<h1><center>Information on Requester</center></h1>");
out.println("<p>The IP address of the node sending the ");
out.println(" request is " + req.getRemoteAddr() + "</p>");
java.net.InetAddress address =
java.net.InetAddress.getByName(req.getRemoteAddr());
out.println("<table border>");
out.println(firstCell("isLinkLocalAddress"));
out.println(lastCell(Boolean.toString(address.isLinkLocalAddress())));
out.println(firstCell("isSiteLocalAddress"));
out.println(lastCell(Boolean.toString(address.isSiteLocalAddress())));
out.println(firstCell("isLoopbackAddress"));
out.println(lastCell(Boolean.toString(address.isLoopbackAddress())));
out.println("</table>");
//
out.println("<h2>Headers</h2>");
out.println("<p>Get list of headers for request</p>");
out.println("<p><ol>");
Enumeration<String> e = req.getHeaderNames();
while( e.hasMoreElements() )
{
String headerName = (String) e.nextElement();
out.println("<li><p>" + headerName +
"</p><p><ul>");
Enumeration<String> e2 = req.getHeaders(headerName);
while (e2.hasMoreElements() )
{ out.println("<li><p>" + e2.nextElement() + "</p></li>"); }
out.println("</ul></p></li>");
}
out.println("</ol></p>");
//
out.println("<p>URL components</p>");
out.println("<table border>");
out.println(doubleCell("getContextPath",
req.getContextPath()));
out.println(doubleCell("getMethod",
req.getMethod()));
out.println(doubleCell("getPathInfo",
req.getPathInfo()));
out.println(doubleCell("getPathTranslated",
req.getPathTranslated()));
out.println(doubleCell("getQueryString",
req.getQueryString()));
out.println(doubleCell("getRequestURI",
req.getRequestURI()));
out.println(doubleCell("getRequestURL",
new String(req.getRequestURL())));
out.println(doubleCell("getServletPath",
req.getServletPath()));
out.println("</table>");
out.println("<p>Cookies</p>");
out.println("</body></html>");
}
}
| BradleyRoss/bradleyross-examples | src/bradleyross/j2ee/servlets/firstServlet.java | Java | lgpl-3.0 | 6,985 |
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonarsource.sonarqube.perf.scanner.suite;
import com.google.common.base.Strings;
import com.sonar.orchestrator.Orchestrator;
import com.sonar.orchestrator.build.BuildResult;
import com.sonar.orchestrator.build.SonarScanner;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.wsclient.services.PropertyCreateQuery;
import org.sonarsource.sonarqube.perf.MavenLogs;
import org.sonarsource.sonarqube.perf.PerfRule;
import org.sonarsource.sonarqube.perf.PerfTestCase;
public class MemoryTest extends PerfTestCase {
@Rule
public PerfRule perfRule = new PerfRule(4) {
@Override
protected void beforeEachRun() {
orchestrator.resetData();
}
};
@ClassRule
public static TemporaryFolder temp = new TemporaryFolder();
@ClassRule
public static Orchestrator orchestrator = ScannerPerfTestSuite.ORCHESTRATOR;
@Before
public void cleanDatabase() {
orchestrator.resetData();
}
@Test
public void should_not_fail_with_limited_xmx_memory_and_no_coverage_per_test() {
orchestrator.executeBuild(
newScanner("-Xmx80m -server -XX:-HeapDumpOnOutOfMemoryError"));
}
int DEPTH = 4;
// Property on root module is duplicated in each module so it may be big
@Test
public void analyzeProjectWithManyModulesAndBigProperties() throws IOException {
File baseDir = temp.newFolder();
prepareModule(baseDir, "moduleA", 1);
prepareModule(baseDir, "moduleB", 1);
prepareModule(baseDir, "moduleC", 1);
FileUtils.write(new File(baseDir, "sonar-project.properties"), "sonar.modules=moduleA,moduleB,moduleC\n", true);
FileUtils.write(new File(baseDir, "sonar-project.properties"), "sonar.myBigProp=" + Strings.repeat("A", 10000), true);
SonarScanner scanner = SonarScanner.create()
.setProperties(
"sonar.projectKey", "big-module-tree",
"sonar.projectName", "Big Module Tree",
"sonar.projectVersion", "1.0",
"sonar.sources", "",
"sonar.showProfiling", "true");
scanner.setEnvironmentVariable("SONAR_RUNNER_OPTS", "-Xmx512m -server")
.setProjectDir(baseDir);
BuildResult result = orchestrator.executeBuild(scanner);
perfRule.assertDurationAround(MavenLogs.extractTotalTime(result.getLogs()), 4847L);
// Second execution with a property on server side
orchestrator.getServer().getAdminWsClient().create(new PropertyCreateQuery("sonar.anotherBigProp", Strings.repeat("B", 1000), "big-module-tree"));
result = orchestrator.executeBuild(scanner);
perfRule.assertDurationAround(MavenLogs.extractTotalTime(result.getLogs()), 4620L);
}
private void prepareModule(File parentDir, String moduleName, int depth) throws IOException {
File moduleDir = new File(parentDir, moduleName);
moduleDir.mkdir();
File projectProps = new File(moduleDir, "sonar-project.properties");
FileUtils.write(projectProps, "sonar.moduleKey=" + moduleName + "\n", true);
if (depth < DEPTH) {
FileUtils.write(projectProps, "sonar.modules=" + moduleName + "A," + moduleName + "B," + moduleName + "C\n", true);
prepareModule(moduleDir, moduleName + "A", depth + 1);
prepareModule(moduleDir, moduleName + "B", depth + 1);
prepareModule(moduleDir, moduleName + "C", depth + 1);
}
}
}
| lbndev/sonarqube | tests/perf/src/test/java/org/sonarsource/sonarqube/perf/scanner/suite/MemoryTest.java | Java | lgpl-3.0 | 4,296 |
<?php
require_once('AdminController.php');
class DocumentsController extends Controller
{
public function Create($virtualDirectoryPath)
{
$virtualDirectory = $this->GetVirtualDirectory($virtualDirectoryPath);
if($virtualDirectory == null){
return $this->HttpNotFound();
}
$this->Set('VirtualDirectory', $virtualDirectory);
return $this->View();
}
private function GetVirtualDirectory($path)
{
if(!is_array($path)){
return null;
}
$directories = $this->Models->VirtualDirectory->Where(array('ParentDirectoryId' => null));
foreach($path as $name){
$directory = $directories->Where(array('Name' => $name))->First;
if($directory == null){
return null;
}
}
}
} | bonahona/ShellShare | Application/Controllers/DocumentsController.php | PHP | lgpl-3.0 | 871 |
package io.vntr.middleware;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.set.TIntSet;
/**
* Created by robertlindquist on 9/23/16.
*/
public interface IMiddlewareAnalyzer extends IMiddleware {
Integer getNumberOfPartitions();
Integer getNumberOfUsers();
Integer getNumberOfFriendships();
TIntSet getUserIds();
TIntSet getPids();
Integer getEdgeCut();
Integer getReplicationCount();
Long getMigrationTally();
double calculateAssortivity();
double calculateExpectedQueryDelay();
void checkValidity();
TIntObjectMap<TIntSet> getPartitionToUserMap();
TIntObjectMap<TIntSet> getPartitionToReplicasMap();
TIntObjectMap<TIntSet> getFriendships();
}
| vntr-admin/combiner | src/main/java/io/vntr/middleware/IMiddlewareAnalyzer.java | Java | lgpl-3.0 | 710 |
<?php
/**
* Created by PhpStorm.
* User: Todociber
* Date: 18/04/2017
* Time: 11:57 AM
*/
class Migration_create_items extends CI_Migration
{
public function up()
{
$this->dbforge->add_field(
array(
"id" => array(
"type" => "INT",
"constraint" => 11,
"unsigned" => TRUE,
"auto_increment" => TRUE,
),
"itemId" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"title" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"globalId" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"category_ebay_id" => array(
'type' => 'int',
'constraint' => 100,
'unsigned' => TRUE,
'null' => FALSE,
),
"galleryURL" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"viewItemURL" => array(
"type" => "VARCHAR",
"constraint" => 500
),
"paymentMethods_ebay_id" => array(
'type' => 'int',
'constraint' => 100,
'unsigned' => TRUE,
'null' => FALSE,
),
"currentPrice" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"convertedCurrentPrice" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"sellingState" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"timeLeft" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"bestOfferStatus" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"buyItNowStatus" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"itemscol" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"startTime" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"endTime" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"listingType" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"gift" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"returnsStatus" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"conditions_id" => array(
'type' => 'int',
'constraint' => 100,
'unsigned' => TRUE,
'null' => FALSE,
),
"isMultiVariationListingStatus" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"topRatedListingStatus" => array(
"type" => "VARCHAR",
"constraint" => 100
),
"Profiles_Ebay_id" => array(
'type' => 'int',
'constraint' => 100,
'unsigned' => TRUE,
'null' => FALSE,
),
"created_at" => array(
"type" => "TIMESTAMP",
),
"updated_at" => array(
"type" => "TIMESTAMP",
),
"deleted_at" => array(
"type" => "TIMESTAMP",
'null' => TRUE,
),
)
);
$this->dbforge->add_field('CONSTRAINT FOREIGN KEY (Profiles_Ebay_id) REFERENCES profiles_ebay(id)');
$this->dbforge->add_field('CONSTRAINT FOREIGN KEY (category_ebay_id) REFERENCES category_ebay(id)');
$this->dbforge->add_field('CONSTRAINT FOREIGN KEY (paymentMethods_ebay_id) REFERENCES paymentMethods_ebay(id)');
$this->dbforge->add_field('CONSTRAINT FOREIGN KEY (conditions_id) REFERENCES conditions_ebay(id)');
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('items');
}
public function down()
{
$this->dbforge->drop_table('items');
}
} | todociber/APiJexanTest | application/migrations/010_create_items.php | PHP | lgpl-3.0 | 5,046 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.setting.ws;
import org.sonar.api.server.ws.WebService;
public class SettingsWs implements WebService {
private final SettingsWsAction[] actions;
public SettingsWs(SettingsWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/settings")
.setDescription("Manage settings.")
.setSince("6.1");
for (SettingsWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| SonarSource/sonarqube | server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingsWs.java | Java | lgpl-3.0 | 1,407 |
๏ปฟ// LICENSE: LGPL 3 - https://www.gnu.org/licenses/lgpl-3.0.txt
// s. http://blog.marcel-kloubert.de
using System;
namespace MarcelJoachimKloubert.CloudNET.SDK
{
/// <summary>
/// A basic object that belongs to a <see cref="CloudServer" />.
/// </summary>
public abstract class CloudServerObjectBase
{
#regionย Fieldsย (2)
private readonly CloudServer _SERVER;
/// <summary>
/// An unique object for thread safe operations.
/// </summary>
protected readonly object _SYNC;
#endregionย Fields
#regionย Constructorsย (2)
/// <summary>
/// Initializes a new instance of the <see cref="CloudServerObjectBase"/> class.
/// </summary>
/// <param name="server">The value for the <see cref="CloudServerObjectBase.Server" /> property.</param>
/// <param name="sync">The value for the <see cref="CloudServerObjectBase._SYNC" /> field.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="server" /> and/or <paramref name="sync" /> are <see langword="null" />.
/// </exception>
protected CloudServerObjectBase(CloudServer server, object sync)
{
if (server == null)
{
throw new ArgumentNullException("server");
}
if (sync == null)
{
throw new ArgumentNullException("sync");
}
this._SERVER = server;
this._SYNC = sync;
}
/// <summary>
/// Initializes a new instance of the <see cref="CloudServerObjectBase"/> class.
/// </summary>
/// <param name="server">The value for the <see cref="CloudServerObjectBase.Server" /> property.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="server" /> is <see langword="null" />.
/// </exception>
protected CloudServerObjectBase(CloudServer server)
: this(server, new object())
{
}
#endregionย Constructors
#regionย Propertiesย (1)
/// <summary>
/// Gets the server that object belongs to.
/// </summary>
public CloudServer Server
{
get { return this._SERVER; }
}
#endregionย Properties
}
}
| mkloubert/CLRToolbox | Projects/MarcelJoachimKloubert.CloudNET/MarcelJoachimKloubert.CloudNET.SDK/CloudServerObjectBase.cs | C# | lgpl-3.0 | 2,355 |
๏ปฟ#include "ege/viewport.h"
#include "image.h"
#include "global.h"
namespace ege
{
void
getviewport(int* pleft, int* ptop, int* pright, int* pbottom, int* pclip,
IMAGE* pimg)
{
auto& vpt(cimg_ref_c(pimg).m_vpt);
if(pleft)
*pleft = vpt.left;
if(ptop)
*ptop = vpt.top;
if(pright)
*pright = vpt.right;
if(pbottom)
*pbottom = vpt.bottom;
if(pclip)
*pclip = vpt.clipflag;
}
void
setviewport(int left, int top, int right, int bottom, int clip, IMAGE* pimg)
{
cimg_ref(pimg).SetViewport(left, top, right, bottom, clip);
}
void
clearviewport(IMAGE* pimg)
{
auto& img(cimg_ref(pimg));
if(img.getdc())
{
::RECT rect{0, 0, img.m_vpt.right - img.m_vpt.left,
img.m_vpt.bottom - img.m_vpt.top};
const auto hbr(::CreateSolidBrush(GetBkColor(img.getdc())));
::FillRect(img.getdc(), &rect, hbr);
::DeleteObject(hbr);
}
}
void
window_getviewport(viewporttype* viewport)
{
auto& pages(get_pages());
viewport->left = pages.base_x;
viewport->top = pages.base_y;
viewport->right = pages.base_w + pages.base_x;
viewport->bottom = pages.base_h + pages.base_y;
}
void
window_getviewport(int* left, int* top, int* right, int* bottom)
{
auto& pages(get_pages());
if(left)
*left = pages.base_x;
if(top)
*top = pages.base_y;
if(right)
*right = pages.base_w + pages.base_x;
if(bottom)
*bottom = pages.base_h + pages.base_y;
}
void
window_setviewport(int left, int top, int right, int bottom)
{
auto& pages(get_pages());
auto& gstate(FetchEGEApplication());
const auto hwnd(gstate._get_hwnd());
const bool same_xy(pages.base_x == left && pages.base_y == top),
same_wh(pages.base_w == bottom - top && pages.base_h == right - left);
pages.base_x = left;
pages.base_y = top;
pages.base_w = right - left;
pages.base_h = bottom - top;
if(!same_xy || !same_wh)
--update_mark_count;
/*ไฟฎๆญฃ็ชๅฃๅคงๅฐ*/
if(!same_wh)
{
::RECT rect, crect;
int dw, dh;
::GetClientRect(hwnd, &crect);
::GetWindowRect(hwnd, &rect);
dw = pages.base_w - crect.right;
dh = pages.base_h - crect.bottom;
{
::HWND hparent = GetParent(hwnd);
if(hparent)
{
::POINT pt{0, 0};
::ClientToScreen(hparent, &pt);
rect.left -= pt.x;
rect.top -= pt.y;
rect.right -= pt.x;
rect.bottom -= pt.y;
}
::MoveWindow(hwnd, rect.left, rect.top,
rect.right + dw - rect.left, rect.bottom + dh - rect.top, true);
}
}
}
} // namespace ege;
| FrankHB/YEGE | EGE/src/ege/viewport.cpp | C++ | lgpl-3.0 | 2,519 |
<?php
/**
* This file is part of MetaModels/core.
*
* (c) 2012-2019 The MetaModels team.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* This project is provided in good faith and hope to be usable by anyone.
*
* @package MetaModels/core
* @author Christian Schiffler <c.schiffler@cyberspectrum.de>
* @copyright 2012-2019 The MetaModels team.
* @license https://github.com/MetaModels/core/blob/master/LICENSE LGPL-3.0-or-later
* @filesource
*/
namespace MetaModels\CoreBundle\DcGeneral;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\Palette\Condition\Property\PropertyConditionInterface;
use MetaModels\Events\CreatePropertyConditionEvent;
use MetaModels\IMetaModel;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* This is the fallback to globals.
*
* @deprecated Only here as bc-layer to MetaModels 2.0 - to be removed in 3.0
*/
class FallbackPropertyConditionFactory
{
/**
* The event dispatcher.
*
* @var EventDispatcherInterface
*/
private $dispatcher;
/**
* Create a new instance.
*
* @param EventDispatcherInterface $dispatcher The event dispatcher.
*/
public function __construct(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}
/**
* Obtain the id list for globally configured types.
*
* @return string[]
*
* @SuppressWarnings(PHPMD.Superglobals)
* @SuppressWarnings(PHPMD.CamelCaseVariableName)
*/
public function getIds()
{
if (!isset($GLOBALS['METAMODELS']['inputscreen_conditions'])) {
return [];
}
// @codingStandardsIgnoreStart Silencing errors is discouraged
@trigger_error('Configuring input screen conditions via global array is deprecated. ' .
'Please implement/configure a valid condition factory.', E_USER_DEPRECATED);
// @codingStandardsIgnoreEnd
return array_keys($GLOBALS['METAMODELS']['inputscreen_conditions']);
}
/**
* Test if the passed type supports nesting.
*
* @param string $conditionType The type name.
*
* @return bool|null
*
* @SuppressWarnings(PHPMD.Superglobals)
* @SuppressWarnings(PHPMD.CamelCaseVariableName)
*/
public function supportsNesting($conditionType)
{
if (!isset($GLOBALS['METAMODELS']['inputscreen_conditions'][$conditionType]['nestingAllowed'])) {
return null;
}
// @codingStandardsIgnoreStart Silencing errors is discouraged
@trigger_error('Configuring input screen conditions via global array is deprecated. ' .
'Please implement/configure a valid condition factory.', E_USER_DEPRECATED);
// @codingStandardsIgnoreEnd
return $GLOBALS['METAMODELS']['inputscreen_conditions'][$conditionType]['nestingAllowed'];
}
/**
* Get the amount of children this type supports - for undefined returns null.
*
* @param string $conditionType The type name.
*
* @return int|null
*
* @SuppressWarnings(PHPMD.Superglobals)
* @SuppressWarnings(PHPMD.CamelCaseVariableName)
*/
public function maxChildren($conditionType)
{
if (!isset($GLOBALS['METAMODELS']['inputscreen_conditions'][$conditionType]['maxChildren'])) {
return null;
}
// @codingStandardsIgnoreStart Silencing errors is discouraged
@trigger_error('Configuring input screen conditions via global array is deprecated. ' .
'Please implement/configure a valid condition factory.', E_USER_DEPRECATED);
// @codingStandardsIgnoreEnd
return $GLOBALS['METAMODELS']['inputscreen_conditions'][$conditionType]['maxChildren'];
}
/**
* Test if an attribute type is supported for the passed condition type.
*
* @param string $conditionType The condition type.
* @param string $attribute The attribute type.
*
* @return bool|null
*
* @SuppressWarnings(PHPMD.Superglobals)
* @SuppressWarnings(PHPMD.CamelCaseVariableName)
*/
public function supportsAttribute($conditionType, $attribute)
{
if (!isset($GLOBALS['METAMODELS']['inputscreen_conditions'][$conditionType]['attributes'])) {
return null;
}
// @codingStandardsIgnoreStart Silencing errors is discouraged
@trigger_error('Configuring input screen conditions via global array is deprecated. ' .
'Please implement/configure a valid condition factory.', E_USER_DEPRECATED);
// @codingStandardsIgnoreEnd
$allowedAttributes = $GLOBALS['METAMODELS']['inputscreen_conditions'][$conditionType]['attributes'];
return (\is_array($allowedAttributes) && !\in_array($attribute, $allowedAttributes, true));
}
/**
* Create a condition from the passed configuration.
*
* @param array $configuration The configuration.
* @param IMetaModel $metaModel The MetaModel instance.
*
* @return PropertyConditionInterface
*
* @throws \RuntimeException When the condition could not be transformed.
*/
public function createCondition(array $configuration, IMetaModel $metaModel)
{
$event = new CreatePropertyConditionEvent($configuration, $metaModel);
$this->dispatcher->dispatch(CreatePropertyConditionEvent::NAME, $event);
if (null === $instance = $event->getInstance()) {
throw new \RuntimeException(sprintf(
'Condition of type %s could not be transformed to an instance.',
$configuration['type']
));
}
// @codingStandardsIgnoreStart Silencing errors is discouraged
@trigger_error('Creating input screen conditions via event is deprecated. ' .
'Please implement a valid condition factory.', E_USER_DEPRECATED);
// @codingStandardsIgnoreEnd
return $instance;
}
}
| MetaModels/core | src/CoreBundle/DcGeneral/FallbackPropertyConditionFactory.php | PHP | lgpl-3.0 | 6,074 |
๏ปฟusing System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Kentor.AuthServices
{
class SignInCommand : ICommand
{
public CommandResult Run(HttpRequestBase request)
{
var idp = IdentityProvider.ConfiguredIdentityProviders.First().Value;
var authnRequest = idp.CreateAuthenticateRequest();
return idp.Bind(authnRequest);
}
}
}
| henningjensen/authservices | Kentor.AuthServices/SignInCommand.cs | C# | lgpl-3.0 | 560 |
package org.zenframework.z8.server.db.sql.functions.geometry;
import java.util.Collection;
import org.zenframework.z8.server.base.table.value.IField;
import org.zenframework.z8.server.db.DatabaseVendor;
import org.zenframework.z8.server.db.FieldType;
import org.zenframework.z8.server.db.sql.FormatOptions;
import org.zenframework.z8.server.db.sql.SqlToken;
import org.zenframework.z8.server.exceptions.db.UnknownDatabaseException;
public class CollectionSize extends SqlToken {
private final SqlToken geometry;
public CollectionSize(SqlToken geometry) {
this.geometry = geometry;
}
@Override
public void collectFields(Collection<IField> fields) {
geometry.collectFields(fields);
}
@Override
public String format(DatabaseVendor vendor, FormatOptions options, boolean logicalContext) {
switch (vendor) {
case Postgres:
return new StringBuilder(1024).append("ST_NumGeometries(").append(geometry.format(vendor, options)).append(')')
.toString();
default:
throw new UnknownDatabaseException();
}
}
@Override
public FieldType type() {
return FieldType.Integer;
}
}
| zenframework/z8 | org.zenframework.z8.server/src/main/java/org/zenframework/z8/server/db/sql/functions/geometry/CollectionSize.java | Java | lgpl-3.0 | 1,106 |
/**
* Copyright (C) 2015 Michael Schnell. All rights reserved.
* http://www.fuin.org/
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see http://www.gnu.org/licenses/.
*/
package org.fuin.srcgen4j.core.velocity;
import java.io.Serializable;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.fuin.objects4j.vo.TrimmedNotEmpty;
import org.fuin.utils4j.Utils4J;
/**
* Container for a key and a value combination.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = { "value", "key" })
@XmlRootElement(name = "argument")
public final class Argument implements Serializable, Comparable<Argument> {
private static final long serialVersionUID = 1L;
@TrimmedNotEmpty
@XmlAttribute
private String key;
@TrimmedNotEmpty
@XmlAttribute
private String value;
/**
* Default constructor.
*/
public Argument() {
super();
}
/**
* Constructor with key and value.
*
* @param key
* Key - Cannot be NULL.
* @param value
* Value - Cannot be NULL.
*/
public Argument(final String key, final String value) {
super();
this.key = key;
this.value = value;
}
/**
* Returns the key.
*
* @return Key - Never NULL.
*/
public final String getKey() {
return key;
}
/**
* Returns the value.
*
* @return Value - Never NULL.
*/
public final String getValue() {
return value;
}
@Override
public final int hashCode() {
return key.hashCode();
}
@Override
public final boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Argument other = (Argument) obj;
return key.equals(other.key);
}
@Override
public final int compareTo(final Argument other) {
return key.compareTo(other.key);
}
@Override
public final String toString() {
return key + "='" + value + "'";
}
/**
* Replaces variables (if defined) in the value.
*
* @param vars
* Variables to use.
*/
public final void init(final Map<String, String> vars) {
value = Utils4J.replaceVars(getValue(), vars);
}
}
| fuinorg/srcgen4j-core | src/main/java/org/fuin/srcgen4j/core/velocity/Argument.java | Java | lgpl-3.0 | 3,357 |
package queueit.security;
public class KnownUserValidationException extends SessionValidationException {
KnownUserValidationException(KnownUserException cause, IQueue queue)
{
super(cause.getMessage(), cause, queue);
}
}
| queueit/QueueIT.Security-JavaEE | QueueIT.Security/src/queueit/security/KnownUserValidationException.java | Java | lgpl-3.0 | 242 |
๏ปฟ/*
* SonarLint for Visual Studio
* Copyright (C) 2015-2016 SonarSource SA
* mailto:contact@sonarsource.com
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
using Microsoft.CodeAnalysis;
namespace SonarLint.Helpers
{
internal class SyntaxNodeSymbolSemanticModelTuple<TSyntax, TSymbol> : SyntaxNodeSemanticModelTuple<TSyntax>
where TSyntax : SyntaxNode
where TSymbol : ISymbol
{
public TSymbol Symbol { get; set; }
}
}
| dbolkensteyn/sonarlint-vs | src/SonarLint.CSharp/Helpers/SyntaxNodeSymbolSemanticModelTuple.cs | C# | lgpl-3.0 | 1,145 |
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EventLoopPlugin;
using FIVES;
namespace BVHAnimationPlugin
{
class AnimationInfo
{
public int frameTime;
public List<string> bvhAnimationString;
public string bvhActionString;
}
class BVHAnimationManager
{
public static BVHAnimationManager Instance;
private string isStoppedEntity;
private string isPausedEntity;
private bool isPaused;
internal BVHAnimationManager() { }
internal void Initialize()
{
EventLoop.Instance.TickFired += new EventHandler<TickEventArgs>(HandleEventTick);
}
internal void Initialize(BVHAnimationPluginInitializer plugin)
{
this.animationPlugin = plugin;
this.isStoppedEntity = "";
this.isPausedEntity = "";
this.isPaused = false;
this.loopCounter = 0;
Initialize();
}
private void HandleEventTick(Object sender, TickEventArgs e)
{
//Triggered within fixed time
lock (RunningAnimationsForEntities)
{
foreach (KeyValuePair<string, AnimationInfo>
animatedEntity in RunningAnimationsForEntities)
{
loopCounter++;
Entity entity = World.Instance.FindEntity(animatedEntity.Key);
//check if this is paused entity
int pausedFrame = 0;
if(this.isPausedEntity.Equals(entity.Guid.ToString("D")))
{
//we should not send the action string again
//we need to take the paused frame
pausedFrame = this.PausedFrameForEntities[this.isPausedEntity];
}
else
{
//otherwise we send it at the very start
string actionString = loopCounter.ToString() + ":" + animatedEntity.Value.bvhActionString;
entity["BVHAnimation"]["bvhaction"].Suggest(actionString);
//FIXME: we need to wait for answer, but how?
System.Threading.Thread.Sleep(500);
}
int frameNum = 0;
foreach (string frame in animatedEntity.Value.bvhAnimationString)
{
frameNum ++;
//firstly check if this is paused entity
if (pausedFrame > 0)
{
if(frameNum < pausedFrame)
continue;
else
{
//clear the paused information
PausedAnimationsForEntities.Remove(this.isPausedEntity);
this.isPaused = false;
PausedFrameForEntities.Remove(this.isPausedEntity);
this.isPausedEntity = "";
}
}
//Not paused
string sendString = frameNum.ToString() + frame;
//Console.WriteLine(sendString);
entity["BVHAnimation"]["bvhframe"].Suggest(sendString);
//FIXME: replace this sleep of pose-to-pose interpolation
System.Threading.Thread.Sleep(animatedEntity.Value.frameTime);
//if receive the signal of stop, just break
if (this.isStoppedEntity.Equals(entity.Guid.ToString("D")))
{
break;
}
//if receive the signal of pause, remember the frame number and break
if(this.isPausedEntity.Equals(entity.Guid.ToString("D")))
{
this.PausedFrameForEntities[this.isPausedEntity] = frameNum;
break;
}
}
}
}
}
public void StartAnimation(string guid, string aniName, BVHSkeleton skeleton)
{
//Clear the stop information
if (this.isStoppedEntity.Equals(guid))
{
this.isStoppedEntity = "";
}
//recover the pause information, and resume
if (this.isPausedEntity.Equals(guid))
{
//recover
if (PausedAnimationsForEntities.ContainsKey(guid))
{
//add the animation to running animation
lock (RunningAnimationsForEntities)
{
if (RunningAnimationsForEntities.ContainsKey(guid))
{
//Means user start a new animation, clear the paused frame
//PausedFrameForEntities.Remove(guid);
}
else
{
//else resume the old animation
RunningAnimationsForEntities.Add(guid, PausedAnimationsForEntities[guid]);
//and remove the old animation
//PausedAnimationsForEntities.Remove(guid);
}
}
}
else
{
Console.WriteLine("No such entity has been paused!");
}
return;
}
AnimationInfo info = new AnimationInfo();
//get frame time
info.frameTime = skeleton.getFrameTime();
//get frame motion data
info.bvhAnimationString = skeleton.GenerateBVHAnimationFrames();
//get frame action
info.bvhActionString = skeleton.GenerateBVHAnimationAction();
lock (RunningAnimationsForEntities)
{
if (!RunningAnimationsForEntities.ContainsKey(guid))
RunningAnimationsForEntities[guid] = new AnimationInfo();
//FIXME: maybe we need to check the animation name to prevent potenial double "start" click
RunningAnimationsForEntities[guid] = info;
}
}
public void PauseAnimation(string guid, string aniName)
{
this.isPaused = true;
this.isPausedEntity = guid;
lock (RunningAnimationsForEntities)
{
if (RunningAnimationsForEntities.ContainsKey(guid))
{
//remember the paused animation
if (!PausedAnimationsForEntities.ContainsKey(guid))
PausedAnimationsForEntities.Add(guid, RunningAnimationsForEntities[guid]);
else
{
Console.WriteLine("Already has the same entity that has been paused!");
}
//then remove the animation from running animation
RunningAnimationsForEntities.Remove(guid);
}
else
{
Console.WriteLine("No animation regarding this avatar playing yet!");
this.isPaused = false;
this.isPausedEntity = "";
}
}
}
public void StopAnimation(string guid, string aniName)
{
this.isStoppedEntity = guid;
//if it is stopped, send the first frame and break
Entity entity = World.Instance.FindEntity(guid);
string firstFrame = null;
if (this.isPausedEntity.Equals(guid))
{
//if it is paused, then we need to take the first frame from paused entity
firstFrame = this.PausedAnimationsForEntities[guid].bvhAnimationString[0];
}
else
{
//if it is not paused
lock (RunningAnimationsForEntities)
{
if (RunningAnimationsForEntities.ContainsKey(guid))
{
firstFrame = RunningAnimationsForEntities[guid].bvhAnimationString[0];
RunningAnimationsForEntities.Remove(guid);
}
else
return; //click more than once stop
}
}
//send the first frame
int firstFrameNum = 1;
string sendFirstString = firstFrameNum.ToString() + firstFrame;
entity["BVHAnimation"]["bvhframe"].Suggest(sendFirstString);
//clear the action info (already in client side)
//clear the pause information
if (this.isPausedEntity.Equals(guid))
{
PausedAnimationsForEntities.Remove(guid);
this.isPaused = false;
this.isPausedEntity = "";
PausedFrameForEntities.Remove(guid);
}
}
//entity name->List of frames, because we can only playback one animation once a time
internal Dictionary<string, AnimationInfo> RunningAnimationsForEntities =
new Dictionary<string, AnimationInfo>();
internal Dictionary<string, AnimationInfo> PausedAnimationsForEntities =
new Dictionary<string, AnimationInfo>();
internal Dictionary<string, int> PausedFrameForEntities = new Dictionary<string, int>();
private int loopCounter;
BVHAnimationPluginInitializer animationPlugin;
}
}
| kufischer/DyVisual | TRW/FiVES_BVH_Ext/Plugins/BVHAnimation/BVHAnimationManager.cs | C# | lgpl-3.0 | 10,124 |
/*******************************************************************************
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
/**
*/
package com.jaspersoft.studio.editor.jrexpressions.javaJRExpression;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>JR Resource Bundle Key Obj</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link com.jaspersoft.studio.editor.jrexpressions.javaJRExpression.JRResourceBundleKeyObj#getBracedIdentifier <em>Braced Identifier</em>}</li>
* </ul>
* </p>
*
* @see com.jaspersoft.studio.editor.jrexpressions.javaJRExpression.JavaJRExpressionPackage#getJRResourceBundleKeyObj()
* @model
* @generated
*/
public interface JRResourceBundleKeyObj extends JasperReportsExpression
{
/**
* Returns the value of the '<em><b>Braced Identifier</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Braced Identifier</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Braced Identifier</em>' attribute.
* @see #setBracedIdentifier(String)
* @see com.jaspersoft.studio.editor.jrexpressions.javaJRExpression.JavaJRExpressionPackage#getJRResourceBundleKeyObj_BracedIdentifier()
* @model
* @generated
*/
String getBracedIdentifier();
/**
* Sets the value of the '{@link com.jaspersoft.studio.editor.jrexpressions.javaJRExpression.JRResourceBundleKeyObj#getBracedIdentifier <em>Braced Identifier</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Braced Identifier</em>' attribute.
* @see #getBracedIdentifier()
* @generated
*/
void setBracedIdentifier(String value);
} // JRResourceBundleKeyObj
| OpenSoftwareSolutions/PDFReporter-Studio | com.jaspersoft.studio.editor.jrexpressions/src-gen/com/jaspersoft/studio/editor/jrexpressions/javaJRExpression/JRResourceBundleKeyObj.java | Java | lgpl-3.0 | 2,341 |
/*
* Sonar PL/SQL Plugin (Community)
* Copyright (C) 2015-2017 Felipe Zorzo
* mailto:felipebzorzo AT gmail DOT com
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.plsqlopen.api.expressions;
import static org.sonar.sslr.tests.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar;
import org.sonar.plugins.plsqlopen.api.RuleTest;
public class CharacterExpressionTest extends RuleTest {
@Before
public void init() {
setRootRule(PlSqlGrammar.EXPRESSION);
}
@Test
public void matchesSimpleConcatenation() {
assertThat(p).matches("'a'||'b'");
}
@Test
public void matchesMultipleConcatenation() {
assertThat(p).matches("'a'||'b'||'c'");
}
@Test
public void matchesVariableConcatenation() {
assertThat(p).matches("var||var");
}
@Test
public void matchesFunctionCallConcatenation() {
assertThat(p).matches("func(var)||func(var)");
}
@Test
public void matchesHostVariableConcatenation() {
assertThat(p).matches(":var||:var");
}
@Test
public void matchesIndicatorVariableConcatenation() {
assertThat(p).matches(":var:indicator||:var:indicator");
}
@Test
public void matchesReplace() {
assertThat(p).matches("replace(var, 'x', 'y')");
}
}
| nmorais/sonar-plsql | plsql-frontend/src/test/java/org/sonar/plugins/plsqlopen/api/expressions/CharacterExpressionTest.java | Java | lgpl-3.0 | 2,129 |
# xampl-pp : XML pull parser
# Copyright (C) 2002-2009 Bob Hutchison
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# #Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
require "Lapidary/TestCase"
require "xampl-pp"
class XppTestInput < Xampl_PP
def input
@input
end
def inputBuffer
@inputBuffer
end
def doSkipWhitespace
skipWhitespace
end
def doRead
read
end
def doExpect(c)
expect(c)
end
def doPeekAt0
peekAt0
end
def doPeekAt1
peekAt1
end
#def peek
#@peek
#end
end
class TC_Input < Lapidary::TestCase
def setup
@xpp = XppTestInput.new
end
#def tearDown
#end
def testInitialStateWithStringSource
@xpp.input = "hello"
assert @xpp.input == nil
assert @xpp.inputBuffer == "hello"
assert @xpp.column == 0
assert @xpp.startDocument?
assert @xpp.line == 1
assert @xpp.column == 0
assert @xpp.elementName.length == 0
assert @xpp.name == nil
assert @xpp.namespace == nil
assert @xpp.prefix == nil
assert @xpp.attributeName.length == 0
assert @xpp.attributeNamespace.length == 0
assert @xpp.attributePrefix.length == 0
assert @xpp.attributeValue.length == 0
end
def testInitialStateWithIOSource
@xpp.input = STDIN
assert @xpp.input == STDIN
assert @xpp.inputBuffer == nil
assert @xpp.column == 0
assert @xpp.startDocument?
assert @xpp.line == 0
assert @xpp.column == 0
assert @xpp.elementName.length == 0
assert @xpp.name == nil
assert @xpp.namespace == nil
assert @xpp.prefix == nil
assert @xpp.attributeName.length == 0
assert @xpp.attributeNamespace.length == 0
assert @xpp.attributePrefix.length == 0
assert @xpp.attributeValue.length == 0
end
def testPeekAtStringSource
@xpp.input = "1_2"
assert ?1 == @xpp.doPeekAt0
@xpp.doRead
assert ?2 == @xpp.doPeekAt1
@xpp.doRead
@xpp.doRead
assert nil == @xpp.doPeekAt0
end
def testPeekAtIOSource000
@xpp.input = File.new("TC_Input000.data")
assert ?1 == @xpp.doPeekAt0
@xpp.doRead
assert ?2 == @xpp.doPeekAt1
@xpp.doRead
@xpp.doRead
assert nil == @xpp.doPeekAt1 # have to get by the end of line
end
def testReadStringSource
@xpp.input = "12345"
assert ?1 == @xpp.doRead
assert 1 == @xpp.column
assert ?2 == @xpp.doRead
assert 2 == @xpp.column
assert ?3 == @xpp.doRead
assert 3 == @xpp.column
assert ?4 == @xpp.doRead
assert 4 == @xpp.column
assert ?5 == @xpp.doRead
assert 5 == @xpp.column
assert nil == @xpp.doRead
assert 0 == @xpp.column
assert 2 == @xpp.line
assert 0 == @xpp.elementName.length
end
def testReadIOSource
@xpp.input = File.new("TC_Input001.data")
assert ?1 == @xpp.doRead
assert 1 == @xpp.column
assert ?_ == @xpp.doRead
assert 2 == @xpp.column
assert ?2 == @xpp.doRead
assert 3 == @xpp.column
assert ?_ == @xpp.doRead
assert 4 == @xpp.column
assert ?_ == @xpp.doRead
assert 5 == @xpp.column
assert ?3 == @xpp.doRead
assert 6 == @xpp.column
assert ?_ == @xpp.doRead
assert 7 == @xpp.column
assert ?_ == @xpp.doRead
assert 8 == @xpp.column
assert ?_ == @xpp.doRead
assert 9 == @xpp.column
assert ?4 == @xpp.doRead
assert 10 == @xpp.column
assert ?_ == @xpp.doRead
assert 11 == @xpp.column
assert ?_ == @xpp.doRead
assert 12 == @xpp.column
assert ?_ == @xpp.doRead
assert 13 == @xpp.column
assert ?_ == @xpp.doRead
assert 14 == @xpp.column
assert ?5 == @xpp.doRead
assert 15 == @xpp.column
assert 1 == @xpp.line
assert ?\n == @xpp.doRead
assert 16 == @xpp.column
assert 1 == @xpp.line
assert nil == @xpp.doRead
assert 0 == @xpp.column
assert 0 == @xpp.elementName.length
end
def testMulipleInputRead000
# read the input until complete
for i in 1..3 do
@xpp.input = "12345"
s = ""
c = @xpp.doRead
while nil != c do
s = s << c
c = @xpp.doRead
end
assert "12345" == s
end
end
def testMulipleInputRead
# read part of the input only
for i in 1..3 do
@xpp.input = "12345"
s = ""
s = s << @xpp.doRead
s = s << @xpp.doRead
s = s << @xpp.doRead
assert "123" == s
end
end
def testExpectRead
@xpp.input = "12345"
assertNothingThrown { @xpp.doExpect(?1) }
assertRaises( RuntimeError ) { @xpp.doExpect(?1) }
end
def testSkipWhitespace
@xpp.input = "12345"
@xpp.doSkipWhitespace
assertNothingThrown { @xpp.doExpect(?1) }
@xpp.input = " 12345"
@xpp.doSkipWhitespace
assertNothingThrown { @xpp.doExpect(?1) }
@xpp.input = " \n \r\n 12345"
@xpp.doSkipWhitespace
assertNothingThrown { @xpp.doExpect(?1) }
@xpp.input = " \00012345"
@xpp.doSkipWhitespace
assertNothingThrown { @xpp.doExpect(0) }
end
end
| hutch/xamplr-pp | lapidary-tests/TC_Input.rb | Ruby | lgpl-3.0 | 5,264 |
// (c) 2013 Stephan Hohe
#if !defined(SQXX_STATEMENT_HPP_INCLUDED)
#define SQXX_STATEMENT_HPP_INCLUDED
#include "datatypes.hpp"
#include "connection.hpp"
#include <map>
// struct from <sqlite3.h>
struct sqlite3_stmt;
namespace sqxx {
class connection;
class parameter;
class column;
/**
* A sql statement
*
* Includes:
*
* - Binding of parameters for prepared statements
* - Accessing of result rows after executing the statement
*
* Wraps the C API struct `sqlite3_stmt` and associated functions.
*
*/
class statement {
private:
sqlite3_stmt *handle;
public:
connection &conn;
protected:
bool completed;
public:
/**
* Constructs a statement object from a connection object and a C API
* statement handle.
*
* Usually not called directly, use `connection::prepare()` instead.
*
* @conn_arg The connection object associated with the statement. A reference
* is stored and the connection object must stay alive until the constructed
* `statement` is destroyed.
*
* @handle_arg A C API statement handle. The constructed `statement` takes
* ownership of the C API handle and will close it on destruction.
*/
statement(connection &conn_arg, sqlite3_stmt *handle_arg);
/*
* Destroys the object, closing the managed C API handle, if necessary.
*/
~statement();
/** Copy construction is disabled */
statement(const statement &) = delete;
/** Copy assignment is disabled */
statement& operator=(const statement&) = delete;
/** Move construction is enabled */
statement(statement &&) = default;
/** Move assignment is enabled */
statement& operator=(statement&&) = default;
/**
* Get count of parameters in prepared statement.
*
* Wraps [`sqlite3_bind_parameter_count()`](http://www.sqlite.org/c3ref/bind_parameter_count.html).
*/
int param_count() const;
/**
* Get index of a named parameter.
*
* Usually only used internally.
*
* To bind a value to a named it is unnecessary to look up its
* index first, the name can be used directly with `bind(name, value)`.
*
* When the same parameter is bound many times for many queries it
* might be useful as a performance optimization to look the name up
* only once, but in this case usually a `parameter` object obtained
* by `statement::param(name)` will be used.
*
* Wraps [`sqlite3_bind_parameter_index()`](http://www.sqlite.org/c3ref/bind_parameter_index.html).
*/
int param_index(const char *name) const;
/** Like <statement::param_index(const char*)> */
int param_index(const std::string &name) const;
/**
* Get a parameter object, by index or name.
*
* Most commonly no parameter objects are created but parameters are bound directly
* with `statement::bind()`.
*
* An explicit parameter object can be useful if you need to bind the same
* parameter for many, many queries and want to avoid the (small) performance
* cost of repeated name lookups. Then you could replace repeated
* `stmt.bind("paramname", value);` by a single `auto p = stmt.param("paramname")`,
* followed by repeated `p.bind(value)`.
*
* The same performance can also be achieved without `parameter` objects by using
* numeric parameter indexes instead of names.
*/
parameter param(int idx);
parameter param(const char *name);
parameter param(const std::string &name);
/**
* Bind parameter values in prepared statements
*
* Parameters values of types `int`, `int64_t`, `double`, `const char*`,
* std::string` and `sqxx:blob` are supported. For each supported type an
* appropriate specialization of `bind<>()` is provided, calling the
* underlying C API function.
*
* Using templates allows the user to specify the desired type as
* `bind<type>(idx, value)`. This can be used to easily disambiguate cases
* where the compiler can't automatically deduce the correct type/overload.
*
* The first parameter of each of these functions is an index or a name
* of the parameter, the second parameter the value that should be bound.
* Parameter indexes start at zero.
*
* bind(0, 123);
* bind("paramname", 345):
*
* For string and blob parameters an optional third parameter is
* available, that specifies if sqlite should make an internal copy of
* the passed value. If the parameter is `false` and no copy is created, the
* caller has to make sure that the passed value stays alive and isn't
* destroyed until the query is completed. Default is to create copies
* of the passed parameters.
*
* bind("param1", std::string("temporary"), true);
* bind("param2", "persistent", false);
*
* If the passed value isn't exactly one supported by sqlite3, overload
* resolution can be ambiguous, which leads to compiler errors. In this
* case manually specify the desired parameter type:
*
* bind<int64_t>("param3", 123U);
*
* When `bind` is called without a value, the parameter is set to `NULL`:
*
* bind("param4");
*
* A `NULL` is bound as well when a passed `const char*` is null, or a
* `nullptr` is passed directly:
*
* const char *str = nullptr;
* bind("param6", str);
* bind("param7", nullptr);
*
*/
/**
* Set a parameter to NULL.
*
* Wraps [`sqlite3_bind_null()`](http://www.sqlite.org/c3ref/bind_blob.html).
*/
void bind(int idx);
void bind(const char *name) { bind(param_index(name)); }
void bind(const std::string &name) { bind(name.c_str()); }
/**
* Set a parameter to a `int`, `int64_t` or `double` value.
*
* Wraps [`sqlite3_bind_int()`](http://www.sqlite.org/c3ref/bind_blob.html),
* [`sqlite3_bind_int64()`](http://www.sqlite.org/c3ref/bind_blob.html).
* [`sqlite3_bind_double()`](http://www.sqlite.org/c3ref/bind_blob.html).
*/
template<typename T>
if_selected_type<T, void, int, int64_t, double>
bind(int idx, T value);
template<typename T>
if_selected_type<T, void, int, int64_t, double>
bind(const char *name, T value) { bind<T>(param_index(name), value); }
template<typename T>
if_selected_type<T, void, int, int64_t, double>
bind(const std::string &name, T value) { bind<T>(name.c_str(), value); }
/**
* Set a parameter to a `const char*` value.
*
* Wraps [`sqlite3_bind_text()`](http://www.sqlite.org/c3ref/bind_blob.html),
*
* For sqlite3 >= v3.8.7, uses 64 bit interfaces
* [`sqlite3_result_text64()`](http://www.sqlite.org/c3ref/result_blob.html),
*/
template<typename T>
if_selected_type<T, void, const char*>
bind(int idx, T value, bool copy=true);
template<typename T>
if_selected_type<T, void, const char*>
bind(const char *name, T value, bool copy=true) { bind<T>(param_index(name), value, copy); }
template<typename T>
if_selected_type<T, void, const char*>
bind(const std::string &name, T value, bool copy=true) { bind<T>(name.c_str(), value, copy); }
/**
* Set a parameter to a `std::string` or `blob` value.
*
* Wraps [`sqlite3_bind_text()`](http://www.sqlite.org/c3ref/bind_blob.html),
* Wraps [`sqlite3_bind_blob()`](http://www.sqlite.org/c3ref/bind_blob.html),
* Wraps [`sqlite3_bind_zeroblob()`](http://www.sqlite.org/c3ref/bind_blob.html),
*
* For sqlite3 >= v3.8.7, uses 64 bit interfaces
* Wraps [`sqlite3_bind_blob64()`](http://www.sqlite.org/c3ref/bind_blob.html),
*
* For sqlite3 >= v3.8.11, uses 64 bit interface
* Wraps [`sqlite3_bind_zeroblob64()`](http://www.sqlite.org/c3ref/bind_blob.html),
*/
template<typename T>
if_selected_type<T, void, std::string, blob>
bind(int idx, const T &value, bool copy=true);
template<typename T>
if_selected_type<T, void, std::string, blob>
bind(const char *name, const T &value, bool copy=true) { bind<T>(param_index(name), value, copy); }
template<typename T>
if_selected_type<T, void, std::string, blob>
bind(const std::string &name, const T &value, bool copy=true) { bind<T>(name.c_str(), value, copy); }
/**
* Reset all bindings on a prepared statement.
*
* Wraps [`sqlite3_clear_bindings()`](http://www.sqlite.org/c3ref/clear_bindings.html)
*/
void clear_bindings();
// Result columns
/**
* Number of columns in a result set.
*
* Wraps [`sqlite3_column_count()`](http://www.sqlite.org/c3ref/column_count.html)
*/
int col_count() const;
private:
// This is just a cache and doesn't change the object state.
// It's ok to create/update the cache on const objects, so we
// make it `mutable`.
mutable bool col_index_table_built = false;
mutable std::map<std::string, int> col_index_table;
public:
/**
* Return the index of a column with name `name`.
*
* If there are multiple columns with the same name, the index
* of one of them is returned.
*
* The first call to this function builds a lookup table that
* is used to translate names to indexes.
*
* Uses a lookup table built from [`sqlite3_column_name()`](http://www.sqlite.org/c3ref/column_name.html) calls
*/
int col_index(const char *name) const;
int col_index(const std::string &name) const;
/**
* Get a column object.
*
* Usually a column object is not necessary, result data can be accessed
* directly using `statement::val<type>(columnindex)`.
*
* A `column` object can be useful to access additional properties of a result
* column, like its declared type and name.
*/
///*
// * When the same columns are accessed by name in a large numbers of column rows,
// * using a column object might slightly improve performance, since name lookup
// * is only done once. Many calls to `stmt.val<type>("colname")` would be
// * replaced by a single call `auto c = stmt.col("colname");` and many calls to
// * `c.val<type>()`.
// *
// * The same performance can also be achieved without `column` objects by using
// * numeric column indexes instead of names.
// */
column col(int idx) const;
column col(const char *name) const;
column col(const std::string &name) const;
/**
* Access the value of a column in the current result row.
*
* Supported types are `int`, `int64_t`, `double`, `const char*`,
* `std::string` and `sqxx::blob`.
*
* When receiving values as `const char*` or `sqxx::blob`, the returned
* data will refer to storage internal to sqlite and subsequent calls
* to `val()` can invalidate the returned data. For more details see the
* [documentation of the corresponding sqlite C API functions](http://www.sqlite.org/c3ref/column_blob.html)
*
* When receiving a value as `std::string`, the data is copied into the
* returned `std::string` object.
*
* TODO: Add a `copy` flag that can be specified to copy values?
*
* Wraps [`sqlite3_column_*()`](http://www.sqlite.org/c3ref/column_blob.html)
*/
template<typename T>
if_sqxx_db_type<T, T> val(int idx) const;
template<typename T>
if_sqxx_db_type<T, T> val(const char *name) const;
template<typename T>
if_sqxx_db_type<T, T> val(const std::string &name) const;
// Statement execution
/**
* Executes a prepared statement or advances to the next row of results.
*
* This is a low-level function, usually it is preferable to execute a
* statement with `run()` and then iterate over the result with `next_row()`
* or use the iterator interface:
*
* stmt.prepare("SELECT name from persons where id = 123;");
* stmt.run();
* for (auto&& : stmt) {
* std::cout << stmt.val<const char*>(0);
* }
*
* Wraps [`sqlite3_step()`](http://www.sqlite.org/c3ref/step.html)
*/
void step();
/** Execute a statement */
void run();
/** Alias for `run()` as an analog to `connection::query()` */
void query();
/** Advance to next result row */
void next_row();
/**
* Resets a statement so that it can be executed again.
*
* Any bound parameters are not automatically unbound by this. Use
* `statement::clear_bindings()` for that.
*
* Wraps ['sqlite3_reset()'](http://www.sqlite.org/c3ref/reset.html).
*/
void reset();
// Result row access
/** Check if all result rows have been processed */
bool done() const { return completed; }
operator bool() const { return !completed; }
class row_iterator : public std::iterator<std::input_iterator_tag, size_t> {
private:
statement *s;
size_t rowidx;
public:
explicit row_iterator(statement *a_s = nullptr);
private:
void check_complete();
public:
size_t operator*() const { return rowidx; }
row_iterator& operator++();
// Not reasonably implementable with correct return type:
void operator++(int) { ++*this; }
bool operator==(const row_iterator &other) const { return (s == other.s); }
bool operator!=(const row_iterator &other) const { return !(*this == other); }
};
/**
* Iterate over the result of query
*/
row_iterator begin() { return row_iterator(this); }
row_iterator end() { return row_iterator(); }
/**
* Receive statement SQL
*
* Wraps [`sqlite3_sql()`](http://www.sqlite.org/c3ref/sql.html)
**/
const char* sql();
/**
* Wraps [`sqlite3_stmt_status()`](http://www.sqlite.org/c3ref/stmt_status.html)
*/
int status(int op, bool reset=false);
int status_fullscan_step(bool reset=false);
int status_sort(bool reset=false);
int status_autoindex(bool reset=false);
int status_vm_step(bool reset=false);
/**
* Determines if the prepared statement writes to the database.
*
* Wraps [`sqlite3_stmt_readonly()`](http://www.sqlite.org/c3ref/stmt_readonly.html)
*/
bool readonly() const;
/**
* Determine if the prepared statement has been reset
*
* Wraps [`sqlite3_stmt_busy()`](http://www.sqlite.org/c3ref/stmt_busy.html)
*/
bool busy() const;
/** Raw access to the underlying `sqlite3_stmt*` handle */
sqlite3_stmt* raw() const { return handle; }
};
} // namespace sqxx
#include "statement.impl.hpp"
#endif // SQXX_STATEMENT_HPP_INCLUDED
| sth/sqxx | statement.hpp | C++ | lgpl-3.0 | 13,733 |
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Install;
use PDO;
use PDOException;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
use Thelia\Config\DatabaseConfiguration;
use Thelia\Config\DefinePropel;
use Thelia\Core\Thelia;
use Thelia\Install\Exception\UpdateException;
use Thelia\Install\Exception\UpToDateException;
use Thelia\Log\Tlog;
use Thelia\Model\ConfigQuery;
/**
* Class Update
* @package Thelia\Install
* @author Manuel Raynaud <manu@thelia.net>
*/
class Update
{
const SQL_DIR = 'update/sql/';
const PHP_DIR = 'update/php/';
protected static $version = array(
'0' => '2.0.0-beta1',
'1' => '2.0.0-beta2',
'2' => '2.0.0-beta3',
'3' => '2.0.0-beta4',
'4' => '2.0.0-RC1',
'5' => '2.0.0',
'6' => '2.0.1',
'7' => '2.0.2',
'8' => '2.0.3-beta',
'9' => '2.0.3-beta2',
'10' => '2.0.3',
'11' => '2.0.4',
'12' => '2.0.5',
'13' => '2.0.6',
'14' => '2.0.7',
'15' => '2.1.0-alpha1',
'16' => '2.1.0-alpha2',
'17' => '2.1.0-beta1',
'18' => '2.1.0-beta2',
'19' => '2.1.0',
'20' => '2.1.1',
'21' => '2.1.2',
'22' => '2.1.3',
'23' => '2.2.0-alpha1',
);
/** @var bool */
protected $usePropel = null;
/** @var null|Tlog */
protected $logger = null;
/** @var array log messages */
protected $logs = [];
/** @var array */
protected $updatedVersions = [];
/** @var PDO */
protected $connection = null;
/** @var string|null */
protected $backupFile = null;
/** @var string */
protected $backupDir = 'local/backup/';
public function __construct($usePropel = true)
{
$this->usePropel = $usePropel;
if ($this->usePropel) {
$this->logger = Tlog::getInstance();
$this->logger->setLevel(Tlog::DEBUG);
} else {
$this->logs = [];
}
$dbConfig = null;
try {
$dbConfig = $this->getDatabaseConfig();
} catch (ParseException $ex) {
throw new UpdateException("database.yml is not a valid file : " . $ex->getMessage());
}
try {
$this->connection = new \PDO(
$dbConfig['dsn'],
$dbConfig['user'],
$dbConfig['password']
);
} catch (\PDOException $ex) {
throw new UpdateException('Wrong connection information' . $ex->getMessage());
}
}
/**
* retrieve the database configuration
*
* @return array containing the database
*/
protected function getDatabaseConfig()
{
$configPath = THELIA_CONF_DIR . "/database.yml";
if (!file_exists($configPath)) {
throw new UpdateException("Thelia is not installed yet");
}
$definePropel = new DefinePropel(
new DatabaseConfiguration(),
Yaml::parse($configPath),
$this->getEnvParameters()
);
return $definePropel->getConfig();
}
/**
* Gets the environment parameters.
*
* Only the parameters starting with "SYMFONY__" are considered.
*
* @return array An array of parameters
*/
protected function getEnvParameters()
{
$parameters = array();
foreach ($_SERVER as $key => $value) {
if (0 === strpos($key, 'SYMFONY__')) {
$parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
}
}
return $parameters;
}
public function isLatestVersion($version = null)
{
if (null === $version) {
$version = $this->getCurrentVersion();
}
$lastEntry = end(self::$version);
return $lastEntry == $version;
}
public function process()
{
$this->updatedVersions = array();
$currentVersion = $this->getCurrentVersion();
$this->log('debug', "start update process");
if (true === $this->isLatestVersion($currentVersion)) {
$this->log('debug', "You already have the latest version. No update available");
throw new UpToDateException('You already have the latest version. No update available');
}
$index = array_search($currentVersion, self::$version);
$this->connection->beginTransaction();
$database = new Database($this->connection);
$version = null;
try {
$size = count(self::$version);
for ($i = ++$index; $i < $size; $i++) {
$version = self::$version[$i];
$this->updateToVersion($version, $database);
$this->updatedVersions[] = $version;
}
$this->connection->commit();
$this->log('debug', 'update successfully');
} catch (\Exception $e) {
$this->connection->rollBack();
$this->log('error', sprintf('error during update process with message : %s', $e->getMessage()));
$ex = new UpdateException($e->getMessage(), $e->getCode(), $e->getPrevious());
$ex->setVersion($version);
throw $ex;
}
$this->log('debug', 'end of update processing');
return $this->updatedVersions;
}
/**
* Backup current DB to file local/backup/update.sql
* @return bool if it succeeds, false otherwise
* @throws \Exception
*/
public function backupDb()
{
$database = new Database($this->connection);
$this->backupFile = THELIA_ROOT . $this->backupDir . 'update.sql';
$backupDir = THELIA_ROOT . $this->backupDir;
$fs = new Filesystem();
try {
$this->log('debug', sprintf('Backup database to file : %s', $this->backupFile));
// test if backup dir exists
if (!$fs->exists($backupDir)) {
$fs->mkdir($backupDir);
}
if (!is_writable($backupDir)) {
throw new \RuntimeException(sprintf('impossible to write in directory : %s', $backupDir));
}
// test if backup file already exists
if ($fs->exists($this->backupFile)) {
// remove file
$fs->remove($this->backupFile);
}
$database->backupDb($this->backupFile);
} catch (\Exception $ex) {
$this->log('error', sprintf('error during backup process with message : %s', $ex->getMessage()));
throw $ex;
}
}
/**
* Restores file local/backup/update.sql to current DB
*
* @return bool if it succeeds, false otherwise
*/
public function restoreDb()
{
$database = new Database($this->connection);
try {
$this->log('debug', sprintf('Restore database with file : %s', $this->backupFile));
if (!file_exists($this->backupFile)) {
return false;
}
$database->restoreDb($this->backupFile);
} catch (\Exception $ex) {
$this->log('error', sprintf('error during restore process with message : %s', $ex->getMessage()));
print $ex->getMessage();
return false;
}
return true;
}
/**
* @return null|string
*/
public function getBackupFile()
{
return $this->backupFile;
}
public function getLogs()
{
return $this->logs;
}
protected function log($level, $message)
{
if ($this->usePropel) {
switch ($level) {
case 'debug':
$this->logger->debug($message);
break;
case 'info':
$this->logger->info($message);
break;
case 'notice':
$this->logger->notice($message);
break;
case 'warning':
$this->logger->warning($message);
break;
case 'error':
$this->logger->error($message);
break;
case 'critical':
$this->logger->critical($message);
break;
}
} else {
$this->logs[] = [$level, $message];
}
}
protected function updateToVersion($version, Database $database)
{
// sql update
$filename = sprintf(
"%s%s%s",
THELIA_SETUP_DIRECTORY,
str_replace('/', DS, self::SQL_DIR),
$version . '.sql'
);
if (file_exists($filename)) {
$this->log('debug', sprintf('inserting file %s', $version . '.sql'));
$database->insertSql(null, [$filename]);
$this->log('debug', sprintf('end inserting file %s', $version . '.sql'));
}
// php update
$filename = sprintf(
"%s%s%s",
THELIA_SETUP_DIRECTORY,
str_replace('/', DS, self::PHP_DIR),
$version . '.php'
);
if (file_exists($filename)) {
$this->log('debug', sprintf('executing file %s', $version . '.php'));
include_once($filename);
$this->log('debug', sprintf('end executing file %s', $version . '.php'));
}
$this->setCurrentVersion($version);
}
public function getCurrentVersion()
{
$stmt = $this->connection->query("SELECT `value` FROM `config` WHERE name='thelia_version'");
return $stmt->fetchColumn();
}
public function setCurrentVersion($version)
{
$currentVersion = null;
if (null !== $this->connection) {
try {
$stmt = $this->connection->prepare('UPDATE config set value = ? where name = ?');
$stmt->execute([$version, 'thelia_version']);
} catch (PDOException $e) {
$this->log('error', sprintf('Error setting current version : %s', $e->getMessage()));
throw $e;
}
}
}
public function getLatestVersion()
{
return end(self::$version);
}
public function getVersions()
{
return self::$version;
}
/**
* @return array
*/
public function getUpdatedVersions()
{
return $this->updatedVersions;
}
/**
* @param array $updatedVersions
*/
public function setUpdatedVersions($updatedVersions)
{
$this->updatedVersions = $updatedVersions;
}
}
| gmichard/thelia | core/lib/Thelia/Install/Update.php | PHP | lgpl-3.0 | 11,553 |
/* Mesquite source code. Copyright 1997-2009 W. Maddison and D. Maddison.
Version 2.71, September 2009.
Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code.
The commenting leaves much to be desired. Please approach this source code with the spirit of helping out.
Perhaps with your help we can be more than a few, and make Mesquite better.
Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
Mesquite's web site is http://mesquiteproject.org
This source code and its compiled class files are free and modifiable under the terms of
GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html)
*/
package mesquite.lib;
import java.util.*;
import java.io.*;
import org.dom4j.*;
import org.dom4j.io.*;
public class XMLUtil {
/*.................................................................................................................*/
public static Element addFilledElement(Element containingElement, String name, String content) {
if (content == null || name == null)
return null;
Element element = DocumentHelper.createElement(name);
element.addText(content);
containingElement.add(element);
return element;
}
/*.................................................................................................................*/
public static Element addFilledElement(Element containingElement, String name, CDATA cdata) {
if (cdata == null || name == null)
return null;
Element element = DocumentHelper.createElement(name);
element.add(cdata);
containingElement.add(element);
return element;
}
public static String getTextFromElement(Element containingElement, String name){
Element e = containingElement.element(name);
if (e == null)
return null;
else return e.getText();
}
/*.................................................................................................................*/
public static String getDocumentAsXMLString(Document doc, boolean escapeText)
{
try {
String encoding = doc.getXMLEncoding();
if (encoding == null)
encoding = "UTF-8";
Writer osw = new StringWriter();
OutputFormat opf = new OutputFormat(" ", true, encoding);
XMLWriter writer = new XMLWriter(osw, opf);
writer.setEscapeText(escapeText);
writer.write(doc);
writer.close();
return osw.toString();
} catch (IOException e) {
MesquiteMessage.warnProgrammer("XML Document could not be returned as string.");
}
return null;
}
/*.................................................................................................................*/
public static String getElementAsXMLString(Element doc, String encoding, boolean escapeText)
{
try {
Writer osw = new StringWriter();
OutputFormat opf = new OutputFormat(" ", true, encoding);
XMLWriter writer = new XMLWriter(osw, opf);
writer.setEscapeText(escapeText);
writer.write(doc);
writer.close();
return osw.toString();
} catch (IOException e) {
MesquiteMessage.warnProgrammer("XML Document could not be returned as string.");
}
return null;
}
/*.................................................................................................................*/
public static String getDocumentAsXMLString(Document doc) {
return getDocumentAsXMLString(doc,true);
}
/*.................................................................................................................*/
public static String getDocumentAsXMLString2(Document doc)
{
try {
String encoding = doc.getXMLEncoding();
//if (encoding == null)
// encoding = "UTF-8";
Writer osw = new StringWriter();
OutputFormat opf = new OutputFormat(" ", true);
XMLWriter writer = new XMLWriter(osw, opf);
writer.write(doc);
writer.close();
return osw.toString();
} catch (IOException e) {
MesquiteMessage.warnProgrammer("XML Document could not be returned as string.");
}
return null;
}
/*.................................................................................................................*/
public static Document getDocumentFromString(String rootElementName, String contents) {
Document doc = null;
try {
doc = DocumentHelper.parseText(contents);
} catch (Exception e) {
return null;
}
if (doc == null || doc.getRootElement() == null) {
return null;
} else if (!StringUtil.blank(rootElementName) && !doc.getRootElement().getName().equals(rootElementName)) {
return null;
}
return doc;
}
/*.................................................................................................................*/
public static Document getDocumentFromString(String contents) {
return getDocumentFromString("",contents);
}
/*.................................................................................................................*/
public static Element getRootXMLElementFromString(String rootElementName, String contents) {
Document doc = getDocumentFromString(rootElementName, contents);
if (doc==null)
return null;
return doc.getRootElement();
}
/*.................................................................................................................*/
public static Element getRootXMLElementFromString(String contents) {
return getRootXMLElementFromString("",contents);
}
/*.................................................................................................................*/
public static Element getRootXMLElementFromURL(String rootElementName, String url) {
SAXReader saxReader = new SAXReader();
Document doc = null;
try {
doc = saxReader.read(url);
} catch (Exception e) {
return null;
}
if (doc == null || doc.getRootElement() == null) {
return null;
} else if (!StringUtil.blank(rootElementName) && !doc.getRootElement().getName().equals(rootElementName)) {
return null;
}
Element root = doc.getRootElement();
return root;
}
/*.................................................................................................................*/
public static Element getRootXMLElementFromURL(String url) {
return getRootXMLElementFromURL("",url);
}
/*.................................................................................................................*/
public static void readXMLPreferences(MesquiteModule module, XMLPreferencesProcessor xmlPrefProcessor, String contents) {
Element root = getRootXMLElementFromString("mesquite",contents);
if (root==null)
return;
Element element = root.element(module.getXMLModuleName());
if (element != null) {
Element versionElement = element.element("version");
if (versionElement == null)
return ;
else {
int version = MesquiteInteger.fromString(element.elementText("version"));
boolean acceptableVersion = (module.getXMLPrefsVersion()==version || !module.xmlPrefsVersionMustMatch());
if (acceptableVersion)
processPreferencesFromXML(xmlPrefProcessor, element);
else
return;
}
}
}
/*.................................................................................................................*/
public static void processPreferencesFromXML ( XMLPreferencesProcessor xmlPrefProcessor, Element element) {
List prefElement = element.elements();
for (Iterator iter = prefElement.iterator(); iter.hasNext();) { // this is going through all of the notices
Element messageElement = (Element) iter.next();
xmlPrefProcessor.processSingleXMLPreference(messageElement.getName(), messageElement.getText());
}
}
}
| MesquiteProject/MesquiteArchive | releases/Mesquite2.71/Mesquite Project/Source/mesquite/lib/XMLUtil.java | Java | lgpl-3.0 | 7,611 |
/**
* Copyright (c) 2012 CNRS
* Author: Olivier Roussel
*
* This file is part of the MPD-dev package.
* MPD-dev 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
* 3 of the License, or (at your option) any later version.
*
* MPD-dev 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 Lesser Public License for more details. You should have
* received a copy of the GNU Lesser General Public License along with
* MPD-dev. If not, see
* <http://www.gnu.org/licenses/>.
**/
#include "bullet_debug_drawer.h"
#include "gui/mpd_viewer.h"
#include "constants.h"
#include "bullet_utils.h"
BulletDebugDrawer::BulletDebugDrawer(MPDViewer* i_viewer):
viewer_(i_viewer),
debug_mode_(0)
{}
BulletDebugDrawer::~BulletDebugDrawer()
{}
void BulletDebugDrawer::clearDraws()
{
viewer_->clearPhysicsObjects();
}
void BulletDebugDrawer::drawLine(const btVector3& i_from, const btVector3& i_to, const btVector3& i_color)
{
viewer_->addPhysicsLine(Y_2_Z_Matrix * toEVector3(i_from),Y_2_Z_Matrix * toEVector3(i_to), toEVector3(i_color));
}
void BulletDebugDrawer::draw3dText(const btVector3& i_pos, const char* i_text)
{
viewer_->addPhysicsText(Y_2_Z_Matrix * toEVector3(i_pos), std::string(i_text));
}
void BulletDebugDrawer::drawContactPoint(const btVector3& ,const btVector3 &,btScalar,int,const btVector3 &)
{
// TODO
}
void BulletDebugDrawer::reportErrorWarning(const char* i_text)
{
std::cout << "[WARNING] BulletDebugDrawer:: " << i_text << std::endl;
}
void BulletDebugDrawer::setDebugMode(int i_mode)
{
debug_mode_ = i_mode;
}
int BulletDebugDrawer::getDebugMode() const
{
return debug_mode_;
}
boost::mutex& BulletDebugDrawer::getPhysicsObjectsMutex()
{
return viewer_->getPhysicsObjectsMutex();
}
| olivier-roussel/mpd-dev | src/bullet_debug_drawer.cc | C++ | lgpl-3.0 | 1,983 |
# Note: This controller is called "MercuryUpdateController" because "MercuryController"
# is an internal controller of Mercury. DO NOT rename this class to MercuryController!
class MercuryUpdateController < ApplicationController
before_filter :ensure_is_admin
# Update content with WYSIWYG editor Mercury
def update
param_hash = params[:content].inject({}) do |memo, content_hash|
content_type, content_attributes = content_hash
memo[content_type] = content_attributes[:value]
memo
end
if @community_customization
if !@community_customization.update_attributes(param_hash)
flash[:error] = I18n.t("mercury.content_too_long")
end
else
@current_community.community_customizations.create(param_hash.merge({:locale => I18n.locale}))
end
render text: ""
end
end
| ziyoucaishi/marketplace | app/controllers/mercury_update_controller.rb | Ruby | lgpl-3.0 | 836 |
<?php
session_start();
/**
* PHPExcel
*
* Copyright (C) 2006 - 2013 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/PHPExcel/Classes/PHPExcel.php';
// open database
$dbfile = 'assets/saved/'.$_SESSION['filename'].$_SESSION['file_ext'];
$db = new SQLite3($dbfile);
$tabledata = $db->querySingle("SELECT matrix FROM nodes_version ORDER BY rowid DESC");
$tabledata = json_decode(str_replace('\"', '"', $tabledata));
$columndata = $db->query("SELECT code, title, desc FROM column");
$rowdata = $db->query("SELECT code, title, desc FROM row");
$nodedata = $db->query("SELECT code, title, desc FROM node");
$alphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Toni Haryanto")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Jadwal Khutbah");
/* Timetable Data */
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'JADWAL KHOTBAH JUM\'AH')
->setCellValue('A3', 'NO')
->setCellValue('B3', 'TGL/BLN/TH')
->setCellValue('C3', 'KODE KHOTIB / KODE MASJID');
$c = 2;
while($column = $columndata->fetchArray(SQLITE3_ASSOC)){
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($alphabet[$c].'4', $column['code']);
$c++;
}
$bataskolom = $c;
$i = 6;
$no = 1;
//print_r($tabledata);
foreach ($tabledata as $row) {
$date = $rowdata->fetchArray(SQLITE3_ASSOC);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$i, $no)
->setCellValue('B'.$i, $date['code']);
$c = 2;
foreach($row as $node){
if($c < $bataskolom)
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($alphabet[$c].$i, $node->code);
$c++;
}
$i++;
$no++;
}
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Data Table');
/* Column Data */
$objWorkSheet = $objPHPExcel->createSheet(1);
$objWorkSheet->setTitle('Data Masjid');
$objPHPExcel->setActiveSheetIndex(1)
->setCellValue('A1', 'DAFTAR MASJID')
->setCellValue('A3', 'KODE')
->setCellValue('B3', 'NAMA MASJID')
->setCellValue('C3', 'KETERANGAN');
$i = 4;
$columndata = $db->query("SELECT code, title, desc FROM column");
while($column = $columndata->fetchArray(SQLITE3_ASSOC)){
$objPHPExcel->setActiveSheetIndex(1)
->setCellValue('A'.$i, $column['code'])
->setCellValue('B'.$i, $column['title'])
->setCellValue('C'.$i, $column['desc']);
$i++;
}
/* Node Data */
$objWorkSheet = $objPHPExcel->createSheet(2);
$objWorkSheet->setTitle('Data Khotib');
$objPHPExcel->setActiveSheetIndex(2)
->setCellValue('A1', 'DAFTAR KHOTIB')
->setCellValue('A3', 'KODE')
->setCellValue('B3', 'NAMA KHOTIB')
->setCellValue('C3', 'KETERANGAN');
$i = 4;
while($node = $nodedata->fetchArray(SQLITE3_ASSOC)){
$objPHPExcel->setActiveSheetIndex(2)
->setCellValue('A'.$i, $node['code'])
->setCellValue('B'.$i, $node['title'])
->setCellValue('C'.$i, $node['desc']);
$i++;
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
$filename = 'data';
if(isset($_GET['filename']))
$filename = $_GET['filename'];
// Redirect output to a clientโs web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
$db->close();
exit;
| yllumi/khatibTimetable | app/export-data.php | PHP | lgpl-3.0 | 5,634 |
package pdem.lib.itext;
import java.io.FileOutputStream;
import java.util.Date;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class FirstPdf {
private static String FILE = "c:/temp/FirstPdf.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
public static void main(String[] args) {
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
addTitlePage(document);
addContent(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// iText allows to add metadata to the PDF which can be viewed in your Adobe
// Reader
// under File -> Properties
private static void addMetaData(Document document) {
document.addTitle("My first PDF");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Lars Vogel");
document.addCreator("Lars Vogel");
}
private static void addTitlePage(Document document)
throws DocumentException {
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
preface.add(new Paragraph("Title of the document", catFont));
addEmptyLine(preface, 1);
// Will create: Report generated by: _name, _date
preface.add(new Paragraph(
"Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
smallBold));
addEmptyLine(preface, 3);
preface.add(new Paragraph(
"This document describes something which is very important ",
smallBold));
addEmptyLine(preface, 8);
preface.add(new Paragraph(
"This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
redFont));
document.add(preface);
// Start a new page
document.newPage();
}
private static void addContent(Document document) throws DocumentException {
Anchor anchor = new Anchor("First Chapter", catFont);
anchor.setName("First Chapter");
// Second parameter is the number of the chapter
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
Paragraph subPara = new Paragraph("Subcategory 1", subFont);
Section subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Hello"));
subPara = new Paragraph("Subcategory 2", subFont);
subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Paragraph 1"));
subCatPart.add(new Paragraph("Paragraph 2"));
subCatPart.add(new Paragraph("Paragraph 3"));
// add a list
createList(subCatPart);
Paragraph paragraph = new Paragraph();
addEmptyLine(paragraph, 5);
subCatPart.add(paragraph);
// add a table
createTable(subCatPart);
// now add all this to the document
document.add(catPart);
// Next section
anchor = new Anchor("Second Chapter", catFont);
anchor.setName("Second Chapter");
// Second parameter is the number of the chapter
catPart = new Chapter(new Paragraph(anchor), 1);
subPara = new Paragraph("Subcategory", subFont);
subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("This is a very important message"));
// now add all this to the document
document.add(catPart);
}
private static void createTable(Section subCatPart)
throws BadElementException {
PdfPTable table = new PdfPTable(3);
// t.setBorderColor(BaseColor.GRAY);
// t.setPadding(4);
// t.setSpacing(4);
// t.setBorderWidth(1);
PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Table Header 2"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Table Header 3"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
table.addCell("1.0");
table.addCell("1.1");
table.addCell("1.2");
table.addCell("2.1");
table.addCell("2.2");
table.addCell("2.3");
subCatPart.add(table);
}
private static void createList(Section subCatPart) {
List list = new List(true, false, 10);
list.add(new ListItem("First point"));
list.add(new ListItem("Second point"));
list.add(new ListItem("Third point"));
subCatPart.add(list);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
} | pdemanget/examples | java/smallTests/src/main/java/pdem/lib/itext/FirstPdf.java | Java | lgpl-3.0 | 7,144 |
/*
* This file is part of the Voodoo Shader Framework.
*
* Copyright (c) 2010-2013 by Sean Sube
*
* The Voodoo Shader Framework 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 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to
* the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 US
*
* Support and more information may be found at
* http://www.voodooshader.com
* or by contacting the lead developer at
* peachykeen@voodooshader.com
*/
#pragma once
#include "VoodooVersion.hpp"
/**
* @addtogroup voodoo_module_ehhookmanager
* @{
* HookManager defs
*/
#define VOODOO_HOOKMANAGER_LIBID {0xCD, 0xCF, 0x87, 0xA6, 0x3C, 0x06, 0xE1, 0x11, 0xB2, 0x2E, 0x00, 0x50, 0x56, 0xC0, 0x00, 0x08}
#define VOODOO_HOOKMANAGER_AUTHOR VOODOO_GLOBAL_AUTHOR
#define VOODOO_HOOKMANAGER_NAME VSTR("Voodoo_EHHookManager")
#define VOODOO_HOOKMANAGER_PRETTYNAME VSTR("Voodoo Shader Hook Manager")
#define VOODOO_HOOKMANAGER_VERSION_MAJOR VOODOO_GLOBAL_VERSION_MAJOR
#define VOODOO_HOOKMANAGER_VERSION_MINOR VOODOO_GLOBAL_VERSION_MINOR
#define VOODOO_HOOKMANAGER_VERSION_PATCH VOODOO_GLOBAL_VERSION_PATCH
#define VOODOO_HOOKMANAGER_VERSION_BUILD VOODOO_GLOBAL_VERSION_BUILD
#define VOODOO_HOOKMANAGER_VERSION_ID VOODOO_GLOBAL_VERSION_ID
/**
* @}
*/ | ssube/VoodooShader | Framework/HookManager/HookManager_Version.hpp | C++ | lgpl-3.0 | 1,819 |
<?php
class blogContactsDeleteHandler extends waEventHandler
{
/**
* @param int[] $params Deleted contact_id
* @see waEventHandler::execute()
* @return void
*/
public function execute($params)
{
$contact_model = new waContactModel();
$contacts = $contact_model->getByField('id',$params,true);
$post_model = new blogPostModel();
$comment_model = new blogCommentModel();
foreach ($contacts as $contact) {
$data = array('contact_id'=>0,'contact_name'=>$contact['name']);
$post_model->updateByField('contact_id',$contact['id'],$data);
$data = array('contact_id'=>0,'name'=>$contact['name'],'auth_provider'=>null);
$comment_model->updateByField('contact_id',$contact['id'],$data);
}
}
} | shomeax/wa-shop-ppg | wa-apps/blog/lib/handlers/contacts.delete.handler.php | PHP | lgpl-3.0 | 834 |
/**
* DataCleaner (community edition)
* Copyright (C) 2014 Neopost - Customer Information Management
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.datacleaner.monitor.scheduling.widgets;
import org.datacleaner.monitor.scheduling.model.ExecutionLog;
import org.datacleaner.monitor.shared.model.TenantIdentifier;
import org.datacleaner.monitor.util.Urls;
import com.google.gwt.user.client.ui.Anchor;
/**
* An anchor to a result report.
*/
public class ResultAnchor extends Anchor {
private final TenantIdentifier _tenant;
public ResultAnchor(TenantIdentifier tenant) {
super();
addStyleName("ResultAnchor");
_tenant = tenant;
}
public void setResult(ExecutionLog executionLog) {
setResult(executionLog, null);
}
public void setResult(ExecutionLog executionLog, String text) {
final String resultId = executionLog.getResultId();
if (resultId == null || !executionLog.isResultPersisted()) {
setEnabled(false);
setText("");
} else {
final String resultFilename = resultId + ".analysis.result.dat";
final String url = Urls.createRelativeUrl("repository/" + _tenant.getId() + "/results/" + resultFilename);
setHref(url);
setTarget("_blank");
if (text == null) {
setText(resultId);
} else {
setText(text);
}
}
}
}
| anandswarupv/DataCleaner | monitor/widgets/src/main/java/org/datacleaner/monitor/scheduling/widgets/ResultAnchor.java | Java | lgpl-3.0 | 2,153 |
package ru.ppsrk.gwt.client;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
public abstract class LongPollingClient<T> {
private int failureDelay;
private LongPollingAsyncCallback asyncCallback = new LongPollingAsyncCallback();
public class LongPollingAsyncCallback implements AsyncCallback<T> {
@Override
public void onFailure(final Throwable caught) {
new Timer() {
@Override
public void run() {
start();
}
}.schedule(failureDelay);
failure(caught);
}
@Override
public void onSuccess(T result) {
try {
if (result != null) {
success(result);
} else {
nothing();
}
} finally {
start();
}
}
}
/**
* Create a new long polling client.
*
* @param failureDelay
* how many ms to wait if the long polling call was unsuccessful
* before restarting. Unsuccessful call means that an exception
* was returned, not just null because there's nothing to send.
* After receiving null the client restarts the polling
* immediately.
*/
public LongPollingClient(int failureDelay) {
this.failureDelay = failureDelay;
}
public void start() {
doRPC(asyncCallback);
}
/**
* Do your RPC call to the server-side and supply this callback.
*
* @param callback
* internal callback which calls your callback and restarts the
* long polling
*/
public abstract void doRPC(LongPollingAsyncCallback callback);
/**
* This is executed on successful retrieval of non-null data from the poll
*
* @param result
*/
public abstract void success(T result);
public void failure(Throwable caught) {
// do nothing by default
}
public void nothing() {
// do nothing when no updates came
}
}
| rkfg/gwtutil | src/main/java/ru/ppsrk/gwt/client/LongPollingClient.java | Java | lgpl-3.0 | 2,173 |
//
// Copyright (C) University College London, 2007-2012, all rights reserved.
//
// This file is part of HemeLB and is provided to you under the terms of
// the GNU LGPL. Please see LICENSE in the top level directory for full
// details.
//
#include "constants.h"
#include "geometry/VolumeTraverser.h"
namespace hemelb
{
namespace geometry
{
VolumeTraverser::VolumeTraverser() :
mCurrentLocation(0), mCurrentNumber(0)
{
}
VolumeTraverser::~VolumeTraverser()
{
}
util::Vector3D<site_t> VolumeTraverser::GetCurrentLocation()
{
return mCurrentLocation;
}
void VolumeTraverser::SetCurrentLocation(const util::Vector3D<site_t>& iLocation)
{
mCurrentLocation = iLocation;
mCurrentNumber = GetIndexFromLocation(iLocation);
}
site_t VolumeTraverser::GetCurrentIndex() const
{
return mCurrentNumber;
}
site_t VolumeTraverser::GetX()
{
return mCurrentLocation.x;
}
site_t VolumeTraverser::GetY()
{
return mCurrentLocation.y;
}
site_t VolumeTraverser::GetZ()
{
return mCurrentLocation.z;
}
site_t VolumeTraverser::GetIndexFromLocation(util::Vector3D<site_t> iLocation) const
{
return ( (iLocation.x * GetYCount() + iLocation.y) * GetZCount()) + iLocation.z;
}
bool VolumeTraverser::TraverseOne()
{
mCurrentNumber++;
mCurrentLocation.z++;
if (mCurrentLocation.z < GetZCount())
{
return true;
}
mCurrentLocation.z = 0;
mCurrentLocation.y++;
if (mCurrentLocation.y < GetYCount())
{
return true;
}
mCurrentLocation.y = 0;
mCurrentLocation.x++;
if (mCurrentLocation.x < GetXCount())
{
return true;
}
return false;
}
void VolumeTraverser::IncrementX()
{
mCurrentLocation.x++;
mCurrentNumber += GetZCount() * GetYCount();
}
void VolumeTraverser::IncrementY()
{
mCurrentLocation.y++;
mCurrentNumber += GetZCount();
}
void VolumeTraverser::IncrementZ()
{
mCurrentLocation.z++;
mCurrentNumber++;
}
void VolumeTraverser::DecrementX()
{
mCurrentLocation.x--;
mCurrentNumber -= GetZCount() * GetYCount();
}
void VolumeTraverser::DecrementY()
{
mCurrentLocation.y--;
mCurrentNumber -= GetZCount();
}
void VolumeTraverser::DecrementZ()
{
mCurrentLocation.z--;
mCurrentNumber--;
}
bool VolumeTraverser::CurrentLocationValid()
{
if (GetCurrentIndex() < 0)
{
return false;
}
if (mCurrentLocation.x < 0 || mCurrentLocation.y < 0 || mCurrentLocation.z < 0
|| mCurrentLocation.x >= GetXCount() || mCurrentLocation.y >= GetYCount()
|| mCurrentLocation.z >= GetZCount())
{
return false;
}
return true;
}
}
}
| jenshnielsen/hemelb | Code/geometry/VolumeTraverser.cc | C++ | lgpl-3.0 | 2,938 |
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hiro.Functors.UnitTests.SampleModel
{
public interface IFoo
{
}
}
| philiplaureano/Hiro | src/UnitTests/SampleModel/IFoo.cs | C# | lgpl-3.0 | 178 |
# -*-coding:Utf-8 -*
import Vue.Figure as figure
import Vue.Donnee as donnee
import Lecture.FonctionLectureClassique as classique
import numpy as np
import sys
########################################################################################
#------------------------------- Input -----------------------------
########################################################################################
if (len(sys.argv)==2):
filename=sys.argv[1]
print(filename+" will be printed")
else:
print("You must give the name of the output file")
sys.exit(1)
outputname_err="/".join(filename.split("/")[0:-1])+"/graphe_"+(filename.split("/")[-1]).split(".")[0]
########################################################################################
#------------------------------- Figure -----------------------------
########################################################################################
colors=["m","b","c","r","g","y","k","firebrick","purple"]
markers=["^","o",".","v"]
(dist,rank) = classique.lecture(filename,0,1)
(err1,err2) = classique.lecture(filename,2,3)
Dist = []
Rank = []
Err1 = []
Err2 = []
Courbes_dist = []
Courbes_rank = []
Courbes_err1 = []
Courbes_err2 = []
compt=0
ymax_err=0
ymin_err=1e30
offset = 49
for i in range(1,6):
Rank.append(rank[compt+0:compt+offset])
Dist.append(dist[compt+0])
Err1.append(err1[compt+0:compt+offset])
Err2.append(err2[compt+0:compt+offset])
ymax_err=max(ymax_err,max(err1[compt+0:compt+offset]))
ymax_err=max(ymax_err,max(err2[compt+0:compt+offset]))
ymin_err=min(ymin_err,min(err1[compt+0:compt+offset]))
ymin_err=min(ymin_err,min(err2[compt+0:compt+offset]))
compt+=offset
ncolor=0
for i in range(0,len(Dist)):
line1={"linestyle":"-","linewidth":3,"linecolor":colors[ncolor]}
line2={"linestyle":"--","linewidth":3,"linecolor":colors[ncolor]}
marker={"markerstyle":"None","markersize":10,"fillstyle":"full"}
Courbes_err1.append(donnee.Ligne(nom=r"ACA - distance="+str(Dist[i]),ordonnee=Err1[i],abscisse=Rank[i],line=line1,marker=marker))
Courbes_err2.append(donnee.Ligne(nom=r"SVD - distance="+str(Dist[i]),ordonnee=Err2[i],abscisse=Rank[i],line=line2,marker=marker))
ncolor+=1
xlim=[min(Rank[0])*0.75,max(Rank[0])*1.01]
ylim_erro=[ymin_err*0.75,ymax_err*1.25]
xlabel={"label":"Rank","fontsize":20}
ylabel_erro={"label":"Relative error","fontsize":20}
# titre={"titre":"Test","fontsize":20,"loc":"center"}
legende={"loc":"upper left","bbox_to_anchor":(1.01,1),"ncol":1,"fontsize":12}
Figure_erro=figure.Graphe1D(id=0,legende=legende,xlim=xlim,ylim=ylim_erro,xlabel=xlabel,ylabel=ylabel_erro,yscale="log",axis="off",format="pdf")
for courbe in Courbes_err1:
Figure_erro.AjoutCourbe(courbe)
for courbe in Courbes_err2:
Figure_erro.AjoutCourbe(courbe)
Figure_erro.TraceGraphe1D()
Figure_erro.EnregistreFigure(outputname_err)
Figure_erro.FermeFigure()
| xclaeys/ElastoPhi | postprocessing/graphes_output_err_decrease.py | Python | lgpl-3.0 | 2,917 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program 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 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine;
use pocketmine\permission\ServerOperator;
interface IPlayer extends ServerOperator{
/**
* @return bool
*/
public function isOnline();
/**
* @return string
*/
public function getName() : string;
/**
* @return bool
*/
public function isBanned();
/**
* @param bool $banned
*/
public function setBanned($banned);
/**
* @return bool
*/
public function isWhitelisted();
/**
* @param bool $value
*/
public function setWhitelisted($value);
/**
* @return Player|null
*/
public function getPlayer();
/**
* @return int|null
*/
public function getFirstPlayed();
/**
* @return int|null
*/
public function getLastPlayed();
/**
* @return mixed
*/
public function hasPlayedBefore();
}
| NebzzTeam/PocketMine-MP | src/pocketmine/IPlayer.php | PHP | lgpl-3.0 | 1,498 |
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.web.requestid;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.sonar.core.util.UuidGenerator;
/**
* This implementation of {@link RequestIdGenerator} creates unique identifiers for HTTP requests leveraging
* {@link UuidGenerator.WithFixedBase#generate(int)} and a counter of HTTP requests.
* <p>
* To work around the limit of unique values produced by {@link UuidGenerator.WithFixedBase#generate(int)}, the
* {@link UuidGenerator.WithFixedBase} instance will be renewed every
* {@link RequestIdConfiguration#getUidGeneratorRenewalCount() RequestIdConfiguration#uidGeneratorRenewalCount}
* HTTP requests.
* </p>
* <p>
* This implementation is Thread safe.
* </p>
*/
public class RequestIdGeneratorImpl implements RequestIdGenerator {
/**
* The value to which the HTTP request count will be compared to (using a modulo operator,
* see {@link #mustRenewUuidGenerator(long)}).
*
* <p>
* This value can't be the last value before {@link UuidGenerator.WithFixedBase#generate(int)} returns a non unique
* value, ie. 2^23-1 because there is no guarantee the renewal will happen before any other thread calls
* {@link UuidGenerator.WithFixedBase#generate(int)} method of the deplated {@link UuidGenerator.WithFixedBase} instance.
* </p>
*
* <p>
* To keep a comfortable margin of error, 2^22 will be used.
* </p>
*/
public static final long UUID_GENERATOR_RENEWAL_COUNT = 4_194_304;
private final AtomicLong counter = new AtomicLong();
private final RequestIdGeneratorBase requestIdGeneratorBase;
private final RequestIdConfiguration requestIdConfiguration;
private final AtomicReference<UuidGenerator.WithFixedBase> uuidGenerator;
public RequestIdGeneratorImpl(RequestIdGeneratorBase requestIdGeneratorBase, RequestIdConfiguration requestIdConfiguration) {
this.requestIdGeneratorBase = requestIdGeneratorBase;
this.uuidGenerator = new AtomicReference<>(requestIdGeneratorBase.createNew());
this.requestIdConfiguration = requestIdConfiguration;
}
@Override
public String generate() {
UuidGenerator.WithFixedBase currentUuidGenerator = this.uuidGenerator.get();
long counterValue = counter.getAndIncrement();
if (counterValue != 0 && mustRenewUuidGenerator(counterValue)) {
UuidGenerator.WithFixedBase newUuidGenerator = requestIdGeneratorBase.createNew();
uuidGenerator.set(newUuidGenerator);
return generate(newUuidGenerator, counterValue);
}
return generate(currentUuidGenerator, counterValue);
}
/**
* Since renewal of {@link UuidGenerator.WithFixedBase} instance is based on the HTTP request counter, only a single
* thread can get the right value which will make this method return true. So, this is thread-safe by design, therefor
* this method doesn't need external synchronization.
* <p>
* The value to which the counter is compared should however be chosen with caution: see {@link #UUID_GENERATOR_RENEWAL_COUNT}.
* </p>
*/
private boolean mustRenewUuidGenerator(long counter) {
return counter % requestIdConfiguration.getUidGeneratorRenewalCount() == 0;
}
private static String generate(UuidGenerator.WithFixedBase uuidGenerator, long increment) {
return Base64.getEncoder().encodeToString(uuidGenerator.generate((int) increment));
}
}
| Godin/sonar | server/sonar-server/src/main/java/org/sonar/server/platform/web/requestid/RequestIdGeneratorImpl.java | Java | lgpl-3.0 | 4,272 |
/*
* Niobe Legion - a versatile client / server framework
* Copyright (C) 2013-2016 by fireandfuel (fireandfuel<at>hotmail<dot>de)
*
* This file (FxDatasetTreeColumn.java) is part of Niobe Legion (module niobe-legion-client).
*
* Niobe Legion 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 3 of the License, or
* (at your option) any later version.
*
* Niobe Legion 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 Niobe Legion. If not, see <http://www.gnu.org/licenses/>.
*/
package niobe.legion.client.gui.databinding;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
public class FxDatasetTreeColumn<C> extends TreeTableColumn<FxDatasetWrapper, C>
{
public FxDatasetTreeColumn(final String key, final String name)
{
this(key, name, null, -1);
}
public FxDatasetTreeColumn(final String key, final String name, int width)
{
this(key, name, null, width);
}
public FxDatasetTreeColumn(final String key, final String name, final boolean editable)
{
this(key, name, editable, null, -1);
}
public FxDatasetTreeColumn(final String key, final String name, final boolean editable, int widht)
{
this(key, name, editable, null, widht);
}
public FxDatasetTreeColumn(final String key, final String name,
final Callback<Integer, ObservableValue<Boolean>> getSelectedProperty)
{
this(key, name, getSelectedProperty, -1);
}
public FxDatasetTreeColumn(final String key, final String name,
final Callback<Integer, ObservableValue<Boolean>> getSelectedProperty, int width)
{
super(name);
this.setCellValueFactory(column -> (ObservableValue<C>) column.getValue().getValue().getProperty(key));
this.setCellFactory(param -> new FxDatasetTreeCell<FxDatasetWrapper, C>(getSelectedProperty));
if(width > -1)
{
this.setPrefWidth(width);
}
}
public FxDatasetTreeColumn(final String key, final String name, final boolean editable,
final Callback<Integer, ObservableValue<Boolean>> getSelectedProperty, int width)
{
this(key, name, getSelectedProperty, width);
this.setEditable(editable);
}
}
| fireandfuel/Niobe-Legion | client/src/niobe/legion/client/gui/databinding/FxDatasetTreeColumn.java | Java | lgpl-3.0 | 2,810 |
/**
*/
package org.ow2.mindEd.adl.textual.fractal.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.ow2.mindEd.adl.textual.fractal.AnnotationsList;
import org.ow2.mindEd.adl.textual.fractal.ArchitectureDefinition;
import org.ow2.mindEd.adl.textual.fractal.ArgumentDefinition;
import org.ow2.mindEd.adl.textual.fractal.FractalPackage;
import org.ow2.mindEd.adl.textual.fractal.SubComponentDefinition;
import org.ow2.mindEd.adl.textual.fractal.TemplateReference;
import org.ow2.mindEd.adl.textual.fractal.TypeReference;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Sub Component Definition</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.ow2.mindEd.adl.textual.fractal.impl.SubComponentDefinitionImpl#getType <em>Type</em>}</li>
* <li>{@link org.ow2.mindEd.adl.textual.fractal.impl.SubComponentDefinitionImpl#getTemplatesList <em>Templates List</em>}</li>
* <li>{@link org.ow2.mindEd.adl.textual.fractal.impl.SubComponentDefinitionImpl#getArgumentsList <em>Arguments List</em>}</li>
* <li>{@link org.ow2.mindEd.adl.textual.fractal.impl.SubComponentDefinitionImpl#getName <em>Name</em>}</li>
* <li>{@link org.ow2.mindEd.adl.textual.fractal.impl.SubComponentDefinitionImpl#getBodyAnnotationsList <em>Body Annotations List</em>}</li>
* <li>{@link org.ow2.mindEd.adl.textual.fractal.impl.SubComponentDefinitionImpl#getBody <em>Body</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class SubComponentDefinitionImpl extends CompositeElementImpl implements SubComponentDefinition
{
/**
* The cached value of the '{@link #getType() <em>Type</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected TypeReference type;
/**
* The cached value of the '{@link #getTemplatesList() <em>Templates List</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTemplatesList()
* @generated
* @ordered
*/
protected EList<TemplateReference> templatesList;
/**
* The cached value of the '{@link #getArgumentsList() <em>Arguments List</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getArgumentsList()
* @generated
* @ordered
*/
protected EList<ArgumentDefinition> argumentsList;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getBodyAnnotationsList() <em>Body Annotations List</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBodyAnnotationsList()
* @generated
* @ordered
*/
protected AnnotationsList bodyAnnotationsList;
/**
* The cached value of the '{@link #getBody() <em>Body</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBody()
* @generated
* @ordered
*/
protected ArchitectureDefinition body;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SubComponentDefinitionImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return FractalPackage.Literals.SUB_COMPONENT_DEFINITION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TypeReference getType()
{
if (type != null && type.eIsProxy())
{
InternalEObject oldType = (InternalEObject)type;
type = (TypeReference)eResolveProxy(oldType);
if (type != oldType)
{
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, FractalPackage.SUB_COMPONENT_DEFINITION__TYPE, oldType, type));
}
}
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TypeReference basicGetType()
{
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setType(TypeReference newType)
{
TypeReference oldType = type;
type = newType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FractalPackage.SUB_COMPONENT_DEFINITION__TYPE, oldType, type));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<TemplateReference> getTemplatesList()
{
if (templatesList == null)
{
templatesList = new EObjectContainmentEList<TemplateReference>(TemplateReference.class, this, FractalPackage.SUB_COMPONENT_DEFINITION__TEMPLATES_LIST);
}
return templatesList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ArgumentDefinition> getArgumentsList()
{
if (argumentsList == null)
{
argumentsList = new EObjectContainmentEList<ArgumentDefinition>(ArgumentDefinition.class, this, FractalPackage.SUB_COMPONENT_DEFINITION__ARGUMENTS_LIST);
}
return argumentsList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName()
{
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName)
{
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FractalPackage.SUB_COMPONENT_DEFINITION__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AnnotationsList getBodyAnnotationsList()
{
return bodyAnnotationsList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetBodyAnnotationsList(AnnotationsList newBodyAnnotationsList, NotificationChain msgs)
{
AnnotationsList oldBodyAnnotationsList = bodyAnnotationsList;
bodyAnnotationsList = newBodyAnnotationsList;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FractalPackage.SUB_COMPONENT_DEFINITION__BODY_ANNOTATIONS_LIST, oldBodyAnnotationsList, newBodyAnnotationsList);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBodyAnnotationsList(AnnotationsList newBodyAnnotationsList)
{
if (newBodyAnnotationsList != bodyAnnotationsList)
{
NotificationChain msgs = null;
if (bodyAnnotationsList != null)
msgs = ((InternalEObject)bodyAnnotationsList).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FractalPackage.SUB_COMPONENT_DEFINITION__BODY_ANNOTATIONS_LIST, null, msgs);
if (newBodyAnnotationsList != null)
msgs = ((InternalEObject)newBodyAnnotationsList).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FractalPackage.SUB_COMPONENT_DEFINITION__BODY_ANNOTATIONS_LIST, null, msgs);
msgs = basicSetBodyAnnotationsList(newBodyAnnotationsList, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FractalPackage.SUB_COMPONENT_DEFINITION__BODY_ANNOTATIONS_LIST, newBodyAnnotationsList, newBodyAnnotationsList));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ArchitectureDefinition getBody()
{
return body;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetBody(ArchitectureDefinition newBody, NotificationChain msgs)
{
ArchitectureDefinition oldBody = body;
body = newBody;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FractalPackage.SUB_COMPONENT_DEFINITION__BODY, oldBody, newBody);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBody(ArchitectureDefinition newBody)
{
if (newBody != body)
{
NotificationChain msgs = null;
if (body != null)
msgs = ((InternalEObject)body).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FractalPackage.SUB_COMPONENT_DEFINITION__BODY, null, msgs);
if (newBody != null)
msgs = ((InternalEObject)newBody).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FractalPackage.SUB_COMPONENT_DEFINITION__BODY, null, msgs);
msgs = basicSetBody(newBody, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FractalPackage.SUB_COMPONENT_DEFINITION__BODY, newBody, newBody));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case FractalPackage.SUB_COMPONENT_DEFINITION__TEMPLATES_LIST:
return ((InternalEList<?>)getTemplatesList()).basicRemove(otherEnd, msgs);
case FractalPackage.SUB_COMPONENT_DEFINITION__ARGUMENTS_LIST:
return ((InternalEList<?>)getArgumentsList()).basicRemove(otherEnd, msgs);
case FractalPackage.SUB_COMPONENT_DEFINITION__BODY_ANNOTATIONS_LIST:
return basicSetBodyAnnotationsList(null, msgs);
case FractalPackage.SUB_COMPONENT_DEFINITION__BODY:
return basicSetBody(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case FractalPackage.SUB_COMPONENT_DEFINITION__TYPE:
if (resolve) return getType();
return basicGetType();
case FractalPackage.SUB_COMPONENT_DEFINITION__TEMPLATES_LIST:
return getTemplatesList();
case FractalPackage.SUB_COMPONENT_DEFINITION__ARGUMENTS_LIST:
return getArgumentsList();
case FractalPackage.SUB_COMPONENT_DEFINITION__NAME:
return getName();
case FractalPackage.SUB_COMPONENT_DEFINITION__BODY_ANNOTATIONS_LIST:
return getBodyAnnotationsList();
case FractalPackage.SUB_COMPONENT_DEFINITION__BODY:
return getBody();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case FractalPackage.SUB_COMPONENT_DEFINITION__TYPE:
setType((TypeReference)newValue);
return;
case FractalPackage.SUB_COMPONENT_DEFINITION__TEMPLATES_LIST:
getTemplatesList().clear();
getTemplatesList().addAll((Collection<? extends TemplateReference>)newValue);
return;
case FractalPackage.SUB_COMPONENT_DEFINITION__ARGUMENTS_LIST:
getArgumentsList().clear();
getArgumentsList().addAll((Collection<? extends ArgumentDefinition>)newValue);
return;
case FractalPackage.SUB_COMPONENT_DEFINITION__NAME:
setName((String)newValue);
return;
case FractalPackage.SUB_COMPONENT_DEFINITION__BODY_ANNOTATIONS_LIST:
setBodyAnnotationsList((AnnotationsList)newValue);
return;
case FractalPackage.SUB_COMPONENT_DEFINITION__BODY:
setBody((ArchitectureDefinition)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case FractalPackage.SUB_COMPONENT_DEFINITION__TYPE:
setType((TypeReference)null);
return;
case FractalPackage.SUB_COMPONENT_DEFINITION__TEMPLATES_LIST:
getTemplatesList().clear();
return;
case FractalPackage.SUB_COMPONENT_DEFINITION__ARGUMENTS_LIST:
getArgumentsList().clear();
return;
case FractalPackage.SUB_COMPONENT_DEFINITION__NAME:
setName(NAME_EDEFAULT);
return;
case FractalPackage.SUB_COMPONENT_DEFINITION__BODY_ANNOTATIONS_LIST:
setBodyAnnotationsList((AnnotationsList)null);
return;
case FractalPackage.SUB_COMPONENT_DEFINITION__BODY:
setBody((ArchitectureDefinition)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case FractalPackage.SUB_COMPONENT_DEFINITION__TYPE:
return type != null;
case FractalPackage.SUB_COMPONENT_DEFINITION__TEMPLATES_LIST:
return templatesList != null && !templatesList.isEmpty();
case FractalPackage.SUB_COMPONENT_DEFINITION__ARGUMENTS_LIST:
return argumentsList != null && !argumentsList.isEmpty();
case FractalPackage.SUB_COMPONENT_DEFINITION__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case FractalPackage.SUB_COMPONENT_DEFINITION__BODY_ANNOTATIONS_LIST:
return bodyAnnotationsList != null;
case FractalPackage.SUB_COMPONENT_DEFINITION__BODY:
return body != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //SubComponentDefinitionImpl
| StephaneSeyvoz/mindEd | org.ow2.mindEd.adl.textual/src-gen/org/ow2/mindEd/adl/textual/fractal/impl/SubComponentDefinitionImpl.java | Java | lgpl-3.0 | 15,405 |
module RubyQz
module Storage
class Memcache
def initialize(config)
end
def write(topic, yaml_data)
end
def read(topic)
end
end
end
end
| benoitgoyette/RubyQz | RubyQz-server/RubyQz/storage/memcache/memcache_storage.rb | Ruby | lgpl-3.0 | 197 |
package org.javlo.component.core;
import org.javlo.context.ContentContext;
public interface IPageRank {
public int getRankValue(ContentContext ctx, String path);
public int getVotes(ContentContext ctx, String path);
}
| Javlo/javlo | src/main/java/org/javlo/component/core/IPageRank.java | Java | lgpl-3.0 | 227 |
/**
* Copyright (C) 2010-2017 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite 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 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package com.examples.with.different.packagename.context;
public interface ISubSubClass {
public boolean innermethod(int i);
}
| sefaakca/EvoSuite-Sefa | client/src/test/java/com/examples/with/different/packagename/context/ISubSubClass.java | Java | lgpl-3.0 | 912 |
using System;
using System.Data.Common;
namespace SqlToolkit.Benchmark
{
public class HandMapper: IReadMapper<BDataObject, BTable>
{
public HandMapper()
{
}
public void LoadInstance(DbDataReader reader, BDataObject model)
{
int column0 = reader.GetInt32(0);
string column1 = reader.GetString(1);
string column2 = reader.GetString(2);
int? column3;
if (reader.IsDBNull(3))
column3 = null;
else
column3 = reader.GetInt32(3);
int? column4;
if (reader.IsDBNull(4))
column4 = null;
else
column4 = reader.GetInt32(4);
bool column5 = reader.GetBoolean(5);
model.Id = column0;
model.Name = column1;
model.NameNull = column2;
model.Rooms = column3;
model.RoomsNull = column4;
model.Verify = column5;
}
public string RequiredColumns
{
get { throw new NotImplementedException(); }
}
}
}
| ExM/SqlToolkit | SqlToolkit.Benchmark/HandMapper.cs | C# | lgpl-3.0 | 890 |
package com.slidingmenu.lib;
import java.lang.reflect.Method;
import org.zywx.wbpalmstar.engine.universalex.EUExUtil;
//import org.zywx.wbpalmstar.widgetone.uex.R;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.slidingmenu.lib.CustomViewAbove.OnPageChangeListener;
public class SlidingMenu extends RelativeLayout {
private static final String TAG = SlidingMenu.class.getSimpleName();
public static final int SLIDING_WINDOW = 0;
public static final int SLIDING_CONTENT = 1;
private boolean mActionbarOverlay = false;
/** Constant value for use with setTouchModeAbove(). Allows the SlidingMenu to be opened with a swipe
* gesture on the screen's margin
*/
public static final int TOUCHMODE_MARGIN = 0;
/** Constant value for use with setTouchModeAbove(). Allows the SlidingMenu to be opened with a swipe
* gesture anywhere on the screen
*/
public static final int TOUCHMODE_FULLSCREEN = 1;
/** Constant value for use with setTouchModeAbove(). Denies the SlidingMenu to be opened with a swipe
* gesture
*/
public static final int TOUCHMODE_NONE = 2;
/** Constant value for use with setMode(). Puts the menu to the left of the content.
*/
public static final int LEFT = 0;
/** Constant value for use with setMode(). Puts the menu to the right of the content.
*/
public static final int RIGHT = 1;
/** Constant value for use with setMode(). Puts menus to the left and right of the content.
*/
public static final int LEFT_RIGHT = 2;
private CustomViewAbove mViewAbove;
private CustomViewBehind mViewBehind;
private OnOpenListener mOpenListener;
private OnOpenListener mSecondaryOpenListner;
private OnCloseListener mCloseListener;
private ImageView mViewBackground;
/**
* The listener interface for receiving onOpen events.
* The class that is interested in processing a onOpen
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addOnOpenListener<code> method. When
* the onOpen event occurs, that object's appropriate
* method is invoked
*/
public interface OnOpenListener {
/**
* On open.
*/
public void onOpen();
}
/**
* The listener interface for receiving onOpened events.
* The class that is interested in processing a onOpened
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addOnOpenedListener<code> method. When
* the onOpened event occurs, that object's appropriate
* method is invoked.
*
* @see OnOpenedEvent
*/
public interface OnOpenedListener {
/**
* On opened.
*/
public void onOpened();
}
/**
* The listener interface for receiving onClose events.
* The class that is interested in processing a onClose
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addOnCloseListener<code> method. When
* the onClose event occurs, that object's appropriate
* method is invoked.
*
* @see OnCloseEvent
*/
public interface OnCloseListener {
/**
* On close.
*/
public void onClose();
}
/**
* The listener interface for receiving onClosed events.
* The class that is interested in processing a onClosed
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addOnClosedListener<code> method. When
* the onClosed event occurs, that object's appropriate
* method is invoked.
*
* @see OnClosedEvent
*/
public interface OnClosedListener {
/**
* On closed.
*/
public void onClosed();
}
/**
* The Interface CanvasTransformer.
*/
public interface CanvasTransformer {
/**
* Transform canvas.
*
* @param canvas the canvas
* @param percentOpen the percent open
*/
public void transformCanvas(Canvas canvas, float percentOpen);
}
/**
* Instantiates a new SlidingMenu.
*
* @param context the associated Context
*/
public SlidingMenu(Context context) {
this(context, null);
}
/**
* Instantiates a new SlidingMenu and attach to Activity.
*
* @param activity the activity to attach slidingmenu
* @param slideStyle the slidingmenu style
*/
public SlidingMenu(Activity activity, int slideStyle) {
this(activity, null);
this.attachToActivity(activity, slideStyle);
}
/**
* Instantiates a new SlidingMenu.
*
* @param context the associated Context
* @param attrs the attrs
*/
public SlidingMenu(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Instantiates a new SlidingMenu.
*
* @param context the associated Context
* @param attrs the attrs
* @param defStyle the def style
*/
public SlidingMenu(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutParams backgroundParams = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mViewBackground = new ImageView(context);
mViewBackground.setScaleType(ImageView.ScaleType.CENTER_CROP);
addView(mViewBackground, backgroundParams);
LayoutParams behindParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mViewBehind = new CustomViewBehind(context);
addView(mViewBehind, behindParams);
LayoutParams aboveParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mViewAbove = new CustomViewAbove(context);
addView(mViewAbove, aboveParams);
// register the CustomViewBehind with the CustomViewAbove
mViewAbove.setCustomViewBehind(mViewBehind);
mViewBehind.setCustomViewAbove(mViewAbove);
mViewAbove.setOnPageChangeListener(new OnPageChangeListener() {
public static final int POSITION_OPEN = 0;
public static final int POSITION_CLOSE = 1;
public static final int POSITION_SECONDARY_OPEN = 2;
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) { }
public void onPageSelected(int position) {
if (position == POSITION_OPEN && mOpenListener != null) {
mOpenListener.onOpen();
} else if (position == POSITION_CLOSE && mCloseListener != null) {
mCloseListener.onClose();
} else if (position == POSITION_SECONDARY_OPEN && mSecondaryOpenListner != null ) {
mSecondaryOpenListner.onOpen();
}
}
});
// now style everything!
// Styleables from XML
int[] styleAttrs = new int[] { EUExUtil.getResStyleableID("mode"),
EUExUtil.getResStyleableID("viewAbove"),
EUExUtil.getResStyleableID("viewBehind"),
EUExUtil.getResStyleableID("behindOffset"),
EUExUtil.getResStyleableID("behindWidth"),
EUExUtil.getResStyleableID("behindScrollScale"),
EUExUtil.getResStyleableID("touchModeAbove"),
EUExUtil.getResStyleableID("touchModeBehind"),
EUExUtil.getResStyleableID("shadowDrawable"),
EUExUtil.getResStyleableID("shadowWidth"),
EUExUtil.getResStyleableID("fadeEnabled"),
EUExUtil.getResStyleableID("fadeDegree"),
EUExUtil.getResStyleableID("selectorEnabled"),
EUExUtil.getResStyleableID("selectorDrawable")};
TypedArray ta = context.obtainStyledAttributes(attrs, styleAttrs);
// TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SlidingMenu);
// set the above and behind views if defined in xml
// int mode = ta.getInt(R.styleable.SlidingMenu_mode, LEFT);
int mode = ta.getInt(EUExUtil.getResStyleableID("SlidingMenu_mode"), LEFT);
setMode(mode);
// int viewAbove = ta.getResourceId(R.styleable.SlidingMenu_viewAbove, -1);
int viewAbove = ta.getResourceId(EUExUtil.getResStyleableID("SlidingMenu_viewAbove"), -1);
if (viewAbove != -1) {
setContent(viewAbove);
} else {
setContent(new FrameLayout(context));
}
// int viewBehind = ta.getResourceId(R.styleable.SlidingMenu_viewBehind, -1);
int viewBehind = ta.getResourceId(EUExUtil.getResStyleableID("SlidingMenu_viewBehind"), -1);
if (viewBehind != -1) {
setMenu(viewBehind);
} else {
setMenu(new FrameLayout(context));
}
// int touchModeAbove = ta.getInt(R.styleable.SlidingMenu_touchModeAbove, TOUCHMODE_MARGIN);
int touchModeAbove = ta.getInt(EUExUtil.getResStyleableID("SlidingMenu_touchModeAbove"), TOUCHMODE_MARGIN);
setTouchModeAbove(touchModeAbove);
// int touchModeBehind = ta.getInt(R.styleable.SlidingMenu_touchModeBehind, TOUCHMODE_MARGIN);
int touchModeBehind = ta.getInt(EUExUtil.getResStyleableID("SlidingMenu_touchModeBehind"), TOUCHMODE_MARGIN);
setTouchModeBehind(touchModeBehind);
// int offsetBehind = (int) ta.getDimension(R.styleable.SlidingMenu_behindOffset, -1);
// int widthBehind = (int) ta.getDimension(R.styleable.SlidingMenu_behindWidth, -1);
int offsetBehind = (int) ta.getDimension(EUExUtil.getResStyleableID("SlidingMenu_behindOffset"), -1);
int widthBehind = (int) ta.getDimension(EUExUtil.getResStyleableID("SlidingMenu_behindWidth"), -1);
if (offsetBehind != -1 && widthBehind != -1)
throw new IllegalStateException("Cannot set both behindOffset and behindWidth for a SlidingMenu");
else if (offsetBehind != -1)
setBehindOffset(offsetBehind);
else if (widthBehind != -1)
setBehindWidth(widthBehind);
else
setBehindOffset(0);
// float scrollOffsetBehind = ta.getFloat(R.styleable.SlidingMenu_behindScrollScale, 0.33f);
float scrollOffsetBehind = ta.getFloat(EUExUtil.getResStyleableID("SlidingMenu_behindScrollScale"), 0.33f);
setBehindScrollScale(scrollOffsetBehind);
// int shadowRes = ta.getResourceId(R.styleable.SlidingMenu_shadowDrawable, -1);
int shadowRes = ta.getResourceId(EUExUtil.getResStyleableID("SlidingMenu_shadowDrawable"), -1);
if (shadowRes != -1) {
setShadowDrawable(shadowRes);
}
// int shadowWidth = (int) ta.getDimension(R.styleable.SlidingMenu_shadowWidth, 0);
int shadowWidth = (int) ta.getDimension(EUExUtil.getResStyleableID("SlidingMenu_shadowWidth"), 0);
setShadowWidth(shadowWidth);
// boolean fadeEnabled = ta.getBoolean(R.styleable.SlidingMenu_fadeEnabled, true);
boolean fadeEnabled = ta.getBoolean(EUExUtil.getResStyleableID("SlidingMenu_fadeEnabled"), true);
setFadeEnabled(fadeEnabled);
// float fadeDeg = ta.getFloat(R.styleable.SlidingMenu_fadeDegree, 0.33f);
float fadeDeg = ta.getFloat(EUExUtil.getResStyleableID("SlidingMenu_fadeDegree"), 0.33f);
setFadeDegree(fadeDeg);
// boolean selectorEnabled = ta.getBoolean(R.styleable.SlidingMenu_selectorEnabled, false);
boolean selectorEnabled = ta.getBoolean(EUExUtil.getResStyleableID("SlidingMenu_selectorEnabled"), false);
setSelectorEnabled(selectorEnabled);
// int selectorRes = ta.getResourceId(R.styleable.SlidingMenu_selectorDrawable, -1);
int selectorRes = ta.getResourceId(EUExUtil.getResStyleableID("SlidingMenu_selectorDrawable"), -1);
if (selectorRes != -1)
setSelectorDrawable(selectorRes);
ta.recycle();
}
/**
* Attaches the SlidingMenu to an entire Activity
*
* @param activity the Activity
* @param slideStyle either SLIDING_CONTENT or SLIDING_WINDOW
*/
public void attachToActivity(Activity activity, int slideStyle) {
attachToActivity(activity, slideStyle, false);
}
/**
* Attaches the SlidingMenu to an entire Activity
*
* @param activity the Activity
* @param slideStyle either SLIDING_CONTENT or SLIDING_WINDOW
* @param actionbarOverlay whether or not the ActionBar is overlaid
*/
public void attachToActivity(Activity activity, int slideStyle, boolean actionbarOverlay) {
if (slideStyle != SLIDING_WINDOW && slideStyle != SLIDING_CONTENT)
throw new IllegalArgumentException("slideStyle must be either SLIDING_WINDOW or SLIDING_CONTENT");
if (getParent() != null)
throw new IllegalStateException("This SlidingMenu appears to already be attached");
// get the window background
TypedArray a = activity.getTheme().obtainStyledAttributes(new int[] {android.R.attr.windowBackground});
int background = a.getResourceId(0, 0);
a.recycle();
switch (slideStyle) {
case SLIDING_WINDOW:
mActionbarOverlay = false;
ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
// save ActionBar themes that have transparent assets
decorChild.setBackgroundResource(background);
decor.removeView(decorChild);
decor.addView(this);
setContent(decorChild);
break;
case SLIDING_CONTENT:
mActionbarOverlay = actionbarOverlay;
// take the above view out of
ViewGroup contentParent = (ViewGroup)activity.findViewById(android.R.id.content);
View content = contentParent.getChildAt(0);
contentParent.removeView(content);
contentParent.addView(this);
setContent(content);
// save people from having transparent backgrounds
if (content.getBackground() == null)
content.setBackgroundResource(background);
break;
}
}
/**
* Set the above view content from a layout resource. The resource will be inflated, adding all top-level views
* to the above view.
*
* @param res the new content
*/
public void setContent(int res) {
setContent(LayoutInflater.from(getContext()).inflate(res, null));
}
/**
* Set the above view content to the given View.
*
* @param view The desired content to display.
*/
public void setContent(View view) {
mViewAbove.setContent(view);
showContent();
}
/**
* Retrieves the current content.
* @return the current content
*/
public View getContent() {
return mViewAbove.getContent();
}
/**
* Set the behind view (menu) content from a layout resource. The resource will be inflated, adding all top-level views
* to the behind view.
*
* @param res the new content
*/
public void setMenu(int res) {
setMenu(LayoutInflater.from(getContext()).inflate(res, null));
}
/**
* Set the behind view (menu) content to the given View.
*
* @param view The desired content to display.
*/
public void setMenu(View v) {
mViewBehind.setContent(v);
}
/**
* Retrieves the main menu.
* @return the main menu
*/
public View getMenu() {
return mViewBehind.getContent();
}
/**
* Set the secondary behind view (right menu) content from a layout resource. The resource will be inflated, adding all top-level views
* to the behind view.
*
* @param res the new content
*/
public void setSecondaryMenu(int res) {
setSecondaryMenu(LayoutInflater.from(getContext()).inflate(res, null));
}
/**
* Set the secondary behind view (right menu) content to the given View.
*
* @param view The desired content to display.
*/
public void setSecondaryMenu(View v) {
mViewBehind.setSecondaryContent(v);
// mViewBehind.invalidate();
}
/**
* Retrieves the current secondary menu (right).
* @return the current menu
*/
public View getSecondaryMenu() {
return mViewBehind.getSecondaryContent();
}
/**
* Sets the sliding enabled.
*
* @param b true to enable sliding, false to disable it.
*/
public void setSlidingEnabled(boolean b) {
mViewAbove.setSlidingEnabled(b);
}
/**
* Checks if is sliding enabled.
*
* @return true, if is sliding enabled
*/
public boolean isSlidingEnabled() {
return mViewAbove.isSlidingEnabled();
}
/**
* Sets which side the SlidingMenu should appear on.
* @param mode must be either SlidingMenu.LEFT or SlidingMenu.RIGHT
*/
public void setMode(int mode) {
if (mode != LEFT && mode != RIGHT && mode != LEFT_RIGHT) {
throw new IllegalStateException("SlidingMenu mode must be LEFT, RIGHT, or LEFT_RIGHT");
}
mViewBehind.setMode(mode);
}
/**
* Returns the current side that the SlidingMenu is on.
* @return the current mode, either SlidingMenu.LEFT or SlidingMenu.RIGHT
*/
public int getMode() {
return mViewBehind.getMode();
}
/**
* Sets whether or not the SlidingMenu is in static mode (i.e. nothing is moving and everything is showing)
*
* @param b true to set static mode, false to disable static mode.
*/
public void setStatic(boolean b) {
if (b) {
setSlidingEnabled(false);
mViewAbove.setCustomViewBehind(null);
mViewAbove.setCurrentItem(1);
// mViewBehind.setCurrentItem(0);
} else {
mViewAbove.setCurrentItem(1);
// mViewBehind.setCurrentItem(1);
mViewAbove.setCustomViewBehind(mViewBehind);
setSlidingEnabled(true);
}
}
/**
* Opens the menu and shows the menu view.
*/
public void showMenu() {
showMenu(true);
}
/**
* Opens the menu and shows the menu view.
*
* @param animate true to animate the transition, false to ignore animation
*/
public void showMenu(boolean animate) {
mViewAbove.setCurrentItem(0, animate);
}
/**
* Opens the menu and shows the secondary menu view. Will default to the regular menu
* if there is only one.
*/
public void showSecondaryMenu() {
showSecondaryMenu(true);
}
/**
* Opens the menu and shows the secondary (right) menu view. Will default to the regular menu
* if there is only one.
*
* @param animate true to animate the transition, false to ignore animation
*/
public void showSecondaryMenu(boolean animate) {
mViewAbove.setCurrentItem(2, animate);
}
/**
* Closes the menu and shows the above view.
*/
public void showContent() {
showContent(true);
}
/**
* Closes the menu and shows the above view.
*
* @param animate true to animate the transition, false to ignore animation
*/
public void showContent(boolean animate) {
mViewAbove.setCurrentItem(1, animate);
}
/**
* Toggle the SlidingMenu. If it is open, it will be closed, and vice versa.
*/
public void toggle() {
toggle(true);
}
/**
* Toggle the SlidingMenu. If it is open, it will be closed, and vice versa.
*
* @param animate true to animate the transition, false to ignore animation
*/
public void toggle(boolean animate) {
if (isMenuShowing()) {
showContent(animate);
} else {
showMenu(animate);
}
}
/**
* Checks if is the behind view showing.
*
* @return Whether or not the behind view is showing
*/
public boolean isMenuShowing() {
return mViewAbove.getCurrentItem() == 0 || mViewAbove.getCurrentItem() == 2;
}
/**
* Checks if is the behind view showing.
*
* @return Whether or not the behind view is showing
*/
public boolean isSecondaryMenuShowing() {
return mViewAbove.getCurrentItem() == 2;
}
/**
* Gets the behind offset.
*
* @return The margin on the right of the screen that the behind view scrolls to
*/
public int getBehindOffset() {
return ((RelativeLayout.LayoutParams)mViewBehind.getLayoutParams()).rightMargin;
}
/**
* Sets the behind offset.
*
* @param i The margin, in pixels, on the right of the screen that the behind view scrolls to.
*/
public void setBehindOffset(int i) {
// RelativeLayout.LayoutParams params = ((RelativeLayout.LayoutParams)mViewBehind.getLayoutParams());
// int bottom = params.bottomMargin;
// int top = params.topMargin;
// int left = params.leftMargin;
// params.setMargins(left, top, i, bottom);
mViewBehind.setWidthOffset(i);
}
/**
* Sets the behind offset.
*
* @param resID The dimension resource id to be set as the behind offset.
* The menu, when open, will leave this width margin on the right of the screen.
*/
public void setBehindOffsetRes(int resID) {
int i = (int) getContext().getResources().getDimension(resID);
setBehindOffset(i);
}
/**
* Sets the above offset.
*
* @param i the new above offset, in pixels
*/
public void setAboveOffset(int i) {
mViewAbove.setAboveOffset(i);
}
/**
* Sets the above offset.
*
* @param resID The dimension resource id to be set as the above offset.
*/
public void setAboveOffsetRes(int resID) {
int i = (int) getContext().getResources().getDimension(resID);
setAboveOffset(i);
}
/**
* Sets the behind width.
*
* @param i The width the Sliding Menu will open to, in pixels
*/
@SuppressWarnings("deprecation")
public void setBehindWidth(int i) {
int width;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
try {
Class<?> cls = Display.class;
Class<?>[] parameterTypes = {Point.class};
Point parameter = new Point();
Method method = cls.getMethod("getSize", parameterTypes);
method.invoke(display, parameter);
width = parameter.x;
} catch (Exception e) {
width = display.getWidth();
}
setBehindOffset(width - i);
}
/**
* Sets the behind width.
*
* @param res The dimension resource id to be set as the behind width offset.
* The menu, when open, will open this wide.
*/
public void setBehindWidthRes(int res) {
int i = (int) getContext().getResources().getDimension(res);
setBehindWidth(i);
}
/**
* Gets the behind scroll scale.
*
* @return The scale of the parallax scroll
*/
public float getBehindScrollScale() {
return mViewBehind.getScrollScale();
}
/**
* Gets the touch mode margin threshold
* @return the touch mode margin threshold
*/
public int getTouchmodeMarginThreshold() {
return mViewBehind.getMarginThreshold();
}
/**
* Set the touch mode margin threshold
* @param touchmodeMarginThreshold
*/
public void setTouchmodeMarginThreshold(int touchmodeMarginThreshold) {
mViewBehind.setMarginThreshold(touchmodeMarginThreshold);
}
/**
* Sets the behind scroll scale.
*
* @param f The scale of the parallax scroll (i.e. 1.0f scrolls 1 pixel for every
* 1 pixel that the above view scrolls and 0.0f scrolls 0 pixels)
*/
public void setBehindScrollScale(float f) {
if (f < 0 && f > 1)
throw new IllegalStateException("ScrollScale must be between 0 and 1");
mViewBehind.setScrollScale(f);
}
/**
* Sets the behind canvas transformer.
*
* @param t the new behind canvas transformer
*/
public void setBehindCanvasTransformer(CanvasTransformer t) {
mViewBehind.setCanvasTransformer(t);
}
/**
* Sets the above canvas transformer.
*
* @param t the new above canvas transformer
*/
public void setAboveCanvasTransformer(CanvasTransformer t) {
mViewAbove.setCanvasTransformer(t);
}
/**
* Gets the touch mode above.
*
* @return the touch mode above
*/
public int getTouchModeAbove() {
return mViewAbove.getTouchMode();
}
/**
* Controls whether the SlidingMenu can be opened with a swipe gesture.
* Options are {@link #TOUCHMODE_MARGIN TOUCHMODE_MARGIN}, {@link #TOUCHMODE_FULLSCREEN TOUCHMODE_FULLSCREEN},
* or {@link #TOUCHMODE_NONE TOUCHMODE_NONE}
*
* @param i the new touch mode
*/
public void setTouchModeAbove(int i) {
if (i != TOUCHMODE_FULLSCREEN && i != TOUCHMODE_MARGIN
&& i != TOUCHMODE_NONE) {
throw new IllegalStateException("TouchMode must be set to either" +
"TOUCHMODE_FULLSCREEN or TOUCHMODE_MARGIN or TOUCHMODE_NONE.");
}
mViewAbove.setTouchMode(i);
}
/**
* Controls whether the SlidingMenu can be opened with a swipe gesture.
* Options are {@link #TOUCHMODE_MARGIN TOUCHMODE_MARGIN}, {@link #TOUCHMODE_FULLSCREEN TOUCHMODE_FULLSCREEN},
* or {@link #TOUCHMODE_NONE TOUCHMODE_NONE}
*
* @param i the new touch mode
*/
public void setTouchModeBehind(int i) {
if (i != TOUCHMODE_FULLSCREEN && i != TOUCHMODE_MARGIN
&& i != TOUCHMODE_NONE) {
throw new IllegalStateException("TouchMode must be set to either" +
"TOUCHMODE_FULLSCREEN or TOUCHMODE_MARGIN or TOUCHMODE_NONE.");
}
mViewBehind.setTouchMode(i);
}
/**
* Sets the shadow drawable.
*
* @param resId the resource ID of the new shadow drawable
*/
public void setShadowDrawable(int resId) {
setShadowDrawable(getContext().getResources().getDrawable(resId));
}
/**
* Sets the shadow drawable.
*
* @param d the new shadow drawable
*/
public void setShadowDrawable(Drawable d) {
mViewBehind.setShadowDrawable(d);
}
/**
* Sets the secondary (right) shadow drawable.
*
* @param resId the resource ID of the new shadow drawable
*/
public void setSecondaryShadowDrawable(int resId) {
setSecondaryShadowDrawable(getContext().getResources().getDrawable(resId));
}
/**
* Sets the secondary (right) shadow drawable.
*
* @param d the new shadow drawable
*/
public void setSecondaryShadowDrawable(Drawable d) {
mViewBehind.setSecondaryShadowDrawable(d);
}
/**
* Sets the shadow width.
*
* @param resId The dimension resource id to be set as the shadow width.
*/
public void setShadowWidthRes(int resId) {
setShadowWidth((int)getResources().getDimension(resId));
}
/**
* Sets the shadow width.
*
* @param pixels the new shadow width, in pixels
*/
public void setShadowWidth(int pixels) {
mViewBehind.setShadowWidth(pixels);
}
/**
* Enables or disables the SlidingMenu's fade in and out
*
* @param b true to enable fade, false to disable it
*/
public void setFadeEnabled(boolean b) {
mViewBehind.setFadeEnabled(b);
}
/**
* Sets how much the SlidingMenu fades in and out. Fade must be enabled, see
* {@link #setFadeEnabled(boolean) setFadeEnabled(boolean)}
*
* @param f the new fade degree, between 0.0f and 1.0f
*/
public void setFadeDegree(float f) {
mViewBehind.setFadeDegree(f);
}
/**
* Enables or disables whether the selector is drawn
*
* @param b true to draw the selector, false to not draw the selector
*/
public void setSelectorEnabled(boolean b) {
mViewBehind.setSelectorEnabled(true);
}
/**
* Sets the selected view. The selector will be drawn here
*
* @param v the new selected view
*/
public void setSelectedView(View v) {
mViewBehind.setSelectedView(v);
}
public void setBackgroundImage(int resid) {
mViewBackground.setBackgroundResource(resid);
}
/**
* Sets the selector drawable.
*
* @param res a resource ID for the selector drawable
*/
public void setSelectorDrawable(int res) {
mViewBehind.setSelectorBitmap(BitmapFactory.decodeResource(getResources(), res));
}
/**
* Sets the selector drawable.
*
* @param b the new selector bitmap
*/
public void setSelectorBitmap(Bitmap b) {
mViewBehind.setSelectorBitmap(b);
}
/**
* Add a View ignored by the Touch Down event when mode is Fullscreen
*
* @param v a view to be ignored
*/
public void addIgnoredView(View v) {
mViewAbove.addIgnoredView(v);
}
/**
* Remove a View ignored by the Touch Down event when mode is Fullscreen
*
* @param v a view not wanted to be ignored anymore
*/
public void removeIgnoredView(View v) {
mViewAbove.removeIgnoredView(v);
}
/**
* Clear the list of Views ignored by the Touch Down event when mode is Fullscreen
*/
public void clearIgnoredViews() {
mViewAbove.clearIgnoredViews();
}
/**
* Sets the OnOpenListener. {@link OnOpenListener#onOpen() OnOpenListener.onOpen()} will be called when the SlidingMenu is opened
*
* @param listener the new OnOpenListener
*/
public void setOnOpenListener(OnOpenListener listener) {
//mViewAbove.setOnOpenListener(listener);
mOpenListener = listener;
}
/**
* Sets the OnOpenListner for secondary menu {@link OnOpenListener#onOpen() OnOpenListener.onOpen()} will be called when the secondary SlidingMenu is opened
*
* @param listener the new OnOpenListener
*/
public void setSecondaryOnOpenListner(OnOpenListener listener) {
mSecondaryOpenListner = listener;
}
/**
* Sets the OnCloseListener. {@link OnCloseListener#onClose() OnCloseListener.onClose()} will be called when any one of the SlidingMenu is closed
*
* @param listener the new setOnCloseListener
*/
public void setOnCloseListener(OnCloseListener listener) {
//mViewAbove.setOnCloseListener(listener);
mCloseListener = listener;
}
/**
* Sets the OnOpenedListener. {@link OnOpenedListener#onOpened() OnOpenedListener.onOpened()} will be called after the SlidingMenu is opened
*
* @param listener the new OnOpenedListener
*/
public void setOnOpenedListener(OnOpenedListener listener) {
mViewAbove.setOnOpenedListener(listener);
}
/**
* Sets the OnClosedListener. {@link OnClosedListener#onClosed() OnClosedListener.onClosed()} will be called after the SlidingMenu is closed
*
* @param listener the new OnClosedListener
*/
public void setOnClosedListener(OnClosedListener listener) {
mViewAbove.setOnClosedListener(listener);
}
public static class SavedState extends BaseSavedState {
private final int mItem;
public SavedState(Parcelable superState, int item) {
super(superState);
mItem = item;
}
private SavedState(Parcel in) {
super(in);
mItem = in.readInt();
}
public int getItem() {
return mItem;
}
/* (non-Javadoc)
* @see android.view.AbsSavedState#writeToParcel(android.os.Parcel, int)
*/
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(mItem);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
/* (non-Javadoc)
* @see android.view.View#onSaveInstanceState()
*/
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState, mViewAbove.getCurrentItem());
return ss;
}
/* (non-Javadoc)
* @see android.view.View#onRestoreInstanceState(android.os.Parcelable)
*/
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
mViewAbove.setCurrentItem(ss.getItem());
}
/* (non-Javadoc)
* @see android.view.ViewGroup#fitSystemWindows(android.graphics.Rect)
*/
@SuppressLint("NewApi")
@Override
protected boolean fitSystemWindows(Rect insets) {
int leftPadding = insets.left;
int rightPadding = insets.right;
int topPadding = insets.top;
int bottomPadding = insets.bottom;
if (!mActionbarOverlay) {
Log.v(TAG, "setting padding!");
setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
}
return true;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void manageLayers(float percentOpen) {
if (!isHardwareAccelerated() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
boolean layer = percentOpen > 0.0f && percentOpen < 1.0f;
final int layerType = layer ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE;
if (layerType != getContent().getLayerType()) {
getHandler().post(new Runnable() {
public void run() {
Log.v(TAG, "changing layerType. hardware? " + (layerType == View.LAYER_TYPE_HARDWARE));
getContent().setLayerType(layerType, null);
getMenu().setLayerType(layerType, null);
if (getSecondaryMenu() != null) {
getSecondaryMenu().setLayerType(layerType, null);
}
}
});
}
}
}
}
| yanxiyue/appcan-android | Engine/src/com/slidingmenu/lib/SlidingMenu.java | Java | lgpl-3.0 | 32,780 |
/*******************************************************************************
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package com.jaspersoft.studio.editor.preview;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import net.sf.jasperreports.eclipse.viewer.action.AReportAction;
import net.sf.jasperreports.eclipse.viewer.action.ZoomActualSizeAction;
import net.sf.jasperreports.eclipse.viewer.action.ZoomInAction;
import net.sf.jasperreports.eclipse.viewer.action.ZoomOutAction;
import net.sf.jasperreports.engine.DefaultJasperReportsContext;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import com.jaspersoft.studio.JaspersoftStudioPlugin;
import com.jaspersoft.studio.data.DataAdapterDescriptor;
import com.jaspersoft.studio.data.DataAdapterManager;
import com.jaspersoft.studio.data.widget.IDataAdapterRunnable;
import com.jaspersoft.studio.editor.JrxmlEditor;
import com.jaspersoft.studio.editor.preview.actions.RunStopAction;
import com.jaspersoft.studio.editor.preview.actions.SwitchViewsAction;
import com.jaspersoft.studio.editor.preview.stats.Statistics;
import com.jaspersoft.studio.editor.preview.toolbar.LeftToolBarManager;
import com.jaspersoft.studio.editor.preview.toolbar.PreviewTopToolBarManager;
import com.jaspersoft.studio.editor.preview.toolbar.TopToolBarManagerJRPrint;
import com.jaspersoft.studio.editor.preview.view.APreview;
import com.jaspersoft.studio.editor.preview.view.control.ReportControler;
import com.jaspersoft.studio.editor.preview.view.report.html.ABrowserViewer;
import com.jaspersoft.studio.messages.Messages;
import com.jaspersoft.studio.preferences.util.PreferencesUtils;
import com.jaspersoft.studio.property.dataset.dialog.DataQueryAdapters;
import com.jaspersoft.studio.swt.toolbar.ToolItemContribution;
import com.jaspersoft.studio.swt.widgets.CSashForm;
import com.jaspersoft.studio.utils.Misc;
import com.jaspersoft.studio.utils.jasper.JasperReportsConfiguration;
public class PreviewContainer extends PreviewJRPrint implements IDataAdapterRunnable, IParametrable, IRunReport {
/**
* Zoom in action
*/
private AReportAction zoomInAction = null;
/**
* Zoom out action
*/
private AReportAction zoomOutAction = null;
/**
* the zoom to 100% action
*/
private AReportAction zoomActualAction = null;
public PreviewContainer() {
super(true);
}
public PreviewContainer(boolean listenResource, JasperReportsConfiguration jrContext) {
super(listenResource);
this.jrContext = jrContext;
}
@Override
public boolean isSaveAsAllowed() {
return true;
}
/**
* Retrieve the action from the contribution items. If the action were already retrieved it dosen't do nothing
*/
private void setActions() {
for (IContributionItem item : topToolBarManager.getContributions()) {
if (zoomInAction != null && zoomOutAction != null && zoomActualAction != null)
return;
if (ZoomInAction.ID.equals(item.getId()) && item instanceof ActionContributionItem) {
zoomInAction = (AReportAction) ((ActionContributionItem) item).getAction();
} else if (ZoomOutAction.ID.equals(item.getId()) && item instanceof ActionContributionItem) {
zoomOutAction = (AReportAction) ((ActionContributionItem) item).getAction();
} else if (ZoomActualSizeAction.ID.equals(item.getId()) && item instanceof ActionContributionItem) {
zoomActualAction = (AReportAction) ((ActionContributionItem) item).getAction();
}
}
}
public AReportAction getZoomInAction() {
setActions();
return zoomInAction;
}
public AReportAction getZoomOutAction() {
setActions();
return zoomOutAction;
}
public AReportAction getZoomActualAction() {
setActions();
return zoomActualAction;
}
@Override
protected void loadJRPrint(IEditorInput input) throws PartInitException {
setJasperPrint(null, null);
if (listenResource) {
InputStream in = null;
IFile file = null;
try {
if (input instanceof IFileEditorInput) {
file = ((IFileEditorInput) input).getFile();
in = file.getContents();
} else {
throw new PartInitException("Invalid Input: Must be IFileEditorInput or FileStoreEditorInput"); //$NON-NLS-1$
}
in = JrxmlEditor.getXML(jrContext, input, file.getCharset(true), in, null);
getJrContext(file);
jrContext.setJasperDesign(JRXmlLoader.load(jrContext, in));
setJasperDesign(jrContext);
} catch (Exception e) {
throw new PartInitException(e.getMessage(), e);
} finally {
if (in != null)
try {
in.close();
} catch (IOException e) {
throw new PartInitException("error closing input stream", e); //$NON-NLS-1$
}
}
}
}
private MultiPageContainer leftContainer;
public MultiPageContainer getLeftContainer() {
if (leftContainer == null)
leftContainer = new MultiPageContainer() {
@Override
public void switchView(Statistics stats, APreview view) {
super.switchView(stats, view);
for (String key : pmap.keySet()) {
if (pmap.get(key) == view) {
leftToolbar.setLabelText(key);
break;
}
}
}
};
return leftContainer;
}
private CSashForm sashform;
private LeftToolBarManager leftToolbar;
/**
* When disposed the mouse wheel filter is removed
*/
@Override
public void dispose() {
super.dispose();
}
@Override
public void createPartControl(Composite parent) {
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new GridLayout(3, false));
PlatformUI.getWorkbench().getHelpSystem().setHelp(container, "com.jaspersoft.studio.doc.editor_preview"); //$NON-NLS-1$
getTopToolBarManager1(container);
getTopToolBarManager(container);
Button lbutton = new Button(container, SWT.PUSH);
lbutton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
lbutton.setImage(JaspersoftStudioPlugin.getInstance().getImage("icons/application-sidebar-expand.png")); //$NON-NLS-1$
lbutton.setToolTipText(Messages.PreviewContainer_buttonText);
lbutton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sashform.upRestore();
}
});
sashform = new CSashForm(container, SWT.HORIZONTAL);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalSpan = 3;
sashform.setLayoutData(gd);
createLeft(parent, sashform);
createRight(sashform);
sashform.setWeights(new int[] { 40, 60 });
}
@Override
protected PreviewTopToolBarManager getTopToolBarManager1(Composite container) {
if (topToolBarManager1 == null) {
IFile file = ((IFileEditorInput) getEditorInput()).getFile();
topToolBarManager1 = new PreviewTopToolBarManager(this, container, DataAdapterManager.getDataAdapter(file));
}
return (PreviewTopToolBarManager) topToolBarManager1;
}
protected TopToolBarManagerJRPrint getTopToolBarManager(Composite container) {
if (topToolBarManager == null)
topToolBarManager = new TopToolBarManagerJRPrint(this, container) {
protected void fillToolbar(IToolBarManager tbManager) {
if (runMode.equals(RunStopAction.MODERUN_LOCAL)) {
if (pvModeAction == null)
pvModeAction = new SwitchViewsAction(container.getRightContainer(), Messages.PreviewContainer_javatitle,
true, getViewFactory());
tbManager.add(pvModeAction);
}
tbManager.add(new Separator());
}
};
return topToolBarManager;
}
/**
* Set the current preview type
*
* @param viewerKey
* key of the type to show
* @param refresh
* flag to set if the preview should also be refreshed
*/
@Override
public void setCurrentViewer(String viewerKey, boolean refresh) {
super.setCurrentViewer(viewerKey, refresh);
// Set the name of the action to align the showed name with the actual type
topToolBarManager.setActionText(viewerKey);
}
protected void createLeft(Composite parent, SashForm sf) {
Composite leftComposite = new Composite(sf, SWT.BORDER);
GridLayout layout = new GridLayout();
layout.marginWidth = 0;
layout.marginHeight = 0;
leftComposite.setLayout(layout);
leftToolbar = new LeftToolBarManager(this, leftComposite);
setupDataAdapter();
final Composite cleftcompo = new Composite(leftComposite, SWT.NONE);
cleftcompo.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE));
cleftcompo.setLayoutData(new GridData(GridData.FILL_BOTH));
cleftcompo.setLayout(new StackLayout());
Composite bottom = new Composite(leftComposite, SWT.NONE);
bottom.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
bottom.setLayout(new GridLayout(2, false));
ToolBar tb = new ToolBar(bottom, SWT.FLAT | SWT.WRAP | SWT.RIGHT);
ToolBarManager tbm = new ToolBarManager(tb);
tbm.add(new RunStopAction(this));
ToolItemContribution tireset = new ToolItemContribution("", SWT.PUSH); //$NON-NLS-1$
tbm.add(tireset);
tbm.update(true);
ToolItem toolItem = tireset.getToolItem();
toolItem.setText(Messages.PreviewContainer_resetactiontitle);
toolItem.setToolTipText(Messages.PreviewContainer_resetactiontooltip);
toolItem.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
reportControler.resetParametersToDefault();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
tbm.update(true);
getLeftContainer().populate(cleftcompo, getReportControler().createControls(cleftcompo));
getLeftContainer().switchView(null, ReportControler.FORM_PARAMETERS);
}
private ABrowserViewer jiveViewer;
@Override
protected Composite createRight(Composite parent) {
super.createRight(parent);
jiveViewer = new ABrowserViewer(rightComposite, jrContext);
return rightComposite;
}
@Override
public boolean switchRightView(APreview view, Statistics stats, MultiPageContainer container) {
reportControler.viewerChanged(view);
return super.switchRightView(view, stats, container);
}
public void runReport(final DataAdapterDescriptor myDataAdapter) {
if (isNotRunning()) {
// check if we can run the report
topToolBarManager.setEnabled(false);
topToolBarManager1.setEnabled(false);
leftToolbar.setEnabled(false);
getLeftContainer().setEnabled(false);
getLeftContainer().switchView(null, ReportControler.FORM_PARAMETERS);
// Cache the DataAdapter used for this report only if it is not null.
if (myDataAdapter != null) {
// TODO should we save the reference in the JRXML ?
dataAdapterDesc = myDataAdapter;
} else {
dataAdapterDesc = ((PreviewTopToolBarManager) topToolBarManager1).getDataSourceWidget().getSelected();
}
addPreviewModeContributeProperties();
reportControler.runReport();
}
}
private void addPreviewModeContributeProperties() {
List<PreviewModeDetails> previewDetails = JaspersoftStudioPlugin.getExtensionManager().getAllPreviewModeDetails(
Misc.nvl(this.runMode));
for (PreviewModeDetails d : previewDetails) {
Map<String, String> previewModeProperties = d.getPreviewModeProperties();
for (String pKey : previewModeProperties.keySet()) {
String pValue = previewModeProperties.get(pKey);
PreferencesUtils.storeJasperReportsProperty(pKey, pValue);
DefaultJasperReportsContext.getInstance().getProperties().put(pKey, pValue);
}
}
APreview view = null;
if (RunStopAction.MODERUN_JIVE.equals(this.runMode)) {
view = jiveViewer;
getRightContainer().switchView(null, jiveViewer);
} else if (RunStopAction.MODERUN_LOCAL.equals(this.runMode)) {
getRightContainer().switchView(null, getDefaultViewerKey());
view = getDefaultViewer();
}
refreshToolbars(view);
}
protected void refreshToolbars(final APreview view) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (topToolBarManager != null)
topToolBarManager.contributeItems(view);
}
});
}
@Override
public void setNotRunning(boolean stoprun) {
super.setNotRunning(stoprun);
if (stoprun) {
getLeftContainer().setEnabled(true);
leftToolbar.setEnabled(true);
}
isRunDirty = false;
}
public void showParameters(boolean showprm) {
if (showprm)
sashform.upRestore();
else
sashform.upHide();
}
private ReportControler reportControler;
public ReportControler getReportControler() {
if (reportControler == null) {
reportControler = new ReportControler(this, jrContext);
}
return reportControler;
}
protected boolean isRunDirty = true;
public void setRunDirty(boolean isRunDirty) {
this.isRunDirty = isRunDirty;
}
public void setJasperDesign(final JasperReportsConfiguration jConfig) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Thread.currentThread().setContextClassLoader(jrContext.getClassLoader());
getReportControler().setJrContext(jConfig);
setupDataAdapter();
if (isRunDirty || getJasperPrint() == null)
runReport(dataAdapterDesc);
isRunDirty = false;
}
});
}
private void setupDataAdapter() {
JasperDesign jd = getReportControler().getJrContext().getJasperDesign();
PreviewTopToolBarManager pt = (PreviewTopToolBarManager) topToolBarManager1;
if (pt != null && jd != null) {
String strda = jd.getProperty(DataQueryAdapters.DEFAULT_DATAADAPTER);
if (strda != null)
pt.setDataAdapters(strda);
}
}
private DataAdapterDescriptor dataAdapterDesc;
public DataAdapterDescriptor getDataAdapterDesc() {
return dataAdapterDesc;
}
private String runMode = RunStopAction.MODERUN_LOCAL;
public void setMode(String mode) {
this.runMode = mode;
if (mode.equals(RunStopAction.MODERUN_JIVE)) {
getRightContainer().switchView(null, jiveViewer);
} else if (mode.equals(RunStopAction.MODERUN_LOCAL)) {
getRightContainer().switchView(null, getDefaultViewerKey());
}
}
public String getMode() {
return runMode;
}
public ABrowserViewer getJiveViewer() {
return jiveViewer;
}
@Override
public void runReport() {
runReport(null);
}
/**
* Set the dirty flag of the preview area
*/
public void setDirty(boolean dirty) {
this.isDirty = dirty;
if (dirty)
isRunDirty = true;
}
}
| OpenSoftwareSolutions/PDFReporter-Studio | com.jaspersoft.studio/src/com/jaspersoft/studio/editor/preview/PreviewContainer.java | Java | lgpl-3.0 | 15,646 |
/*
* Created on 2006-09-01
*
* @author M.Olszewski
*/
package net.java.dante.algorithms;
import net.java.dante.algorithms.data.WeaponData;
import net.java.dante.sim.data.object.ObjectSize;
import net.java.dante.sim.data.template.types.WeaponTemplateData;
/**
* Implementation of {@link net.java.dante.algorithms.data.WeaponData} interface.
*
* @author M.Olszewski
*/
class WeaponDataImpl implements WeaponData
{
/** This weapon's template data. */
private WeaponTemplateData weaponData;
/**
* Creates instance of {@link WeaponDataImpl} class.
*
* @param weaponTemplateData - this weapon's template data.
*/
WeaponDataImpl(WeaponTemplateData weaponTemplateData)
{
if (weaponTemplateData == null)
{
throw new NullPointerException("Specified weaponTemplateData is null!");
}
weaponData = weaponTemplateData;
}
/**
* @see net.java.dante.algorithms.data.WeaponData#getExplosionRange()
*/
public double getExplosionRange()
{
return weaponData.getExplosionRange();
}
/**
* @see net.java.dante.algorithms.data.WeaponData#getMaxDamage()
*/
public int getMaxDamage()
{
return weaponData.getMaxDamage();
}
/**
* @see net.java.dante.algorithms.data.WeaponData#getMaxSpeed()
*/
public double getMaxSpeed()
{
return weaponData.getMaxSpeed();
}
/**
* @see net.java.dante.algorithms.data.WeaponData#getMinDamage()
*/
public int getMinDamage()
{
return weaponData.getMinDamage();
}
/**
* @see net.java.dante.algorithms.data.WeaponData#getProjectileSize()
*/
public ObjectSize getProjectileSize()
{
return weaponData.getProjectileSize();
}
/**
* @see net.java.dante.algorithms.data.WeaponData#getRange()
*/
public double getRange()
{
return weaponData.getRange();
}
/**
* @see net.java.dante.algorithms.data.WeaponData#getReloadTime()
*/
public long getReloadTime()
{
return weaponData.getReloadTime();
}
} | molszewski/dante | module/AlgorithmsFramework/src/net/java/dante/algorithms/WeaponDataImpl.java | Java | lgpl-3.0 | 1,983 |
import {IDOC_STATE} from 'idoc/idoc-constants';
// Gets any prefix:uuid until ?, # or / is matched
const INSTANCE_ID_REGEX = new RegExp('([a-z]+:[^?#/]+)', 'g');
export class UrlUtils {
/**
* Searches for an a parameter in a URL.
*
* @param url url to process
* @param name name of the parameter
* @returns {string} value of the parameter or null if missing
*/
static getParameter(url, name) {
let result = UrlUtils.getParameterArray(url, name);
return result instanceof Array && result.length > 0 ? result[0] : null;
}
/**
* @param url
* @param name
* @returns {*} an array with URL parameters values (multiple parameters with the same name) or undefined
*/
static getParameterArray(url, name) {
let decodedUrl = decodeURIComponent(url);
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
let regex = new RegExp('[\\?&]' + name + '=([^&#]*)', 'g');
let results, match;
while ((match = regex.exec(decodedUrl)) !== null) {
if (results === undefined) {
results = [];
}
results.push(decodeURIComponent(match[1].replace(/\+/g, ' ')));
}
return results;
}
static getParamSeparator(url) {
return url.indexOf('?') !== -1 ? '&' : '?';
}
/**
* Extracts url fragment from given url if any. The url is decoded first.
*
* @param url
* @returns The url fragment string or empty string if no fragment is found.
*/
static getUrlFragment(url) {
let hash = url.replace('/#', '');
hash = decodeURIComponent(hash);
hash = hash.indexOf('#') !== -1 ? hash.slice(hash.indexOf('#') + 1) : '';
return hash;
}
/**
* Extract instance identifier from url by specific pattern.
*
* @returns instance identifier or null
*/
static getIdFromUrl(url) {
if (!url) {
return null;
}
var decodedUrl = decodeURIComponent(url);
var results = decodedUrl.match(INSTANCE_ID_REGEX);
// Returns the last match (if host:port is matched too)
return results === null ? null : results[results.length - 1];
}
static buildIdocUrl(instanceId, tabId = '', params = {}) {
if (!instanceId) {
throw Error('Instance id is required!');
}
let url = `/#/${IDOC_STATE}/${instanceId}`;
let paramsLen = Object.keys(params).length;
if (paramsLen > 0) {
url += '?';
Object.keys(params).forEach((key) => {
url += `${key}=${params[key]}&`;
});
url = url.substring(0, url.length - 1);
}
if (tabId) {
url += `#${tabId}`;
}
return url;
}
static appendQueryParam(url, param, value) {
let querySeparator = UrlUtils.getParamSeparator(url);
return `${url}${querySeparator}${param}=${value}`;
}
/**
* Removes query param from url along with its value, if the param is available.
*
* @param window the window object, could be the global window or an adapter
* @param paramName name of the query param that will be removed
*/
static removeQueryParam(window, paramName) {
let url = window.location.href;
if (url.indexOf(paramName + '=') !== -1) {
let regex = new RegExp('[?&]{0,1}' + paramName + '=[^&#]+');
let replaced = url.replace(regex, '');
UrlUtils.replaceUrl(window, replaced);
}
}
/**
* Replaces the current url with given one without making redirect.
*
* @param window the window object, could be the global window or an adapter
* @param url that will be set
*/
static replaceUrl(window, url) {
window.history.replaceState({}, '', url);
}
} | SirmaITT/conservation-space-1.7.0 | docker/sep-ui/src/common/url-utils.js | JavaScript | lgpl-3.0 | 3,561 |
/*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer 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 Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package hmi.faceanimationui.converters;
public interface ActivationListener
{
void activationChanged(float activation);
} | ArticulatedSocialAgentsPlatform/HmiCore | HmiFaceAnimationUI/src/hmi/faceanimationui/converters/ActivationListener.java | Java | lgpl-3.0 | 1,141 |
import * as RDF from "rdf-js";
declare module "hdt" {
export interface SearchTermsOpts {
limit?: number;
position?: "subject" | "predicate" | "object";
prefix?: string;
subject?: string; // mutually exclusive with prefix and prioritized
object?: string, // mutually exclusive with prefix and prioritized
}
export interface SearchLiteralsOpts {
limit?: number;
offset?: number;
}
export interface SearchLiteralsResult {
literals: RDF.Literal[];
totalCount: number;
}
export interface SearchTriplesOpts {
limit?: number;
offset?: number;
}
export interface SearchResult {
triples: RDF.Quad[];
totalCount: number;
hasExactCount: boolean;
}
export interface Document {
searchTriples(sub?: RDF.Term, pred?: RDF.Term, obj?: RDF.Term, opts?: SearchTriplesOpts): Promise<SearchResult>;
countTriples(sub?: RDF.Term, pred?: RDF.Term, obj?: RDF.Term): Promise<SearchResult>;
searchLiterals(substring: string, opts?: SearchLiteralsOpts): Promise<SearchLiteralsResult>;
searchTerms(opts?: SearchTermsOpts): Promise<string[]>;
close(): Promise<void>;
readHeader(): Promise<string>;
changeHeader(triples:string, outputFile:string): Promise<Document>;
}
export function fromFile(filename: string, opts?: { dataFactory?: RDF.DataFactory }): Promise<Document>;
}
| RubenVerborgh/HDT-Node | lib/hdt.d.ts | TypeScript | lgpl-3.0 | 1,362 |
#Importing helper class for RBPRM
from hpp.corbaserver.rbprm.rbprmbuilder import Builder
from hpp.corbaserver.rbprm.rbprmfullbody import FullBody
from hpp.corbaserver.rbprm.problem_solver import ProblemSolver
from hpp.gepetto import Viewer
#reference pose for hyq
from hyq_ref_pose import hyq_ref
from hpp.corbaserver.rbprm.state_alg import *
from numpy import array
#calling script darpa_hyq_path to compute root path
import mount_hyq_path as tp
from os import environ
ins_dir = environ['DEVEL_DIR']
db_dir = ins_dir+"/install/share/hyq-rbprm/database/hyq_"
from hpp.corbaserver import Client
packageName = "hyq_description"
meshPackageName = "hyq_description"
rootJointType = "freeflyer"
# Information to retrieve urdf and srdf files.
urdfName = "hyq"
urdfSuffix = ""
srdfSuffix = ""
# This time we load the full body model of HyQ
fullBody = FullBody ()
fullBody.loadFullBodyModel(urdfName, rootJointType, meshPackageName, packageName, urdfSuffix, srdfSuffix)
fullBody.setJointBounds ("base_joint_xyz", [-4,6, -1, 1, 0.3, 2.5])
# Setting a number of sample configurations used
nbSamples = 20000
ps = tp.ProblemSolver(fullBody)
r = tp.Viewer (ps, viewerClient=tp.r.client)
rootName = 'base_joint_xyz'
cType = "_3_DOF"
rLegId = 'rfleg'
rLeg = 'rf_haa_joint'
rfoot = 'rf_foot_joint'
offset = [0.,-0.021,0.]
normal = [0,1,0]
legx = 0.02; legy = 0.02
def addLimbDb(limbId, heuristicName, loadValues = True, disableEffectorCollision = False):
fullBody.addLimbDatabase(str(db_dir+limbId+'.db'), limbId, heuristicName,loadValues, disableEffectorCollision)
fullBody.addLimb(rLegId,rLeg,rfoot,offset,normal, legx, legy, nbSamples, "jointlimits", 0.1, cType)
lLegId = 'lhleg'
lLeg = 'lh_haa_joint'
lfoot = 'lh_foot_joint'
fullBody.addLimb(lLegId,lLeg,lfoot,offset,normal, legx, legy, nbSamples, "jointlimits", 0.05, cType)
#~
rarmId = 'rhleg'
rarm = 'rh_haa_joint'
rHand = 'rh_foot_joint'
fullBody.addLimb(rarmId,rarm,rHand,offset,normal, legx, legy, nbSamples, "jointlimits", 0.05, cType)
larmId = 'lfleg'
larm = 'lf_haa_joint'
lHand = 'lf_foot_joint'
fullBody.addLimb(larmId,larm,lHand,offset,normal, legx, legy, nbSamples, "jointlimits", 0.05, cType)
fullBody.runLimbSampleAnalysis(rLegId, "jointLimitsDistance", True)
fullBody.runLimbSampleAnalysis(lLegId, "jointLimitsDistance", True)
fullBody.runLimbSampleAnalysis(rarmId, "jointLimitsDistance", True)
fullBody.runLimbSampleAnalysis(larmId, "jointLimitsDistance", True)
#~ q_init = hyq_ref[:]; q_init[0:7] = tp.q_init[0:7];
#~ q_goal = hyq_ref[:]; q_goal[0:7] = tp.q_goal[0:7];
q_init = hyq_ref[:]; q_init[0:7] = tp.q_init[0:7]; q_init[2]=hyq_ref[2]+0.02
q_goal = hyq_ref[:]; q_goal[0:7] = tp.q_goal[0:7]; q_init[2]=hyq_ref[2]+0.02
# Randomly generating a contact configuration at q_init
#~ fullBody.setCurrentConfig (q_init)
#~ q_init = fullBody.generateContacts(q_init, [0,0,1])
# Randomly generating a contact configuration at q_end
#~ fullBody.setCurrentConfig (q_goal)
#~ q_goal = fullBody.generateContacts(q_goal, [0,0,1])
# specifying the full body configurations as start and goal state of the problem
fullBody.setStartState(q_init,[rLegId,lLegId,rarmId,larmId])
fullBody.setEndState(q_goal,[rLegId,lLegId,rarmId,larmId])
#~ fullBody.setStartState(q_init,[rLegId,lLegId,rarmId])
#~ fullBody.setEndState(q_goal,[rLegId,lLegId,rarmId])
r(q_init)
configs = []
from hpp.gepetto import PathPlayer
pp = PathPlayer (fullBody.client.basic, r)
from hpp.corbaserver.rbprm.tools.cwc_trajectory_helper import step, clean,stats, saveAllData, play_traj
#~ limbsCOMConstraints = { rLegId : {'file': "hyq/"+rLegId+"_com.ineq", 'effector' : rfoot},
#~ lLegId : {'file': "hyq/"+lLegId+"_com.ineq", 'effector' : lfoot},
#~ rarmId : {'file': "hyq/"+rarmId+"_com.ineq", 'effector' : rHand},
#~ larmId : {'file': "hyq/"+larmId+"_com.ineq", 'effector' : lHand} }
limbsCOMConstraints = { rLegId : {'file': "hrp2/RL_com.ineq", 'effector' : rfoot},
lLegId : {'file': "hrp2/LL_com.ineq", 'effector' : lfoot},
rarmId : {'file': "hrp2/RA_com.ineq", 'effector' : rHand},
larmId : {'file': "hrp2/LA_com.ineq", 'effector' : lHand} }
def initConfig():
r.client.gui.setVisibility("hyq", "ON")
tp.cl.problem.selectProblem("default")
tp.r.client.gui.setVisibility("toto", "OFF")
tp.r.client.gui.setVisibility("hyq_trunk_large", "OFF")
r(q_init)
def endConfig():
r.client.gui.setVisibility("hyq", "ON")
tp.cl.problem.selectProblem("default")
tp.r.client.gui.setVisibility("toto", "OFF")
tp.r.client.gui.setVisibility("hyq_trunk_large", "OFF")
r(q_goal)
def rootPath():
r.client.gui.setVisibility("hyq", "OFF")
tp.cl.problem.selectProblem("rbprm_path")
tp.r.client.gui.setVisibility("toto", "OFF")
r.client.gui.setVisibility("hyq", "OFF")
tp.r.client.gui.setVisibility("hyq_trunk_large", "ON")
tp.pp(0)
tp.r.client.gui.setVisibility("hyq_trunk_large", "OFF")
r.client.gui.setVisibility("hyq", "ON")
tp.cl.problem.selectProblem("default")
def genPlan(stepsize=0.06):
tp.cl.problem.selectProblem("default")
r.client.gui.setVisibility("hyq", "ON")
tp.r.client.gui.setVisibility("toto", "OFF")
tp.r.client.gui.setVisibility("hyq_trunk_large", "OFF")
global configs
start = time.clock()
configs = fullBody.interpolate(stepsize, 5, 5, True)
end = time.clock()
print "Contact plan generated in " + str(end-start) + "seconds"
def contactPlan(step = 0.5):
r.client.gui.setVisibility("hyq", "ON")
tp.cl.problem.selectProblem("default")
tp.r.client.gui.setVisibility("toto", "OFF")
tp.r.client.gui.setVisibility("hyq_trunk_large", "OFF")
global configs
for i in range(0,len(configs)):
r(configs[i]);
time.sleep(step)
def a():
print "initial configuration"
initConfig()
def b():
print "end configuration"
endConfig()
def c():
print "displaying root path"
rootPath()
def d(step=0.06):
print "computing contact plan"
genPlan(step)
def e(step = 0.5):
print "displaying contact plan"
contactPlan(step)
from bezier_traj import go0, go2, init_bezier_traj, reset
from hpp.corbaserver.rbprm.tools.cwc_trajectory_helper import play_trajectory
import time
from hpp.corbaserver.rbprm.rbprmstate import State
from hpp.corbaserver.rbprm.state_alg import addNewContact, isContactReachable, closestTransform, removeContact, addNewContactIfReachable, projectToFeasibleCom
path = []
def sc(ec):
pass
def pl(iid = None):
global path
if iid == None:
iid = len(path) -1
play_trajectory(fullBody,pp,path[iid])
def plc(ctx = 0, iid = None):
sc(ctx)
pl(iid)
def go():
return go0(states, mu=0.6,num_optim=2, use_kin = context == 0)
def plall(first = 0):
global path
sc(first)
for pId in range(len(path)):
play_trajectory(fullBody,pp,path[pId])
from pickle import load, dump
def save(fname):
sc(0)
all_data=[[],[]]
global states
for s in states:
all_data[0]+=[[s.q(), s.getLimbsInContact()]]
f = open(fname, "w")
dump(all_data,f)
f.close()
def load_save(fname):
f = open(fname, "r+")
all_data = load (f)
f.close()
sc(0)
global states
states = []
#~ for i in range(0,len(all_data[0]),2):
#~ print "q",all_data[0][i]
#~ print "lic",all_data[0][i+1]
#~ states+=[State(fullBody,q=all_data[0][i], limbsIncontact = all_data[0][i+1]) ]
for _, s in enumerate(all_data[0]):
states+=[State(fullBody,q=s[0], limbsIncontact = s[1]) ]
r(states[0].q())
def onepath(ol, ctxt=1, nopt=1, mu=1, effector = False):
reset()
sc(ctxt)
global path
global states
print "ctxt", ctxt
print "q", len(states[ol+1].q())
s = max(norm(array(states[ol+1].q()) - array(states[ol].q())), 1.) * 0.4
print "s",s
if(ol > len(path) -1):
path += [go0([states[ol],states[ol+1]], num_optim=nopt, mu=mu, use_kin = False, s=s, effector = effector)]
else:
path[ol]=go0([states[ol],states[ol+1]], num_optim=nopt, mu=mu, use_kin = False, s=s, effector = effector)
all_paths[ctxt] = path
def onepath2(states_subset, ctxt=1, nopt=1, mu=1, effector = False):
reset()
sc(ctxt)
global path
global states
#~ print "ctxt", ctxt
#~ print "q", len(states[ol+1].q())
#~ s = max(norm(array(states_subset[1].q()) - array(states_subset[0].q())), 1.) * 0.4
#~ print "s",s
#~ if(ol > len(path) -1):
path = all_paths[ctxt][:]
path += [go2(states_subset, num_optim=nopt, mu=mu, use_kin = False, s=None, effector = effector)]
#~ else:
#~ path[ol]=go2(states_subset, num_optim=nopt, mu=mu, use_kin = False, s=s, effector = effector)
all_paths[ctxt] = path
def save_paths(fname):
f = open(fname, "w")
dump(all_paths,f)
f.close()
#now try with latest paths
global all_path
global path
sc(0)
all_paths[0] = path[:]
f = open(fname+"all", "w")
dump(all_paths,f)
f.close()
def load_paths(fname):
f = open(fname, "r")
global all_paths
all_paths = load (f)
f.close()
sc(0)
global path
path = all_paths[0][:]
def sh(ctxt, i):
sc(ctxt)
r(states[i].q())
def lc():
load_save("19_06_s")
load_paths("19_06_p")
#~ save_paths("19_06_p_save")
save("19_06_s_save")
def sac():
save("19_06_s")
save_paths("19_06_p")
init_bezier_traj(fullBody, r, pp, configs, limbsCOMConstraints)
all_paths = [[],[]]
from hpp.corbaserver.rbprm.state_alg import *
#~ d(0.07);e(0.01)
i=0
#~ d(0.09); e(0.01); states = planToStates(fullBody,configs)
#~ lc()
#~ le = min(38, len(states)-10)
#~ onepath2(states [0:-1],nopt=3,mu=0.99,effector=True)
#~ e(0.01)
| pFernbach/hpp-rbprm-corba | script/scenarios/sandbox/siggraph_asia/chair/mount_hyq.py | Python | lgpl-3.0 | 9,667 |
# -*- coding: utf-8 -*-
#
# Copyright 2009: Johannes Raggam, BlueDynamics Alliance
# http://bluedynamics.com
# GNU Lesser General Public License Version 2 or later
__author__ = """Johannes Raggam <johannes@raggam.co.at>"""
__docformat__ = 'plaintext'
from setuptools import setup, find_packages
import sys, os
version = '1.0'
shortdesc ="Test models and executions for activities"
longdesc = open(os.path.join(os.path.dirname(__file__), 'README.txt')).read()
longdesc += open(os.path.join(os.path.dirname(__file__), 'LICENSE.txt')).read()
setup(name='activities.test.hospital',
version=version,
description=shortdesc,
long_description=longdesc,
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Zope3',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules'
], # Get strings from http://pypi.python.org/pypi?:action=list_classifiers
keywords='UML Activities runtime',
author='Johannes Raggam',
author_email='johannes@raggam.co.at',
url='',
license='LGPL',
packages = find_packages('src'),
package_dir = {'': 'src'},
namespace_packages=['activities','activities.test'],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
# -*- Extra requirements: -*
'activities.metamodel',
'activities.runtime',
],
extras_require={
'test': [
'interlude',
]
},
entry_points="""
# -*- Entry points: -*-
""",
)
| bluedynamics/activities.test.hospital | setup.py | Python | lgpl-3.0 | 1,827 |
<?php
namespace pocketmine\event\block;
use pocketmine\block\Block;
use pocketmine\event\block\BlockEvent;
use pocketmine\event\Cancellable;
use pocketmine\item\Item;
use pocketmine\Player;
//TODO:call this event somewhere?
class ItemFrameDropItemEvent extends BlockEvent implements Cancellable{
public static $handlerList = null;
/** @var \pocketmine\Player */
private $player;
/** @var \pocketmine\item\Item */
private $item;
private $dropChance;
/**
* @param Block $block
* @param Player $player
* @param Item $dropItem
* @param Float $dropChance
*/
public function __construct(Block $block, Player $player, Item $dropItem, $dropChance){
parent::__construct($block);
$this->player = $player;
$this->item = $dropItem;
$this->dropChance = (float) $dropChance;
}
/**
* @return Player
*/
public function getPlayer(){
return $this->player;
}
/**
* @return Item
*/
public function getDropItem(){
return $this->item;
}
public function setDropItem(Item $item){
$this->item = $item;
}
/**
* @return Float
*/
public function getItemDropChance(){
return $this->dropChance;
}
public function setItemDropChance($chance){
$this->dropChance = (float) $chance;
}
} | ClearSkyTeam/ClearSky | src/pocketmine/event/block/ItemFrameDropItemEvent.php | PHP | lgpl-3.0 | 1,233 |
package buildcraft.core;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import buildcraft.core.lib.engines.BlockEngineBase;
import buildcraft.core.lib.engines.TileEngineBase;
public class BlockEngine extends BlockEngineBase {
private final ArrayList<Class<? extends TileEngineBase>> engineTiles;
private final ArrayList<String> names;
public BlockEngine() {
super();
setBlockName("engineBlock");
engineTiles = new ArrayList<Class<? extends TileEngineBase>>(16);
names = new ArrayList<String>(16);
}
@Override
public String getUnlocalizedName(int metadata) {
return names.get(metadata % names.size());
}
public void registerTile(Class<? extends TileEngineBase> engineTile, String name) {
engineTiles.add(engineTile);
names.add(name);
}
@Override
public TileEntity createTileEntity(World world, int metadata) {
try {
return engineTiles.get(metadata % engineTiles.size()).newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) {
for (int i = 0; i < engineTiles.size(); i++) {
itemList.add(new ItemStack(this, 1, i));
}
}
public int getEngineCount() {
return engineTiles.size();
}
}
| hea3ven/BuildCraft | common/buildcraft/core/BlockEngine.java | Java | lgpl-3.0 | 1,503 |
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Signum.Entities.DynamicQuery;
using Signum.Entities.Chart;
using Signum.Entities;
using Signum.Entities.Isolation;
namespace Signum.Services
{
[ServiceContract]
public interface IIsolationServer
{
[OperationContract, NetDataContract]
Lite<IsolationEntity> GetOnlyIsolation(List<Lite<Entity>> selectedEntities);
}
}
| mapacheL/extensions | Signum.Entities.Extensions/Isolation/IIsolationServer.cs | C# | lgpl-3.0 | 489 |
// 2016-01-13T09:42+08:00
#include <iostream>
const int LEAD_NUMBERS = 12;
typedef double *Buffer[LEAD_NUMBERS];
class Data
{
public:
Data(bool cond) : cond_(cond) {}
const Buffer &GetData() const {
#if 1
// In VS2010, code below causes a syntax error:
// error C2440: 'return' : cannot convert from 'double *const *' to 'const Buffer (&)'
// Reason: cannot convert from 'double *const *' to 'const Buffer'
// There are no conversions to array types, although there are conversions to references or pointers to arrays
return cond_ ? buf0_ : buf1_;
#else
if (cond_) {
return buf0_;
} else {
return buf1_;
}
#endif
}
private:
bool cond_;
Buffer buf0_;
Buffer buf1_;
};
int main()
{
return 0;
}
| myd7349/Ongoing-Study | cpp/conditional_operator_test/conditional_operator_test.cpp | C++ | lgpl-3.0 | 823 |
package com.nath99000.toughertools.item.Weaponry;
import com.nath99000.toughertools.Reference.Names;
import com.nath99000.toughertools.item.Wrapper.ItemTT;
import com.nath99000.toughertools.item.Wrapper.UniqueTT;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import java.util.List;
public class ItemDartGun extends UniqueTT {
public ItemDartGun() {
super();
setUnlocalizedName("DartGun");
setMaxDamage(43);
this.setFull3D();
}
public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer player) {
if (!player.capabilities.isCreativeMode) {
if (player.inventory.hasItem(Items.arrow)) {
itemstack.damageItem(1, player);
world.playSoundAtEntity(player, "random.bow", 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F));
if (!world.isRemote) {
EntityArrow entityarrow = new EntityArrow(world, player, 3F);
entityarrow.setIsCritical(true);
world.spawnEntityInWorld(entityarrow);
player.inventory.consumeInventoryItem(Items.arrow);
}
return itemstack;
}
return itemstack;
} else {
world.playSoundAtEntity(player, "random.bow", 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F));
if (!world.isRemote) {
EntityArrow entityarrow = new EntityArrow(world, player, 3F);
entityarrow.setIsCritical(true);
world.spawnEntityInWorld(entityarrow);
}
}
return itemstack;
}
public void addInformation(ItemStack par1, EntityPlayer par2, List par3, boolean par4)
{
{
par3.add(Names.common);
}
}
}
| Nath99000/TougherTools | src/main/java/com/nath99000/toughertools/item/Weaponry/ItemDartGun.java | Java | lgpl-3.0 | 1,960 |
/* Mesquite source code. Copyright 1997-2009 W. Maddison and D. Maddison.
Version 2.71, September 2009.
Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code.
The commenting leaves much to be desired. Please approach this source code with the spirit of helping out.
Perhaps with your help we can be more than a few, and make Mesquite better.
Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
Mesquite's web site is http://mesquiteproject.org
This source code and its compiled class files are free and modifiable under the terms of
GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html)
*/
package mesquite.treefarm.TopologyCongruent;
/*New October 7, '08. oliver
* Modified 16 October '08 to use the built-in Tree.equalsTopology method - DRM */
import mesquite.lib.*;
import mesquite.lib.duties.*;
public class TopologyCongruent extends BooleanForTree {
OneTreeSource constraintTreeSource;
Tree constraintTree;
public boolean startJob(String arguments, Object condition, boolean hiredByName) {
constraintTreeSource = (OneTreeSource)hireEmployee(OneTreeSource.class, "One Tree Source");
if(constraintTreeSource==null){
return sorry(getName() + " couldn't start because no constraint tree was obtained.");
}
return true;
}
/*..............................................................................*/
public void calculateBoolean(Tree tree, MesquiteBoolean result, MesquiteString resultString) {
if(tree==null || result==null){
return;
}
constraintTree = constraintTreeSource.getTree(tree.getTaxa()).cloneTree();
if(constraintTree==null || constraintTree.getTaxa()!=tree.getTaxa())
return;
MesquiteBoolean isConsistent = new MesquiteBoolean(true);
isConsistent.setValue(tree.equalsTopology(constraintTree, false));
result.setValue(isConsistent.getValue());
if (resultString!=null)
if (isConsistent.getValue())
resultString.setValue("Tree congruent");
else
resultString.setValue("Tree incongruent");
}
/*..............................................................................*/
public String getName() {
return "Tree Congruent with Constraint Tree Topology";
}
/*..............................................................................*/
/** returns an explanation of what the module does.*/
public String getExplanation(){
return "Determines if tree matches topology of a given constraint tree. This module does not handle backbone constraints; all trees must have the same taxa present. For backbone constraint trees, where the constraint tree need not contain all taxa, use the 'Tree Congruent with Backbone Constraint Tree Topology' module.";
}
/*........................................................*/
public int getVersionOfFirstRelease(){
return 260;
}
/*........................................................*/
public boolean isPrerelease(){
return false;
}
}
| MesquiteProject/MesquiteArchive | releases/Mesquite2.71/Mesquite Project/Source/mesquite/treefarm/TopologyCongruent/TopologyCongruent.java | Java | lgpl-3.0 | 3,095 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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 3 of the License, or
(at your option) any later version.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "finspaceresponse.h"
#include "finspaceresponse_p.h"
#include <QDebug>
#include <QXmlStreamReader>
namespace QtAws {
namespace finspace {
/*!
* \class QtAws::finspace::finspaceResponse
* \brief The finspaceResponse class provides an interface for finspace responses.
*
* \inmodule QtAwsfinspace
*/
/*!
* Constructs a finspaceResponse object with parent \a parent.
*/
finspaceResponse::finspaceResponse(QObject * const parent)
: QtAws::Core::AwsAbstractResponse(new finspaceResponsePrivate(this), parent)
{
}
/*!
* \internal
* Constructs a finspaceResponse object with private implementation \a d,
* and parent \a parent.
*
* This overload allows derived classes to provide their own private class
* implementation that inherits from finspaceResponsePrivate.
*/
finspaceResponse::finspaceResponse(finspaceResponsePrivate * const d, QObject * const parent)
: QtAws::Core::AwsAbstractResponse(d, parent)
{
}
/*!
* \reimp
*/
void finspaceResponse::parseFailure(QIODevice &response)
{
//Q_D(finspaceResponse);
Q_UNUSED(response);
/*QXmlStreamReader xml(&response);
if (xml.readNextStartElement()) {
if (xml.name() == QLatin1String("ErrorResponse")) {
d->parseErrorResponse(xml);
} else {
qWarning() << "ignoring" << xml.name();
xml.skipCurrentElement();
}
}
setXmlError(xml);*/
}
/*!
* \class QtAws::finspace::finspaceResponsePrivate
* \brief The finspaceResponsePrivate class provides private implementation for finspaceResponse.
* \internal
*
* \inmodule QtAwsfinspace
*/
/*!
* Constructs a finspaceResponsePrivate object with public implementation \a q.
*/
finspaceResponsePrivate::finspaceResponsePrivate(
finspaceResponse * const q) : QtAws::Core::AwsAbstractResponsePrivate(q)
{
}
} // namespace finspace
} // namespace QtAws
| pcolby/libqtaws | src/finspace/finspaceresponse.cpp | C++ | lgpl-3.0 | 2,600 |
/*
* This file is part of Spoutcraft.
*
* Copyright (c) 2011 SpoutcraftDev <http://spoutcraft.org/>
* Spoutcraft is licensed under the GNU Lesser General Public License.
*
* Spoutcraft 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 3 of the License, or
* (at your option) any later version.
*
* Spoutcraft is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.spoutcraft.client.packet;
import java.util.HashMap;
public enum PacketType {
PacketKeyPress(0, PacketKeyPress.class),
PacketAirTime(1, PacketAirTime.class),
PacketSkinURL(2, PacketSkinURL.class),
PacketEntityTitle(3, PacketEntityTitle.class),
//PacketPluginReload(4, PacketPluginReload.class),
PacketRenderDistance(5, PacketRenderDistance.class),
PacketAlert(6, PacketAlert.class),
PacketPlaySound(7, PacketPlaySound.class),
PacketDownloadMusic(8, PacketDownloadMusic.class),
PacketClipboardText(9, PacketClipboardText.class),
PacketMusicChange(10, PacketMusicChange.class),
PacketWidget(11, PacketWidget.class),
PacketStopMusic(12, PacketStopMusic.class),
PacketItemName(13, PacketItemName.class),
PacketSky(14, PacketSky.class),
//PacketTexturePack(15, PacketTexturePack.class),
//PacketWorldSeed(16, PacketWorldSeed.class),
PacketNotification(17, PacketNotification.class),
PacketScreenAction(18, PacketScreenAction.class),
PacketControlAction(19, PacketControlAction.class),
//PacketCacheHashUpdate(20, PacketCacheHashUpdate.class),
PacketAllowVisualCheats(21, PacketAllowVisualCheats.class),
PacketWidgetRemove(22, PacketWidgetRemove.class),
PacketEntitySkin(23, PacketEntitySkin.class),
PacketBiomeWeather(24, PacketBiomeWeather.class),
PacketChunkRefresh(25, PacketChunkRefresh.class),
PacketOpenScreen(26, PacketOpenScreen.class),
PacketPreCacheFile(27, PacketPreCacheFile.class),
PacketCacheFile(28, PacketCacheFile.class),
PacketCacheDeleteFile(29, PacketCacheDeleteFile.class),
PacketPreCacheCompleted(30, PacketPreCacheCompleted.class),
PacketMovementModifiers(31, PacketMovementModifiers.class),
PacketSetVelocity(32, PacketSetVelocity.class),
PacketFullVersion(33, PacketFullVersion.class),
//PacketCustomId(34, PacketCustomId.class),
//PacketItemTexture(35, PacketItemTexture.class),
//PacketBlockHardness(36, PacketBlockHardness.class),
PacketOpenSignGUI(37, PacketOpenSignGUI.class),
PacketCustomBlockOverride(38, PacketCustomBlockOverride.class),
PacketCustomBlockDesign(39, PacketCustomBlockDesign.class),
//PacketUniqueId(40, PacketUniqueId.class),
PacketKeyBinding(41, PacketKeyBinding.class),
PacketBlockData(42, PacketBlockData.class),
PacketCustomMultiBlockOverride(43, PacketCustomMultiBlockOverride.class),
//PacketServerPlugins(44, PacketServerPlugins.class),
//PacketAddonData(45, PacketAddonData.class),
//PacketCustomMaterial(46, PacketCustomMaterial.class),
PacketScreenshot(47, PacketScreenshot.class),
PacketGenericItem(48, PacketGenericItem.class),
PacketGenericTool(49, PacketGenericTool.class),
PacketGenericBlock(50, PacketGenericBlock.class),
PacketCustomBlockChunkOverride(51, PacketCustomBlockChunkOverride.class),
PacketGenericFood(52, PacketGenericFood.class),
PacketEntityInformation(53, PacketEntityInformation.class),
PacketComboBox(54, PacketComboBox.class),
PacketFocusUpdate(55, PacketFocusUpdate.class),
//PacketClientAddons(56, PacketClientAddons.class),
PacketPermissionUpdate(57, PacketPermissionUpdate.class),
PacketSpawnTextEntity(58, PacketSpawnTextEntity.class),
PacketSlotClick(59, PacketSlotClick.class),
PacketWaypoint(60, PacketWaypoint.class),
PacketParticle(61, PacketParticle.class),
PacketAccessory(62, org.spoutcraft.client.player.accessories.PacketAccessory.class),
PacketValidatePrecache(63, PacketValidatePrecache.class),
PacketRequestPrecache(64, PacketRequestPrecache.class),
PacketSendPrecache(65, PacketSendPrecache.class),
PacketSendLink(66, PacketSendLink.class);
private final int id;
private final Class<? extends SpoutPacket> packetClass;
private static final HashMap<Integer, PacketType> lookupId = new HashMap<Integer, PacketType>();
PacketType(final int type, final Class<? extends SpoutPacket> packetClass) {
this.id = type;
this.packetClass = packetClass;
}
public int getId() {
return id;
}
public Class<? extends SpoutPacket> getPacketClass() {
return packetClass;
}
public static PacketType getPacketFromId(int id) {
return lookupId.get(id);
}
static {
for (PacketType packet : values()) {
lookupId.put(packet.getId(), packet);
}
}
}
| Spoutcraft/Spoutcraft | src/main/java/org/spoutcraft/client/packet/PacketType.java | Java | lgpl-3.0 | 4,986 |
<?php
require_once('app.php');
//List out all Movie Gallery
$movie_gallery_count = Count_movie_gallery(-1);
$movie_gallery_data = Select_movie_gallery(-1);
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<movies>\n";
if (($movie_gallery_count) > 0) { ?>
<?php for ($i = 0; $i <= ($movie_gallery_count - 1); $i++) {
echo " <movie>\n";
echo " <id>".$movie_gallery_data['id'][$i]."</id>\n";
echo " <title>".$movie_gallery_data['title'][$i]."</title>\n";
echo " <date>".$movie_gallery_data['cr_time_long'][$i]."</date>\n";
echo " <date_str>".$movie_gallery_data['cr_time'][$i]."</date_str>\n";
echo " <thumb>".$movie_gallery_data['thumb'][$i]."</thumb>\n";
echo " <link>".$movie_gallery_data['link'][$i]."</link>\n";
echo " <aspect>\n";
echo " <option>".$movie_gallery_data['aspect_option'][$i]."</option>\n";
echo " <width>".$movie_gallery_data['aspect_width'][$i]."</width>\n";
echo " <height>".$movie_gallery_data['aspect_height'][$i]."</height>\n";
echo " </aspect>\n";
echo " </movie>\n";
}
}
echo "</movies>\n";
?> | Francis-Underwood/eNotice-CMS | inotice-cms/xml/chi/movgallery.php | PHP | lgpl-3.0 | 1,077 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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 3 of the License, or
(at your option) any later version.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "describereplicationtaskassessmentrunsresponse.h"
#include "describereplicationtaskassessmentrunsresponse_p.h"
#include <QDebug>
#include <QNetworkReply>
#include <QXmlStreamReader>
namespace QtAws {
namespace DatabaseMigrationService {
/*!
* \class QtAws::DatabaseMigrationService::DescribeReplicationTaskAssessmentRunsResponse
* \brief The DescribeReplicationTaskAssessmentRunsResponse class provides an interace for DatabaseMigrationService DescribeReplicationTaskAssessmentRuns responses.
*
* \inmodule QtAwsDatabaseMigrationService
*
* <fullname>AWS Database Migration Service</fullname>
*
* AWS Database Migration Service (AWS DMS) can migrate your data to and from the most widely used commercial and
* open-source databases such as Oracle, PostgreSQL, Microsoft SQL Server, Amazon Redshift, MariaDB, Amazon Aurora, MySQL,
* and SAP Adaptive Server Enterprise (ASE). The service supports homogeneous migrations such as Oracle to Oracle, as well
* as heterogeneous migrations between different database platforms, such as Oracle to MySQL or SQL Server to
*
* PostgreSQL>
*
* For more information about AWS DMS, see <a href="https://docs.aws.amazon.com/dms/latest/userguide/Welcome.html">What Is
* AWS Database Migration Service?</a> in the <i>AWS Database Migration User Guide.</i>
*
* \sa DatabaseMigrationServiceClient::describeReplicationTaskAssessmentRuns
*/
/*!
* Constructs a DescribeReplicationTaskAssessmentRunsResponse object for \a reply to \a request, with parent \a parent.
*/
DescribeReplicationTaskAssessmentRunsResponse::DescribeReplicationTaskAssessmentRunsResponse(
const DescribeReplicationTaskAssessmentRunsRequest &request,
QNetworkReply * const reply,
QObject * const parent)
: DatabaseMigrationServiceResponse(new DescribeReplicationTaskAssessmentRunsResponsePrivate(this), parent)
{
setRequest(new DescribeReplicationTaskAssessmentRunsRequest(request));
setReply(reply);
}
/*!
* \reimp
*/
const DescribeReplicationTaskAssessmentRunsRequest * DescribeReplicationTaskAssessmentRunsResponse::request() const
{
Q_D(const DescribeReplicationTaskAssessmentRunsResponse);
return static_cast<const DescribeReplicationTaskAssessmentRunsRequest *>(d->request);
}
/*!
* \reimp
* Parses a successful DatabaseMigrationService DescribeReplicationTaskAssessmentRuns \a response.
*/
void DescribeReplicationTaskAssessmentRunsResponse::parseSuccess(QIODevice &response)
{
//Q_D(DescribeReplicationTaskAssessmentRunsResponse);
QXmlStreamReader xml(&response);
/// @todo
}
/*!
* \class QtAws::DatabaseMigrationService::DescribeReplicationTaskAssessmentRunsResponsePrivate
* \brief The DescribeReplicationTaskAssessmentRunsResponsePrivate class provides private implementation for DescribeReplicationTaskAssessmentRunsResponse.
* \internal
*
* \inmodule QtAwsDatabaseMigrationService
*/
/*!
* Constructs a DescribeReplicationTaskAssessmentRunsResponsePrivate object with public implementation \a q.
*/
DescribeReplicationTaskAssessmentRunsResponsePrivate::DescribeReplicationTaskAssessmentRunsResponsePrivate(
DescribeReplicationTaskAssessmentRunsResponse * const q) : DatabaseMigrationServiceResponsePrivate(q)
{
}
/*!
* Parses a DatabaseMigrationService DescribeReplicationTaskAssessmentRuns response element from \a xml.
*/
void DescribeReplicationTaskAssessmentRunsResponsePrivate::parseDescribeReplicationTaskAssessmentRunsResponse(QXmlStreamReader &xml)
{
Q_ASSERT(xml.name() == QLatin1String("DescribeReplicationTaskAssessmentRunsResponse"));
Q_UNUSED(xml) ///< @todo
}
} // namespace DatabaseMigrationService
} // namespace QtAws
| pcolby/libqtaws | src/databasemigrationservice/describereplicationtaskassessmentrunsresponse.cpp | C++ | lgpl-3.0 | 4,414 |
๏ปฟ/*
xWinForms ยฉ 2007-2009
Eric Grossinger - ericgrossinger@gmail.com
*/
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace xWinFormsLib
{
class Math
{
public static float GetAngleFrom2DVectors(Vector2 OriginLoc, Vector2 TargetLoc, bool bRadian)
{
double Angle;
float xDist = OriginLoc.X - TargetLoc.X;
float yDist = OriginLoc.Y - TargetLoc.Y;
double norm = System.Math.Abs(xDist) + System.Math.Abs(yDist);
if ((xDist >= 0) & (yDist >= 0))
{
//Lower Right Quadran
Angle = 90 * (yDist / norm) + 270;
}
else if ((xDist <= 0) && (yDist >= 0))
{
//Lower Left Quadran
Angle = -90 * (yDist / norm) + 90;
}
else if (((xDist) <= 0) && ((yDist) <= 0))
{
//Upper Left Quadran
Angle = 90 * (xDist / norm) + 180;
}
else
{
//Upper Right Quadran
Angle = 90 * (xDist / norm) + 180;
}
if (bRadian)
Angle = MathHelper.ToRadians(System.Convert.ToSingle(Angle));
return System.Convert.ToSingle(Angle);
}
}
}
| Akhrameev/Diplom_last_version | xWinFormsLib/Core/Math.cs | C# | lgpl-3.0 | 1,329 |
/*! Subsample.cpp
*
* Copyright (C) 2011 Alastair Quadros.
*
* This file is part of LaserLib.
*
* LaserLib 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 3 of the License, or (at your option)
* any later version.
*
* LaserLib 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 LaserLib. If not, see <http://www.gnu.org/licenses/>.
*
* \author Alastair Quadros
* \date 31-05-2011
*/
#include "Subsample.h"
void SubSampleEven( Selector& sel, int nTotal, std::vector<int>& sample )
{
std::vector< bool > isDone; //referenced by global point id
isDone.assign(nTotal, false);
sample.reserve(nTotal);
for( unsigned int i=0 ; i<nTotal ; i++ )
{
if( isDone[i] )
continue;
std::vector<int>& neighs = sel.SelectRegion(i);
sample.push_back(i);
for( unsigned int j=0 ; j<neighs.size() ; j++ )
{
isDone[neighs[j]] = true;
}
}
}
void SubSampleKeysEvenly( Selector& sel, int nTotal, Vect<int>::type& keys, std::vector<int>& sample )
{
std::vector< bool > isDone; //referenced by global point id
isDone.assign(nTotal, false);
sample.reserve(nTotal);
for( unsigned int i=0 ; i<keys.size() ; i++ )
{
int id = keys(i);
if( isDone[id] )
continue;
std::vector<int>& neighs = sel.SelectRegion(id);
//if( neighs.size() == 0 )
// continue;
sample.push_back(id);
for( unsigned int j=0 ; j<neighs.size() ; j++ )
{
isDone[neighs[j]] = true;
}
}
}
void LocalMax( Selector& sel, int nTotal, Vect<int>::type& items, Vect<double>::type& val, Vect<double>::type maxBy )
{
std::vector< bool > isDone; //referenced by global point id
isDone.assign(nTotal, false);
for( int i=0 ; i<items.size() ; i++ )
{
unsigned int id = items(i);
if( isDone[id] )
continue;
std::vector<int>& neighs = sel.SelectRegion(id);
if( neighs.size() == 0 )
continue;
//find if its max
bool isMax = true;
for( unsigned int j=0 ; j<neighs.size() ; j++ )
{
if( neighs[j] == id ){ continue; }
if( val(id) <= val(neighs[j]) )
{
isMax = false;
break;
}
}
if( isMax )
{
//mark isDone so we don't do these neighbours.
//average amount val is above its neighbours.
double sum=0.0;
for( unsigned int j=0 ; j<neighs.size() ; j++ )
{
if( neighs[j] == id ){ continue; }
isDone[neighs[j]] = true;
sum += val(id) - val(neighs[j]);
}
maxBy(id) = sum/(neighs.size()-1);
}
neighs.clear();
}
}
/*
Process: select a region, set all to 'done', if points have very different surface normals, set them to 'kept'.
Do not select regions about 'done' points. Finally, find the 'kept' status of the 'items' in question, store
kept ones in 'sample.'
if the dot product of the two surface normals is below 'thresh' (angle between them is large enough), keep them.
*/
void SubsampleBySurfNorm( Selector& sel, int nTotal, Vect<int>::type& items, Mat3<double>::type& sn,
double thresh, std::vector<int>& sample )
{
std::vector<bool> isKept, isDone;
isKept.assign(nTotal, false);
isDone.assign(nTotal, false);
for( int i=0 ; i<items.size() ; i++ )
{
unsigned int id = items.coeff(i);
if( isDone[id] )
continue;
std::vector<int>& neighs = sel.SelectRegion(id);
Eigen::MatrixBase< Mat3<double>::type >::RowXpr snId = sn.row(id);
isKept[id] = true;
for( unsigned int j=0 ; j<neighs.size() ; j++ )
{
//if surf norm is similar to point 'id', remove.
int nid = neighs[j];
isDone[nid] = true;
double dotP = sn.row(nid).dot( snId );
if( dotP < thresh )
isKept[nid] = true;
}
neighs.clear();
}
//only care about 'items'
for( int i=0 ; i<items.size() ; i++ )
{
unsigned int id = items.coeff(i);
if( isKept[id] )
sample.push_back(id);
}
}
| aquad/laserlib | DataStore/Subsample.cpp | C++ | lgpl-3.0 | 4,732 |
๏ปฟusing System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ExtractTestJson")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ExtractTestJson")]
[assembly: AssemblyCopyright("Copyright ยฉ 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("276dc67e-7892-4ea2-90ec-4a28f84e07a2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| rnicoll/ncrypto-currency-exchange | ExtractTestJson/Properties/AssemblyInfo.cs | C# | lgpl-3.0 | 1,406 |
<?php
namespace ICS;
/**
* ICSObjects
*
* @author Olivarรจs Georges <dev@olivares-georges.net>
* @contributor @zapad (Github)
*
*/
abstract class Objects implements iObjects, \IteratorAggregate {
protected $children;
protected $content;
protected $parsers = array();
protected $extended;
public function __construct($content = null) {
$this->content = trim($content);
}
public function getIterator() {
return new \ArrayObject((array) $this->children);
}
public function getChildren() {
return (array) $this->children;
}
public function getChild($index) {
return $this->children[$index];
}
/**
* Setup header field from extended set
*/
public function setExtended($field, $value) {
$this->extended[$field] = $value;
}
/**
* Get array of all extended fields, available in current ICS file
*/
public function getExtended() {
if (! $this->extended)
$this->extended = array();
return $this->extended;
}
public function getMetas() {
$metas = array();
$rc = new \ReflectionClass($this);
foreach( $rc->getProperties() as $var )
switch($var->getName()) {
case 'children':
case 'parsers':
case 'content':
break;
case 'extended':
$metas = array_merge($metas, $this->getExtended());
break;
default;
$var->setAccessible(true);
$metas[$var->getName()] = $var->getValue($this);
break;
}
return $metas;
}
public function addChildren($child) {
if( is_string($child) ) {
$class = 'ICS\\Element\\' . $child;
if( class_exists($class) )
$child = new $class();
}
if( !is_array($this->children) )
throw new Exception('You can\'t attach children into this node');
if( !($child instanceof Objects) )
throw new Exception('Argument 1 passed to ICSObjects::addChildren() must be an instance of ICSObjects');
$this->children[] = $child;
return $child;
}
public function parse() {
$content = $this->content;
foreach( (array) $this->parsers as $parser ) {
$parser = 'ICS\\Element\\' . $parser;
if( !is_subclass_of($parser, 'ICS\\Objects') )
throw new Exception(sprintf('Child `%s` object must be an instance of ICS\\Objects', $parser));
// @TODO: To edit
$content2 = null;
foreach( explode(PHP_EOL, $content) as $line )
if( preg_match('`^([A-Z:=]+[:;])`', trim($line)) )
$content2 .= PHP_EOL . trim($line); // single-line prop.
else
$content2 .= trim($line); // multi-line prop. (\n)
$content = $parser::parseObject($this, trim($content2));
}
return $content;
}
public function save($filename = null, $indent = false) {
$content = trim($this->saveObject($indent === true ? ' ' : $indent));
$content = preg_replace('`^([[:blank:]]*[A-Z]+):([A-Z]+)([;=])(.*)$`mi', '$1;$2$3$4', $content);
if( $filename )
file_put_contents($filename, $content);
return $content;
}
public function __set($name, $value) {
if( !is_array($this->{strtolower($name)}) )
$this->{strtolower($name)} = $value;
}
public function __toString() {
return (String) $this->save(null, true);
}
// auto toString
public function __invoke($indent = true) {
return (String) $this->save(null, $indent);
}
protected function genericSaveObject($indent, $vBeginTag, $vEndTag) {
$return = array();
$return[] = $vBeginTag;
foreach( $this->getDatas() as $name => $value ) {
if( $value !== null && !is_array($value) )
$return[] = $indent . strtoupper($name) . ':' . trim($value);
}
foreach( $this->getExtended() as $name => $value ) {
if( $value !== null )
$return[] = $indent . strtoupper($name) . ':' . $value;
}
foreach( $this->getChildren() as $event ) {
$return[] = $indent . implode(PHP_EOL . $indent, explode(PHP_EOL, $event->save(null, $indent)));
}
$return[] = $vEndTag;
return $indent . implode(PHP_EOL, $return);
}
}
?> | Thiktak/PhpICS | PhpICS/ICS/Objects.php | PHP | lgpl-3.0 | 4,125 |
<?php
/*
* This file is part of the foomo Opensource Framework.
*
* The foomo Opensource Framework 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 3 of the
* License, or (at your option) any later version.
*
* The foomo Opensource Framework 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
* the foomo Opensource Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Foomo;
/**
* @link www.foomo.org
* @license www.gnu.org/licenses/lgpl.txt
* @author jan <jan@bestbytes.de>
*/
class TimerTest extends \PHPUnit_Framework_TestCase {
public function testStopwatchAccumulation()
{
$timer = new Timer\Simple();
$timer->start(__METHOD__);
usleep(100000);
$timer->stop(__METHOD__);
$accumulated = $timer->accumulateStopWatchEntries(array(__METHOD__ => 'foo'));
$this->assertGreaterThanOrEqual(0.1, $accumulated['foo']);
$this->assertLessThanOrEqual(0.11, $accumulated['foo']);
$timer = new Timer\Simple();
$timer->start(__METHOD__);
usleep(100000);
$timer->stop(__METHOD__);
$timer->start(__METHOD__);
$timer->start(__METHOD__);
usleep(100000);
$timer->stop(__METHOD__);
$timer->stop(__METHOD__);
$accumulated = $timer->accumulateStopWatchEntries(array(__METHOD__ => 'foo'));
$this->assertGreaterThanOrEqual(0.3, $accumulated['foo']);
$this->assertLessThanOrEqual(0.31, $accumulated['foo']);
}
} | foomo/Foomo | tests/Foomo/TimerTest.php | PHP | lgpl-3.0 | 1,775 |
$.fn.croneditor = function(opts) {
var el = this;
// Write the HTML template to the document
$(el).html(tmpl);
var cronArr = ["*", "*", "*", "*", "*", "*"];
if (typeof opts.value === "string") {
cronArr = opts.value.split(' ');
}
$( ".tabs" ).tabs({
activate: function( event, ui ) {
switch ($(ui.newTab).attr('id')) {
// Seconds
case 'button-second-every':
cronArr[0] = "*";
break;
case 'button-second-n':
cronArr[0] = "*/" + $( "#tabs-second .slider" ).slider("value");
break;
// Minutes
case 'button-minute-every':
cronArr[1] = "*";
break;
case 'button-minute-n':
cronArr[1] = "*/" + $( "#tabs-minute .slider" ).slider("value");
break;
case 'button-minute-each':
cronArr[1] = "*";
// TODO: toggle off selected minutes on load
//$('.tabs-minute-format input[checked="checked"]').click()
$('.tabs-minute-format').html('');
drawEachMinutes();
break;
// Hours
case 'button-hour-every':
cronArr[2] = "*";
break;
case 'button-hour-n':
cronArr[2] = "*/" + $( "#tabs-hour .slider" ).slider("value");
break;
case 'button-hour-each':
cronArr[2] = "*";
$('.tabs-hour-format').html('');
drawEachHours();
break;
// Days
case 'button-day-every':
cronArr[3] = "*";
break;
case 'button-day-each':
cronArr[3] = "*";
$('.tabs-day-format').html('');
drawEachDays();
break;
// Months
case 'button-month-every':
cronArr[4] = "*";
break;
case 'button-month-each':
cronArr[4] = "*";
$('.tabs-month-format').html('');
drawEachMonths();
break;
// Weeks
case 'button-week-every':
cronArr[5] = "*";
break;
case 'button-week-each':
cronArr[5] = "*";
$('.tabs-week-format').html('');
drawEachWeek();
break;
}
drawCron();
}
});
function drawCron () {
var newCron = cronArr.join(' ');
$('#cronString').val(newCron);
// TODO: add back next estimated cron time
/*
var last = new Date();
$('.next').html('');
var job = new cron.CronTime(newCron);
var next = job._getNextDateFrom(new Date());
$('.next').append('<span id="nextRun">' + dateformat(next, "ddd mmm dd yyyy HH:mm:ss") + '</span><br/>');
*/
/*
setInterval(function(){
drawCron();
}, 500);
*/
/*
$('#cronString').keyup(function(){
cronArr = $('#cronString').val().split(' ');
console.log('updated', cronArr)
});
*/
}
$('#clear').click(function(){
$('#cronString').val('* * * * * *');
cronArr = ["*","*","*","*","*", "*"];
});
$( "#tabs-second .slider" ).slider({
min: 1,
max: 59,
slide: function( event, ui ) {
cronArr[0] = "*/" + ui.value;
$('#tabs-second-n .preview').html('ๆฏ้ ' + ui.value + ' ็ง');
drawCron();
}
});
$( "#tabs-minute .slider" ).slider({
min: 1,
max: 59,
slide: function( event, ui ) {
cronArr[1] = "*/" + ui.value;
$('#tabs-minute-n .preview').html('ๆฏ้ ' + ui.value + ' ๅ้');
drawCron();
}
});
$( "#tabs-hour .slider" ).slider({
min: 1,
max: 23,
slide: function( event, ui ) {
cronArr[2] = "*/" + ui.value;
$('#tabs-hour-n .preview').html('ๆฏ้ ' + ui.value + ' ๅฐๆถ');
drawCron();
}
});
// TOOD: All draw* functions can be combined into a few smaller methods
function drawEachMinutes () {
// minutes
for (var i = 0; i < 60; i++) {
var padded = i;
if(padded.toString().length === 1) {
padded = "0" + padded;
}
$('.tabs-minute-format').append('<input type="checkbox" id="minute-check' + i + '"><label for="minute-check' + i + '">' + padded + '</label>');
if (i !== 0 && (i+1) % 10 === 0) {
$('.tabs-minute-format').append('<br/>');
}
}
$('.tabs-minute-format input').button();
$('.tabs-minute-format').buttonset();
$('.tabs-minute-format input[type="checkbox"]').click(function(){
var newItem = $(this).attr('id').replace('minute-check', '');
if(cronArr[1] === "*") {
cronArr[1] = $(this).attr('id').replace('minute-check', '');
} else {
// if value already in list, toggle it off
var list = cronArr[1].split(',');
if (list.indexOf(newItem) !== -1) {
list.splice(list.indexOf(newItem), 1);
cronArr[1] = list.join(',');
} else {
// else toggle it on
cronArr[1] = cronArr[1] + "," + newItem;
}
if(cronArr[1] === "") {
cronArr[1] = "*";
}
}
drawCron();
});
}
function drawEachHours () {
// hours
for (var i = 0; i < 24; i++) {
var padded = i;
if(padded.toString().length === 1) {
padded = "0" + padded;
}
$('.tabs-hour-format').append('<input type="checkbox" id="hour-check' + i + '"><label for="hour-check' + i + '">' + padded + '</label>');
if (i !== 0 && (i+1) % 12 === 0) {
$('.tabs-hour-format').append('<br/>');
}
}
$('.tabs-hour-format input').button();
$('.tabs-hour-format').buttonset();
$('.tabs-hour-format input[type="checkbox"]').click(function(){
var newItem = $(this).attr('id').replace('hour-check', '');
if(cronArr[2] === "*") {
cronArr[2] = $(this).attr('id').replace('hour-check', '');
} else {
// if value already in list, toggle it off
var list = cronArr[2].split(',');
if (list.indexOf(newItem) !== -1) {
list.splice(list.indexOf(newItem), 1);
cronArr[2] = list.join(',');
} else {
// else toggle it on
cronArr[2] = cronArr[2] + "," + newItem;
}
if(cronArr[2] === "") {
cronArr[2] = "*";
}
}
drawCron();
});
};
function drawEachDays () {
// days
for (var i = 1; i < 32; i++) {
var padded = i;
if(padded.toString().length === 1) {
padded = "0" + padded;
}
$('.tabs-day-format').append('<input type="checkbox" id="day-check' + i + '"><label for="day-check' + i + '">' + padded + '</label>');
if (i !== 0 && (i) % 7 === 0) {
$('.tabs-day-format').append('<br/>');
}
}
$('.tabs-day-format input').button();
$('.tabs-day-format').buttonset();
$('.tabs-day-format input[type="checkbox"]').click(function(){
var newItem = $(this).attr('id').replace('day-check', '');
if(cronArr[3] === "*") {
cronArr[3] = $(this).attr('id').replace('day-check', '');
} else {
// if value already in list, toggle it off
var list = cronArr[3].split(',');
if (list.indexOf(newItem) !== -1) {
list.splice(list.indexOf(newItem), 1);
cronArr[3] = list.join(',');
} else {
// else toggle it on
cronArr[3] = cronArr[3] + "," + newItem;
}
if(cronArr[3] === "") {
cronArr[3] = "*";
}
}
drawCron();
});
};
function drawEachMonths () {
// months
//var months = [null, 'Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
var months = [null, 'ไธๆ', 'ไบๆ', 'ไธๆ', 'ๅๆ', 'ไบๆ', 'ๅ
ญๆ', 'ไธๆ', 'ๅ
ซๆ', 'ไนๆ', 'ๅๆ', 'ๅไธๆ', 'ๅไบๆ'];
for (var i = 1; i < 13; i++) {
var padded = i;
if(padded.toString().length === 1) {
//padded = "0" + padded;
}
$('.tabs-month-format').append('<input type="checkbox" id="month-check' + i + '"><label for="month-check' + i + '">' + months[i] + '</label>');
}
$('.tabs-month-format input').button();
$('.tabs-month-format').buttonset();
$('.tabs-month-format input[type="checkbox"]').click(function(){
var newItem = $(this).attr('id').replace('month-check', '');
if(cronArr[4] === "*") {
cronArr[4] = $(this).attr('id').replace('month-check', '');
} else {
// if value already in list, toggle it off
var list = cronArr[4].split(',');
if (list.indexOf(newItem) !== -1) {
list.splice(list.indexOf(newItem), 1);
cronArr[4] = list.join(',');
} else {
// else toggle it on
cronArr[4] = cronArr[4] + "," + newItem;
}
if(cronArr[4] === "") {
cronArr[4] = "*";
}
}
drawCron();
});
};
function drawEachWeek () {
// weeks
//var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var days = ['ๆๆๅคฉ', 'ๆๆไธ', 'ๆๆไบ', 'ๆๆไธ', 'ๆๆๅ', 'ๆ็ไบ', 'ๆๆๅ
ญ'];
for (var i = 0; i < 7; i++) {
var padded = i;
if(padded.toString().length === 1) {
//padded = "0" + padded;
}
$('.tabs-week-format').append('<input type="checkbox" id="week-check' + i + '"><label for="week-check' + i + '">' + days[i] + '</label>');
}
$('.tabs-week-format input').button();
$('.tabs-week-format').buttonset();
$('.tabs-week-format input[type="checkbox"]').click(function(){
var newItem = $(this).attr('id').replace('week-check', '');
if(cronArr[5] === "*") {
cronArr[5] = $(this).attr('id').replace('week-check', '');
} else {
// if value already in list, toggle it off
var list = cronArr[5].split(',');
if (list.indexOf(newItem) !== -1) {
list.splice(list.indexOf(newItem), 1);
cronArr[5] = list.join(',');
} else {
// else toggle it on
cronArr[5] = cronArr[5] + "," + newItem;
}
if(cronArr[5] === "") {
cronArr[5] = "*";
}
}
drawCron();
});
};
// TODO: Refactor these methods into smaller methods
drawEachMinutes();
drawEachHours();
drawEachDays();
drawEachMonths();
drawCron();
};
// HTML Template for plugin
var tmpl = '<input type="text" id="cronString" value="* * * * * * ?" size="80"/>\
<br/>\
<input type="button" value="้็ฝฎ" id="clear"/>\
<br/>\
<!-- TODO: add back next estimated time -->\
<!-- <span>Will run next at:<em><span class="next"></span></em></span> -->\
<!-- the cron editor will be here -->\
<div id="tabs" class="tabs">\
<ul>\
<li><a href="#tabs-second">็ง</a></li>\
<li><a href="#tabs-minute">ๅ้</a></li>\
<li><a href="#tabs-hour">ๅฐๆถ</a></li>\
<li><a href="#tabs-day">ๆไปฝไธญ็ๅคฉ</a></li>\
<li><a href="#tabs-month">ๆไปฝ</a></li>\
<li><a href="#tabs-week">ๆๆๅ ๏ผ</a></li>\
</ul>\
<div id="tabs-second">\
<div class="tabs">\
<ul>\
<li id="button-second-every"><a href="#tabs-second-every">ๆฏ็ง</a></li>\
<li id="button-second-n"><a href="#tabs-second-n">้ๅ ็ง</a></li>\
</ul>\
<div id="tabs-second-every" class="preview">\
<div>*</div>\
<div>ๆฏ็ง</div>\
</div>\
<div id="tabs-second-n">\
<div class="preview"> ๆฏ้1็ง</div>\
<div class="slider"></div>\
</div>\
</div>\
</div>\
<div id="tabs-minute">\
<div class="tabs">\
<ul>\
<li id="button-minute-every"><a href="#tabs-minute-every">ๆฏๅ้</a></li>\
<li id="button-minute-n"><a href="#tabs-minute-n">้ๅ ๅ้</a></li>\
<li id="button-minute-each"><a href="#tabs-minute-each">้้ๅฎ็ๅ้</a></li>\
</ul>\
<div id="tabs-minute-every" class="preview">\
<div>*</div>\
<div>ๆฏๅ้</div>\
</div>\
<div id="tabs-minute-n">\
<div class="preview">ๆฏ้1ๅ้</div>\
<div class="slider"></div>\
</div>\
<div id="tabs-minute-each" class="preview">\
<div>้้ๅฎ็ๅ้</div><br/>\
<div class="tabs-minute-format"></div>\
</div>\
</div>\
</div>\
<div id="tabs-hour">\
<div class="tabs">\
<ul>\
<li id="button-hour-every"><a href="#tabs-hour-every">ๆฏๅฐๆถ</a></li>\
<li id="button-hour-n"><a href="#tabs-hour-n">้ๅ ๅฐๆถ</a></li>\
<li id="button-hour-each"><a href="#tabs-hour-each">้้ๅฎ็ๅฐๆถ</a></li>\
</ul>\
<div id="tabs-hour-every" class="preview">\
<div>*</div>\
<div>ๆฏๅฐๆถ</div>\
</div>\
<div id="tabs-hour-n">\
<div class="preview">ๆฏ้1ๅฐๆถ</div>\
<div class="slider"></div>\
</div>\
<div id="tabs-hour-each" class="preview">\
<div>้้ๅฎ็ๅฐๆถ</div><br/>\
<div class="tabs-hour-format"></div>\
</div>\
</div>\
</div>\
<div id="tabs-day">\
<div class="tabs">\
<ul>\
<li id="button-day-every"><a href="#tabs-day-every">ๆฏๅคฉ/ๆ</a></li>\
<li id="button-day-each"><a href="#tabs-day-each">้ๅฎ็ๆฅๆ</a></li>\
</ul>\
<div id="tabs-day-every" class="preview">\
<div>*</div>\
<div>ๆฏๅคฉ/ๆ</div>\
</div>\
<div id="tabs-day-each" class="preview">\
<div>้ๅฎ็ๆฅๆ</div><br/>\
<div class="tabs-day-format"></div>\
</div>\
</div>\
</div>\
<div id="tabs-month">\
<div class="tabs">\
<ul>\
<li id="button-month-every"><a href="#tabs-month-every">ๆฏๆ</a></li>\
<li id="button-month-each"><a href="#tabs-month-each">้ๅฎ็ๆไปฝ</a></li>\
</ul>\
<div id="tabs-month-every" class="preview">\
<div>*</div>\
<div>ๆฏๆ</div>\
</div>\
<div id="tabs-month-each" class="preview">\
<div>้ๅฎ็ๆไปฝ</div><br/>\
<div class="tabs-month-format"></div>\
</div>\
</div>\
</div>\
<div id="tabs-week">\
<div class="tabs">\
<ul>\
<li id="button-week-every"><a href="#tabs-week-every">ๆฏๅคฉ/ๅจ</a></li>\
<li id="button-week-each"><a href="#tabs-week-each">้ๅฎ็ๆๆๅ </a></li>\
</ul>\
<div id="tabs-week-every" class="preview">\
<div>*</div>\
<div>ๆฏๅคฉ/ๅจ</div>\
</div>\
<div id="tabs-week-each">\
<div class="preview">้ๅฎ็ๆๆๅ </div><br/>\
<div class="tabs-week-format"></div>\
</div>\
</div>\
</div>\
</div>'; | liushuishang/YayCrawler | yaycrawler.admin/src/main/resources/static/assets/global/plugins/cron-editor/js/jquery.croneditor.js | JavaScript | lgpl-3.0 | 14,595 |